ziadrone commited on
Commit
5e041d9
·
verified ·
1 Parent(s): e239203

Upload ShivikM4ForCausalLM

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +22 -0
  3. generation_config.json +4 -0
  4. model.safetensors +3 -0
  5. modeling_shivik_m4.py +331 -0
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,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ShivikM4ForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_shivik_m4.ShivikM4Config",
7
+ "AutoModelForCausalLM": "modeling_shivik_m4.ShivikM4ForCausalLM"
8
+ },
9
+ "dtype": "bfloat16",
10
+ "head_dim": 64,
11
+ "hidden_size": 2048,
12
+ "intermediate_size": 8192,
13
+ "max_position_embeddings": 4096,
14
+ "model_type": "shivik_m4",
15
+ "num_attention_heads": 32,
16
+ "num_hidden_layers": 24,
17
+ "num_key_value_heads": 32,
18
+ "rms_norm_eps": 1e-05,
19
+ "rope_theta": 100000.0,
20
+ "transformers_version": "4.57.3",
21
+ "vocab_size": 49179
22
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.57.3"
4
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30c64883c2a3cc74dcad686748325e36a75ff601668a3a54ede9c3a02abf63d2
3
+ size 3422888544
modeling_shivik_m4.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SHIVIK-M4 Model Architecture (SmolLM2-Compatible)
3
+ ==================================================
4
+ Matched to SmolLM2-1.7B for weight loading:
5
+ - 24 layers, 2048 hidden, 32 heads (MHA - all heads are KV heads)
6
+ - Full RoPE, SwiGLU MLP, RMSNorm
7
+ """
8
+
9
+ import math
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+
14
+ from transformers import PreTrainedModel, PretrainedConfig
15
+ from transformers.generation import GenerationMixin
16
+ from transformers.modeling_outputs import CausalLMOutputWithPast
17
+
18
+
19
+ class ShivikM4Config(PretrainedConfig):
20
+ model_type = "shivik_m4"
21
+
22
+ def __init__(
23
+ self,
24
+ vocab_size=49152,
25
+ hidden_size=2048,
26
+ intermediate_size=8192,
27
+ num_hidden_layers=24,
28
+ num_attention_heads=32,
29
+ num_key_value_heads=32, # MHA for SmolLM2 compatibility
30
+ head_dim=64,
31
+ rms_norm_eps=1e-5,
32
+ max_position_embeddings=4096,
33
+ rope_theta=100000.0,
34
+ tie_word_embeddings=True,
35
+ **kwargs,
36
+ ):
37
+ self.vocab_size = vocab_size
38
+ self.hidden_size = hidden_size
39
+ self.intermediate_size = intermediate_size
40
+ self.num_hidden_layers = num_hidden_layers
41
+ self.num_attention_heads = num_attention_heads
42
+ self.num_key_value_heads = num_key_value_heads
43
+ self.head_dim = head_dim
44
+ self.rms_norm_eps = rms_norm_eps
45
+ self.max_position_embeddings = max_position_embeddings
46
+ self.rope_theta = rope_theta
47
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
48
+
49
+
50
+ class ShivikM4RMSNorm(nn.Module):
51
+ def __init__(self, dim, eps=1e-5):
52
+ super().__init__()
53
+ self.eps = eps
54
+ self.weight = nn.Parameter(torch.ones(dim))
55
+
56
+ def forward(self, x):
57
+ dtype = x.dtype
58
+ x = x.float()
59
+ norm = x.pow(2).mean(-1, keepdim=True)
60
+ x = x * torch.rsqrt(norm + self.eps)
61
+ return (self.weight * x).to(dtype)
62
+
63
+
64
+ class ShivikM4RotaryEmbedding(nn.Module):
65
+ def __init__(self, dim, max_position_embeddings, base=10000.0):
66
+ super().__init__()
67
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
68
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
69
+ self.max_seq_len_cached = max_position_embeddings
70
+ self._set_cos_sin_cache(max_position_embeddings)
71
+
72
+ def _set_cos_sin_cache(self, seq_len):
73
+ self.max_seq_len_cached = seq_len
74
+ t = torch.arange(seq_len, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
75
+ freqs = torch.outer(t, self.inv_freq)
76
+ emb = torch.cat([freqs, freqs], dim=-1)
77
+ self.register_buffer("cos_cached", emb.cos().unsqueeze(0).unsqueeze(0), persistent=False)
78
+ self.register_buffer("sin_cached", emb.sin().unsqueeze(0).unsqueeze(0), persistent=False)
79
+
80
+ def forward(self, x, seq_len):
81
+ if seq_len > self.max_seq_len_cached:
82
+ self._set_cos_sin_cache(seq_len)
83
+ return (
84
+ self.cos_cached[:, :, :seq_len, :].to(x.dtype),
85
+ self.sin_cached[:, :, :seq_len, :].to(x.dtype),
86
+ )
87
+
88
+
89
+ def rotate_half(x):
90
+ x1, x2 = x.chunk(2, dim=-1)
91
+ return torch.cat((-x2, x1), dim=-1)
92
+
93
+
94
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
95
+ cos = cos.squeeze(0).squeeze(0)
96
+ sin = sin.squeeze(0).squeeze(0)
97
+ cos = cos[position_ids].unsqueeze(1)
98
+ sin = sin[position_ids].unsqueeze(1)
99
+ q_embed = (q * cos) + (rotate_half(q) * sin)
100
+ k_embed = (k * cos) + (rotate_half(k) * sin)
101
+ return q_embed, k_embed
102
+
103
+
104
+ class ShivikM4Attention(nn.Module):
105
+ def __init__(self, config: ShivikM4Config):
106
+ super().__init__()
107
+ self.hidden_size = config.hidden_size
108
+ self.num_heads = config.num_attention_heads
109
+ self.head_dim = config.head_dim
110
+ self.num_kv_heads = config.num_key_value_heads
111
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
112
+ self.scale = 1.0 / math.sqrt(self.head_dim)
113
+
114
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
115
+ self.k_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
116
+ self.v_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
117
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
118
+
119
+ self.rotary_emb = ShivikM4RotaryEmbedding(
120
+ self.head_dim, config.max_position_embeddings, config.rope_theta
121
+ )
122
+
123
+ def forward(
124
+ self,
125
+ hidden_states,
126
+ attention_mask=None,
127
+ position_ids=None,
128
+ past_key_value=None,
129
+ use_cache=False,
130
+ ):
131
+ bsz, q_len, _ = hidden_states.size()
132
+
133
+ q = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
134
+ k = self.k_proj(hidden_states).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
135
+ v = self.v_proj(hidden_states).view(bsz, q_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
136
+
137
+ past_kv_len = 0
138
+ if past_key_value is not None and past_key_value[0] is not None:
139
+ past_kv_len = past_key_value[0].shape[2]
140
+
141
+ cos, sin = self.rotary_emb(v, seq_len=past_kv_len + q_len)
142
+ q, k = apply_rotary_pos_emb(q, k, cos, sin, position_ids)
143
+
144
+ if past_key_value is not None and past_key_value[0] is not None:
145
+ k = torch.cat([past_key_value[0], k], dim=2)
146
+ v = torch.cat([past_key_value[1], v], dim=2)
147
+
148
+ present_kv = (k, v) if use_cache else None
149
+
150
+ # GQA expansion (for MHA, num_kv_groups=1, so this is a no-op)
151
+ if self.num_kv_groups > 1:
152
+ k_expanded = k.repeat_interleave(self.num_kv_groups, dim=1)
153
+ v_expanded = v.repeat_interleave(self.num_kv_groups, dim=1)
154
+ else:
155
+ k_expanded = k
156
+ v_expanded = v
157
+
158
+ attn_weights = torch.matmul(q, k_expanded.transpose(2, 3)) * self.scale
159
+
160
+ if attention_mask is not None:
161
+ attn_weights = attn_weights + attention_mask
162
+
163
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
164
+ attn_output = torch.matmul(attn_weights, v_expanded)
165
+
166
+ attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, q_len, self.hidden_size)
167
+ return self.o_proj(attn_output), present_kv
168
+
169
+
170
+ class ShivikM4MLP(nn.Module):
171
+ def __init__(self, config):
172
+ super().__init__()
173
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
174
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
175
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
176
+
177
+ def forward(self, x):
178
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
179
+
180
+
181
+ class ShivikM4DecoderLayer(nn.Module):
182
+ def __init__(self, config):
183
+ super().__init__()
184
+ self.input_layernorm = ShivikM4RMSNorm(config.hidden_size, config.rms_norm_eps)
185
+ self.self_attn = ShivikM4Attention(config)
186
+ self.post_attention_layernorm = ShivikM4RMSNorm(config.hidden_size, config.rms_norm_eps)
187
+ self.mlp = ShivikM4MLP(config)
188
+
189
+ def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None, use_cache=False):
190
+ residual = hidden_states
191
+ hidden_states = self.input_layernorm(hidden_states)
192
+ hidden_states, present_kv = self.self_attn(
193
+ hidden_states, attention_mask, position_ids, past_key_value, use_cache
194
+ )
195
+ hidden_states = residual + hidden_states
196
+
197
+ residual = hidden_states
198
+ hidden_states = self.post_attention_layernorm(hidden_states)
199
+ hidden_states = self.mlp(hidden_states)
200
+ hidden_states = residual + hidden_states
201
+
202
+ return hidden_states, present_kv
203
+
204
+
205
+ class ShivikM4Model(PreTrainedModel):
206
+ config_class = ShivikM4Config
207
+
208
+ def __init__(self, config):
209
+ super().__init__(config)
210
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
211
+ self.layers = nn.ModuleList([ShivikM4DecoderLayer(config) for _ in range(config.num_hidden_layers)])
212
+ self.norm = ShivikM4RMSNorm(config.hidden_size, config.rms_norm_eps)
213
+
214
+ def _make_causal_mask(self, q_len, kv_len, dtype, device):
215
+ if q_len == kv_len:
216
+ mask = torch.full((q_len, kv_len), torch.finfo(dtype).min, dtype=dtype, device=device)
217
+ mask = torch.triu(mask, diagonal=1)
218
+ else:
219
+ mask = torch.zeros((q_len, kv_len), dtype=dtype, device=device)
220
+ return mask[None, None, :, :]
221
+
222
+ def forward(self, input_ids, attention_mask=None, position_ids=None, past_key_values=None, use_cache=None):
223
+ bsz, seq_len = input_ids.shape
224
+
225
+ past_len = 0
226
+ if past_key_values is not None and past_key_values[0] is not None and past_key_values[0][0] is not None:
227
+ past_len = past_key_values[0][0].shape[2]
228
+
229
+ if position_ids is None:
230
+ position_ids = torch.arange(past_len, past_len + seq_len, device=input_ids.device).unsqueeze(0)
231
+
232
+ hidden_states = self.embed_tokens(input_ids)
233
+
234
+ kv_len = past_len + seq_len
235
+ causal_mask = self._make_causal_mask(seq_len, kv_len, hidden_states.dtype, hidden_states.device)
236
+
237
+ if attention_mask is not None:
238
+ padding_mask = (1.0 - attention_mask[:, None, None, :].to(hidden_states.dtype)) * torch.finfo(hidden_states.dtype).min
239
+ causal_mask = causal_mask + padding_mask
240
+
241
+ next_cache = () if use_cache else None
242
+ for i, layer in enumerate(self.layers):
243
+ past_kv = past_key_values[i] if past_key_values is not None else None
244
+ hidden_states, present_kv = layer(hidden_states, causal_mask, position_ids, past_kv, use_cache)
245
+ if use_cache:
246
+ next_cache += (present_kv,)
247
+
248
+ hidden_states = self.norm(hidden_states)
249
+ return hidden_states, next_cache
250
+
251
+
252
+ class ShivikM4ForCausalLM(PreTrainedModel, GenerationMixin):
253
+ config_class = ShivikM4Config
254
+ _tied_weights_keys = ["lm_head.weight"]
255
+
256
+ def __init__(self, config):
257
+ super().__init__(config)
258
+ self.model = ShivikM4Model(config)
259
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
260
+ if config.tie_word_embeddings:
261
+ self.lm_head.weight = self.model.embed_tokens.weight
262
+
263
+ def get_input_embeddings(self):
264
+ return self.model.embed_tokens
265
+
266
+ def set_input_embeddings(self, value):
267
+ self.model.embed_tokens = value
268
+
269
+ def get_output_embeddings(self):
270
+ return self.lm_head
271
+
272
+ def set_output_embeddings(self, new_embeddings):
273
+ self.lm_head = new_embeddings
274
+
275
+ def forward(
276
+ self,
277
+ input_ids,
278
+ attention_mask=None,
279
+ position_ids=None,
280
+ past_key_values=None,
281
+ use_cache=None,
282
+ labels=None,
283
+ **kwargs,
284
+ ):
285
+ outputs = self.model(input_ids, attention_mask, position_ids, past_key_values, use_cache)
286
+ hidden_states, past_key_values = outputs
287
+
288
+ logits = self.lm_head(hidden_states)
289
+
290
+ loss = None
291
+ if labels is not None:
292
+ shift_logits = logits[..., :-1, :].contiguous()
293
+ shift_labels = labels[..., 1:].contiguous()
294
+ loss = F.cross_entropy(
295
+ shift_logits.view(-1, self.config.vocab_size),
296
+ shift_labels.view(-1),
297
+ )
298
+
299
+ return CausalLMOutputWithPast(
300
+ loss=loss,
301
+ logits=logits,
302
+ past_key_values=past_key_values,
303
+ )
304
+
305
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **kwargs):
306
+ past_len = 0
307
+ if past_key_values is not None and past_key_values[0] is not None and past_key_values[0][0] is not None:
308
+ past_len = past_key_values[0][0].shape[2]
309
+ input_ids = input_ids[:, -1:]
310
+
311
+ position_ids = torch.arange(
312
+ past_len, past_len + input_ids.shape[1],
313
+ dtype=torch.long, device=input_ids.device
314
+ ).unsqueeze(0)
315
+
316
+ return {
317
+ "input_ids": input_ids,
318
+ "past_key_values": past_key_values,
319
+ "use_cache": kwargs.get("use_cache", True),
320
+ "position_ids": position_ids,
321
+ "attention_mask": attention_mask,
322
+ }
323
+
324
+ @staticmethod
325
+ def _reorder_cache(past_key_values, beam_idx):
326
+ reordered = ()
327
+ for layer_past in past_key_values:
328
+ reordered += (
329
+ tuple(state.index_select(0, beam_idx) for state in layer_past),
330
+ )
331
+ return reordered