jon-tow commited on
Commit
0225bfd
1 Parent(s): b42bea9

feat: add base weights for `stablelm-2-12b`

Browse files
README.md CHANGED
@@ -1,12 +1,4 @@
1
  ---
2
- license: other
3
- datasets:
4
- - tiiuae/falcon-refinedweb
5
- - togethercomputer/RedPajama-Data-1T
6
- - uonlp/CulturaX
7
- - CarperAI/pilev2-dev
8
- - bigcode/starcoderdata
9
- - DataProvenanceInitiative/Commercially-Verified-Licenses
10
  language:
11
  - en
12
  - de
@@ -15,8 +7,16 @@ language:
15
  - it
16
  - nl
17
  - pt
 
18
  tags:
19
  - causal-lm
 
 
 
 
 
 
 
20
  ---
21
  # `Stable LM 2 12B`
22
 
 
1
  ---
 
 
 
 
 
 
 
 
2
  language:
3
  - en
4
  - de
 
7
  - it
8
  - nl
9
  - pt
10
+ license: other
11
  tags:
12
  - causal-lm
13
+ datasets:
14
+ - tiiuae/falcon-refinedweb
15
+ - togethercomputer/RedPajama-Data-1T
16
+ - uonlp/CulturaX
17
+ - CarperAI/pilev2-dev
18
+ - bigcode/starcoderdata
19
+ - DataProvenanceInitiative/Commercially-Verified-Licenses
20
  ---
21
  # `Stable LM 2 12B`
