zinoubm commited on
Commit
9509760
·
verified ·
1 Parent(s): 4d2d99a

Upload StableLMEpochForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "stabilityai/ar-stablelm-2-chat",
3
+ "architectures": [
4
+ "StableLMEpochForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_stablelm_epoch.StableLMEpochConfig",
8
+ "AutoModelForCausalLM": "modeling_stablelm_epoch.StableLMEpochForCausalLM"
9
+ },
10
+ "bos_token_id": 100257,
11
+ "eos_token_id": 100278,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 2048,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 5632,
16
+ "max_position_embeddings": 4096,
17
+ "model_type": "stablelm_epoch",
18
+ "norm_eps": 1e-05,
19
+ "num_attention_heads": 32,
20
+ "num_heads": 32,
21
+ "num_hidden_layers": 24,
22
+ "num_key_value_heads": 32,
23
+ "rope_pct": 0.25,
24
+ "rope_theta": 10000,
25
+ "rotary_scaling_factor": 1.0,
26
+ "tie_word_embeddings": false,
27
+ "torch_dtype": "float16",
28
+ "transformers_version": "4.47.1",
29
+ "use_cache": false,
30
+ "use_qkv_bias": true,
31
+ "vocab_size": 100352
32
+ }
configuration_stablelm_epoch.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Stability and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """ StableLM Epoch model configuration"""
15
+ from transformers import PretrainedConfig
16
+ from transformers.utils import logging
17
+
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class StableLMEpochConfig(PretrainedConfig):
23
+ r"""
24
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
25
+ documentation from [`PretrainedConfig`] for more information.
26
+
27
+ Args:
28
+ vocab_size (`int`, *optional*, defaults to 50_304):
29
+ Vocabulary size of the StableLM model. Defines the number of different tokens that
30
+ can be represented by the `inputs_ids` passed when calling [`StableLMEpochModel`].
31
+ intermediate_size (`int`, *optional*, defaults to 6912):
32
+ Dimension of the MLP representations.
33
+ hidden_size (`int`, *optional*, defaults to 2560):
34
+ Dimension of the decoder layers and the pooler layer.
35
+ num_hidden_layers (`int`, *optional*, defaults to 32):
36
+ Number of hidden layers in the Transformer decoder.
37
+ num_attention_heads (`int`, *optional*, defaults to 32):
38
+ Number of attention heads for each attention layer in the Transformer encoder.
39
+ num_key_value_heads (`int`, *optional*):
40
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
41
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
42
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
43
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
44
+ by meanpooling all the original heads within that group. For more details checkout [this
45
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
46
+ `num_attention_heads`.
47
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
48
+ The non-linear activation function (function or string).
49
+ rope_pct (`float`, *optional*, defaults to 1.0):
50
+ Percentage of hidden dimensions to allocate to rotary embeddings.
51
+ rope_theta (`float`, *optional*, defaults to 10000.0):
52
+ The base period of the RoPE embeddings.
53
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
54
+ The maximum sequence length that this model might ever be used with.
55
+ Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
56
+ initializer_range (`float`, *optional*, defaults to 1e-5):
57
+ The standard deviation of the truncated_normal_initializer for initializing
58
+ all weight matrices.
59
+ norm_eps (`float`, *optional*, defaults to 1e-8):
60
+ The epsilon used by the normalization layers.
61
+ use_cache (`bool`, *optional*, defaults to `True`):
62
+ Whether or not the model should return the last key/values attentions
63
+ (not used by all models). Only relevant if `config.is_decoder=True`.
64
+ use_qkv_bias (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should use bias for qkv layers.
66
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
67
+ Whether to tie weight embeddings
68
+ """
69
+ model_type = "stablelm_epoch"
70
+ keys_to_ignore_at_inference = ["past_key_values"]
71
+
72
+ def __init__(
73
+ self,
74
+ vocab_size=50_304,
75
+ intermediate_size=6912,
76
+ hidden_size=2560,
77
+ num_hidden_layers=32,
78
+ num_attention_heads=32,
79
+ num_key_value_heads=32,
80
+ hidden_act="silu",
81
+ rope_pct=0.25,
82
+ rope_theta=10_000,
83
+ max_position_embeddings=4096,
84
+ initializer_range=0.02,
85
+ norm_eps=1.0e-5,
86
+ use_cache=True,
87
+ use_qkv_bias=True,
88
+ bos_token_id=0,
89
+ eos_token_id=2,
90
+ tie_word_embeddings=False,
91
+ **kwargs,
92
+ ):
93
+ self.vocab_size = vocab_size
94
+ self.max_position_embeddings = max_position_embeddings
95
+ self.intermediate_size = intermediate_size
96
+ self.hidden_size = hidden_size
97
+ self.num_hidden_layers = num_hidden_layers
98
+ self.num_attention_heads = num_attention_heads
99
+ self.num_key_value_heads = num_key_value_heads
100
+ self.hidden_act = hidden_act
101
+ self.rope_pct = rope_pct
102
+ self.rope_theta = rope_theta
103
+ self.initializer_range = initializer_range
104
+ self.norm_eps = norm_eps
105
+ self.use_cache = use_cache
106
+ self.use_qkv_bias = use_qkv_bias
107
+ self.tie_word_embeddings = tie_word_embeddings
108
+ super().__init__(
109
+ bos_token_id=bos_token_id,
110
+ eos_token_id=eos_token_id,
111
+ tie_word_embeddings=tie_word_embeddings,
112
+ **kwargs,
113
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 100257,
4
+ "do_sample": true,
5
+ "eos_token_id": 100257,
6
+ "transformers_version": "4.47.1"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94ae8c5568e0f7791382c326f6dd7346e768486fdbc81a945fe23abe5f8fc9be
3
+ size 3289069184
modeling_stablelm_epoch.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Stability AI, EleutherAI, 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
+ #
16
+ # This code is based off the following work:
17
+ # https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
18
+ # https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt_neox/modeling_gpt_neox.py
19
+ """ PyTorch StableLM Epoch model. """
20
+ from typing import Optional, Tuple, Union
21
+ import math
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import CrossEntropyLoss
27
+ from transformers.modeling_outputs import (
28
+ BaseModelOutputWithPast,
29
+ CausalLMOutputWithPast,
30
+ )
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import logging
33
+
34
+ from .configuration_stablelm_epoch import StableLMEpochConfig
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
41
+ def _make_causal_mask(
42
+ input_ids_shape: torch.Size,
43
+ dtype: torch.dtype,
44
+ device: torch.device,
45
+ past_key_values_length: int = 0,
46
+ ):
47
+ """Make causal mask used for bi-directional self-attention."""
48
+ batch_size, tgt_len = input_ids_shape
49
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(torch.float16).min, device=device)
50
+ mask_cond = torch.arange(mask.size(-1), device=device)
51
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
52
+ mask = mask.to(dtype)
53
+ if past_key_values_length > 0:
54
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
55
+ return mask[None, None, :, :].expand(batch_size, 1, tgt_len, tgt_len + past_key_values_length)
56
+
57
+
58
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
59
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
60
+ """Expands attention_mask from `[batch_size, seq_len]` to `[batch_size, 1, tgt_seq_len, src_seq_len]`."""
61
+ batch_size, src_len = mask.size()
62
+ tgt_len = tgt_len if tgt_len is not None else src_len
63
+
64
+ expanded_mask = mask[:, None, None, :].expand(batch_size, 1, tgt_len, src_len).to(dtype)
65
+ inverted_mask = 1.0 - expanded_mask
66
+
67
+ return inverted_mask.masked_fill(
68
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
69
+ )
70
+
71
+
72
+ class RotaryEmbedding(nn.Module):
73
+ def __init__(
74
+ self,
75
+ dim: int,
76
+ max_position_embeddings: int,
77
+ base: int = 10_000,
78
+ device: Optional[torch.device] = None,
79
+ ):
80
+ super().__init__()
81
+
82
+ self.dim = dim
83
+ self.max_position_embeddings = max_position_embeddings
84
+ self.base = base
85
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
86
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
87
+
88
+ # Build here to make `torch.jit.trace` work.
89
+ self._set_cos_sin_cache(
90
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype(),
91
+ )
92
+
93
+ def _set_cos_sin_cache(self, seq_len: int, device: torch.device, dtype: torch.dtype):
94
+ self.max_seq_len_cached = seq_len
95
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
96
+
97
+ # Don't do einsum, it converts fp32 to fp16 under AMP
98
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
99
+ freqs = torch.outer(t, self.inv_freq)
100
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
101
+ emb = torch.cat((freqs, freqs), dim=-1)
102
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
103
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
104
+
105
+ def forward(self, x: torch.Tensor, seq_len: Optional[int] = None):
106
+ # x: [batch_size, num_heads, seq_len, head_size]
107
+ if seq_len > self.max_seq_len_cached:
108
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.get_default_dtype())
109
+ return (
110
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
111
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
112
+ )
113
+
114
+
115
+ def rotate_half(x: torch.Tensor):
116
+ """Rotates half the hidden dims of the input."""
117
+ x1, x2 = torch.chunk(x, 2, dim=-1)
118
+ return torch.cat((-x2, x1), dim=-1)
119
+
120
+
121
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
122
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
123
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
124
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
125
+ cos = cos[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]
126
+ sin = sin[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]
127
+ q_embed = (q * cos) + (rotate_half(q) * sin)
128
+ k_embed = (k * cos) + (rotate_half(k) * sin)
129
+ return q_embed, k_embed
130
+
131
+
132
+ class MLP(nn.Module):
133
+ def __init__(self, config: StableLMEpochConfig):
134
+ super().__init__()
135
+ self.config = config
136
+ self.hidden_size = config.hidden_size
137
+ self.intermediate_size = config.intermediate_size
138
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
139
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
140
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
141
+ self.act_fn = nn.SiLU()
142
+
143
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
144
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
145
+
146
+
147
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
148
+ """
149
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
150
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
151
+ """
152
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
153
+ if n_rep == 1:
154
+ return hidden_states
155
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
156
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
157
+
158
+
159
+ class Attention(nn.Module):
160
+ def __init__(self, config: StableLMEpochConfig):
161
+ super().__init__()
162
+ self.config = config
163
+ self.hidden_size = config.hidden_size
164
+ self.num_heads = config.num_attention_heads
165
+ self.head_dim = self.hidden_size // self.num_heads
166
+ self.num_key_value_heads = config.num_key_value_heads
167
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
168
+ self.max_position_embeddings = config.max_position_embeddings
169
+
170
+ if (self.head_dim * self.num_heads) != self.hidden_size:
171
+ raise ValueError(
172
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
173
+ f" and `num_heads`: {self.num_heads})."
174
+ )
175
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.use_qkv_bias)
176
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)
177
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.use_qkv_bias)
178
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
179
+
180
+ self._init_rope()
181
+
182
+ def _init_rope(self):
183
+ self.rotary_ndims = int(self.head_dim * self.config.rope_pct)
184
+ self.rotary_emb = RotaryEmbedding(
185
+ self.rotary_ndims,
186
+ max_position_embeddings=self.config.max_position_embeddings,
187
+ base=self.config.rope_theta,
188
+ )
189
+
190
+ def forward(
191
+ self,
192
+ hidden_states: torch.FloatTensor,
193
+ attention_mask: torch.FloatTensor,
194
+ position_ids: torch.LongTensor,
195
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
196
+ output_attentions: Optional[bool] = False,
197
+ use_cache: Optional[bool] = False,
198
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
199
+ bsz, q_len, _ = hidden_states.size()
200
+
201
+ query_states = self.q_proj(hidden_states)
202
+ key_states = self.k_proj(hidden_states)
203
+ value_states = self.v_proj(hidden_states)
204
+
205
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
206
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
207
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
208
+
209
+ query_rot = query_states[..., : self.rotary_ndims]
210
+ query_pass = query_states[..., self.rotary_ndims :]
211
+ key_rot = key_states[..., : self.rotary_ndims]
212
+ key_pass = key_states[..., self.rotary_ndims :]
213
+
214
+ kv_seq_len = key_states.shape[-2]
215
+ if past_key_value is not None:
216
+ kv_seq_len += past_key_value[0].shape[-2]
217
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
218
+ query_states, key_states = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
219
+
220
+ # [batch_size, num_heads, seq_len, head_dim]
221
+ query_states = torch.cat((query_states, query_pass), dim=-1)
222
+ key_states = torch.cat((key_states, key_pass), dim=-1)
223
+
224
+ if past_key_value is not None:
225
+ # Reuse k, v, self_attention
226
+ key_states = torch.cat((past_key_value[0], key_states), dim=2)
227
+ value_states = torch.cat((past_key_value[1], value_states), dim=2)
228
+
229
+ past_key_value = (key_states, value_states) if use_cache else None
230
+
231
+ # Repeat k/v heads if n_kv_heads < n_heads
232
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
233
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
234
+
235
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
236
+
237
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
238
+ raise ValueError(
239
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
240
+ f" {attn_weights.size()}"
241
+ )
242
+
243
+ if attention_mask is not None:
244
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
245
+ raise ValueError(
246
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
247
+ )
248
+ attn_weights = attn_weights + attention_mask
249
+
250
+ # Upcast attention to fp32
251
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
252
+ attn_output = torch.matmul(attn_weights, value_states)
253
+
254
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
255
+ raise ValueError(
256
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
257
+ f" {attn_output.size()}"
258
+ )
259
+
260
+ # Merge heads
261
+ attn_output = attn_output.transpose(1, 2).contiguous()
262
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
263
+
264
+ # Final linear projection
265
+ attn_output = self.o_proj(attn_output)
266
+
267
+ if not output_attentions:
268
+ attn_weights = None
269
+
270
+ return attn_output, attn_weights, past_key_value
271
+
272
+
273
+ class DecoderLayer(nn.Module):
274
+ def __init__(self, config: StableLMEpochConfig):
275
+ super().__init__()
276
+ self.self_attn = Attention(config)
277
+ self.mlp = MLP(config)
278
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
279
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
280
+
281
+ def forward(
282
+ self,
283
+ hidden_states: Optional[torch.FloatTensor],
284
+ attention_mask: Optional[torch.FloatTensor] = None,
285
+ position_ids: Optional[torch.LongTensor] = None,
286
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
287
+ output_attentions: Optional[bool] = False,
288
+ use_cache: Optional[bool] = False,
289
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
290
+ residual = hidden_states
291
+
292
+ hidden_states = self.input_layernorm(hidden_states)
293
+
294
+ # Self Attention
295
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
296
+ hidden_states=hidden_states,
297
+ attention_mask=attention_mask,
298
+ position_ids=position_ids,
299
+ past_key_value=past_key_value,
300
+ output_attentions=output_attentions,
301
+ use_cache=use_cache,
302
+ )
303
+ hidden_states = residual + hidden_states
304
+
305
+ # Fully Connected
306
+ residual = hidden_states
307
+ hidden_states = self.post_attention_layernorm(hidden_states)
308
+ hidden_states = self.mlp(hidden_states)
309
+ hidden_states = residual + hidden_states
310
+
311
+ outputs = (hidden_states,)
312
+
313
+ if output_attentions:
314
+ outputs += (self_attn_weights,)
315
+
316
+ if use_cache:
317
+ outputs += (present_key_value,)
318
+
319
+ return outputs
320
+
321
+
322
+ class StableLMEpochPreTrainedModel(PreTrainedModel):
323
+ """An abstract class to handle weights initialization and a simple interface
324
+ for downloading and loading pretrained models.
325
+ """
326
+
327
+ config_class = StableLMEpochConfig
328
+ base_model_prefix = "transformer"
329
+ supports_gradient_checkpointing = True
330
+ _no_split_modules = ["DecoderLayer"]
331
+ _skip_keys_device_placement = "past_key_values"
332
+
333
+ def _init_weights(self, module: nn.Module):
334
+ """Initialize the weights"""
335
+ if isinstance(module, nn.Linear):
336
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
337
+ if module.bias is not None:
338
+ module.bias.data.zero_()
339
+ elif isinstance(module, nn.Embedding):
340
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
341
+ if module.padding_idx is not None:
342
+ module.weight.data[module.padding_idx].zero_()
343
+ elif isinstance(module, nn.LayerNorm):
344
+ module.bias.data.zero_()
345
+ module.weight.data.fill_(1.0)
346
+
347
+ def _set_gradient_checkpointing(self, module: nn.Module, value=False):
348
+ if isinstance(module, StableLMEpochModel):
349
+ module.gradient_checkpointing = value
350
+
351
+
352
+ class StableLMEpochModel(StableLMEpochPreTrainedModel):
353
+ def __init__(self, config: StableLMEpochConfig):
354
+ super().__init__(config)
355
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
356
+ self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
357
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
358
+
359
+ self.gradient_checkpointing = False
360
+ # Initialize weights and apply final processing
361
+ self.post_init()
362
+
363
+ def get_input_embeddings(self):
364
+ return self.embed_tokens
365
+
366
+ def set_input_embeddings(self, value: nn.Module):
367
+ self.embed_tokens = value
368
+
369
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
370
+ def _prepare_decoder_attention_mask(
371
+ self,
372
+ attention_mask: torch.Tensor,
373
+ input_shape: torch.Size,
374
+ inputs_embeds: torch.Tensor,
375
+ past_key_values_length: int,
376
+ ):
377
+ # Create causal mask
378
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
379
+ combined_attention_mask = None
380
+ if input_shape[-1] > 1:
381
+ combined_attention_mask = _make_causal_mask(
382
+ input_shape,
383
+ inputs_embeds.dtype,
384
+ device=inputs_embeds.device,
385
+ past_key_values_length=past_key_values_length,
386
+ )
387
+
388
+ if attention_mask is not None:
389
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
390
+ expanded_attn_mask = _expand_mask(
391
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
392
+ ).to(inputs_embeds.device)
393
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
394
+
395
+ return combined_attention_mask
396
+
397
+ def forward(
398
+ self,
399
+ input_ids: Optional[torch.LongTensor] = None,
400
+ attention_mask: Optional[torch.FloatTensor] = None,
401
+ position_ids: Optional[torch.LongTensor] = None,
402
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
403
+ inputs_embeds: Optional[torch.FloatTensor] = None,
404
+ use_cache: Optional[bool] = None,
405
+ output_attentions: Optional[bool] = None,
406
+ output_hidden_states: Optional[bool] = None,
407
+ return_dict: Optional[bool] = None,
408
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
409
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
410
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
411
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
412
+
413
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
414
+
415
+ # Retrieve input_ids and inputs_embeds
416
+ if input_ids is not None and inputs_embeds is not None:
417
+ raise ValueError(
418
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
419
+ )
420
+ elif input_ids is not None:
421
+ batch_size, seq_length = input_ids.shape
422
+ elif inputs_embeds is not None:
423
+ batch_size, seq_length, _ = inputs_embeds.shape
424
+ else:
425
+ raise ValueError(
426
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
427
+ )
428
+
429
+ seq_length_with_past = seq_length
430
+ past_key_values_length = 0
431
+
432
+ if past_key_values is not None:
433
+ past_key_values_length = past_key_values[0][0].shape[2]
434
+ seq_length_with_past = seq_length_with_past + past_key_values_length
435
+
436
+ if position_ids is None:
437
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
438
+ position_ids = torch.arange(
439
+ past_key_values_length,
440
+ seq_length + past_key_values_length,
441
+ dtype=torch.long,
442
+ device=device,
443
+ )
444
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
445
+ else:
446
+ position_ids = position_ids.view(-1, seq_length).long()
447
+
448
+ if inputs_embeds is None:
449
+ inputs_embeds = self.embed_tokens(input_ids)
450
+ # Embed positions
451
+ if attention_mask is None:
452
+ attention_mask = torch.ones(
453
+ (batch_size, seq_length_with_past),
454
+ dtype=torch.bool,
455
+ device=inputs_embeds.device,
456
+ )
457
+ attention_mask = self._prepare_decoder_attention_mask(
458
+ attention_mask,
459
+ (batch_size, seq_length),
460
+ inputs_embeds,
461
+ past_key_values_length,
462
+ )
463
+
464
+ hidden_states = inputs_embeds
465
+
466
+ if self.gradient_checkpointing and self.training:
467
+ if use_cache:
468
+ logger.warning(
469
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
470
+ )
471
+ use_cache = False
472
+
473
+ # Decoder layers
474
+ all_hidden_states = () if output_hidden_states else None
475
+ all_self_attns = () if output_attentions else None
476
+ next_decoder_cache = () if use_cache else None
477
+
478
+ for idx, decoder_layer in enumerate(self.layers):
479
+ if output_hidden_states:
480
+ all_hidden_states += (hidden_states,)
481
+
482
+ past_key_value = (
483
+ past_key_values[idx] if past_key_values is not None else None
484
+ )
485
+
486
+ if self.gradient_checkpointing and self.training:
487
+
488
+ def create_custom_forward(module):
489
+ def custom_forward(*inputs):
490
+ # None for past_key_value
491
+ return module(*inputs, past_key_value, output_attentions)
492
+
493
+ return custom_forward
494
+
495
+ layer_outputs = torch.utils.checkpoint.checkpoint(
496
+ create_custom_forward(decoder_layer),
497
+ hidden_states,
498
+ attention_mask,
499
+ position_ids,
500
+ )
501
+ else:
502
+ layer_outputs = decoder_layer(
503
+ hidden_states,
504
+ attention_mask=attention_mask,
505
+ position_ids=position_ids,
506
+ past_key_value=past_key_value,
507
+ output_attentions=output_attentions,
508
+ use_cache=use_cache,
509
+ )
510
+
511
+ hidden_states = layer_outputs[0]
512
+
513
+ if use_cache:
514
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
515
+
516
+ if output_attentions:
517
+ all_self_attns += (layer_outputs[1],)
518
+
519
+ hidden_states = self.norm(hidden_states)
520
+
521
+ # Add hidden states from the last decoder layer
522
+ if output_hidden_states:
523
+ all_hidden_states += (hidden_states,)
524
+
525
+ next_cache = next_decoder_cache if use_cache else None
526
+ if not return_dict:
527
+ return tuple(
528
+ v
529
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
530
+ if v is not None
531
+ )
532
+ return BaseModelOutputWithPast(
533
+ last_hidden_state=hidden_states,
534
+ past_key_values=next_cache,
535
+ hidden_states=all_hidden_states,
536
+ attentions=all_self_attns,
537
+ )
538
+
539
+
540
+ class StableLMEpochForCausalLM(StableLMEpochPreTrainedModel):
541
+ _tied_weights_keys = ["lm_head.weight"]
542
+
543
+ def __init__(self, config: StableLMEpochConfig):
544
+ super().__init__(config)
545
+
546
+ self.model = StableLMEpochModel(config)
547
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
548
+
549
+ # Initialize weights and apply final processing
550
+ self.post_init()
551
+
552
+ def get_input_embeddings(self):
553
+ return self.model.embed_tokens
554
+
555
+ def set_input_embeddings(self, value):
556
+ self.model.embed_tokens = value
557
+
558
+ def get_output_embeddings(self):
559
+ return self.lm_head
560
+
561
+ def set_output_embeddings(self, new_embeddings: nn.Module):
562
+ self.lm_head = new_embeddings
563
+
564
+ def get_decoder(self):
565
+ return self.model
566
+
567
+ def set_decoder(self, decoder):
568
+ self.model = decoder
569
+
570
+ def forward(
571
+ self,
572
+ input_ids: Optional[torch.LongTensor] = None,
573
+ attention_mask: Optional[torch.FloatTensor] = None,
574
+ position_ids: Optional[torch.LongTensor] = None,
575
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
576
+ inputs_embeds: Optional[torch.FloatTensor] = None,
577
+ labels: Optional[torch.LongTensor] = None,
578
+ use_cache: Optional[bool] = None,
579
+ output_attentions: Optional[bool] = None,
580
+ output_hidden_states: Optional[bool] = None,
581
+ return_dict: Optional[bool] = None,
582
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
583
+ output_attentions = (
584
+ output_attentions
585
+ if output_attentions is not None
586
+ else self.config.output_attentions
587
+ )
588
+ output_hidden_states = (
589
+ output_hidden_states
590
+ if output_hidden_states is not None
591
+ else self.config.output_hidden_states
592
+ )
593
+ return_dict = (
594
+ return_dict if return_dict is not None else self.config.use_return_dict
595
+ )
596
+
597
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
598
+ outputs = self.model(
599
+ input_ids,
600
+ attention_mask=attention_mask,
601
+ position_ids=position_ids,
602
+ past_key_values=past_key_values,
603
+ inputs_embeds=inputs_embeds,
604
+ use_cache=use_cache,
605
+ output_attentions=output_attentions,
606
+ output_hidden_states=output_hidden_states,
607
+ return_dict=return_dict,
608
+ )
609
+
610
+ hidden_states = outputs[0]
611
+ logits = self.lm_head(hidden_states).float()
612
+
613
+ loss = None
614
+ if labels is not None:
615
+ # Shift so that tokens < n predict n
616
+ shift_logits = logits[..., :-1, :].contiguous()
617
+ shift_labels = labels[..., 1:].contiguous()
618
+ # Flatten the tokens
619
+ loss_fct = CrossEntropyLoss()
620
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
621
+ shift_labels = shift_labels.view(-1)
622
+ # Enable model parallelism
623
+ shift_labels = shift_labels.to(shift_logits.device)
624
+ loss = loss_fct(shift_logits, shift_labels)
625
+
626
+ if not return_dict:
627
+ output = (logits,) + outputs[1:]
628
+ return (loss,) + output if loss is not None else output
629
+
630
+ return CausalLMOutputWithPast(
631
+ loss=loss,
632
+ logits=logits,
633
+ past_key_values=outputs.past_key_values,
634
+ hidden_states=outputs.hidden_states,
635
+ attentions=outputs.attentions,
636
+ )
637
+
638
+ def prepare_inputs_for_generation(
639
+ self,
640
+ input_ids,
641
+ past_key_values: Optional[torch.Tensor] = None,
642
+ attention_mask: Optional[torch.Tensor] = None,
643
+ inputs_embeds: Optional[torch.Tensor] = None,
644
+ **kwargs,
645
+ ):
646
+ # Trim decoder_input_ids if past is used
647
+ if past_key_values and past_key_values[0] is not None:
648
+ input_ids = input_ids[:, -1:]
649
+
650
+ position_ids = kwargs.get("position_ids", None)
651
+ if attention_mask is not None and position_ids is None:
652
+ # Create position_ids on the fly for batch generation
653
+ position_ids = attention_mask.long().cumsum(-1) - 1
654
+ position_ids.masked_fill_(attention_mask == 0, 1)
655
+ if past_key_values:
656
+ position_ids = position_ids[:, -1].unsqueeze(-1)
657
+
658
+ # If `inputs_embeds` are passed, we only want to use them in the 1st generation step
659
+ if inputs_embeds is not None and past_key_values is None:
660
+ model_inputs = {"inputs_embeds": inputs_embeds}
661
+ else:
662
+ model_inputs = {"input_ids": input_ids}
663
+
664
+ model_inputs.update(
665
+ {
666
+ "attention_mask": attention_mask,
667
+ "past_key_values": past_key_values,
668
+ "use_cache": kwargs.get("use_cache"),
669
+ "position_ids": position_ids,
670
+ }
671
+ )
672
+ return model_inputs
673
+
674
+ @staticmethod
675
+ def _reorder_cache(past_key_values, beam_idx):
676
+ reordered_past = ()
677
+ for layer_past in past_key_values:
678
+ reordered_past += (
679
+ tuple(
680
+ past_state.index_select(0, beam_idx.to(past_state.device))
681
+ for past_state in layer_past
682
+ ),
683
+ )
684
+ return reordered_past
685
+
686
+
687
+ StableLMEpochConfig.register_for_auto_class()
688
+ StableLMEpochForCausalLM.register_for_auto_class("AutoModelForCausalLM")