small fix with torch.finfo
Browse files- modeling_lsg_distilbert.py +115 -291
modeling_lsg_distilbert.py
CHANGED
@@ -49,10 +49,11 @@ class LSGDistilBertConfig(DistilBertConfig):
|
|
49 |
self.sparse_block_size = sparse_block_size
|
50 |
self.sparsity_factor = sparsity_factor
|
51 |
self.sparsity_type = sparsity_type
|
52 |
-
|
53 |
if sparsity_type not in [None, "none", "norm", "lsh", "pooling", "stride", "block_stride"]:
|
54 |
logger.warning(
|
55 |
-
"[WARNING CONFIG]: sparsity_mode not in [None, 'none', 'norm', 'lsh', 'pooling', 'stride', 'block_stride'],
|
|
|
56 |
self.sparsity_type = None
|
57 |
|
58 |
if self.sparsity_type in ["stride", "block_stride"]:
|
@@ -60,7 +61,7 @@ class LSGDistilBertConfig(DistilBertConfig):
|
|
60 |
logger.warning(
|
61 |
"[WARNING CONFIG]: sparsity_factor > encoder_attention_heads is not recommended for stride/block_stride sparsity"
|
62 |
)
|
63 |
-
|
64 |
if self.num_global_tokens < 1:
|
65 |
logger.warning(
|
66 |
"[WARNING CONFIG]: num_global_tokens < 1 is not compatible, setting num_global_tokens=1"
|
@@ -68,13 +69,23 @@ class LSGDistilBertConfig(DistilBertConfig):
|
|
68 |
self.num_global_tokens = 1
|
69 |
elif self.num_global_tokens > 512:
|
70 |
logger.warning(
|
71 |
-
"[WARNING CONFIG]: num_global_tokens > 512 is not
|
72 |
)
|
73 |
self.num_global_tokens = 512
|
74 |
|
75 |
if self.sparsity_factor > 0:
|
76 |
assert self.block_size % self.sparsity_factor == 0, "[ERROR CONFIG]: block_size must be divisible by sparsity_factor"
|
77 |
assert self.block_size//self.sparsity_factor >= 1, "[ERROR CONFIG]: make sure block_size >= sparsity_factor"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
|
80 |
class LSGEmbeddings(Embeddings):
|
@@ -232,7 +243,7 @@ class CausalAttentionProduct(nn.Module):
|
|
232 |
diagonal=-1
|
233 |
)
|
234 |
causal_mask = causal_mask.T * torch.finfo(attention_scores.dtype).min
|
235 |
-
attention_scores[..., -causal_shape[0]:, -causal_shape[1]:] = causal_mask
|
236 |
|
237 |
del attention_mask
|
238 |
|
@@ -515,7 +526,8 @@ class LSGSelfAttention(BaseSelfAttention):
|
|
515 |
keys = keys.sum(dim=-2) / (mask + 1e-6)
|
516 |
values = values.sum(dim=-2) / (mask + 1e-6)
|
517 |
|
518 |
-
mask = (1. - mask.clamp(0, 1))
|
|
|
519 |
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
|
520 |
|
521 |
def get_sparse_tokens_with_stride(self, keys, values, mask):
|
@@ -580,7 +592,8 @@ class LSGSelfAttention(BaseSelfAttention):
|
|
580 |
keys /= mask + 1e-8
|
581 |
values /= mask + 1e-8
|
582 |
|
583 |
-
mask = (1. - mask.clamp(0, 1))
|
|
|
584 |
|
585 |
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
|
586 |
|
@@ -607,150 +620,27 @@ class LSGSelfAttention(BaseSelfAttention):
|
|
607 |
|
608 |
def forward(
|
609 |
self,
|
610 |
-
|
611 |
-
|
|
|
|
|
612 |
head_mask=None,
|
613 |
-
|
614 |
-
encoder_attention_mask=None,
|
615 |
-
past_key_value=None,
|
616 |
-
output_attentions=False,
|
617 |
-
):
|
618 |
-
|
619 |
-
query_layer = self.q_lin(hidden_states)
|
620 |
-
|
621 |
-
# If this is instantiated as a cross-attention module, the keys
|
622 |
-
# and values come from an encoder; the attention mask needs to be
|
623 |
-
# such that the encoder's padding tokens are not attended to.
|
624 |
-
is_cross_attention = encoder_hidden_states is not None
|
625 |
-
|
626 |
-
if is_cross_attention and past_key_value is not None:
|
627 |
-
# reuse k,v, cross_attentions
|
628 |
-
key_layer = past_key_value[0]
|
629 |
-
value_layer = past_key_value[1]
|
630 |
-
attention_mask = encoder_attention_mask
|
631 |
-
elif is_cross_attention:
|
632 |
-
key_layer = self.transpose_for_scores(self.k_lin(encoder_hidden_states))
|
633 |
-
value_layer = self.transpose_for_scores(self.v_lin(encoder_hidden_states))
|
634 |
-
attention_mask = encoder_attention_mask
|
635 |
-
elif past_key_value is not None:
|
636 |
-
key_layer = self.transpose_for_scores(self.k_lin(hidden_states))
|
637 |
-
value_layer = self.transpose_for_scores(self.v_lin(hidden_states))
|
638 |
-
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
639 |
-
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
640 |
-
else:
|
641 |
-
key_layer = self.transpose_for_scores(self.k_lin(hidden_states))
|
642 |
-
value_layer = self.transpose_for_scores(self.v_lin(hidden_states))
|
643 |
-
|
644 |
-
query_layer = self.transpose_for_scores(query_layer)
|
645 |
-
|
646 |
-
if self.is_decoder:
|
647 |
-
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
648 |
-
# Further calls to cross_attention layer can then reuse all cross-attention
|
649 |
-
# key/value_states (first "if" case)
|
650 |
-
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
651 |
-
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
652 |
-
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
653 |
-
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
654 |
-
past_key_value = (key_layer, value_layer)
|
655 |
-
|
656 |
-
if is_cross_attention:
|
657 |
-
outputs = self.cross_attention_forward(
|
658 |
-
query_layer=query_layer,
|
659 |
-
key_layer=key_layer,
|
660 |
-
value_layer=value_layer,
|
661 |
-
attention_mask=attention_mask,
|
662 |
-
output_attentions=output_attentions
|
663 |
-
)
|
664 |
-
else:
|
665 |
-
outputs = self.causal_forward(
|
666 |
-
query_layer,
|
667 |
-
key_layer,
|
668 |
-
value_layer,
|
669 |
-
attention_mask=attention_mask,
|
670 |
-
output_attentions=output_attentions,
|
671 |
-
)
|
672 |
-
|
673 |
-
outputs = outputs + ((key_layer, value_layer),)
|
674 |
-
|
675 |
-
else:
|
676 |
-
outputs = self.not_causal_forward(
|
677 |
-
query_layer,
|
678 |
-
key_layer,
|
679 |
-
value_layer,
|
680 |
-
attention_mask=attention_mask,
|
681 |
-
output_attentions=output_attentions
|
682 |
-
)
|
683 |
-
|
684 |
-
#if head_mask is not None:
|
685 |
-
# outputs = (outputs[0] * head_mask[:, :, :1, :1], ) + outputs[1:]
|
686 |
-
return (self.out_lin(outputs[0]),) + outputs[1:]
|
687 |
-
|
688 |
-
def causal_forward(
|
689 |
-
self,
|
690 |
-
query_layer,
|
691 |
-
key_layer,
|
692 |
-
value_layer,
|
693 |
-
attention_mask=None,
|
694 |
-
output_attentions=False,
|
695 |
):
|
696 |
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
|
701 |
-
|
702 |
-
# Split input into global tokens and other tokens
|
703 |
-
split = (self.num_global_tokens, t - self.num_global_tokens)
|
704 |
-
global_query, query_layer = query_layer.split(split, dim=-2)
|
705 |
-
|
706 |
-
# Use normal causal attention if local attention covers every tokens
|
707 |
-
if t <= 2 * self.block_size + self.num_global_tokens:
|
708 |
-
context_layer = self.causal_attention(
|
709 |
-
query_layer=query_layer,
|
710 |
-
key_layer=key_layer,
|
711 |
-
value_layer=value_layer,
|
712 |
-
attention_mask=attention_mask,
|
713 |
-
causal_shape=(t - self.num_global_tokens, t - self.num_global_tokens)
|
714 |
-
)
|
715 |
-
|
716 |
-
context_layer = torch.cat([global_query, context_layer], dim=-2)
|
717 |
-
return (self.reshape_output(context_layer), )
|
718 |
-
|
719 |
-
# Split K Q M on global and non global
|
720 |
-
global_key, key_layer = key_layer.split(split, dim=-2)
|
721 |
-
global_value, value_layer = value_layer.split(split, dim=-2)
|
722 |
-
global_mask, attention_mask = attention_mask.split(split, dim=-1)
|
723 |
-
|
724 |
-
n, h, t, d = key_layer.size()
|
725 |
-
|
726 |
-
# Get sparse idx
|
727 |
-
sparse_key, sparse_value, sparse_mask = (None, None, None)
|
728 |
-
if self.sparse_block_size and self.sparsity_factor > 0:
|
729 |
-
sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
|
730 |
-
|
731 |
-
# Expand masks on heads
|
732 |
-
attention_mask = attention_mask.expand(-1, h, -1, -1)
|
733 |
-
global_mask = global_mask.expand(-1, h, -1, -1)
|
734 |
|
735 |
-
|
736 |
-
|
737 |
-
|
738 |
-
key_layer,
|
739 |
value_layer,
|
740 |
-
attention_mask,
|
741 |
-
|
742 |
-
sparse_value=sparse_value,
|
743 |
-
sparse_mask=sparse_mask,
|
744 |
-
global_key=global_key,
|
745 |
-
global_value=global_value,
|
746 |
-
global_mask=global_mask
|
747 |
)
|
748 |
|
749 |
-
|
750 |
-
context_layer = torch.cat([global_query, context_layer], dim=-2)
|
751 |
-
context_layer = self.reshape_output(context_layer)
|
752 |
-
|
753 |
-
return (context_layer,)
|
754 |
|
755 |
def not_causal_forward(
|
756 |
self,
|
@@ -825,105 +715,31 @@ class LSGSelfAttention(BaseSelfAttention):
|
|
825 |
|
826 |
return (context_layer,)
|
827 |
|
828 |
-
def cross_attention_forward(
|
829 |
-
self,
|
830 |
-
query_layer,
|
831 |
-
key_layer,
|
832 |
-
value_layer,
|
833 |
-
attention_mask=None,
|
834 |
-
output_attentions=False,
|
835 |
-
):
|
836 |
-
|
837 |
-
context_layer = self.full_attention(
|
838 |
-
query_layer=query_layer,
|
839 |
-
key_layer=key_layer,
|
840 |
-
value_layer=value_layer,
|
841 |
-
attention_mask=attention_mask
|
842 |
-
)
|
843 |
-
return (self.reshape_output(context_layer), )
|
844 |
-
|
845 |
def chunk(self, x, chunk_size):
|
846 |
|
847 |
n, h, t, d = x.size()
|
848 |
return x.reshape(n, h, -1, chunk_size, d)
|
849 |
|
850 |
|
851 |
-
class LSGTransformerBlock(
|
852 |
|
853 |
def __init__(self, config):
|
854 |
|
855 |
-
|
856 |
|
857 |
assert config.dim % config.n_heads == 0
|
858 |
|
859 |
self.attention = LSGSelfAttention(config)
|
860 |
-
self.sa_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
|
861 |
-
|
862 |
-
self.ffn = FFN(config)
|
863 |
-
self.output_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
|
864 |
-
|
865 |
-
def forward(self, x, attn_mask=None, head_mask=None, output_attentions=False):
|
866 |
-
"""
|
867 |
-
Parameters:
|
868 |
-
x: torch.tensor(bs, seq_length, dim)
|
869 |
-
attn_mask: torch.tensor(bs, seq_length)
|
870 |
-
|
871 |
-
Returns:
|
872 |
-
sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
|
873 |
-
torch.tensor(bs, seq_length, dim) The output of the transformer block contextualization.
|
874 |
-
"""
|
875 |
-
# Self-Attention
|
876 |
-
sa_output = self.attention(
|
877 |
-
hidden_states=x,
|
878 |
-
attention_mask=torch.finfo(x.dtype).min*(1 - attn_mask).unsqueeze(1).unsqueeze(1),
|
879 |
-
head_mask=head_mask,
|
880 |
-
output_attentions=output_attentions,
|
881 |
-
)
|
882 |
-
if output_attentions:
|
883 |
-
sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
|
884 |
-
else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples
|
885 |
-
assert type(sa_output) == tuple
|
886 |
-
sa_output = sa_output[0]
|
887 |
-
sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)
|
888 |
-
|
889 |
-
# Feed Forward Network
|
890 |
-
ffn_output = self.ffn(sa_output) # (bs, seq_length, dim)
|
891 |
-
ffn_output = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)
|
892 |
-
|
893 |
-
output = (ffn_output,)
|
894 |
-
if output_attentions:
|
895 |
-
output = (sa_weights,) + output
|
896 |
-
return output
|
897 |
|
898 |
|
899 |
class LSGTransformer(Transformer):
|
900 |
|
901 |
def __init__(self, config):
|
902 |
|
903 |
-
|
904 |
|
905 |
-
self.n_layers = config.n_layers
|
906 |
self.layer = nn.ModuleList([LSGTransformerBlock(config) for _ in range(config.n_layers)])
|
907 |
|
908 |
-
|
909 |
-
class LSGDistilBertPreTrainedModel(DistilBertPreTrainedModel):
|
910 |
-
"""
|
911 |
-
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
912 |
-
models.
|
913 |
-
"""
|
914 |
-
|
915 |
-
config_class = LSGDistilBertConfig
|
916 |
-
|
917 |
-
|
918 |
-
class LSGDistilBertModel(LSGDistilBertPreTrainedModel, DistilBertModel):
|
919 |
-
|
920 |
-
def __init__(self, config):
|
921 |
-
|
922 |
-
LSGDistilBertPreTrainedModel.__init__(self, config)
|
923 |
-
|
924 |
-
self.embeddings = LSGEmbeddings(config) # Embeddings
|
925 |
-
self.transformer = LSGTransformer(config) # Encoder
|
926 |
-
|
927 |
assert hasattr(config, "num_global_tokens")
|
928 |
self.num_global_tokens = config.num_global_tokens
|
929 |
self.pad_idx = config.pad_token_id
|
@@ -934,97 +750,105 @@ class LSGDistilBertModel(LSGDistilBertPreTrainedModel, DistilBertModel):
|
|
934 |
self.mask_first_token = config.mask_first_token
|
935 |
self.pool_with_global = config.pool_with_global
|
936 |
|
937 |
-
# Initialize weights and apply final processing
|
938 |
-
self.post_init()
|
939 |
-
|
940 |
def forward(
|
941 |
self,
|
942 |
-
|
943 |
-
|
944 |
-
head_mask=None,
|
945 |
-
|
946 |
-
|
947 |
-
|
948 |
-
|
949 |
-
|
950 |
-
|
951 |
-
|
952 |
-
n, t =
|
953 |
|
954 |
-
if attention_mask is None:
|
955 |
-
attention_mask = torch.ones(n, t, device=inputs_.device, dtype=inputs_.dtype)
|
956 |
-
if self.mask_first_token:
|
957 |
-
attention_mask[:,0] = 0
|
958 |
-
|
959 |
b = self.block_size * 2
|
960 |
pad = t % self.block_size
|
961 |
|
962 |
# Check if t is multiple of block_size and pad
|
963 |
if self.adaptive and t > b and pad > 0:
|
964 |
pad_length = self.block_size - pad
|
965 |
-
|
966 |
-
|
967 |
-
|
968 |
-
|
969 |
-
|
970 |
-
attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=0)
|
971 |
-
|
972 |
-
n, t_ = attention_mask.size()
|
973 |
|
974 |
-
|
975 |
-
|
976 |
-
|
|
|
|
|
977 |
head_mask=head_mask,
|
978 |
-
inputs_embeds=inputs_embeds,
|
979 |
output_attentions=output_attentions,
|
980 |
output_hidden_states=output_hidden_states,
|
981 |
-
return_dict=return_dict
|
982 |
-
|
983 |
|
984 |
-
|
985 |
if self.pool_with_global:
|
986 |
-
|
987 |
-
|
988 |
-
diff = t - t_
|
989 |
-
n, _, d = context.size()
|
990 |
-
context = context[..., self.num_global_tokens:, :]
|
991 |
|
992 |
# Adapt sequence to initial shape
|
993 |
-
|
994 |
-
|
995 |
-
|
996 |
if not return_dict:
|
997 |
-
return (
|
|
|
|
|
|
|
998 |
|
999 |
-
return BaseModelOutput(
|
1000 |
-
last_hidden_state=context,
|
1001 |
-
hidden_states=encoder_outputs.hidden_states,
|
1002 |
-
attentions=encoder_outputs.attentions,
|
1003 |
-
)
|
1004 |
|
1005 |
-
|
1006 |
-
|
1007 |
-
|
1008 |
-
|
1009 |
-
|
1010 |
-
|
1011 |
-
|
1012 |
-
|
1013 |
-
return_dict=None,
|
1014 |
-
):
|
1015 |
-
|
1016 |
-
# Prepare head mask if needed
|
1017 |
-
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
1018 |
-
inputs_embeds = self.embeddings(input_ids, inputs_embeds) # (bs, seq_length, dim)
|
1019 |
-
return self.transformer(
|
1020 |
-
x=inputs_embeds,
|
1021 |
-
attn_mask=attention_mask,
|
1022 |
-
head_mask=head_mask,
|
1023 |
-
output_attentions=output_attentions,
|
1024 |
-
output_hidden_states=output_hidden_states,
|
1025 |
-
return_dict=return_dict,
|
1026 |
-
)
|
1027 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1028 |
|
1029 |
class LSGDistilBertForMaskedLM(LSGDistilBertPreTrainedModel, DistilBertForMaskedLM):
|
1030 |
|
|
|
49 |
self.sparse_block_size = sparse_block_size
|
50 |
self.sparsity_factor = sparsity_factor
|
51 |
self.sparsity_type = sparsity_type
|
52 |
+
|
53 |
if sparsity_type not in [None, "none", "norm", "lsh", "pooling", "stride", "block_stride"]:
|
54 |
logger.warning(
|
55 |
+
"[WARNING CONFIG]: sparsity_mode not in [None, 'none', 'norm', 'lsh', 'pooling', 'stride', 'block_stride'], \
|
56 |
+
setting sparsity_type=None, computation will skip sparse attention")
|
57 |
self.sparsity_type = None
|
58 |
|
59 |
if self.sparsity_type in ["stride", "block_stride"]:
|
|
|
61 |
logger.warning(
|
62 |
"[WARNING CONFIG]: sparsity_factor > encoder_attention_heads is not recommended for stride/block_stride sparsity"
|
63 |
)
|
64 |
+
|
65 |
if self.num_global_tokens < 1:
|
66 |
logger.warning(
|
67 |
"[WARNING CONFIG]: num_global_tokens < 1 is not compatible, setting num_global_tokens=1"
|
|
|
69 |
self.num_global_tokens = 1
|
70 |
elif self.num_global_tokens > 512:
|
71 |
logger.warning(
|
72 |
+
"[WARNING CONFIG]: num_global_tokens > 512 is not allowed, setting num_global_tokens=512"
|
73 |
)
|
74 |
self.num_global_tokens = 512
|
75 |
|
76 |
if self.sparsity_factor > 0:
|
77 |
assert self.block_size % self.sparsity_factor == 0, "[ERROR CONFIG]: block_size must be divisible by sparsity_factor"
|
78 |
assert self.block_size//self.sparsity_factor >= 1, "[ERROR CONFIG]: make sure block_size >= sparsity_factor"
|
79 |
+
|
80 |
+
if self.mask_first_token and not pool_with_global:
|
81 |
+
logger.warning(
|
82 |
+
"[WARNING CONFIG]: pool_with_global==False is not compatible with mask_first_token==True. Setting pool_with_global to True.")
|
83 |
+
self.pool_with_global = True
|
84 |
+
|
85 |
+
if hasattr(self, "position_embedding_type"):
|
86 |
+
if self.position_embedding_type != "absolute":
|
87 |
+
logger.warning(
|
88 |
+
"[WARNING CONFIG]: LSG Attention is not compatible with relative positional embedding and will skip its computation. Set position_embedding_type='absolute' to remove this warning.")
|
89 |
|
90 |
|
91 |
class LSGEmbeddings(Embeddings):
|
|
|
243 |
diagonal=-1
|
244 |
)
|
245 |
causal_mask = causal_mask.T * torch.finfo(attention_scores.dtype).min
|
246 |
+
attention_scores[..., -causal_shape[0]:, -causal_shape[1] + 1:] = causal_mask[:, 1:]
|
247 |
|
248 |
del attention_mask
|
249 |
|
|
|
526 |
keys = keys.sum(dim=-2) / (mask + 1e-6)
|
527 |
values = values.sum(dim=-2) / (mask + 1e-6)
|
528 |
|
529 |
+
mask = (1. - mask.clamp(0, 1))
|
530 |
+
mask *= torch.finfo(mask.dtype).min
|
531 |
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
|
532 |
|
533 |
def get_sparse_tokens_with_stride(self, keys, values, mask):
|
|
|
592 |
keys /= mask + 1e-8
|
593 |
values /= mask + 1e-8
|
594 |
|
595 |
+
mask = (1. - mask.clamp(0, 1))
|
596 |
+
mask *= torch.finfo(mask.dtype).min
|
597 |
|
598 |
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
|
599 |
|
|
|
620 |
|
621 |
def forward(
|
622 |
self,
|
623 |
+
query,
|
624 |
+
key,
|
625 |
+
value,
|
626 |
+
mask=None,
|
627 |
head_mask=None,
|
628 |
+
output_attentions=None,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
629 |
):
|
630 |
|
631 |
+
key_layer = self.transpose_for_scores(self.k_lin(key))
|
632 |
+
value_layer = self.transpose_for_scores(self.v_lin(value))
|
633 |
+
query_layer = self.transpose_for_scores(self.q_lin(query))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
634 |
|
635 |
+
outputs = self.not_causal_forward(
|
636 |
+
query_layer,
|
637 |
+
key_layer,
|
|
|
638 |
value_layer,
|
639 |
+
attention_mask=mask,
|
640 |
+
output_attentions=output_attentions
|
|
|
|
|
|
|
|
|
|
|
641 |
)
|
642 |
|
643 |
+
return (self.out_lin(outputs[0]),) + outputs[1:]
|
|
|
|
|
|
|
|
|
644 |
|
645 |
def not_causal_forward(
|
646 |
self,
|
|
|
715 |
|
716 |
return (context_layer,)
|
717 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
718 |
def chunk(self, x, chunk_size):
|
719 |
|
720 |
n, h, t, d = x.size()
|
721 |
return x.reshape(n, h, -1, chunk_size, d)
|
722 |
|
723 |
|
724 |
+
class LSGTransformerBlock(TransformerBlock):
|
725 |
|
726 |
def __init__(self, config):
|
727 |
|
728 |
+
super().__init__(config)
|
729 |
|
730 |
assert config.dim % config.n_heads == 0
|
731 |
|
732 |
self.attention = LSGSelfAttention(config)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
733 |
|
734 |
|
735 |
class LSGTransformer(Transformer):
|
736 |
|
737 |
def __init__(self, config):
|
738 |
|
739 |
+
super().__init__(config)
|
740 |
|
|
|
741 |
self.layer = nn.ModuleList([LSGTransformerBlock(config) for _ in range(config.n_layers)])
|
742 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
743 |
assert hasattr(config, "num_global_tokens")
|
744 |
self.num_global_tokens = config.num_global_tokens
|
745 |
self.pad_idx = config.pad_token_id
|
|
|
750 |
self.mask_first_token = config.mask_first_token
|
751 |
self.pool_with_global = config.pool_with_global
|
752 |
|
|
|
|
|
|
|
753 |
def forward(
|
754 |
self,
|
755 |
+
x: torch.Tensor,
|
756 |
+
attn_mask: Optional[torch.Tensor] = None,
|
757 |
+
head_mask: Optional[torch.Tensor] = None,
|
758 |
+
output_attentions: bool = False,
|
759 |
+
output_hidden_states: bool = False,
|
760 |
+
return_dict: Optional[bool] = None,
|
761 |
+
) -> Union[BaseModelOutput, Tuple[torch.Tensor, ...]]: # docstyle-ignore
|
762 |
+
|
763 |
+
attn_mask = attn_mask.float()
|
764 |
+
mask_value = 0
|
765 |
+
n, t = attn_mask.size()
|
766 |
|
|
|
|
|
|
|
|
|
|
|
767 |
b = self.block_size * 2
|
768 |
pad = t % self.block_size
|
769 |
|
770 |
# Check if t is multiple of block_size and pad
|
771 |
if self.adaptive and t > b and pad > 0:
|
772 |
pad_length = self.block_size - pad
|
773 |
+
x = torch.nn.functional.pad(x.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
|
774 |
+
attn_mask = torch.nn.functional.pad(attn_mask, (0, pad_length), value=mask_value)
|
775 |
+
|
776 |
+
if self.mask_first_token:
|
777 |
+
attn_mask[..., 0] = mask_value
|
|
|
|
|
|
|
778 |
|
779 |
+
attn_mask = torch.finfo(x.dtype).min*(1 - attn_mask).unsqueeze(1).unsqueeze(1)
|
780 |
+
|
781 |
+
encoder_outputs = super().forward(
|
782 |
+
x=x,
|
783 |
+
attn_mask=attn_mask,
|
784 |
head_mask=head_mask,
|
|
|
785 |
output_attentions=output_attentions,
|
786 |
output_hidden_states=output_hidden_states,
|
787 |
+
return_dict=return_dict
|
788 |
+
)
|
789 |
|
790 |
+
sequence_output = encoder_outputs[0]
|
791 |
if self.pool_with_global:
|
792 |
+
sequence_output[:, self.num_global_tokens] = sequence_output[:, 0]
|
|
|
|
|
|
|
|
|
793 |
|
794 |
# Adapt sequence to initial shape
|
795 |
+
sequence_output = sequence_output[..., self.num_global_tokens: t + self.num_global_tokens, :]
|
796 |
+
|
|
|
797 |
if not return_dict:
|
798 |
+
return (sequence_output, ) + encoder_outputs[1:]
|
799 |
+
|
800 |
+
encoder_outputs.last_hidden_state = sequence_output
|
801 |
+
return encoder_outputs
|
802 |
|
|
|
|
|
|
|
|
|
|
|
803 |
|
804 |
+
class LSGDistilBertPreTrainedModel(DistilBertPreTrainedModel):
|
805 |
+
"""
|
806 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
807 |
+
models.
|
808 |
+
"""
|
809 |
+
|
810 |
+
config_class = LSGDistilBertConfig
|
811 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
812 |
|
813 |
+
class LSGDistilBertModel(LSGDistilBertPreTrainedModel, DistilBertModel):
|
814 |
+
|
815 |
+
def __init__(self, config):
|
816 |
+
|
817 |
+
LSGDistilBertPreTrainedModel.__init__(self, config)
|
818 |
+
|
819 |
+
self.embeddings = LSGEmbeddings(config) # Embeddings
|
820 |
+
self.transformer = LSGTransformer(config) # Encoder
|
821 |
+
self.num_global_tokens = config.num_global_tokens
|
822 |
+
# Initialize weights and apply final processing
|
823 |
+
self.post_init()
|
824 |
+
|
825 |
+
def forward(
|
826 |
+
self,
|
827 |
+
input_ids: Optional[torch.Tensor] = None,
|
828 |
+
attention_mask: Optional[torch.Tensor] = None,
|
829 |
+
head_mask: Optional[torch.Tensor] = None,
|
830 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
831 |
+
output_attentions: Optional[bool] = None,
|
832 |
+
output_hidden_states: Optional[bool] = None,
|
833 |
+
return_dict: Optional[bool] = None,
|
834 |
+
) -> Union[BaseModelOutput, Tuple[torch.Tensor, ...]]:
|
835 |
+
|
836 |
+
|
837 |
+
if input_ids is None and inputs_embeds is not None:
|
838 |
+
inputs_embeds = self.embeddings(None, inputs_embeds)
|
839 |
+
if attention_mask is None:
|
840 |
+
n, t, d = inputs_embeds.size()
|
841 |
+
attention_mask = torch.ones(n, t - self.num_global_tokens, device=inputs_embeds.device)
|
842 |
+
|
843 |
+
return super().forward(
|
844 |
+
input_ids=input_ids,
|
845 |
+
attention_mask=attention_mask,
|
846 |
+
head_mask=head_mask,
|
847 |
+
inputs_embeds=inputs_embeds,
|
848 |
+
output_attentions=output_attentions,
|
849 |
+
output_hidden_states=output_hidden_states,
|
850 |
+
return_dict=return_dict
|
851 |
+
)
|
852 |
|
853 |
class LSGDistilBertForMaskedLM(LSGDistilBertPreTrainedModel, DistilBertForMaskedLM):
|
854 |
|