22
 
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/weka2/ckpts/stablelm_2_release/stablelm-2-12b/stablelm-2-12b/",
3
+ "architectures": [
4
+ "StableLmForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_stablelm.StableLmConfig",
9
+ "AutoModelForCausalLM": "modeling_stablelm.StableLmForCausalLM"
10
+ },
11
+ "bos_token_id": 100257,
12
+ "eos_token_id": 100257,
13
+ "hidden_act": "silu",
14
+ "hidden_dropout": 0.0,
15
+ "hidden_size": 5120,
16
+ "initializer_range": 0.01,
17
+ "intermediate_size": 13824,
18
+ "layer_norm_eps": 1e-05,
19
+ "max_position_embeddings": 4096,
20
+ "model_type": "stablelm",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 40,
23
+ "num_key_value_heads": 8,
24
+ "partial_rotary_factor": 0.25,
25
+ "qk_layernorm": true,
26
+ "rope_scaling": null,
27
+ "rope_theta": 10000,
28
+ "rotary_scaling_factor": 1.0,
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.39.0.dev0",
32
+ "use_cache": true,
33
+ "use_norm_bias": false,
34
+ "use_parallel_residual": true,
35
+ "use_qkv_bias": false,
36
+ "vocab_size": 100352
37
+ }
configuration_stablelm.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Stability AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ StableLM model configuration """
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ STABLELM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "stabilityai/stablelm-3b-4e1t": "https://huggingface.co/stabilityai/stablelm-3b-4e1t/resolve/main/config.json",
25
+ # See all StableLM models at https://huggingface.co/models?filter=stablelm
26
+ }
27
+
28
+
29
+ class StableLmConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`~StableLmModel`].
32
+ It is used to instantiate an StableLM model according to the specified arguments, defining the model
33
+ architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
34
+ the StableLM [stabilityai/stablelm-3b-4e1t](https://huggingface.co/stabilityai/stablelm-3b-4e1t) architecture.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used
37
+ to control the model outputs. Read the documentation from [`PretrainedConfig`]
38
+ for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 50304):
43
+ Vocabulary size of the StableLM model. Defines the number of different tokens that
44
+ can be represented by the `inputs_ids` passed when calling [`StableLmModel`].
45
+ intermediate_size (`int`, *optional*, defaults to 6912):
46
+ Dimension of the MLP representations.
47
+ hidden_size (`int`, *optional*, defaults to 2560):
48
+ Number of hidden layers in the Transformer decoder.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ num_key_value_heads (`int`, *optional*, defaults to 32):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string).
63
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
64
+ The maximum sequence length that this model might ever be used with.
65
+ Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing
68
+ all weight matrices.
69
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
70
+ The epsilon used by the normalization layers.
71
+ use_cache (`bool`, *optional*, defaults to `True`):
72
+ Whether or not the model should return the last key/values attentions
73
+ (not used by all models). Only relevant if `config.is_decoder=True`.
74
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
75
+ Whether the model's input and output word embeddings should be tied.
76
+ rope_theta (`float`, *optional*, defaults to `10000.0`):
77
+ The base period of the RoPE embeddings.
78
+ rope_scaling (`Dict`, *optional*):
79
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
80
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
81
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
82
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
83
+ these scaling strategies behave:
84
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
85
+ is an experimental feature, subject to breaking API changes in future versions.
86
+ use_qkv_bias (`bool`, *optional*, defaults to `False`):
87
+ Whether or not the model should use bias for qkv layers.
88
+ qk_layernorm (`bool`, *optional*, defaults to `False`):
89
+ Whether or not to normalize, per head, the Queries and Keys after projecting the hidden states.
90
+ use_parallel_residual (`bool`, *optional*, defaults to `False`):
91
+ Whether to use a "parallel" formulation in each Transformer layer, which can provide a slight training
92
+ speedup at large scales.
93
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
94
+ The dropout ratio after applying the MLP to the hidden states.
95
+ attention_dropout (`float`, *optional*, defaults to 0.0):
96
+ The dropout ratio for the attention probabilities.
97
+ partial_rotary_factor (`float`, *optional*, defaults to 0.25):
98
+ Percentage of the query and keys which will have rotary embedding.
99
+ bos_token_id (int, *optional*, defaults to 0):
100
+ The id of the `BOS` token in the vocabulary.
101
+ eos_token_id (int, *optional*, defaults to 0):
102
+ The id of the `EOS` token in the vocabulary.
103
+
104
+ Example:
105
+
106
+ ```python
107
+ >>> from transformers import StableLmModel, StableLmConfig
108
+
109
+ >>> # Initializing a StableLM stablelm-3b style configuration
110
+ >>> configuration = StableLmConfig()
111
+ ```"""
112
+
113
+ model_type = "stablelm"
114
+ keys_to_ignore_at_inference = ["past_key_values"]
115
+
116
+ def __init__(
117
+ self,
118
+ vocab_size=50304,
119
+ intermediate_size=6912,
120
+ hidden_size=2560,
121
+ num_hidden_layers=32,
122
+ num_attention_heads=32,
123
+ num_key_value_heads=32,
124
+ hidden_act="silu",
125
+ max_position_embeddings=4096,
126
+ initializer_range=0.02,
127
+ layer_norm_eps=1.0e-5,
128
+ use_cache=True,
129
+ tie_word_embeddings=False,
130
+ rope_theta=10_000,
131
+ rope_scaling=None,
132
+ use_qkv_bias=False,
133
+ qk_layernorm=False,
134
+ use_parallel_residual=False,
135
+ hidden_dropout=0.0,
136
+ attention_dropout=0.0,
137
+ partial_rotary_factor=0.25,
138
+ bos_token_id=0,
139
+ eos_token_id=0,
140
+ **kwargs,
141
+ ):
142
+ self.vocab_size = vocab_size
143
+ self.max_position_embeddings = max_position_embeddings
144
+
145
+ self.hidden_size = hidden_size
146
+ self.intermediate_size = intermediate_size
147
+ self.num_hidden_layers = num_hidden_layers
148
+ self.num_attention_heads = num_attention_heads
149
+ self.num_key_value_heads = num_key_value_heads
150
+ self.hidden_act = hidden_act
151
+
152
+ self.initializer_range = initializer_range
153
+ self.layer_norm_eps = layer_norm_eps
154
+ self.use_cache = use_cache
155
+ self.rope_theta = rope_theta
156
+ self.rope_scaling = rope_scaling
157
+ self.use_qkv_bias = use_qkv_bias
158
+ self.qk_layernorm = qk_layernorm
159
+ self.use_parallel_residual = use_parallel_residual
160
+ self.hidden_dropout = hidden_dropout
161
+ self.attention_dropout = attention_dropout
162
+ self.partial_rotary_factor = partial_rotary_factor
163
+ self._rope_scaling_validation()
164
+
165
+ super().__init__(
166
+ bos_token_id=bos_token_id,
167
+ eos_token_id=eos_token_id,
168
+ tie_word_embeddings=tie_word_embeddings,
169
+ **kwargs,
170
+ )
171
+
172
+ # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
173
+ def _rope_scaling_validation(self):
174
+ """
175
+ Validate the `rope_scaling` configuration.
176
+ """
177
+ if self.rope_scaling is None:
178
+ return
179
+
180
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
181
+ raise ValueError(
182
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
183
+ f"got {self.rope_scaling}"
184
+ )
185
+ rope_scaling_type = self.rope_scaling.get("type", None)
186
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
187
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
188
+ raise ValueError(
189
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
190
+ )
191
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
192
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 100257,
4
+ "eos_token_id": 100257,
5
+ "transformers_version": "4.39.0.dev0"
6
+ }
model-00001-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a686bccfe82ae4179290acbecb4013be1c28be10b61a31c7662f429d52f10f8
3
+ size 4996740184
model-00002-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56ecc36f56662969030058c3a7c8331421ff6e7ea4c174d909e534c305ba411d
3
+ size 4988954032
model-00003-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52f2e7b92dbd730a788c605e9e1a44e77afbaa6a434f590b077a9d708b31a4d7
3
+ size 4988954112
model-00004-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbe9a95df52c185b17cb6fd75c57d3ddd6354dc4728b81f7127022d1bd86d8c0
3
+ size 4949632512
model-00005-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ca50c82b6e8792dcf282b60ce8686f86a38addadb6c9ac7ac55bd1f1849406e
3
+ size 4362333000
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_stablelm.py ADDED
@@ -0,0 +1,1392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch StableLM model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache
32
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
33
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
34
+ from transformers.modeling_utils import PreTrainedModel
35
+ from transformers.utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from .configuration_stablelm import StableLmConfig
44
+
45
+
46
+ try:
47
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
48
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
49
+ except:
50
+ flash_attn_func, flash_attn_varlen_func = None, None
51
+ index_first_axis, pad_input, unpad_input = None, None, None
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+ _CONFIG_FOR_DOC = "StableLmConfig"
57
+
58
+
59
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
60
+ def _get_unpad_data(attention_mask):
61
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
62
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
63
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
64
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
65
+ return (
66
+ indices,
67
+ cu_seqlens,
68
+ max_seqlen_in_batch,
69
+ )
70
+
71
+
72
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->StableLm
73
+ class StableLmRotaryEmbedding(nn.Module):
74
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
75
+ super().__init__()
76
+
77
+ self.dim = dim
78
+ self.max_position_embeddings = max_position_embeddings
79
+ self.base = base
80
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
81
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
82
+
83
+ # Build here to make `torch.jit.trace` work.
84
+ self._set_cos_sin_cache(
85
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
86
+ )
87
+
88
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
89
+ self.max_seq_len_cached = seq_len
90
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
91
+
92
+ freqs = torch.outer(t, self.inv_freq)
93
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
94
+ emb = torch.cat((freqs, freqs), dim=-1)
95
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
96
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
97
+
98
+ def forward(self, x, seq_len=None):
99
+ # x: [bs, num_attention_heads, seq_len, head_size]
100
+ if seq_len > self.max_seq_len_cached:
101
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
102
+
103
+ return (
104
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
105
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
106
+ )
107
+
108
+
109
+ # Copied from transformers.models.falcon.modeling_falcon.FalconLinearScalingRotaryEmbedding with Falcon->StableLm
110
+ class StableLmLinearScalingRotaryEmbedding(StableLmRotaryEmbedding):
111
+ """StableLmRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
112
+
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
114
+ self.scaling_factor = scaling_factor
115
+ super().__init__(dim, max_position_embeddings, base, device)
116
+
117
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
118
+ self.max_seq_len_cached = seq_len
119
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
120
+ t = t / self.scaling_factor
121
+
122
+ freqs = torch.outer(t, self.inv_freq)
123
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
124
+ emb = torch.cat((freqs, freqs), dim=-1)
125
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
126
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
127
+
128
+
129
+ # Copied from transformers.models.falcon.modeling_falcon.FalconDynamicNTKScalingRotaryEmbedding with Falcon->StableLm
130
+ class StableLmDynamicNTKScalingRotaryEmbedding(StableLmRotaryEmbedding):
131
+ """StableLmRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
132
+
133
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
134
+ self.scaling_factor = scaling_factor
135
+ super().__init__(dim, max_position_embeddings, base, device)
136
+
137
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
138
+ self.max_seq_len_cached = seq_len
139
+
140
+ if seq_len > self.max_position_embeddings:
141
+ base = self.base * (
142
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
143
+ ) ** (self.dim / (self.dim - 2))
144
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
145
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
146
+
147
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
148
+
149
+ freqs = torch.outer(t, self.inv_freq)
150
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
151
+ emb = torch.cat((freqs, freqs), dim=-1)
152
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
153
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
154
+
155
+
156
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
157
+ def rotate_half(x):
158
+ """Rotates half the hidden dims of the input."""
159
+ x1 = x[..., : x.shape[-1] // 2]
160
+ x2 = x[..., x.shape[-1] // 2 :]
161
+ return torch.cat((-x2, x1), dim=-1)
162
+
163
+
164
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
165
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
166
+ """Applies Rotary Position Embedding to the query and key tensors.
167
+
168
+ Args:
169
+ q (`torch.Tensor`): The query tensor.
170
+ k (`torch.Tensor`): The key tensor.
171
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
172
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
173
+ position_ids (`torch.Tensor`):
174
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
175
+ used to pass offsetted position ids when working with a KV-cache.
176
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
177
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
178
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
179
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
180
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
181
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
182
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
183
+ Returns:
184
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
185
+ """
186
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
187
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
188
+ q_embed = (q * cos) + (rotate_half(q) * sin)
189
+ k_embed = (k * cos) + (rotate_half(k) * sin)
190
+ return q_embed, k_embed
191
+
192
+
193
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->StableLm
194
+ class StableLmMLP(nn.Module):
195
+ def __init__(self, config):
196
+ super().__init__()
197
+ self.config = config
198
+ self.hidden_size = config.hidden_size
199
+ self.intermediate_size = config.intermediate_size
200
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
201
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
202
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
203
+ self.act_fn = ACT2FN[config.hidden_act]
204
+
205
+ def forward(self, x):
206
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
207
+
208
+
209
+ class StableLmLayerNormPerHead(nn.Module):
210
+ def __init__(self, dim, num_heads, eps=1e-5, bias=False):
211
+ super().__init__()
212
+ self.dim = dim
213
+ self.num_heads = num_heads
214
+ self.norms = nn.ModuleList([nn.LayerNorm(dim, eps=eps, bias=bias) for _ in range(self.num_heads)])
215
+
216
+ def forward(self, hidden_states: torch.Tensor):
217
+ # Split along the num_heads axis to get per-head inputs
218
+ # [batch_size, num_heads, seq_len, head_dim] -> [batch_size, 1, seq_len, head_dim] * num_heads
219
+ states_per_heads = torch.split(hidden_states, 1, dim=1)
220
+ # Normalize and merge the heads back together
221
+ return torch.cat([norm(hidden_states) for norm, hidden_states in zip(self.norms, states_per_heads)], dim=1)
222
+
223
+
224
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
225
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
226
+ """
227
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
228
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
229
+ """
230
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
231
+ if n_rep == 1:
232
+ return hidden_states
233
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
234
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
235
+
236
+
237
+ class StableLmAttention(nn.Module):
238
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
239
+
240
+ def __init__(self, config: StableLmConfig, layer_idx: Optional[int] = None):
241
+ super().__init__()
242
+ self.config = config
243
+ self.layer_idx = layer_idx
244
+ if layer_idx is None:
245
+ logger.warning_once(
246
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
247
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
248
+ "when creating this class."
249
+ )
250
+
251
+ self.hidden_size = config.hidden_size
252
+ self.num_heads = config.num_attention_heads
253
+ self.head_dim = self.hidden_size // self.num_heads
254
+ self.num_key_value_heads = config.num_key_value_heads
255
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
256
+ self.max_position_embeddings = config.max_position_embeddings
257
+ self.rope_theta = config.rope_theta
258
+ self.partial_rotary_factor = config.partial_rotary_factor
259
+ self.is_causal = True
260
+
261
+ if (self.head_dim * self.num_heads) != self.hidden_size:
262
+ raise ValueError(
263
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
264
+ f" and `num_heads`: {self.num_heads})."
265
+ )
266
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.use_qkv_bias)
267
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)
268
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)
269
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
270
+
271
+ self.qk_layernorm = config.qk_layernorm
272
+ if self.qk_layernorm:
273
+ self.q_layernorm = StableLmLayerNormPerHead(self.head_dim, self.num_heads, eps=config.layer_norm_eps)
274
+ self.k_layernorm = StableLmLayerNormPerHead(
275
+ self.head_dim, self.num_key_value_heads, eps=config.layer_norm_eps
276
+ )
277
+
278
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
279
+ self._init_rope()
280
+
281
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonAttention._init_rope with Persimmon->StableLm
282
+ def _init_rope(self):
283
+ if self.config.rope_scaling is None:
284
+ self.rotary_emb = StableLmRotaryEmbedding(
285
+ int(self.partial_rotary_factor * self.head_dim),
286
+ max_position_embeddings=self.max_position_embeddings,
287
+ base=self.rope_theta,
288
+ )
289
+ else:
290
+ scaling_type = self.config.rope_scaling["type"]
291
+ scaling_factor = self.config.rope_scaling["factor"]
292
+ if scaling_type == "linear":
293
+ self.rotary_emb = StableLmLinearScalingRotaryEmbedding(
294
+ int(self.partial_rotary_factor * self.head_dim),
295
+ max_position_embeddings=self.max_position_embeddings,
296
+ scaling_factor=scaling_factor,
297
+ base=self.rope_theta,
298
+ )
299
+ elif scaling_type == "dynamic":
300
+ self.rotary_emb = StableLmDynamicNTKScalingRotaryEmbedding(
301
+ int(self.partial_rotary_factor * self.head_dim),
302
+ max_position_embeddings=self.max_position_embeddings,
303
+ scaling_factor=scaling_factor,
304
+ base=self.rope_theta,
305
+ )
306
+ else:
307
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
308
+
309
+ def forward(
310
+ self,
311
+ hidden_states: torch.Tensor,
312
+ attention_mask: Optional[torch.Tensor] = None,
313
+ position_ids: Optional[torch.LongTensor] = None,
314
+ past_key_value: Optional[Cache] = None,
315
+ output_attentions: bool = False,
316
+ use_cache: bool = False,
317
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
318
+ bsz, q_len, _ = hidden_states.size()
319
+
320
+ query_states = self.q_proj(hidden_states)
321
+ key_states = self.k_proj(hidden_states)
322
+ value_states = self.v_proj(hidden_states)
323
+
324
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
325
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
326
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
327
+
328
+ if self.qk_layernorm:
329
+ query_states = self.q_layernorm(query_states)
330
+ key_states = self.k_layernorm(key_states)
331
+
332
+ kv_seq_len = key_states.shape[-2]
333
+ if past_key_value is not None:
334
+ if self.layer_idx is None:
335
+ raise ValueError(
336
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
337
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
338
+ "with a layer index."
339
+ )
340
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
341
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
342
+
343
+ # Partial rotary embedding
344
+ query_rot, query_pass = (
345
+ query_states[..., : self.rotary_emb.dim],
346
+ query_states[..., self.rotary_emb.dim :],
347
+ )
348
+ key_rot, key_pass = (
349
+ key_states[..., : self.rotary_emb.dim],
350
+ key_states[..., self.rotary_emb.dim :],
351
+ )
352
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
353
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
354
+
355
+ # [batch_size, seq_length, num_heads, head_dim]
356
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
357
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
358
+
359
+ if past_key_value is not None:
360
+ # Specific to RoPE models with partial rotation
361
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
362
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
363
+
364
+ # Repeat k/v heads if n_kv_heads < n_heads
365
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
366
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
367
+
368
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
369
+
370
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
371
+ raise ValueError(
372
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
373
+ f" {attn_weights.size()}"
374
+ )
375
+
376
+ if attention_mask is not None:
377
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
378
+ raise ValueError(
379
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
380
+ )
381
+ attn_weights = attn_weights + attention_mask
382
+
383
+ # upcast attention to fp32
384
+ attn_weights = nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query_states.dtype)
385
+ attn_weights = self.attention_dropout(attn_weights)
386
+
387
+ attn_output = torch.matmul(attn_weights, value_states)
388
+
389
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
390
+ raise ValueError(
391
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
392
+ f" {attn_output.size()}"
393
+ )
394
+
395
+ attn_output = attn_output.transpose(1, 2).contiguous()
396
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
397
+
398
+ attn_output = self.o_proj(attn_output)
399
+
400
+ if not output_attentions:
401
+ attn_weights = None
402
+
403
+ return attn_output, attn_weights, past_key_value
404
+
405
+
406
+ class StableLmSdpaAttention(StableLmAttention):
407
+ def forward(
408
+ self,
409
+ hidden_states: torch.Tensor,
410
+ attention_mask: Optional[torch.Tensor] = None,
411
+ position_ids: Optional[torch.LongTensor] = None,
412
+ past_key_value: Optional[Cache] = None,
413
+ output_attentions: bool = False,
414
+ use_cache: bool = False,
415
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
416
+ if output_attentions:
417
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
418
+ logger.warning_once(
419
+ "StableLmModel is using StableLmSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
420
+ '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.'
421
+ )
422
+ return super().forward(
423
+ hidden_states=hidden_states,
424
+ attention_mask=attention_mask,
425
+ position_ids=position_ids,
426
+ past_key_value=past_key_value,
427
+ output_attentions=output_attentions,
428
+ use_cache=use_cache,
429
+ )
430
+
431
+ bsz, q_len, _ = hidden_states.size()
432
+
433
+ query_states = self.q_proj(hidden_states)
434
+ key_states = self.k_proj(hidden_states)
435
+ value_states = self.v_proj(hidden_states)
436
+
437
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
438
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
439
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
440
+
441
+ if self.qk_layernorm:
442
+ query_states = self.q_layernorm(query_states)
443
+ key_states = self.k_layernorm(key_states)
444
+
445
+ kv_seq_len = key_states.shape[-2]
446
+ if past_key_value is not None:
447
+ if self.layer_idx is None:
448
+ raise ValueError(
449
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
450
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
451
+ "with a layer index."
452
+ )
453
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
454
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
455
+
456
+ # Partial rotary embedding
457
+ query_rot, query_pass = (
458
+ query_states[..., : self.rotary_emb.dim],
459
+ query_states[..., self.rotary_emb.dim :],
460
+ )
461
+ key_rot, key_pass = (
462
+ key_states[..., : self.rotary_emb.dim],
463
+ key_states[..., self.rotary_emb.dim :],
464
+ )
465
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
466
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
467
+
468
+ # [batch_size, seq_length, num_heads, head_dim]
469
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
470
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
471
+
472
+ if past_key_value is not None:
473
+ # Specific to RoPE models with partial rotation
474
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
475
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
476
+
477
+ # Repeat k/v heads if n_kv_heads < n_heads
478
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
479
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
480
+
481
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
482
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
483
+ if query_states.device.type == "cuda" and attention_mask is not None:
484
+ query_states = query_states.contiguous()
485
+ key_states = key_states.contiguous()
486
+ value_states = value_states.contiguous()
487
+
488
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
489
+ query_states,
490
+ key_states,
491
+ value_states,
492
+ attn_mask=attention_mask,
493
+ dropout_p=self.attention_dropout.p if self.training else 0.0,
494
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
495
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
496
+ )
497
+
498
+ attn_output = attn_output.transpose(1, 2).contiguous()
499
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
500
+
501
+ attn_output = self.o_proj(attn_output)
502
+
503
+ return attn_output, None, past_key_value
504
+
505
+
506
+ class StableLmFlashAttention2(StableLmAttention):
507
+ """
508
+ StableLM flash attention module. This module inherits from `StableLmAttention` as the weights of the module stays
509
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
510
+ flash attention and deal with padding tokens in case the input contains any of them.
511
+ """
512
+
513
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
514
+ def __init__(self, *args, **kwargs):
515
+ super().__init__(*args, **kwargs)
516
+
517
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
518
+ # 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.
519
+ # 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).
520
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
521
+
522
+ def forward(
523
+ self,
524
+ hidden_states: torch.Tensor,
525
+ attention_mask: Optional[torch.LongTensor] = None,
526
+ position_ids: Optional[torch.LongTensor] = None,
527
+ past_key_value: Optional[Cache] = None,
528
+ output_attentions: bool = False,
529
+ use_cache: bool = False,
530
+ **kwargs,
531
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
532
+ # StableLmFlashAttention2 attention does not support output_attentions
533
+
534
+ output_attentions = False
535
+
536
+ bsz, q_len, _ = hidden_states.size()
537
+
538
+ query_states = self.q_proj(hidden_states)
539
+ key_states = self.k_proj(hidden_states)
540
+ value_states = self.v_proj(hidden_states)
541
+
542
+ # Flash attention requires the input to have the shape
543
+ # batch_size x seq_length x head_dim x hidden_dim
544
+ # therefore we just need to keep the original shape
545
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
546
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
547
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
548
+
549
+ if self.qk_layernorm:
550
+ query_states = self.q_layernorm(query_states)
551
+ key_states = self.k_layernorm(key_states)
552
+
553
+ kv_seq_len = key_states.shape[-2]
554
+ if past_key_value is not None:
555
+ if self.layer_idx is None:
556
+ raise ValueError(
557
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
558
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
559
+ "with a layer index."
560
+ )
561
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
562
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
563
+
564
+ # Partial rotary embedding
565
+ query_rot, query_pass = (
566
+ query_states[..., : self.rotary_emb.dim],
567
+ query_states[..., self.rotary_emb.dim :],
568
+ )
569
+ key_rot, key_pass = (
570
+ key_states[..., : self.rotary_emb.dim],
571
+ key_states[..., self.rotary_emb.dim :],
572
+ )
573
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
574
+
575
+ # [batch_size, seq_length, num_heads, head_dim]
576
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
577
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
578
+
579
+ if past_key_value is not None:
580
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
581
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
582
+
583
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
584
+ # to be able to avoid many of these transpose/reshape/view.
585
+ query_states = query_states.transpose(1, 2)
586
+ key_states = key_states.transpose(1, 2)
587
+ value_states = value_states.transpose(1, 2)
588
+
589
+ dropout_rate = self.attention_dropout.p if self.training else 0.0
590
+
591
+ attn_output = self._flash_attention_forward(
592
+ query_states,
593
+ key_states,
594
+ value_states,
595
+ attention_mask,
596
+ q_len,
597
+ dropout=dropout_rate,
598
+ )
599
+
600
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
601
+ attn_output = self.o_proj(attn_output)
602
+
603
+ if not output_attentions:
604
+ attn_weights = None
605
+
606
+ return attn_output, attn_weights, past_key_value
607
+
608
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
609
+ def _flash_attention_forward(
610
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
611
+ ):
612
+ """
613
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
614
+ first unpad the input, then computes the attention scores and pad the final attention scores.
615
+
616
+ Args:
617
+ query_states (`torch.Tensor`):
618
+ Input query states to be passed to Flash Attention API
619
+ key_states (`torch.Tensor`):
620
+ Input key states to be passed to Flash Attention API
621
+ value_states (`torch.Tensor`):
622
+ Input value states to be passed to Flash Attention API
623
+ attention_mask (`torch.Tensor`):
624
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
625
+ position of padding tokens and 1 for the position of non-padding tokens.
626
+ dropout (`float`):
627
+ Attention dropout
628
+ softmax_scale (`float`, *optional*):
629
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
630
+ """
631
+ if not self._flash_attn_uses_top_left_mask:
632
+ causal = self.is_causal
633
+ else:
634
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
635
+ causal = self.is_causal and query_length != 1
636
+
637
+ # Contains at least one padding token in the sequence
638
+ if attention_mask is not None:
639
+ batch_size = query_states.shape[0]
640
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
641
+ query_states, key_states, value_states, attention_mask, query_length
642
+ )
643
+
644
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
645
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
646
+
647
+ attn_output_unpad = flash_attn_varlen_func(
648
+ query_states,
649
+ key_states,
650
+ value_states,
651
+ cu_seqlens_q=cu_seqlens_q,
652
+ cu_seqlens_k=cu_seqlens_k,
653
+ max_seqlen_q=max_seqlen_in_batch_q,
654
+ max_seqlen_k=max_seqlen_in_batch_k,
655
+ dropout_p=dropout,
656
+ softmax_scale=softmax_scale,
657
+ causal=causal,
658
+ )
659
+
660
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
661
+ else:
662
+ attn_output = flash_attn_func(
663
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
664
+ )
665
+
666
+ return attn_output
667
+
668
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
669
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
670
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
671
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
672
+
673
+ key_layer = index_first_axis(
674
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
675
+ )
676
+ value_layer = index_first_axis(
677
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
678
+ )
679
+ if query_length == kv_seq_len:
680
+ query_layer = index_first_axis(
681
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
682
+ )
683
+ cu_seqlens_q = cu_seqlens_k
684
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
685
+ indices_q = indices_k
686
+ elif query_length == 1:
687
+ max_seqlen_in_batch_q = 1
688
+ cu_seqlens_q = torch.arange(
689
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
690
+ ) # There is a memcpy here, that is very bad.
691
+ indices_q = cu_seqlens_q[:-1]
692
+ query_layer = query_layer.squeeze(1)
693
+ else:
694
+ # The -q_len: slice assumes left padding.
695
+ attention_mask = attention_mask[:, -query_length:]
696
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
697
+
698
+ return (
699
+ query_layer,
700
+ key_layer,
701
+ value_layer,
702
+ indices_q,
703
+ (cu_seqlens_q, cu_seqlens_k),
704
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
705
+ )
706
+
707
+
708
+ ATTENTION_CLASSES = {
709
+ "eager": StableLmAttention,
710
+ "sdpa": StableLmSdpaAttention,
711
+ "flash_attention_2": StableLmFlashAttention2,
712
+ }
713
+
714
+
715
+ class StableLmDecoderLayer(nn.Module):
716
+ def __init__(self, config: StableLmConfig, layer_idx: int):
717
+ super().__init__()
718
+ self.use_parallel_residual = config.use_parallel_residual
719
+ self.hidden_size = config.hidden_size
720
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
721
+ self.mlp = StableLmMLP(config)
722
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
723
+ self.post_attention_layernorm = None
724
+ if not self.use_parallel_residual:
725
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
726
+ self.dropout = nn.Dropout(config.hidden_dropout)
727
+
728
+ def forward(
729
+ self,
730
+ hidden_states: torch.Tensor,
731
+ attention_mask: Optional[torch.Tensor] = None,
732
+ position_ids: Optional[torch.LongTensor] = None,
733
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
734
+ output_attentions: Optional[bool] = False,
735
+ use_cache: Optional[bool] = False,
736
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
737
+ """
738
+ Args:
739
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
740
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
741
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
742
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
743
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
744
+ `[0, config.n_positions - 1]`.
745
+
746
+ [What are position IDs?](../glossary#position-ids)
747
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
748
+ cached past key and value projection states
749
+ output_attentions (`bool`, *optional*):
750
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
751
+ returned tensors for more detail.
752
+ use_cache (`bool`, *optional*):
753
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
754
+ (see `past_key_values`).
755
+ """
756
+
757
+ residual = hidden_states
758
+
759
+ hidden_states = self.input_layernorm(hidden_states)
760
+
761
+ # Self Attention
762
+ self_attn_output, self_attn_weights, present_key_value = self.self_attn(
763
+ hidden_states=hidden_states,
764
+ attention_mask=attention_mask,
765
+ position_ids=position_ids,
766
+ past_key_value=past_key_value,
767
+ output_attentions=output_attentions,
768
+ use_cache=use_cache,
769
+ )
770
+
771
+ # copied from transformers.models.gpt_neox.modeling_gpt_neox.GPTNeoXLayer.forward
772
+ if self.use_parallel_residual:
773
+ # x = x + attn(ln1(x)) + mlp(ln1(x))
774
+ # Fully Connected
775
+ mlp_output = self.mlp(hidden_states)
776
+ mlp_output = self.dropout(mlp_output)
777
+ hidden_states = residual + self_attn_output + mlp_output
778
+ else:
779
+ # x = x + attn(ln1(x))
780
+ # x = x + mlp(ln2(x))
781
+ residual = residual + self_attn_output
782
+ # Fully Connected
783
+ mlp_output = self.mlp(self.post_attention_layernorm(residual))
784
+ mlp_output = self.dropout(mlp_output)
785
+ hidden_states = residual + mlp_output
786
+
787
+ outputs = (hidden_states,)
788
+
789
+ if output_attentions:
790
+ outputs += (self_attn_weights,)
791
+
792
+ if use_cache:
793
+ outputs += (present_key_value,)
794
+
795
+ return outputs
796
+
797
+
798
+ STABLELM_START_DOCSTRING = r"""
799
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
800
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
801
+ etc.)
802
+
803
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
804
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
805
+ and behavior.
806
+
807
+ Parameters:
808
+ config ([`StableLmConfig`]):
809
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
810
+ load the weights associated with the model, only the configuration. Check out the
811
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
812
+ """
813
+
814
+
815
+ @add_start_docstrings(
816
+ "The bare StableLm Model outputting raw hidden-states without any specific head on top.",
817
+ STABLELM_START_DOCSTRING,
818
+ )
819
+ class StableLmPreTrainedModel(PreTrainedModel):
820
+ config_class = StableLmConfig
821
+ base_model_prefix = "model"
822
+ supports_gradient_checkpointing = True
823
+ _no_split_modules = ["StableLmDecoderLayer"]
824
+ _skip_keys_device_placement = "past_key_values"
825
+ _supports_flash_attn_2 = True
826
+ _supports_cache_class = True
827
+ _supports_sdpa = True
828
+
829
+ def _init_weights(self, module):
830
+ std = self.config.initializer_range
831
+ if isinstance(module, nn.Linear):
832
+ module.weight.data.normal_(mean=0.0, std=std)
833
+ if module.bias is not None:
834
+ module.bias.data.zero_()
835
+ elif isinstance(module, nn.Embedding):
836
+ module.weight.data.normal_(mean=0.0, std=std)
837
+ if module.padding_idx is not None:
838
+ module.weight.data[module.padding_idx].zero_()
839
+
840
+
841
+ STABLELM_INPUTS_DOCSTRING = r"""
842
+ Args:
843
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
844
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
845
+ it.
846
+
847
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
848
+ [`PreTrainedTokenizer.__call__`] for details.
849
+
850
+ [What are input IDs?](../glossary#input-ids)
851
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
852
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
853
+
854
+ - 1 for tokens that are **not masked**,
855
+ - 0 for tokens that are **masked**.
856
+
857
+ [What are attention masks?](../glossary#attention-mask)
858
+
859
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
860
+ [`PreTrainedTokenizer.__call__`] for details.
861
+
862
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
863
+ `past_key_values`).
864
+
865
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
866
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
867
+ information on the default strategy.
868
+
869
+ - 1 indicates the head is **not masked**,
870
+ - 0 indicates the head is **masked**.
871
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
872
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
873
+ config.n_positions - 1]`.
874
+
875
+ [What are position IDs?](../glossary#position-ids)
876
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
877
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
878
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
879
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
880
+
881
+ Two formats are allowed:
882
+ - a [`~cache_utils.Cache`] instance;
883
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
884
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
885
+ cache format.
886
+
887
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
888
+ legacy cache format will be returned.
889
+
890
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
891
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
892
+ of shape `(batch_size, sequence_length)`.
893
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
894
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
895
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
896
+ model's internal embedding lookup matrix.
897
+ use_cache (`bool`, *optional*):
898
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
899
+ `past_key_values`).
900
+ output_attentions (`bool`, *optional*):
901
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
902
+ tensors for more detail.
903
+ output_hidden_states (`bool`, *optional*):
904
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
905
+ more detail.
906
+ return_dict (`bool`, *optional*):
907
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
908
+ """
909
+
910
+
911
+ @add_start_docstrings(
912
+ "The bare StableLm Model outputting raw hidden-states without any specific head on top.",
913
+ STABLELM_START_DOCSTRING,
914
+ )
915
+ class StableLmModel(StableLmPreTrainedModel):
916
+ """
917
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`StableLmDecoderLayer`]
918
+
919
+ Args:
920
+ config: StableLmConfig
921
+ """
922
+
923
+ def __init__(self, config: StableLmConfig):
924
+ super().__init__(config)
925
+ self.padding_idx = config.pad_token_id
926
+ self.vocab_size = config.vocab_size
927
+
928
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
929
+ self.layers = nn.ModuleList(
930
+ [StableLmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
931
+ )
932
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
933
+
934
+ self._attn_implementation = config._attn_implementation
935
+ self.gradient_checkpointing = False
936
+ # Initialize weights and apply final processing
937
+ self.post_init()
938
+
939
+ def get_input_embeddings(self):
940
+ return self.embed_tokens
941
+
942
+ def set_input_embeddings(self, value):
943
+ self.embed_tokens = value
944
+
945
+ @add_start_docstrings_to_model_forward(STABLELM_INPUTS_DOCSTRING)
946
+ def forward(
947
+ self,
948
+ input_ids: torch.LongTensor = None,
949
+ attention_mask: Optional[torch.Tensor] = None,
950
+ position_ids: Optional[torch.LongTensor] = None,
951
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
952
+ inputs_embeds: Optional[torch.FloatTensor] = None,
953
+ use_cache: Optional[bool] = None,
954
+ output_attentions: Optional[bool] = None,
955
+ output_hidden_states: Optional[bool] = None,
956
+ return_dict: Optional[bool] = None,
957
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
958
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
959
+ output_hidden_states = (
960
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
961
+ )
962
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
963
+
964
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
965
+
966
+ # retrieve input_ids and inputs_embeds
967
+ if input_ids is not None and inputs_embeds is not None:
968
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
969
+ elif input_ids is not None:
970
+ batch_size, seq_length = input_ids.shape
971
+ elif inputs_embeds is not None:
972
+ batch_size, seq_length, _ = inputs_embeds.shape
973
+ else:
974
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
975
+
976
+ seq_length_with_past = seq_length
977
+ past_key_values_length = 0
978
+
979
+ if self.gradient_checkpointing and self.training:
980
+ if use_cache:
981
+ logger.warning_once(
982
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
983
+ )
984
+ use_cache = False
985
+
986
+ if use_cache:
987
+ use_legacy_cache = not isinstance(past_key_values, Cache)
988
+ if use_legacy_cache:
989
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
990
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
991
+ seq_length_with_past = seq_length_with_past + past_key_values_length
992
+
993
+ if position_ids is None:
994
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
995
+ position_ids = torch.arange(
996
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
997
+ )
998
+ position_ids = position_ids.unsqueeze(0)
999
+
1000
+ if inputs_embeds is None:
1001
+ inputs_embeds = self.embed_tokens(input_ids)
1002
+ # embed positions
1003
+ if self._attn_implementation == "flash_attention_2":
1004
+ # 2d mask is passed through the layers
1005
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1006
+ # for output_attentions case used fallback to eager attention realization
1007
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1008
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1009
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1010
+ )
1011
+ else:
1012
+ # 4d mask is passed through the layers
1013
+ attention_mask = _prepare_4d_causal_attention_mask(
1014
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1015
+ )
1016
+
1017
+ hidden_states = inputs_embeds
1018
+
1019
+ # decoder layers
1020
+ all_hidden_states = () if output_hidden_states else None
1021
+ all_self_attns = () if output_attentions else None
1022
+ next_decoder_cache = None
1023
+
1024
+ for decoder_layer in self.layers:
1025
+ if output_hidden_states:
1026
+ all_hidden_states += (hidden_states,)
1027
+
1028
+ if self.gradient_checkpointing and self.training:
1029
+ layer_outputs = self._gradient_checkpointing_func(
1030
+ decoder_layer.__call__,
1031
+ hidden_states,
1032
+ attention_mask,
1033
+ position_ids,
1034
+ past_key_values,
1035
+ output_attentions,
1036
+ )
1037
+ else:
1038
+ layer_outputs = decoder_layer(
1039
+ hidden_states,
1040
+ attention_mask=attention_mask,
1041
+ position_ids=position_ids,
1042
+ past_key_value=past_key_values,
1043
+ output_attentions=output_attentions,
1044
+ use_cache=use_cache,
1045
+ )
1046
+
1047
+ hidden_states = layer_outputs[0]
1048
+
1049
+ if use_cache:
1050
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1051
+
1052
+ if output_attentions:
1053
+ all_self_attns += (layer_outputs[1],)
1054
+
1055
+ hidden_states = self.norm(hidden_states)
1056
+
1057
+ # add hidden states from the last decoder layer
1058
+ if output_hidden_states:
1059
+ all_hidden_states += (hidden_states,)
1060
+
1061
+ next_cache = None
1062
+ if use_cache:
1063
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1064
+
1065
+ if not return_dict:
1066
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1067
+ return BaseModelOutputWithPast(
1068
+ last_hidden_state=hidden_states,
1069
+ past_key_values=next_cache,
1070
+ hidden_states=all_hidden_states,
1071
+ attentions=all_self_attns,
1072
+ )
1073
+
1074
+
1075
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM with PERSIMMON->STABLELM,Persimmon->StableLm
1076
+ class StableLmForCausalLM(StableLmPreTrainedModel):
1077
+ _tied_weights_keys = ["lm_head.weight"]
1078
+
1079
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with LLAMA->STABLELM,Llama->StableLm
1080
+ def __init__(self, config):
1081
+ super().__init__(config)
1082
+ self.model = StableLmModel(config)
1083
+ self.vocab_size = config.vocab_size
1084
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1085
+
1086
+ # Initialize weights and apply final processing
1087
+ self.post_init()
1088
+
1089
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1090
+ def get_input_embeddings(self):
1091
+ return self.model.embed_tokens
1092
+
1093
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1094
+ def set_input_embeddings(self, value):
1095
+ self.model.embed_tokens = value
1096
+
1097
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1098
+ def get_output_embeddings(self):
1099
+ return self.lm_head
1100
+
1101
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1102
+ def set_output_embeddings(self, new_embeddings):
1103
+ self.lm_head = new_embeddings
1104
+
1105
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1106
+ def set_decoder(self, decoder):
1107
+ self.model = decoder
1108
+
1109
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1110
+ def get_decoder(self):
1111
+ return self.model
1112
+
1113
+ @add_start_docstrings_to_model_forward(STABLELM_INPUTS_DOCSTRING)
1114
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1115
+ # Ignore copy
1116
+ def forward(
1117
+ self,
1118
+ input_ids: torch.LongTensor = None,
1119
+ attention_mask: Optional[torch.Tensor] = None,
1120
+ position_ids: Optional[torch.LongTensor] = None,
1121
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1122
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1123
+ labels: Optional[torch.LongTensor] = None,
1124
+ use_cache: Optional[bool] = None,
1125
+ output_attentions: Optional[bool] = None,
1126
+ output_hidden_states: Optional[bool] = None,
1127
+ return_dict: Optional[bool] = None,
1128
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1129
+ r"""
1130
+ Args:
1131
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1132
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1133
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1134
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1135
+
1136
+ Returns:
1137
+
1138
+ Example:
1139
+
1140
+ ```python
1141
+ >>> from transformers import AutoTokenizer, StableLmForCausalLM
1142
+
1143
+ >>> model = StableLmForCausalLM.from_pretrained("stabilityai/stablelm-3b-4e1t")
1144
+ >>> tokenizer = AutoTokenizer.from_pretrained("stabilityai/stablelm-3b-4e1t")
1145
+
1146
+ >>> prompt = "The weather is always wonderful in"
1147
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1148
+
1149
+ >>> # Generate
1150
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1151
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1152
+ 'The weather is always wonderful in the summer in the city of San Diego. The city is located on the coast of the Pacific Ocean and is surrounded by'
1153
+ ```"""
1154
+
1155
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1156
+ output_hidden_states = (
1157
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1158
+ )
1159
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1160
+
1161
+ outputs = self.model(
1162
+ input_ids=input_ids,
1163
+ attention_mask=attention_mask,
1164
+ position_ids=position_ids,
1165
+ past_key_values=past_key_values,
1166
+ inputs_embeds=inputs_embeds,
1167
+ use_cache=use_cache,
1168
+ output_attentions=output_attentions,
1169
+ output_hidden_states=output_hidden_states,
1170
+ return_dict=return_dict,
1171
+ )
1172
+
1173
+ hidden_states = outputs[0]
1174
+ logits = self.lm_head(hidden_states)
1175
+
1176
+ loss = None
1177
+ if labels is not None:
1178
+ # Shift so that tokens < n predict n
1179
+ shift_logits = logits[..., :-1, :].contiguous()
1180
+ shift_labels = labels[..., 1:].contiguous()
1181
+ # Flatten the tokens
1182
+ loss_fct = CrossEntropyLoss()
1183
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1184
+ shift_labels = shift_labels.view(-1)
1185
+ # Enable model parallelism
1186
+ shift_labels = shift_labels.to(shift_logits.device)
1187
+ loss = loss_fct(shift_logits, shift_labels)
1188
+
1189
+ if not return_dict:
1190
+ output = (logits,) + outputs[1:]
1191
+ return (loss,) + output if loss is not None else output
1192
+
1193
+ return CausalLMOutputWithPast(
1194
+ loss=loss,
1195
+ logits=logits,
1196
+ past_key_values=outputs.past_key_values,
1197
+ hidden_states=outputs.hidden_states,
1198
+ attentions=outputs.attentions,
1199
+ )
1200
+
1201
+ def prepare_inputs_for_generation(
1202
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1203
+ ):
1204
+ if past_key_values is not None:
1205
+ if isinstance(past_key_values, Cache):
1206
+ cache_length = past_key_values.get_seq_length()
1207
+ past_length = past_key_values.seen_tokens
1208
+ max_cache_length = past_key_values.get_max_length()
1209
+ else:
1210
+ cache_length = past_length = past_key_values[0][0].shape[2]
1211
+ max_cache_length = None
1212
+
1213
+ # Keep only the unprocessed tokens:
1214
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1215
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1216
+ # input)
1217
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1218
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1219
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1220
+ # input_ids based on the past_length.
1221
+ elif past_length < input_ids.shape[1]:
1222
+ input_ids = input_ids[:, past_length:]
1223
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1224
+
1225
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1226
+ if (
1227
+ max_cache_length is not None
1228
+ and attention_mask is not None
1229
+ and cache_length + input_ids.shape[1] > max_cache_length
1230
+ ):
1231
+ attention_mask = attention_mask[:, -max_cache_length:]
1232
+
1233
+ position_ids = kwargs.get("position_ids", None)
1234
+ if attention_mask is not None and position_ids is None:
1235
+ # create position_ids on the fly for batch generation
1236
+ position_ids = attention_mask.long().cumsum(-1) - 1
1237
+ position_ids.masked_fill_(attention_mask == 0, 1)
1238
+ if past_key_values:
1239
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1240
+
1241
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1242
+ if inputs_embeds is not None and past_key_values is None:
1243
+ model_inputs = {"inputs_embeds": inputs_embeds}
1244
+ else:
1245
+ model_inputs = {"input_ids": input_ids}
1246
+
1247
+ model_inputs.update(
1248
+ {
1249
+ "position_ids": position_ids,
1250
+ "past_key_values": past_key_values,
1251
+ "use_cache": kwargs.get("use_cache"),
1252
+ "attention_mask": attention_mask,
1253
+ }
1254
+ )
1255
+ return model_inputs
1256
+
1257
+ @staticmethod
1258
+ def _reorder_cache(past_key_values, beam_idx):
1259
+ reordered_past = ()
1260
+ for layer_past in past_key_values:
1261
+ reordered_past += (
1262
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1263
+ )
1264
+ return reordered_past
1265
+
1266
+
1267
+ @add_start_docstrings(
1268
+ """
1269
+ The StableLm transformer with a sequence classification head on top (linear layer).
1270
+
1271
+ [`StableLmForSequenceClassification`] uses the last token in order to do the classification, as other causal
1272
+ models (e.g. GPT-2) do.
1273
+
1274
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1275
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1276
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1277
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1278
+ each row of the batch).
1279
+ """,
1280
+ STABLELM_START_DOCSTRING,
1281
+ )
1282
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->STABLELM,Llama->StableLm
1283
+ class StableLmForSequenceClassification(StableLmPreTrainedModel):
1284
+ def __init__(self, config):
1285
+ super().__init__(config)
1286
+ self.num_labels = config.num_labels
1287
+ self.model = StableLmModel(config)
1288
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1289
+
1290
+ # Initialize weights and apply final processing
1291
+ self.post_init()
1292
+
1293
+ def get_input_embeddings(self):
1294
+ return self.model.embed_tokens
1295
+
1296
+ def set_input_embeddings(self, value):
1297
+ self.model.embed_tokens = value
1298
+
1299
+ @add_start_docstrings_to_model_forward(STABLELM_INPUTS_DOCSTRING)
1300
+ def forward(
1301
+ self,
1302
+ input_ids: torch.LongTensor = None,
1303
+ attention_mask: Optional[torch.Tensor] = None,
1304
+ position_ids: Optional[torch.LongTensor] = None,
1305
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1306
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1307
+ labels: Optional[torch.LongTensor] = None,
1308
+ use_cache: Optional[bool] = None,
1309
+ output_attentions: Optional[bool] = None,
1310
+ output_hidden_states: Optional[bool] = None,
1311
+ return_dict: Optional[bool] = None,
1312
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1313
+ r"""
1314
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1315
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1316
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1317
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1318
+ """
1319
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1320
+
1321
+ transformer_outputs = self.model(
1322
+ input_ids,
1323
+ attention_mask=attention_mask,
1324
+ position_ids=position_ids,
1325
+ past_key_values=past_key_values,
1326
+ inputs_embeds=inputs_embeds,
1327
+ use_cache=use_cache,
1328
+ output_attentions=output_attentions,
1329
+ output_hidden_states=output_hidden_states,
1330
+ return_dict=return_dict,
1331
+ )
1332
+ hidden_states = transformer_outputs[0]
1333
+ logits = self.score(hidden_states)
1334
+
1335
+ if input_ids is not None:
1336
+ batch_size = input_ids.shape[0]
1337
+ else:
1338
+ batch_size = inputs_embeds.shape[0]
1339
+
1340
+ if self.config.pad_token_id is None and batch_size != 1:
1341
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1342
+ if self.config.pad_token_id is None:
1343
+ sequence_lengths = -1
1344
+ else:
1345
+ if input_ids is not None:
1346
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1347
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1348
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1349
+ sequence_lengths = sequence_lengths.to(logits.device)
1350
+ else:
1351
+ sequence_lengths = -1
1352
+
1353
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1354
+
1355
+ loss = None
1356
+ if labels is not None:
1357
+ labels = labels.to(logits.device)
1358
+ if self.config.problem_type is None:
1359
+ if self.num_labels == 1:
1360
+ self.config.problem_type = "regression"
1361
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1362
+ self.config.problem_type = "single_label_classification"
1363
+ else:
1364
+ self.config.problem_type = "multi_label_classification"
1365
+
1366
+ if self.config.problem_type == "regression":
1367
+ loss_fct = MSELoss()
1368
+ if self.num_labels == 1:
1369
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1370
+ else:
1371
+ loss = loss_fct(pooled_logits, labels)
1372
+ elif self.config.problem_type == "single_label_classification":
1373
+ loss_fct = CrossEntropyLoss()
1374
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1375
+ elif self.config.problem_type == "multi_label_classification":
1376
+ loss_fct = BCEWithLogitsLoss()
1377
+ loss = loss_fct(pooled_logits, labels)
1378
+ if not return_dict:
1379
+ output = (pooled_logits,) + transformer_outputs[1:]
1380
+ return ((loss,) + output) if loss is not None else output
1381
+
1382
+ return SequenceClassifierOutputWithPast(
1383
+ loss=loss,
1384
+ logits=pooled_logits,
1385
+ past_key_values=transformer_outputs.past_key_values,
1386
+ hidden_states=transformer_outputs.hidden_states,
1387
+ attentions=transformer_outputs.attentions,
1388
+ )
1389
+
1390
+
1391
+ StableLmConfig.register_for_auto_class()
1392
+ StableLmForCausalLM.register_for_auto_class("AutoModelForCausalLM")