eunhwanpark-motiftech commited on
Commit
2c87a95
·
verified ·
1 Parent(s): 6908d73

Upload 4 files

Browse files
Files changed (4) hide show
  1. config.json +35 -0
  2. configuration_motif.py +167 -0
  3. generation_config.json +10 -0
  4. modeling_motif.py +1378 -0
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "absolute_position_embedding": false,
3
+ "architectures": [
4
+ "MotifForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_motif.MotifConfig",
9
+ "AutoModelForCausalLM": "modeling_motif.MotifForCausalLM"
10
+ },
11
+ "bos_token_id": 219396,
12
+ "eos_token_id": 219395,
13
+ "hidden_act": "poly_norm",
14
+ "hidden_size": 2048,
15
+ "initializer_range": 2e-05,
16
+ "intermediate_size": 8192,
17
+ "loss_reduction": "mean",
18
+ "max_position_embeddings": 16384,
19
+ "max_window_layers": 28,
20
+ "model_type": "Motif",
21
+ "num_attention_heads": 16,
22
+ "num_hidden_layers": 32,
23
+ "num_key_value_heads": 16,
24
+ "rms_norm_eps": 1e-06,
25
+ "rope_scaling": null,
26
+ "rope_theta": 500000.0,
27
+ "sliding_window": null,
28
+ "tie_word_embeddings": true,
29
+ "torch_dtype": "bfloat16",
30
+ "transformers_version": "4.46.3",
31
+ "use_bias": false,
32
+ "use_cache": true,
33
+ "use_sliding_window": false,
34
+ "vocab_size": 219520
35
+ }
configuration_motif.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional
3
+
4
+ from transformers.configuration_utils import PretrainedConfig
5
+ from transformers.modeling_rope_utils import rope_config_validation
6
+ from transformers.utils import logging
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+
11
+ class MotifConfig(PretrainedConfig):
12
+ r"""
13
+ This is the configuration class to store the configuration of a [`MotifModel`]. It is used to instantiate a
14
+ Motif model according to the specified arguments, defining the model architecture. Instantiating a configuration
15
+ with the defaults will yield a similar configuration to that of
16
+ Motif-102B [moreh/Motif-102B](https://huggingface.co/moreh/Motif-102B).
17
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
18
+ documentation from [`PretrainedConfig`] for more information.
19
+ Args:
20
+ vocab_size (`int`, *optional*, defaults to 151936):
21
+ Vocabulary size of the Motif model. Defines the number of different tokens that can be represented by the
22
+ `inputs_ids` passed when calling [`MotifModel`]
23
+ hidden_size (`int`, *optional*, defaults to 4096):
24
+ Dimension of the hidden representations.
25
+ intermediate_size (`int`, *optional*, defaults to 22016):
26
+ Dimension of the MLP representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer encoder.
29
+ num_attention_heads (`int`, *optional*, defaults to 32):
30
+ Number of attention heads for each attention layer in the Transformer encoder.
31
+ num_key_value_heads (`int`, *optional*, defaults to 32):
32
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
33
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
34
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
35
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
36
+ by meanpooling all the original heads within that group. For more details checkout [this
37
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
38
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
39
+ The non-linear activation function (function or string) in the decoder.
40
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
41
+ The maximum sequence length that this model might ever be used with.
42
+ initializer_range (`float`, *optional*, defaults to 0.02):
43
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
44
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
45
+ The epsilon used by the rms normalization layers.
46
+ use_cache (`bool`, *optional*, defaults to `True`):
47
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
48
+ relevant if `config.is_decoder=True`.
49
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
50
+ Whether the model's input and output word embeddings should be tied.
51
+ rope_theta (`float`, *optional*, defaults to 10000.0):
52
+ The base period of the RoPE embeddings.
53
+ rope_scaling (`Dict`, *optional*):
54
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
55
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
56
+ accordingly.
57
+ Expected contents:
58
+ `rope_type` (`str`):
59
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
60
+ 'llama3'], with 'default' being the original RoPE implementation.
61
+ `factor` (`float`, *optional*):
62
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
63
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
64
+ original maximum pre-trained length.
65
+ `original_max_position_embeddings` (`int`, *optional*):
66
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
67
+ pretraining.
68
+ `attention_factor` (`float`, *optional*):
69
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
70
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
71
+ `factor` field to infer the suggested value.
72
+ `beta_fast` (`float`, *optional*):
73
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
74
+ ramp function. If unspecified, it defaults to 32.
75
+ `beta_slow` (`float`, *optional*):
76
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
77
+ ramp function. If unspecified, it defaults to 1.
78
+ `short_factor` (`List[float]`, *optional*):
79
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
80
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
81
+ size divided by the number of attention heads divided by 2
82
+ `long_factor` (`List[float]`, *optional*):
83
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
84
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
85
+ size divided by the number of attention heads divided by 2
86
+ `low_freq_factor` (`float`, *optional*):
87
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
88
+ `high_freq_factor` (`float`, *optional*):
89
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
90
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
91
+ Whether to use sliding window attention.
92
+ sliding_window (`int`, *optional*, defaults to 4096):
93
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
94
+ max_window_layers (`int`, *optional*, defaults to 28):
95
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
96
+ attention_dropout (`float`, *optional*, defaults to 0.0):
97
+ The dropout ratio for the attention probabilities.
98
+ ```python
99
+ >>> from transformers import MotifModel, MotifConfig
100
+ >>> # Initializing a Motif style configuration
101
+ >>> configuration = MotifConfig()
102
+ >>> # Initializing a model from the Motif-102B style configuration
103
+ >>> model = MotifModel(configuration)
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+
108
+ model_type = "Motif"
109
+ keys_to_ignore_at_inference = ["past_key_values"]
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=151936,
114
+ hidden_size=4096,
115
+ intermediate_size=22016,
116
+ num_hidden_layers=32,
117
+ num_attention_heads=32,
118
+ num_key_value_heads=32,
119
+ hidden_act="silu",
120
+ max_position_embeddings=32768,
121
+ initializer_range=0.02,
122
+ rms_norm_eps=1e-6,
123
+ use_cache=True,
124
+ tie_word_embeddings=False,
125
+ rope_theta=10000.0,
126
+ rope_scaling=None,
127
+ use_sliding_window=False,
128
+ sliding_window=4096,
129
+ max_window_layers=28,
130
+ attention_dropout=0.0,
131
+ **kwargs,
132
+ ):
133
+
134
+ self.vocab_size = vocab_size
135
+ self.max_position_embeddings = max_position_embeddings
136
+ self.hidden_size = hidden_size
137
+ self.intermediate_size = intermediate_size
138
+ self.num_hidden_layers = num_hidden_layers
139
+ self.num_attention_heads = num_attention_heads
140
+ self.use_sliding_window = use_sliding_window
141
+ self.sliding_window = sliding_window if use_sliding_window else None
142
+ self.max_window_layers = max_window_layers
143
+
144
+ # for backward compatibility
145
+ if num_key_value_heads is None:
146
+ num_key_value_heads = num_attention_heads
147
+
148
+ self.num_key_value_heads = num_key_value_heads
149
+ self.hidden_act = hidden_act
150
+ self.initializer_range = initializer_range
151
+ self.rms_norm_eps = rms_norm_eps
152
+ self.use_cache = use_cache
153
+ self.rope_theta = rope_theta
154
+ self.rope_scaling = rope_scaling
155
+ self.attention_dropout = attention_dropout
156
+
157
+ # Validate the correctness of rotary position embeddings parameters
158
+ # BC: if there is a 'type' field, move it to 'rope_type'.
159
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
160
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
161
+ rope_config_validation(self)
162
+
163
+ super().__init__(
164
+ tie_word_embeddings=tie_word_embeddings,
165
+ **kwargs,
166
+ )
167
+ logger.info(f' kwargs : {kwargs}')
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 219396,
4
+ "eos_token_id": [
5
+ 219395,
6
+ 219405
7
+ ],
8
+ "transformers_version": "4.51.3",
9
+ "use_cache": true
10
+ }
modeling_motif.py ADDED
@@ -0,0 +1,1378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import List, Optional, Tuple, Union
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ import torch.utils.checkpoint
8
+ from torch import nn
9
+ from torch.nn import CrossEntropyLoss
10
+ from transformers.activations import ACT2CLS as _ACT2CLS
11
+ from transformers.activations import ClassInstantier
12
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
13
+ from transformers.generation import GenerationMixin
14
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
15
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
16
+ from transformers.modeling_outputs import CausalLMOutputWithPast, ModelOutput
17
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
18
+ from transformers.modeling_utils import PreTrainedModel
19
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
20
+ from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available,
21
+ is_flash_attn_greater_or_equal_2_10, logging, replace_return_docstrings)
22
+
23
+ from .configuration_motif import MotifConfig
24
+
25
+
26
+ class PolyNorm(torch.nn.Module):
27
+ """
28
+ A trainable activation function introduced in https://arxiv.org/html/2411.03884v1.
29
+ The code is copied from https://github.com/BryceZhuo/PolyCom?tab=readme-ov-file/README.md
30
+ """
31
+
32
+ def __init__(self, eps=1e-6):
33
+ super(PolyNorm, self).__init__()
34
+ self.weight = torch.nn.Parameter(torch.ones(3) / 3)
35
+ self.bias = torch.nn.Parameter(torch.zeros(1))
36
+ self.eps = eps
37
+
38
+ def _norm(self, x):
39
+ return x / torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
40
+
41
+ def forward(self, x):
42
+ return self.weight[0] * self._norm(x ** 3) + self.weight[1] * self._norm(
43
+ x ** 2) + self.weight[2] * self._norm(x) + self.bias
44
+
45
+
46
+ CUSTOM_ACT2CLS = {"poly_norm": PolyNorm}
47
+ ACT2CLS = {**_ACT2CLS, **CUSTOM_ACT2CLS}
48
+ ACT2FN = ClassInstantier(ACT2CLS)
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ if is_flash_attn_2_available():
53
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
54
+
55
+ _CONFIG_FOR_DOC = "MotifConfig"
56
+
57
+
58
+ class MotifRMSNorm(nn.Module):
59
+
60
+ def __init__(self, hidden_size, eps=1e-6):
61
+ """
62
+ MotifRMSNorm is equivalent to T5LayerNorm
63
+ """
64
+ super().__init__()
65
+ self.weight = nn.Parameter(torch.ones(hidden_size))
66
+ self.variance_epsilon = eps
67
+
68
+ def forward(self, hidden_states):
69
+ input_dtype = hidden_states.dtype
70
+ hidden_states = hidden_states.to(torch.float32)
71
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
72
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
73
+ return self.weight * hidden_states.to(input_dtype)
74
+
75
+ def extra_repr(self):
76
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
77
+
78
+
79
+ ALL_LAYERNORM_LAYERS.append(MotifRMSNorm)
80
+
81
+
82
+ class MotifRotaryEmbeddingWithCache(nn.Module):
83
+ """
84
+ Rotary positional embedding module with caching for efficiency.
85
+
86
+ Args:
87
+ dim (int): Dimensionality of the embedding.
88
+ max_position_embeddings (int): Maximum sequence length for caching. Default is 2048.
89
+ base (int): Base for computing inverse frequency. Default is 10000.
90
+ device (torch.device, optional): Device for tensor storage.
91
+
92
+ Methods:
93
+ forward(x, seq_len=None):
94
+ Computes cosine and sine embeddings for input sequence length.
95
+ Automatically updates cache if `seq_len` exceeds cached length.
96
+
97
+ Attributes:
98
+ inv_freq (torch.Tensor): Inverse frequency tensor for position encoding.
99
+ cos_cached (torch.Tensor): Cached cosine embeddings.
100
+ sin_cached (torch.Tensor): Cached sine embeddings.
101
+ """
102
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
103
+ super().__init__()
104
+
105
+ self.dim = dim
106
+ self.max_position_embeddings = max_position_embeddings
107
+ self.base = base
108
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
109
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
110
+
111
+ self._set_cos_sin_cache(seq_len=max_position_embeddings,
112
+ device=self.inv_freq.device,
113
+ dtype=torch.get_default_dtype())
114
+
115
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
116
+ self.max_seq_len_cached = seq_len
117
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
118
+
119
+ freqs = torch.outer(t, self.inv_freq)
120
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
121
+ emb = torch.cat((freqs, freqs), dim=-1)
122
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
123
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
124
+
125
+ def forward(self, x, seq_len=None):
126
+ # x: [bs, num_attention_heads, seq_len, head_size]
127
+ if seq_len > self.max_seq_len_cached:
128
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
129
+
130
+ return (
131
+ self.cos_cached[ :seq_len].to(dtype=x.dtype),
132
+ self.sin_cached[ :seq_len].to(dtype=x.dtype),
133
+ )
134
+
135
+
136
+ class MotifRotaryEmbedding(nn.Module):
137
+
138
+ def __init__(
139
+ self,
140
+ dim=None,
141
+ max_position_embeddings=2048,
142
+ base=10000,
143
+ device=None,
144
+ scaling_factor=1.0,
145
+ rope_type="default",
146
+ config: Optional[MotifConfig] = None,
147
+ ):
148
+ super().__init__()
149
+ # TODO (joao): remove the `if` below, only used for BC
150
+ self.rope_kwargs = {}
151
+ if config is None:
152
+ logger.warning_once(
153
+ "`MotifRotaryEmbedding` can now be fully parameterized by passing the model config through the "
154
+ "`config` argument. All other arguments will be removed in v4.46")
155
+ self.rope_kwargs = {
156
+ "rope_type": rope_type,
157
+ "factor": scaling_factor,
158
+ "dim": dim,
159
+ "base": base,
160
+ "max_position_embeddings": max_position_embeddings,
161
+ }
162
+ self.rope_type = rope_type
163
+ self.max_seq_len_cached = max_position_embeddings
164
+ self.original_max_seq_len = max_position_embeddings
165
+ else:
166
+ if config.rope_scaling is not None:
167
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
168
+ else:
169
+ self.rope_type = "default"
170
+ self.max_seq_len_cached = config.max_position_embeddings
171
+ self.original_max_seq_len = config.max_position_embeddings
172
+
173
+ self.config = config
174
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
175
+
176
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
177
+
178
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
179
+ self.original_inv_freq = self.inv_freq
180
+
181
+ def _dynamic_frequency_update(self, position_ids, device):
182
+ """
183
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
184
+ 1 - growing beyond the cached sequence length (allow scaling)
185
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
186
+ """
187
+ seq_len = torch.max(position_ids) + 1
188
+ if seq_len > self.max_seq_len_cached: # growth
189
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config,
190
+ device,
191
+ seq_len=seq_len,
192
+ **self.rope_kwargs)
193
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
194
+ self.max_seq_len_cached = seq_len
195
+
196
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
197
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
198
+ self.max_seq_len_cached = self.original_max_seq_len
199
+
200
+ @torch.no_grad()
201
+ def forward(self, x, position_ids):
202
+ if "dynamic" in self.rope_type:
203
+ self._dynamic_frequency_update(position_ids, device=x.device)
204
+
205
+ # Core RoPE block
206
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
207
+ position_ids_expanded = position_ids[:, None, :].float()
208
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
209
+ device_type = x.device.type
210
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
211
+ with torch.autocast(device_type=device_type, enabled=False):
212
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
213
+ emb = torch.cat((freqs, freqs), dim=-1)
214
+ cos = emb.cos()
215
+ sin = emb.sin()
216
+
217
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
218
+ cos = cos * self.attention_scaling
219
+ sin = sin * self.attention_scaling
220
+
221
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
222
+
223
+
224
+ def rotate_half(x):
225
+ """
226
+ Rotates half of the dimensions of the input tensor using torch.roll and in-place negation.
227
+
228
+ Args:
229
+ x (torch.Tensor): The input tensor.
230
+
231
+ Returns:
232
+ torch.Tensor: A tensor where the latter half of the dimensions are negated
233
+ and moved before the first half.
234
+ """
235
+ half_size = x.shape[-1] // 2
236
+ rotated_tensor = torch.roll(x, shifts=-half_size, dims=-1)
237
+ rotated_tensor[..., :half_size] *= -1
238
+
239
+ return rotated_tensor
240
+
241
+
242
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
243
+ """
244
+ Applies rotary position embeddings to the input tensors.
245
+
246
+ Args:
247
+ q (torch.Tensor): Query tensor of shape (B, NH, S, D_KV).
248
+ k (torch.Tensor): Key tensor of shape (B, NH, S, D_KV).
249
+ cos (torch.Tensor): Cosine values for rotary embedding.
250
+ sin (torch.Tensor): Sine values for rotary embedding.
251
+ unsqueeze_dim (int, optional): Dimension along which `cos` and `sin` are unsqueezed.
252
+ Defaults to 1.
253
+
254
+ Returns:
255
+ Tuple[torch.Tensor, torch.Tensor]: Returns transformed query and key tensors after applying rotary embeddings.
256
+ """
257
+ '''
258
+ # (B, NH, S, D_KV) -> (B, S, NH, D_KV)
259
+ cos = cos.unsqueeze(unsqueeze_dim)
260
+ sin = sin.unsqueeze(unsqueeze_dim)
261
+ q_embed = (q * cos) + (rotate_half(q) * sin)
262
+ k_embed = (k * cos) + (rotate_half(k) * sin)
263
+ '''
264
+ device = q.device
265
+ return map(
266
+ lambda x: (x * cos[position_ids].unsqueeze(unsqueeze_dim).to(device)) +
267
+ (rotate_half(x) * sin[position_ids].unsqueeze(unsqueeze_dim).to(device)), (q, k))
268
+
269
+
270
+ class MotifMLP(nn.Module):
271
+
272
+ def __init__(self, config):
273
+ super().__init__()
274
+ self.hidden_size = config.hidden_size
275
+ self.intermediate_size = config.intermediate_size
276
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
277
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.use_bias)
278
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
279
+ self.act_fn = ACT2FN[config.hidden_act]
280
+
281
+ def forward(self, hidden_state):
282
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
283
+
284
+
285
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
286
+
287
+
288
+ """
289
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
290
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
291
+
292
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
293
+ if n_rep == 1:
294
+ return hidden_states
295
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
296
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
297
+ """
298
+
299
+ return torch.repeat_interleave(hidden_states, dim=1, repeats=n_rep)
300
+
301
+
302
+ class MotifAttention(nn.Module):
303
+ """
304
+ Differential Attention (DiffAttention) module.
305
+
306
+ Implements the Differential Attention from
307
+ "DIFFERENTIAL TRANSFORMER" (https://arxiv.org/pdf/2410.05258).
308
+
309
+ Overview
310
+ Standard transformers often over-allocate attention to irrelevant context.
311
+ DiffAttention addresses this by computing attention as the difference between
312
+ two separate softmax attention maps, effectively canceling noise and promoting
313
+ sparse, structured attention patterns.
314
+
315
+ Reference Implementation
316
+ https://github.com/microsoft/unilm/tree/master/Diff-Transformer
317
+
318
+ Args
319
+ The differential attention mechanism computes attention as the difference of two softmax attention scores, weighted by a learnable scalar λ.
320
+ λ is re-parameterized as λ = exp(λ_q1 · λ_k1) − exp(λ_q2 · λ_k2) + λ_init.
321
+ - lambda_q1, lambda_q2 (nn.Parameter): Learnable vectors used to compute the first and second components of λ for query transformations.
322
+ - lambda_k1, lambda_k2 (nn.Parameter): Learnable vectors used to compute the first and second components of λ for key transformations.
323
+ - lambda_init (float): A constant used for initializing λ, typically set as λ_init = 0.8 − 0.6 × exp(−0.3 × (layer_index − 1)).
324
+
325
+ """
326
+
327
+ def __init__(self, config: MotifConfig, layer_idx: Optional[int] = None):
328
+ super().__init__()
329
+ self.config = config
330
+ self.layer_idx = layer_idx
331
+ if layer_idx is None:
332
+ logger.warning_once(
333
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
334
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
335
+ "when creating this class.")
336
+
337
+
338
+ self.hidden_size = config.hidden_size
339
+ self.num_heads = config.num_attention_heads
340
+ self.head_dim = self.hidden_size // self.num_heads
341
+ self.num_key_value_heads = config.num_key_value_heads
342
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
343
+ self.max_position_embeddings = config.max_position_embeddings
344
+ self.rope_theta = config.rope_theta
345
+ self.is_causal = True
346
+ self.attention_dropout = config.attention_dropout
347
+
348
+ if (self.head_dim * self.num_heads) != self.hidden_size:
349
+ raise ValueError(f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
350
+ f" and `num_heads`: {self.num_heads}).")
351
+
352
+ self.num_heads //= 2
353
+ self.num_key_value_heads //= 2
354
+ self.n_rep = self.num_heads // self.num_key_value_heads
355
+
356
+ self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
357
+ self.k_proj = nn.Linear(self.hidden_size, self.hidden_size // self.n_rep, bias=False)
358
+ self.v_proj = nn.Linear(self.hidden_size, self.hidden_size // self.n_rep, bias=False)
359
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
360
+
361
+ for name in ["lambda_q1", "lambda_k1", "lambda_q2", "lambda_k2"]:
362
+ setattr(self, name, nn.Parameter(torch.zeros(self.head_dim, dtype=torch.float32)))
363
+ getattr(self, name).data.normal_(mean=0.0, std=0.1)
364
+
365
+ self.subln = MotifRMSNorm(2 * self.head_dim, eps=1e-5)
366
+ self.lambda_init = 0.8 - 0.6 * math.exp(-0.3 * (layer_idx - 1))
367
+
368
+ self.rotary_emb = MotifRotaryEmbeddingWithCache(self.head_dim,
369
+ max_position_embeddings=self.max_position_embeddings,
370
+ base=self.rope_theta)
371
+
372
+ def forward(
373
+ self,
374
+ hidden_states: torch.Tensor,
375
+ attention_mask: Optional[torch.Tensor] = None,
376
+ position_ids: Optional[torch.LongTensor] = None,
377
+ past_key_value: Optional[Cache] = None,
378
+ output_attentions: bool = False,
379
+ use_cache: bool = False,
380
+ cache_position: Optional[torch.LongTensor] = None,
381
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
382
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
383
+ bsz, q_len, _ = hidden_states.size()
384
+
385
+ query_states = self.q_proj(hidden_states)
386
+ key_states = self.k_proj(hidden_states)
387
+ value_states = self.v_proj(hidden_states)
388
+
389
+ query_states = query_states.view(bsz, q_len, 2 * self.num_heads, self.head_dim).transpose(1, 2)
390
+ key_states = key_states.view(bsz, q_len, 2 * self.num_key_value_heads, self.head_dim).transpose(1, 2)
391
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, 2 * self.head_dim).transpose(1, 2)
392
+
393
+ kv_seq_len = key_states.shape[-2]
394
+ if position_embeddings is None:
395
+ logger.warning_once(
396
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
397
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
398
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
399
+ "removed and `position_embeddings` will be mandatory.")
400
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
401
+ else:
402
+ cos, sin = (self.rotary_emb(value_states, q_len + past_key_value.get_usable_length(q_len, self.layer_idx))
403
+ if use_cache else position_embeddings)
404
+
405
+ query_states, key_states = apply_rotary_pos_emb(query_states,
406
+ key_states,
407
+ cos,
408
+ sin,
409
+ position_ids=position_ids)
410
+
411
+ if past_key_value is not None:
412
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
413
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
414
+
415
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
416
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
417
+
418
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
419
+
420
+ kv_seq_len = key_states.shape[-2]
421
+ offset = kv_seq_len - q_len
422
+
423
+ attention_mask = torch.triu(
424
+ torch.full((q_len, kv_seq_len), float("-inf"), dtype=attn_weights.dtype, device=attn_weights.device),
425
+ 1 + offset)
426
+
427
+ attn_weights = attn_weights + attention_mask
428
+
429
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
430
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
431
+
432
+ lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1).float()).type_as(attn_weights)
433
+ lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1).float()).type_as(attn_weights)
434
+ lambda_full = lambda_1 - lambda_2 + self.lambda_init
435
+ attn_weights = attn_weights.view(bsz, self.num_heads, 2, q_len, -1)
436
+ attn_weights = attn_weights[:, :, 0] - lambda_full * attn_weights[:, :, 1]
437
+
438
+ attn_output = torch.matmul(attn_weights, value_states)
439
+
440
+ attn_output = self.subln(attn_output)
441
+ attn_output = attn_output * (1 - self.lambda_init)
442
+
443
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim * 2):
444
+ raise ValueError(f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
445
+ f" {attn_output.size()}")
446
+
447
+ attn_output = attn_output.transpose(1, 2).contiguous()
448
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
449
+
450
+ attn_output = self.o_proj(attn_output)
451
+
452
+ if not output_attentions:
453
+ attn_weights = None
454
+
455
+ return attn_output, attn_weights, past_key_value
456
+
457
+
458
+ class MotifFlashAttention2(MotifAttention):
459
+ """
460
+ Motif flash attention module, following Motif attention module. This module inherits from `MotifAttention`
461
+ as the weights of the module stays untouched. The only required change would be on the forward pass
462
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
463
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
464
+ config.max_window_layers layers.
465
+ """
466
+
467
+ def __init__(self, *args, **kwargs):
468
+ super().__init__(*args, **kwargs)
469
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
470
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
471
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
472
+
473
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
474
+
475
+ logger.info(f'flash attention is used {not self._flash_attn_uses_top_left_mask}')
476
+
477
+ def _reshape_heads(self, tensor, batch_size, seq_len):
478
+ """2-way head split tensor reshape"""
479
+ return tensor.reshape(batch_size, seq_len, self.num_heads, 2, self.head_dim)
480
+
481
+ def _restore_shape(self, tensor, batch_size, seq_len):
482
+ """restore tensor"""
483
+ return tensor.reshape(batch_size, seq_len, self.num_heads, self.head_dim)
484
+
485
+ def _compute_attention(self, query_states, key_states, value_states, attention_mask, q_len, position_ids,
486
+ dropout_rate, sliding_window):
487
+ """Flash Attention 2 implements"""
488
+ _input_type = query_states.dtype
489
+ scale_factor = 1.0 / math.sqrt(self.head_dim)
490
+ if not self._flash_attn_uses_top_left_mask:
491
+ causal = self.is_causal
492
+ else:
493
+ causal = self.is_causal and q_len != 1
494
+
495
+ attn_out = _flash_attention_forward(query_states.bfloat16(),
496
+ key_states.bfloat16(),
497
+ value_states.bfloat16(),
498
+ attention_mask,
499
+ q_len,
500
+ position_ids=position_ids,
501
+ dropout=dropout_rate,
502
+ sliding_window=sliding_window,
503
+ is_causal=True,
504
+ softmax_scale=scale_factor,
505
+ use_top_left_mask=self._flash_attn_uses_top_left_mask)
506
+ return attn_out.to(_input_type)
507
+
508
+ def forward(
509
+ self,
510
+ hidden_states: torch.Tensor,
511
+ attention_mask: Optional[torch.Tensor] = None,
512
+ position_ids: Optional[torch.LongTensor] = None,
513
+ past_key_value: Optional[Cache] = None,
514
+ output_attentions: bool = False,
515
+ use_cache: bool = False,
516
+ cache_position: Optional[torch.LongTensor] = None,
517
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
518
+ ):
519
+ bsz, q_len, _ = hidden_states.size()
520
+
521
+ query_states = self.q_proj(hidden_states)
522
+ key_states = self.k_proj(hidden_states)
523
+ value_states = self.v_proj(hidden_states)
524
+
525
+ query_states = query_states.view(bsz, q_len, 2 * self.num_heads, self.head_dim).transpose(1, 2)
526
+ key_states = key_states.view(bsz, q_len, 2 * self.num_key_value_heads, self.head_dim).transpose(1, 2)
527
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, 2 * self.head_dim).transpose(1, 2)
528
+ kv_seq_len = key_states.shape[-2]
529
+ if position_embeddings is None:
530
+ logger.warning_once(
531
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
532
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
533
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
534
+ "removed and `position_embeddings` will be mandatory.")
535
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
536
+ else:
537
+ cos, sin = (self.rotary_emb(value_states, q_len + past_key_value.get_usable_length(q_len, self.layer_idx))
538
+ if use_cache else position_embeddings)
539
+
540
+ query_states, key_states = apply_rotary_pos_emb(query_states,
541
+ key_states,
542
+ cos,
543
+ sin,
544
+ position_ids=position_ids)
545
+
546
+ if past_key_value is not None:
547
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
548
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
549
+
550
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
551
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
552
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
553
+
554
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
555
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
556
+ # cast them back in float16 just to be sure everything works as expected.
557
+ input_dtype = query_states.dtype
558
+ if input_dtype == torch.float32:
559
+ if torch.is_autocast_enabled():
560
+ target_dtype = torch.get_autocast_gpu_dtype()
561
+ # Handle the case where the model is quantized
562
+ elif hasattr(self.config, "_pre_quantization_dtype"):
563
+ target_dtype = self.config._pre_quantization_dtype
564
+ else:
565
+ target_dtype = self.q_proj.weight.dtype
566
+
567
+ logger.warning_once(
568
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
569
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
570
+ f" {target_dtype}.")
571
+
572
+ query_states = query_states.to(target_dtype)
573
+ key_states = key_states.to(target_dtype)
574
+ value_states = value_states.to(target_dtype)
575
+
576
+ q_len = query_states.shape[-2]
577
+ kv_seq_len = key_states.shape[-2]
578
+
579
+ # Reashape to the expected shape for Flash Attention
580
+ query_states = query_states.transpose(1, 2)
581
+ key_states = key_states.transpose(1, 2)
582
+ value_states = value_states.transpose(1, 2)
583
+
584
+ if (self.config.use_sliding_window and getattr(self.config, "sliding_window", None) is not None
585
+ and self.layer_idx >= self.config.max_window_layers):
586
+ sliding_window = self.config.sliding_window
587
+ else:
588
+ sliding_window = None
589
+
590
+ q = self._reshape_heads(query_states, bsz, q_len)
591
+ k = self._reshape_heads(key_states, bsz, kv_seq_len)
592
+ v = self._reshape_heads(value_states, bsz, kv_seq_len)
593
+
594
+ q1, q2 = q[..., 0, :], q[..., 1, :]
595
+ k1, k2 = k[..., 0, :], k[..., 1, :]
596
+ v1, v2 = v[..., 0, :], v[..., 1, :]
597
+
598
+ q1, q2, k1, k2, v1, v2 = map(lambda x: self._restore_shape(x, bsz, q_len if x is q1 or x is q2 else kv_seq_len),
599
+ (q1, q2, k1, k2, v1, v2))
600
+
601
+ q1, q2 = q1.contiguous(), q2.contiguous()
602
+ k1, k2 = k1.contiguous(), k2.contiguous()
603
+ v1, v2 = v1.contiguous(), v2.contiguous()
604
+
605
+ attn11, attn12 = self._compute_attention(q1, k1, v1, attention_mask, q_len, position_ids, dropout_rate, sliding_window), \
606
+ self._compute_attention(q1, k1, v2, attention_mask, q_len, position_ids, dropout_rate, sliding_window)
607
+ attn21, attn22 = self._compute_attention(q2, k2, v1, attention_mask, q_len, position_ids, dropout_rate, sliding_window), \
608
+ self._compute_attention(q2, k2, v2, attention_mask, q_len, position_ids, dropout_rate, sliding_window)
609
+
610
+ attn1, attn2 = torch.cat([attn11, attn12], dim=-1), torch.cat([attn21, attn22], dim=-1)
611
+
612
+ lambda_q1 = self.lambda_q1.unsqueeze(0).expand([bsz, self.lambda_q1.shape[0]]) # bsz, num_head
613
+ lambda_q2 = self.lambda_q2.unsqueeze(0).expand([bsz, self.lambda_q2.shape[0]]) # bsz, num_head
614
+
615
+ lambda_1 = torch.exp(torch.sum(lambda_q1 * self.lambda_k1, dim=-1).float()).type_as(attn1) # bsz
616
+ lambda_2 = torch.exp(torch.sum(lambda_q2 * self.lambda_k2, dim=-1).float()).type_as(attn2) # bsz
617
+
618
+ lambda_full = lambda_1 - lambda_2 + self.lambda_init
619
+
620
+ attn_output = attn1 - lambda_full.view([bsz, 1, 1, 1]) * attn2
621
+
622
+ attn_output = self.subln(attn_output)
623
+ attn_output = attn_output * (1 - self.lambda_init)
624
+
625
+ if attn_output.size() != (bsz, q_len, self.num_heads, self.head_dim * 2):
626
+ raise ValueError(f"`attn_output` should be of size {(bsz, q_len, self.num_heads, 2*self.head_dim)}, but is"
627
+ f" {attn_output.size()}")
628
+
629
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
630
+ attn_output = self.o_proj(attn_output)
631
+
632
+ return attn_output, None, past_key_value
633
+
634
+
635
+ class MotifSdpaAttention(MotifAttention):
636
+ """
637
+ Motif attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
638
+ `MotifAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
639
+ SDPA API.
640
+ """
641
+
642
+ def forward(
643
+ self,
644
+ hidden_states: torch.Tensor,
645
+ attention_mask: Optional[torch.Tensor] = None,
646
+ position_ids: Optional[torch.LongTensor] = None,
647
+ past_key_value: Optional[Cache] = None,
648
+ output_attentions: bool = False,
649
+ use_cache: bool = False,
650
+ cache_position: Optional[torch.LongTensor] = None,
651
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
652
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
653
+ if output_attentions:
654
+ logger.warning_once(
655
+ "MotifModel is using MotifSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
656
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
657
+ )
658
+ return super().forward(
659
+ hidden_states=hidden_states,
660
+ attention_mask=attention_mask,
661
+ position_ids=position_ids,
662
+ past_key_value=past_key_value,
663
+ output_attentions=output_attentions,
664
+ use_cache=use_cache,
665
+ )
666
+
667
+ bsz, q_len, _ = hidden_states.size()
668
+
669
+ query_states = self.q_proj(hidden_states)
670
+ key_states = self.k_proj(hidden_states)
671
+ value_states = self.v_proj(hidden_states)
672
+
673
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
674
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
675
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
676
+ kv_seq_len = key_states.shape[-2]
677
+ if position_embeddings is None:
678
+ logger.warning_once(
679
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
680
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
681
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
682
+ "removed and `position_embeddings` will be mandatory.")
683
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
684
+ else:
685
+ cos, sin = position_embeddings
686
+ query_states, key_states = apply_rotary_pos_emb(query_states,
687
+ key_states,
688
+ cos,
689
+ sin)
690
+
691
+ if past_key_value is not None:
692
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
693
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
694
+
695
+ query_states = query_states.transpose(1, 2).reshape(bsz, q_len, self.hidden_size)
696
+ key_states = key_states.transpose(1, 2).reshape(bsz, q_len, self.hidden_size // self.num_key_value_groups)
697
+ value_states = value_states.transpose(1, 2).reshape(bsz, q_len, self.hidden_size // self.num_key_value_groups)
698
+
699
+ batch, query_length, key_length = query_states.size(0), query_states.size(-2), key_states.size(-2)
700
+ masked_bias = attention_mask.expand(batch, self.num_heads, query_length, key_length)
701
+
702
+ # Compute Scale Factor
703
+ scale_factor = 1.0
704
+ scale_factor /= float(self.head_dim) ** 0.5
705
+
706
+ attn_output = ScaledDotProductAttention(query_states,
707
+ key_states,
708
+ value_states,
709
+ masked_bias,
710
+ dropout_rate=0.0,
711
+ training=self.training,
712
+ attn_weight_scale_factor=scale_factor,
713
+ num_kv_groups=self.num_key_value_groups,
714
+ recompute_mode=False)
715
+ attn_output = attn_output.to(hidden_states.dtype)
716
+
717
+ attn_output = self.o_proj(attn_output)
718
+
719
+ return attn_output, None, past_key_value
720
+
721
+
722
+ MOTIF_ATTENTION_CLASSES = {
723
+ "eager": MotifAttention,
724
+ "flash_attention_2": MotifFlashAttention2,
725
+ "sdpa": MotifAttention,
726
+ }
727
+
728
+
729
+ class MotifDecoderLayer(nn.Module):
730
+
731
+ def __init__(self, config: MotifConfig, layer_idx: int):
732
+ super().__init__()
733
+ self.hidden_size = config.hidden_size
734
+ if config.sliding_window and config._attn_implementation != "flash_attention_2":
735
+ logger.warning_once(
736
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
737
+ "unexpected results may be encountered.")
738
+ self.self_attn = MOTIF_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
739
+ self.mlp = MotifMLP(config)
740
+
741
+ self.input_layernorm = MotifRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
742
+ self.post_attention_layernorm = MotifRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
743
+
744
+
745
+ def forward(
746
+ self,
747
+ hidden_states: torch.Tensor,
748
+ attention_mask: Optional[torch.Tensor] = None,
749
+ position_ids: Optional[torch.LongTensor] = None,
750
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
751
+ output_attentions: Optional[bool] = False,
752
+ use_cache: Optional[bool] = False,
753
+ cache_position: Optional[torch.LongTensor] = None,
754
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
755
+ **kwargs,
756
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
757
+ """
758
+ Args:
759
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
760
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
761
+ `(batch, sequence_length)` where padding elements are indicated by 0.
762
+ output_attentions (`bool`, *optional*):
763
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
764
+ returned tensors for more detail.
765
+ use_cache (`bool`, *optional*):
766
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
767
+ (see `past_key_values`).
768
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
769
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
770
+ Indices depicting the position of the input sequence tokens in the sequence.
771
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
772
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
773
+ with `head_dim` being the embedding dimension of each attention head.
774
+ kwargs (`dict`, *optional*):
775
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
776
+ into the model
777
+ """
778
+
779
+ residual = hidden_states
780
+
781
+ hidden_states = self.input_layernorm(hidden_states)
782
+
783
+ # Self Attention
784
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
785
+ hidden_states=hidden_states,
786
+ attention_mask=attention_mask,
787
+ position_ids=position_ids,
788
+ past_key_value=past_key_value,
789
+ output_attentions=output_attentions,
790
+ use_cache=use_cache,
791
+ cache_position=cache_position,
792
+ position_embeddings=position_embeddings,
793
+ )
794
+ hidden_states = residual + hidden_states
795
+
796
+ # Fully Connected
797
+ residual = hidden_states
798
+ hidden_states = self.post_attention_layernorm(hidden_states)
799
+ hidden_states = self.mlp(hidden_states)
800
+ hidden_states = residual + hidden_states
801
+
802
+ outputs = (hidden_states, )
803
+
804
+ if output_attentions:
805
+ outputs += (self_attn_weights, )
806
+
807
+ if use_cache:
808
+ outputs += (present_key_value, )
809
+
810
+ return outputs
811
+
812
+
813
+ MOTIF_START_DOCSTRING = r"""
814
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
815
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
816
+ etc.)
817
+
818
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
819
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
820
+ and behavior.
821
+
822
+ Parameters:
823
+ config ([`MotifConfig`]):
824
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
825
+ load the weights associated with the model, only the configuration. Check out the
826
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
827
+ """
828
+
829
+
830
+ @add_start_docstrings(
831
+ "The bare Motif Model outputting raw hidden-states without any specific head on top.",
832
+ MOTIF_START_DOCSTRING,
833
+ )
834
+ class MotifPreTrainedModel(PreTrainedModel):
835
+ config_class = MotifConfig
836
+ base_model_prefix = "model"
837
+ supports_gradient_checkpointing = True
838
+ _no_split_modules = ["MotifDecoderLayer"]
839
+ _skip_keys_device_placement = "past_key_values"
840
+ _supports_flash_attn_2 = True
841
+ _supports_sdpa = True
842
+ _supports_cache_class = True
843
+ _supports_quantized_cache = True
844
+ _supports_static_cache = True
845
+
846
+ def _init_weights(self, module):
847
+ module_std = self.config.initializer_range
848
+ if isinstance(module, nn.Linear):
849
+ module.weight.data.normal_(mean=0.0, std=module_std)
850
+ module.weight.data = torch.where(abs(module.weight.data) > module_std*3, 0, module.weight.data)
851
+ if module.bias is not None:
852
+ module.bias.data.zero_()
853
+
854
+ elif isinstance(module, nn.Embedding):
855
+ module.weight.data.normal_(mean=0.0, std=module_std)
856
+ module.weight.data = torch.where(abs(module.weight.data) > module_std*3, 0, module.weight.data)
857
+ if module.padding_idx is not None:
858
+ module.weight.data[module.padding_idx].zero_()
859
+
860
+
861
+ @dataclass
862
+ class MotifModelOutputWithPast(ModelOutput):
863
+ """
864
+ This augments `BaseModelOutputWithPast` in `transformers.modeling_outputs` with new optional keys: `causal_mask`, `position_embeddings`.
865
+ The optional keys are currently used in the following ways:
866
+ - pass information to the token-wise last attention layers in multi-token training
867
+ """
868
+ last_hidden_state: torch.FloatTensor = None
869
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
870
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
871
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
872
+ causal_mask: Optional[torch.Tensor] = None
873
+ position_embeddings: Optional[torch.FloatTensor] = None
874
+
875
+
876
+ MOTIF_INPUTS_DOCSTRING = r"""
877
+ Args:
878
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
879
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
880
+ it.
881
+
882
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
883
+ [`PreTrainedTokenizer.__call__`] for details.
884
+
885
+ [What are input IDs?](../glossary#input-ids)
886
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
887
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
888
+
889
+ - 1 for tokens that are **not masked**,
890
+ - 0 for tokens that are **masked**.
891
+
892
+ [What are attention masks?](../glossary#attention-mask)
893
+
894
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
895
+ [`PreTrainedTokenizer.__call__`] for details.
896
+
897
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
898
+ `past_key_values`).
899
+
900
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
901
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
902
+ information on the default strategy.
903
+
904
+ - 1 indicates the head is **not masked**,
905
+ - 0 indicates the head is **masked**.
906
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
907
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
908
+ config.n_positions - 1]`.
909
+
910
+ [What are position IDs?](../glossary#position-ids)
911
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
912
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
913
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
914
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
915
+
916
+ Two formats are allowed:
917
+ - a [`~cache_utils.Cache`] instance, see our
918
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
919
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
920
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
921
+ cache format.
922
+
923
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
924
+ legacy cache format will be returned.
925
+
926
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
927
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
928
+ of shape `(batch_size, sequence_length)`.
929
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
930
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
931
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
932
+ model's internal embedding lookup matrix.
933
+ use_cache (`bool`, *optional*):
934
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
935
+ `past_key_values`).
936
+ output_attentions (`bool`, *optional*):
937
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
938
+ tensors for more detail.
939
+ output_hidden_states (`bool`, *optional*):
940
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
941
+ more detail.
942
+ return_dict (`bool`, *optional*):
943
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
944
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
945
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
946
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
947
+ the complete sequence length.
948
+ """
949
+
950
+
951
+ @add_start_docstrings(
952
+ "The bare Motif Model outputting raw hidden-states without any specific head on top.",
953
+ MOTIF_START_DOCSTRING,
954
+ )
955
+ class MotifModel(MotifPreTrainedModel):
956
+ """
957
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MotifDecoderLayer`]
958
+
959
+ Args:
960
+ config: MotifConfig
961
+ """
962
+
963
+ def __init__(self, config: MotifConfig):
964
+ super().__init__(config)
965
+ self.padding_idx = config.pad_token_id
966
+ self.vocab_size = config.vocab_size
967
+
968
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
969
+ num_hidden_layers = config.num_hidden_layers
970
+ self.layers = nn.ModuleList([MotifDecoderLayer(config = config, layer_idx=layer_idx) for layer_idx in range(num_hidden_layers)])
971
+ self.norm = MotifRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
972
+ self.hidden_size = config.hidden_size
973
+ self.num_heads = config.num_attention_heads
974
+ self.head_dim = self.hidden_size // self.num_heads
975
+ self.max_position_embeddings = config.max_position_embeddings
976
+ self.rope_theta = config.rope_theta
977
+ self.rotary_emb = MotifRotaryEmbeddingWithCache(self.head_dim,
978
+ max_position_embeddings=self.max_position_embeddings,
979
+ base=self.rope_theta)
980
+
981
+ self.gradient_checkpointing = False
982
+ self.post_init()
983
+
984
+ def get_input_embeddings(self):
985
+ return self.embed_tokens
986
+
987
+ def set_input_embeddings(self, value):
988
+ self.embed_tokens = value
989
+
990
+ @add_start_docstrings_to_model_forward(MOTIF_INPUTS_DOCSTRING)
991
+ def forward(
992
+ self,
993
+ input_ids: torch.LongTensor = None,
994
+ attention_mask: Optional[torch.Tensor] = None,
995
+ position_ids: Optional[torch.LongTensor] = None,
996
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
997
+ inputs_embeds: Optional[torch.FloatTensor] = None,
998
+ use_cache: Optional[bool] = None,
999
+ output_attentions: Optional[bool] = None,
1000
+ output_hidden_states: Optional[bool] = None,
1001
+ return_dict: Optional[bool] = None,
1002
+ cache_position: Optional[torch.LongTensor] = None,
1003
+ outputs_include_causal_mask: bool = False,
1004
+ outputs_include_position_embeddings: bool = False,
1005
+ ) -> Union[Tuple, MotifModelOutputWithPast]:
1006
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1007
+ output_hidden_states = (output_hidden_states
1008
+ if output_hidden_states is not None else self.config.output_hidden_states)
1009
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1010
+
1011
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1012
+
1013
+ if (input_ids is None) ^ (inputs_embeds is not None):
1014
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1015
+
1016
+ if self.gradient_checkpointing and self.training:
1017
+ if use_cache:
1018
+ logger.warning_once(
1019
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")
1020
+ use_cache = False
1021
+
1022
+ return_legacy_cache = False
1023
+ if use_cache and not isinstance(past_key_values, Cache):
1024
+ return_legacy_cache = True
1025
+ if past_key_values is None:
1026
+ past_key_values = DynamicCache()
1027
+ else:
1028
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1029
+ logger.warning_once(
1030
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
1031
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
1032
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)")
1033
+
1034
+ if inputs_embeds is None:
1035
+ inputs_embeds = self.embed_tokens(input_ids)
1036
+
1037
+ if cache_position is None:
1038
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1039
+ cache_position = torch.arange(past_seen_tokens,
1040
+ past_seen_tokens + inputs_embeds.shape[1],
1041
+ device=inputs_embeds.device)
1042
+ if position_ids is None:
1043
+ position_ids = cache_position.unsqueeze(0)
1044
+
1045
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position, past_key_values,
1046
+ output_attentions)
1047
+
1048
+ hidden_states = inputs_embeds
1049
+ bsz, q_len, _ = hidden_states.size()
1050
+ position_embeddings = self.rotary_emb(hidden_states, seq_len=q_len)
1051
+
1052
+ all_hidden_states = () if output_hidden_states else None
1053
+ all_self_attns = () if output_attentions else None
1054
+ next_decoder_cache = None
1055
+
1056
+ for idx, decoder_layer in enumerate(self.layers):
1057
+ if output_hidden_states:
1058
+ all_hidden_states += (hidden_states, )
1059
+
1060
+ if self.gradient_checkpointing and self.training:
1061
+ layer_outputs = self._gradient_checkpointing_func(
1062
+ decoder_layer.__call__,
1063
+ hidden_states,
1064
+ causal_mask,
1065
+ position_ids,
1066
+ past_key_values,
1067
+ output_attentions,
1068
+ use_cache,
1069
+ cache_position,
1070
+ position_embeddings,
1071
+ )
1072
+ else:
1073
+ layer_outputs = decoder_layer(
1074
+ hidden_states,
1075
+ attention_mask=causal_mask,
1076
+ position_ids=position_ids,
1077
+ past_key_value=past_key_values,
1078
+ output_attentions=output_attentions,
1079
+ use_cache=use_cache,
1080
+ cache_position=cache_position,
1081
+ position_embeddings=position_embeddings,
1082
+ )
1083
+
1084
+ hidden_states = layer_outputs[0]
1085
+
1086
+ if use_cache:
1087
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1088
+
1089
+ if output_attentions:
1090
+ all_self_attns += (layer_outputs[1], )
1091
+
1092
+ hidden_states = self.norm(hidden_states)
1093
+
1094
+ if output_hidden_states:
1095
+ all_hidden_states += (hidden_states, )
1096
+
1097
+ next_cache = next_decoder_cache if use_cache else None
1098
+ if return_legacy_cache:
1099
+ next_cache = next_cache.to_legacy_cache()
1100
+
1101
+ causal_mask_output = causal_mask if outputs_include_causal_mask else None
1102
+ position_embeddings_output = position_embeddings if outputs_include_position_embeddings else None
1103
+ if not return_dict:
1104
+ return tuple(v for v in [
1105
+ hidden_states, next_cache, all_hidden_states, all_self_attns, causal_mask_output,
1106
+ position_embeddings_output
1107
+ ] if v is not None)
1108
+ return MotifModelOutputWithPast(last_hidden_state=hidden_states,
1109
+ past_key_values=next_cache,
1110
+ hidden_states=all_hidden_states,
1111
+ attentions=all_self_attns,
1112
+ causal_mask=causal_mask_output,
1113
+ position_embeddings=position_embeddings_output)
1114
+
1115
+ def _update_causal_mask(
1116
+ self,
1117
+ attention_mask: torch.Tensor,
1118
+ input_tensor: torch.Tensor,
1119
+ cache_position: torch.Tensor,
1120
+ past_key_values: Cache,
1121
+ output_attentions: bool,
1122
+ ):
1123
+ if self.config._attn_implementation == "flash_attention_2":
1124
+ if attention_mask is not None and 0.0 in attention_mask:
1125
+ return attention_mask
1126
+ return None
1127
+
1128
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1129
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1130
+ # to infer the attention mask.
1131
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1132
+ using_static_cache = isinstance(past_key_values, StaticCache)
1133
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
1134
+
1135
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1136
+ if (self.config._attn_implementation == "sdpa" and not (using_static_cache or using_sliding_window_cache)
1137
+ and not output_attentions):
1138
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1139
+ attention_mask,
1140
+ inputs_embeds=input_tensor,
1141
+ past_key_values_length=past_seen_tokens,
1142
+ sliding_window=self.config.sliding_window,
1143
+ is_training=self.training,
1144
+ ):
1145
+ return None
1146
+
1147
+ dtype, device = input_tensor.dtype, input_tensor.device
1148
+ min_dtype = torch.finfo(dtype).min
1149
+ sequence_length = input_tensor.shape[1]
1150
+
1151
+ # SlidingWindowCache or StaticCache
1152
+ if using_sliding_window_cache or using_static_cache:
1153
+ target_length = past_key_values.get_max_cache_shape()
1154
+ # DynamicCache or no cache
1155
+ else:
1156
+ target_length = (attention_mask.shape[-1]
1157
+ if isinstance(attention_mask, torch.Tensor) else past_seen_tokens + sequence_length + 1)
1158
+
1159
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1160
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1161
+ attention_mask,
1162
+ sequence_length=sequence_length,
1163
+ target_length=target_length,
1164
+ dtype=dtype,
1165
+ device=device,
1166
+ cache_position=cache_position,
1167
+ batch_size=input_tensor.shape[0],
1168
+ config=self.config,
1169
+ past_key_values=past_key_values,
1170
+ )
1171
+
1172
+ if (self.config._attn_implementation == "sdpa" and attention_mask is not None
1173
+ and attention_mask.device.type == "cuda" and not output_attentions):
1174
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1175
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1176
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1177
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1178
+
1179
+ return causal_mask
1180
+
1181
+ @staticmethod
1182
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1183
+ attention_mask: torch.Tensor,
1184
+ sequence_length: int,
1185
+ target_length: int,
1186
+ dtype: torch.dtype,
1187
+ device: torch.device,
1188
+ cache_position: torch.Tensor,
1189
+ batch_size: int,
1190
+ config: MotifConfig,
1191
+ past_key_values: Cache,
1192
+ ):
1193
+ """
1194
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1195
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1196
+
1197
+ Args:
1198
+ attention_mask (`torch.Tensor`):
1199
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
1200
+ sequence_length (`int`):
1201
+ The sequence length being processed.
1202
+ target_length (`int`):
1203
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
1204
+ dtype (`torch.dtype`):
1205
+ The dtype to use for the 4D attention mask.
1206
+ device (`torch.device`):
1207
+ The device to plcae the 4D attention mask on.
1208
+ cache_position (`torch.Tensor`):
1209
+ Indices depicting the position of the input sequence tokens in the sequence.
1210
+ batch_size (`torch.Tensor`):
1211
+ Batch size.
1212
+ config (`MotifConfig`):
1213
+ The model's configuration class
1214
+ past_key_values (`Cache`):
1215
+ The cache class that is being used currently to generate
1216
+ """
1217
+ if attention_mask is not None and attention_mask.dim() == 4:
1218
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1219
+ causal_mask = attention_mask
1220
+ else:
1221
+ min_dtype = torch.finfo(dtype).min
1222
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
1223
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1224
+ if config.sliding_window is not None:
1225
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1226
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1227
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
1228
+ sliding_attend_mask = torch.arange(
1229
+ target_length, device=device) <= (cache_position.reshape(-1, 1) - config.sliding_window)
1230
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1231
+ causal_mask *= diagonal_attend_mask
1232
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1233
+ if attention_mask is not None:
1234
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1235
+ if attention_mask.shape[-1] > target_length:
1236
+ attention_mask = attention_mask[:, :target_length]
1237
+ mask_length = attention_mask.shape[-1]
1238
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1239
+ padding_mask = padding_mask == 0
1240
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1241
+ padding_mask, min_dtype)
1242
+ return causal_mask
1243
+
1244
+
1245
+ class MotifForCausalLM(MotifPreTrainedModel, GenerationMixin):
1246
+ _tied_weights_keys = ["lm_head.weight"]
1247
+
1248
+ def __init__(self, config: MotifConfig):
1249
+ super().__init__(config)
1250
+ self.model = MotifModel(config)
1251
+ self.vocab_size = config.vocab_size
1252
+
1253
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1254
+
1255
+ # Initialize weights and apply final processing
1256
+ self.post_init()
1257
+
1258
+ if getattr(config, "tie_word_embeddings", True):
1259
+ self.tie_weights()
1260
+
1261
+ def get_input_embeddings(self):
1262
+ return self.model.embed_tokens
1263
+
1264
+ def set_input_embeddings(self, value):
1265
+ self.model.embed_tokens = value
1266
+
1267
+ def get_output_embeddings(self):
1268
+ return self.lm_head
1269
+
1270
+ def set_output_embeddings(self, new_embeddings):
1271
+ self.lm_head = new_embeddings
1272
+
1273
+ def set_decoder(self, decoder):
1274
+ self.model = decoder
1275
+
1276
+ def get_decoder(self):
1277
+ return self.model
1278
+
1279
+
1280
+ @add_start_docstrings_to_model_forward(MOTIF_INPUTS_DOCSTRING)
1281
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1282
+ def forward(
1283
+ self,
1284
+ input_ids: torch.LongTensor = None,
1285
+ attention_mask: Optional[torch.Tensor] = None,
1286
+ position_ids: Optional[torch.LongTensor] = None,
1287
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1288
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1289
+ labels: Optional[torch.LongTensor] = None,
1290
+ use_cache: Optional[bool] = None,
1291
+ output_attentions: Optional[bool] = None,
1292
+ output_hidden_states: Optional[bool] = None,
1293
+ return_dict: Optional[bool] = None,
1294
+ cache_position: Optional[torch.LongTensor] = None,
1295
+ num_logits_to_keep: int = 0,
1296
+ **loss_kwargs,
1297
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1298
+ r"""
1299
+ Args:
1300
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1301
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1302
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1303
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1304
+
1305
+ num_logits_to_keep (`int`, *optional*):
1306
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1307
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1308
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1309
+
1310
+ Returns:
1311
+
1312
+ Example:
1313
+
1314
+ ```python
1315
+ >>> from transformers import AutoTokenizer, MotifForCausalLM
1316
+
1317
+ >>> model = MotifForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1318
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1319
+
1320
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1321
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1322
+
1323
+ >>> # Generate
1324
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1325
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1326
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1327
+ ```"""
1328
+
1329
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1330
+ output_hidden_states = (output_hidden_states
1331
+ if output_hidden_states is not None else self.config.output_hidden_states)
1332
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1333
+
1334
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1335
+ outputs: MotifModelOutputWithPast = self.model(
1336
+ input_ids=input_ids,
1337
+ attention_mask=attention_mask,
1338
+ position_ids=position_ids,
1339
+ past_key_values=past_key_values,
1340
+ inputs_embeds=inputs_embeds,
1341
+ use_cache=use_cache,
1342
+ output_attentions=output_attentions,
1343
+ output_hidden_states=output_hidden_states,
1344
+ return_dict=return_dict,
1345
+ cache_position=cache_position,
1346
+ )
1347
+
1348
+ hidden_states = outputs[0]
1349
+
1350
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1351
+ hidden_states = hidden_states
1352
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1353
+ logits = logits.float()
1354
+
1355
+ loss = None
1356
+ if labels is not None:
1357
+ logits = logits
1358
+ # Shift so that tokens < n predict n
1359
+ shift_logits = logits[..., :-1, :].contiguous()
1360
+ shift_labels = labels[..., 1:].contiguous()
1361
+ # Flatten the tokens
1362
+ loss_fct = CrossEntropyLoss()
1363
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1364
+ shift_labels = shift_labels.view(-1)
1365
+ shift_labels = shift_labels.to(shift_logits.device)
1366
+ loss = loss_fct(shift_logits, shift_labels)
1367
+
1368
+ if not return_dict:
1369
+ output = (logits, ) + outputs[1:]
1370
+ return (loss, ) + output if loss is not None else output
1371
+
1372
+ return CausalLMOutputWithPast(
1373
+ loss=loss,
1374
+ logits=logits,
1375
+ past_key_values=outputs.past_key_values,
1376
+ hidden_states=outputs.hidden_states,
1377
+ attentions=outputs.attentions,
1378
+ )