SatyaSriVelpuri commited on
Commit
178f6a2
·
verified ·
1 Parent(s): 157989e

Upload modeling_parambharatgen.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_parambharatgen.py +1038 -0
modeling_parambharatgen.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This file is based on Meta's LLaMA model implementation in the Hugging Face Transformers library + Some modifications.
5
+ # source: https://github.com/ArtificialZeng/transformers-Explained/blob/main/src/transformers/models/llama/modeling_llama.py
6
+ #
7
+ # Modifications Copyright (c) 2025 BharatGen
8
+ #
9
+ # Licensed under the MIT License.
10
+ #
11
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ # of this software and associated documentation files (the "Software"), to deal
13
+ # in the Software without restriction, including without limitation the rights
14
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ # copies of the Software, and to permit persons to whom the Software is
16
+ # furnished to do so, subject to the following conditions:
17
+ #
18
+ # The above copyright notice and this permission notice shall be included in all
19
+ # copies or substantial portions of the Software.
20
+ #
21
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ # SOFTWARE.
28
+
29
+ """ PyTorch ParamBharatGen model."""
30
+ import math
31
+ from typing import List, Optional, Tuple, Union
32
+
33
+ import torch
34
+ import torch.nn.functional as F
35
+ import torch.utils.checkpoint
36
+ from torch import nn
37
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
38
+
39
+ from transformers.activations import ACT2FN
40
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
43
+ from .config_parambharatgen import ParamBharatGenConfig
44
+ from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+ _CONFIG_FOR_DOC = "ParamBharatGenConfig"
49
+
50
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
51
+ def _make_causal_mask(
52
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
53
+ ):
54
+ """
55
+ Make causal mask used for bi-directional self-attention.
56
+ """
57
+ bsz, tgt_len = input_ids_shape
58
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
59
+ mask_cond = torch.arange(mask.size(-1), device=device)
60
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
61
+ mask = mask.to(dtype)
62
+
63
+ if past_key_values_length > 0:
64
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
65
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
66
+
67
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
68
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
69
+ """
70
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
71
+ """
72
+ bsz, src_len = mask.size()
73
+ tgt_len = tgt_len if tgt_len is not None else src_len
74
+
75
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
76
+
77
+ inverted_mask = 1.0 - expanded_mask
78
+
79
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
80
+
81
+
82
+ class ParamBharatGenRMSNorm(nn.Module):
83
+ def __init__(self, hidden_size, eps=1e-6):
84
+ """
85
+ ParamBharatGenRMSNorm is equivalent to T5LayerNorm
86
+ """
87
+ super().__init__()
88
+ self.weight = nn.Parameter(torch.ones(hidden_size))
89
+ self.variance_epsilon = eps
90
+
91
+ def forward(self, hidden_states):
92
+ input_dtype = hidden_states.dtype
93
+ hidden_states = hidden_states.to(torch.float32)
94
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
95
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
96
+ return self.weight * hidden_states.to(input_dtype)
97
+
98
+
99
+ class ParamBharatGenRotaryEmbedding(nn.Module):
100
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
101
+ super().__init__()
102
+
103
+ self.dim = dim
104
+ self.max_position_embeddings = max_position_embeddings
105
+ self.base = base
106
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
107
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
108
+
109
+ # Build here to make `torch.jit.trace` work.
110
+ self._set_cos_sin_cache(
111
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
112
+ )
113
+
114
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
115
+ self.max_seq_len_cached = seq_len
116
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
117
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
118
+ emb = torch.cat((freqs, freqs), dim=-1)
119
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
120
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
121
+
122
+ def forward(self, x, seq_len=None):
123
+ if seq_len > self.max_seq_len_cached:
124
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
125
+ return (
126
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
127
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
128
+ )
129
+
130
+
131
+
132
+ class ParamBharatGenLinearScalingRotaryEmbedding(ParamBharatGenRotaryEmbedding):
133
+ """ParamBharatGenRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
134
+
135
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
136
+ self.scaling_factor = scaling_factor
137
+ super().__init__(dim, max_position_embeddings, base, device)
138
+
139
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
140
+ self.max_seq_len_cached = seq_len
141
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
142
+ t = t / self.scaling_factor
143
+
144
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
145
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
146
+ emb = torch.cat((freqs, freqs), dim=-1)
147
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
148
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
149
+
150
+
151
+ class ParamBharatGenDynamicNTKScalingRotaryEmbedding(ParamBharatGenRotaryEmbedding):
152
+ """ParamBharatGenRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
153
+
154
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
155
+ self.scaling_factor = scaling_factor
156
+ super().__init__(dim, max_position_embeddings, base, device)
157
+
158
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
159
+ self.max_seq_len_cached = seq_len
160
+
161
+ if seq_len > self.max_position_embeddings:
162
+ base = self.base * (
163
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
164
+ ) ** (self.dim / (self.dim - 2))
165
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
166
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
167
+
168
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
169
+
170
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
171
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
172
+ emb = torch.cat((freqs, freqs), dim=-1)
173
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
174
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
175
+
176
+
177
+ def rotate_half(x):
178
+ """Rotates half the hidden dims of the input."""
179
+ x1 = x[..., : x.shape[-1] // 2]
180
+ x2 = x[..., x.shape[-1] // 2 :]
181
+ return torch.cat((-x2, x1), dim=-1)
182
+
183
+
184
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
185
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
186
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
187
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
188
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
189
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
190
+ q_embed = (q * cos) + (rotate_half(q) * sin)
191
+ k_embed = (k * cos) + (rotate_half(k) * sin)
192
+ return q_embed, k_embed
193
+
194
+
195
+ class ParamBharatGenMLP(nn.Module):
196
+ def __init__(self, config):
197
+ super().__init__()
198
+ self.config = config
199
+ self.hidden_size = config.hidden_size
200
+ # Use custom_mlp_ratio instead of intermediate_size
201
+ if hasattr(config, 'custom_mlp_ratio'):
202
+ self.intermediate_size = int(config.hidden_size * config.custom_mlp_ratio)
203
+ else:
204
+ self.intermediate_size = config.intermediate_size
205
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
206
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
207
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
208
+ self.act_fn = ACT2FN[config.hidden_act]
209
+
210
+ def forward(self, x):
211
+ if self.config.pretraining_tp > 1:
212
+ slice = self.intermediate_size // self.config.pretraining_tp
213
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
214
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
215
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
216
+
217
+ gate_proj = torch.cat(
218
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
219
+ )
220
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
221
+
222
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
223
+ down_proj = [
224
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
225
+ ]
226
+ down_proj = sum(down_proj)
227
+ else:
228
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
229
+
230
+ return down_proj
231
+
232
+
233
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
234
+ """
235
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
236
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
237
+ """
238
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
239
+ if n_rep == 1:
240
+ return hidden_states
241
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
242
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
243
+
244
+
245
+ class ParamBharatGenAttention(nn.Module):
246
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
247
+
248
+ def __init__(self, config: ParamBharatGenConfig):
249
+ super().__init__()
250
+ self.config = config
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
+
259
+ if (self.head_dim * self.num_heads) != self.hidden_size:
260
+ raise ValueError(
261
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
262
+ f" and `num_heads`: {self.num_heads})."
263
+ )
264
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
265
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
266
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
267
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
268
+ self._init_rope()
269
+
270
+ def _init_rope(self):
271
+ if self.config.rope_scaling is None:
272
+ self.rotary_emb = ParamBharatGenRotaryEmbedding(
273
+ self.head_dim,
274
+ max_position_embeddings=self.max_position_embeddings,
275
+ base=self.rope_theta,
276
+ )
277
+ else:
278
+ rs = self.config.rope_scaling or {}
279
+ scaling_type = rs.get("type", rs.get("rope_type", "linear"))
280
+ scaling_factor = rs.get("factor", rs.get("scaling_factor", 1.0))
281
+ if scaling_type in ("linear", "default"):
282
+ self.rotary_emb = ParamBharatGenLinearScalingRotaryEmbedding(
283
+ self.head_dim,
284
+ max_position_embeddings=self.max_position_embeddings,
285
+ scaling_factor=scaling_factor,
286
+ base=self.rope_theta,
287
+ )
288
+ elif scaling_type == "dynamic":
289
+ self.rotary_emb = ParamBharatGenDynamicNTKScalingRotaryEmbedding(
290
+ self.head_dim,
291
+ max_position_embeddings=self.max_position_embeddings,
292
+ scaling_factor=scaling_factor,
293
+ base=self.rope_theta,
294
+ )
295
+ else:
296
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
297
+
298
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
299
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
300
+
301
+ def forward(
302
+ self,
303
+ hidden_states: torch.Tensor,
304
+ attention_mask: Optional[torch.Tensor] = None,
305
+ position_ids: Optional[torch.LongTensor] = None,
306
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
307
+ output_attentions: bool = False,
308
+ use_cache: bool = False,
309
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
310
+ bsz, q_len, _ = hidden_states.size()
311
+
312
+ if self.config.pretraining_tp > 1:
313
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
314
+ query_slices = self.q_proj.weight.split(
315
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
316
+ )
317
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
318
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
319
+
320
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
321
+ query_states = torch.cat(query_states, dim=-1)
322
+
323
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
324
+ key_states = torch.cat(key_states, dim=-1)
325
+
326
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
327
+ value_states = torch.cat(value_states, dim=-1)
328
+
329
+ else:
330
+ query_states = self.q_proj(hidden_states)
331
+ key_states = self.k_proj(hidden_states)
332
+ value_states = self.v_proj(hidden_states)
333
+
334
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
335
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
336
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
337
+
338
+ kv_seq_len = key_states.shape[-2]
339
+ if past_key_value is not None:
340
+ kv_seq_len += past_key_value[0].shape[-2]
341
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
342
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
343
+
344
+ if past_key_value is not None:
345
+ # reuse k, v, self_attention
346
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
347
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
348
+
349
+ past_key_value = (key_states, value_states) if use_cache else None
350
+
351
+ # repeat k/v heads if n_kv_heads < n_heads
352
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
353
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
354
+
355
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
356
+
357
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
358
+ raise ValueError(
359
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
360
+ f" {attn_weights.size()}"
361
+ )
362
+
363
+ if attention_mask is not None:
364
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
365
+ raise ValueError(
366
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
367
+ )
368
+ attn_weights = attn_weights + attention_mask
369
+
370
+ # upcast attention to fp32
371
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
372
+ attn_output = torch.matmul(attn_weights, value_states)
373
+
374
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
375
+ raise ValueError(
376
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
377
+ f" {attn_output.size()}"
378
+ )
379
+
380
+ attn_output = attn_output.transpose(1, 2).contiguous()
381
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
382
+
383
+ if self.config.pretraining_tp > 1:
384
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
385
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
386
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
387
+ else:
388
+ attn_output = self.o_proj(attn_output)
389
+
390
+ if not output_attentions:
391
+ attn_weights = None
392
+
393
+ return attn_output, attn_weights, past_key_value
394
+
395
+
396
+ class ParamBharatGenDecoderLayer(nn.Module):
397
+ def __init__(self, config: ParamBharatGenConfig):
398
+ super().__init__()
399
+ self.hidden_size = config.hidden_size
400
+ self.self_attn = ParamBharatGenAttention(config=config)
401
+ self.mlp = ParamBharatGenMLP(config)
402
+ self.input_layernorm = ParamBharatGenRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
403
+ self.post_attention_layernorm = ParamBharatGenRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
404
+
405
+ def forward(
406
+ self,
407
+ hidden_states: torch.Tensor,
408
+ attention_mask: Optional[torch.Tensor] = None,
409
+ position_ids: Optional[torch.LongTensor] = None,
410
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
411
+ output_attentions: Optional[bool] = False,
412
+ use_cache: Optional[bool] = False,
413
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
414
+ """
415
+ Args:
416
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
417
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
418
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
419
+ output_attentions (`bool`, *optional*):
420
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
421
+ returned tensors for more detail.
422
+ use_cache (`bool`, *optional*):
423
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
424
+ (see `past_key_values`).
425
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
426
+ """
427
+
428
+ residual = hidden_states
429
+
430
+ hidden_states = self.input_layernorm(hidden_states)
431
+
432
+ # Self Attention
433
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
434
+ hidden_states=hidden_states,
435
+ attention_mask=attention_mask,
436
+ position_ids=position_ids,
437
+ past_key_value=past_key_value,
438
+ output_attentions=output_attentions,
439
+ use_cache=use_cache,
440
+ )
441
+ hidden_states = residual + hidden_states
442
+
443
+ # Fully Connected
444
+ residual = hidden_states
445
+ hidden_states = self.post_attention_layernorm(hidden_states)
446
+ hidden_states = self.mlp(hidden_states)
447
+ hidden_states = residual + hidden_states
448
+
449
+ outputs = (hidden_states,)
450
+
451
+ if output_attentions:
452
+ outputs += (self_attn_weights,)
453
+
454
+ if use_cache:
455
+ outputs += (present_key_value,)
456
+
457
+ return outputs
458
+
459
+
460
+ PARAMBHARATGEN_START_DOCSTRING = r"""
461
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
462
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
463
+ etc.)
464
+
465
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
466
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
467
+ and behavior.
468
+
469
+ Parameters:
470
+ config ([`ParamBharatGenConfig`]):
471
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
472
+ load the weights associated with the model, only the configuration. Check out the
473
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
474
+ """
475
+
476
+
477
+ @add_start_docstrings(
478
+ "The bare ParamBharatGen Model outputting raw hidden-states without any specific head on top.",
479
+ PARAMBHARATGEN_START_DOCSTRING,
480
+ )
481
+ class ParamBharatGenPreTrainedModel(PreTrainedModel):
482
+ config_class = ParamBharatGenConfig
483
+ base_model_prefix = "model"
484
+ supports_gradient_checkpointing = True
485
+ _no_split_modules = ["ParamBharatGenDecoderLayer"]
486
+ _skip_keys_device_placement = "past_key_values"
487
+
488
+ def _init_weights(self, module):
489
+ std = self.config.initializer_range
490
+ if isinstance(module, nn.Linear):
491
+ module.weight.data.normal_(mean=0.0, std=std)
492
+ if module.bias is not None:
493
+ module.bias.data.zero_()
494
+ elif isinstance(module, nn.Embedding):
495
+ module.weight.data.normal_(mean=0.0, std=std)
496
+ if module.padding_idx is not None:
497
+ module.weight.data[module.padding_idx].zero_()
498
+
499
+ def _set_gradient_checkpointing(self, module, value=False):
500
+ if isinstance(module, ParamBharatGenModel):
501
+ module.gradient_checkpointing = value
502
+
503
+
504
+ PARAMBHARATGEN_INPUTS_DOCSTRING = r"""
505
+ Args:
506
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
507
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
508
+ it.
509
+
510
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
511
+ [`PreTrainedTokenizer.__call__`] for details.
512
+
513
+ [What are input IDs?](../glossary#input-ids)
514
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
515
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
516
+
517
+ - 1 for tokens that are **not masked**,
518
+ - 0 for tokens that are **masked**.
519
+
520
+ [What are attention masks?](../glossary#attention-mask)
521
+
522
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
523
+ [`PreTrainedTokenizer.__call__`] for details.
524
+
525
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
526
+ `past_key_values`).
527
+
528
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
529
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
530
+ information on the default strategy.
531
+
532
+ - 1 indicates the head is **not masked**,
533
+ - 0 indicates the head is **masked**.
534
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
535
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
536
+ config.n_positions - 1]`.
537
+
538
+ [What are position IDs?](../glossary#position-ids)
539
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
540
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
541
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
542
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
543
+
544
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
545
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
546
+
547
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
548
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
549
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
550
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
551
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
552
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
553
+ model's internal embedding lookup matrix.
554
+ use_cache (`bool`, *optional*):
555
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
556
+ `past_key_values`).
557
+ output_attentions (`bool`, *optional*):
558
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
559
+ tensors for more detail.
560
+ output_hidden_states (`bool`, *optional*):
561
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
562
+ more detail.
563
+ return_dict (`bool`, *optional*):
564
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
565
+ """
566
+
567
+
568
+ @add_start_docstrings(
569
+ "The bare ParamBharatGen Model outputting raw hidden-states without any specific head on top.",
570
+ PARAMBHARATGEN_START_DOCSTRING,
571
+ )
572
+ class ParamBharatGenModel(ParamBharatGenPreTrainedModel):
573
+ """
574
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ParamBharatGenDecoderLayer`]
575
+
576
+ Args:
577
+ config: ParamBharatGenConfig
578
+ """
579
+ config_class = ParamBharatGenConfig
580
+
581
+ def __init__(self, config: ParamBharatGenConfig):
582
+ super().__init__(config)
583
+ self.padding_idx = config.pad_token_id
584
+ self.vocab_size = config.vocab_size
585
+
586
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
587
+ self.layers = nn.ModuleList([ParamBharatGenDecoderLayer(config) for _ in range(config.num_hidden_layers)])
588
+ self.norm = ParamBharatGenRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
589
+
590
+ self.gradient_checkpointing = False
591
+ # Initialize weights and apply final processing
592
+ self.post_init()
593
+
594
+ def get_input_embeddings(self):
595
+ return self.embed_tokens
596
+
597
+ def set_input_embeddings(self, value):
598
+ self.embed_tokens = value
599
+
600
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
601
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
602
+ # create causal mask
603
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
604
+ combined_attention_mask = None
605
+ if input_shape[-1] > 1:
606
+ combined_attention_mask = _make_causal_mask(
607
+ input_shape,
608
+ inputs_embeds.dtype,
609
+ device=inputs_embeds.device,
610
+ past_key_values_length=past_key_values_length,
611
+ )
612
+
613
+ if attention_mask is not None:
614
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
615
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
616
+ inputs_embeds.device
617
+ )
618
+ combined_attention_mask = (
619
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
620
+ )
621
+
622
+ return combined_attention_mask
623
+
624
+ @add_start_docstrings_to_model_forward(PARAMBHARATGEN_INPUTS_DOCSTRING)
625
+ def forward(
626
+ self,
627
+ input_ids: torch.LongTensor = None,
628
+ attention_mask: Optional[torch.Tensor] = None,
629
+ position_ids: Optional[torch.LongTensor] = None,
630
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
631
+ inputs_embeds: Optional[torch.FloatTensor] = None,
632
+ use_cache: Optional[bool] = None,
633
+ output_attentions: Optional[bool] = None,
634
+ output_hidden_states: Optional[bool] = None,
635
+ return_dict: Optional[bool] = None,
636
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
637
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
638
+ output_hidden_states = (
639
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
640
+ )
641
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
642
+
643
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
644
+
645
+ # retrieve input_ids and inputs_embeds
646
+ if input_ids is not None and inputs_embeds is not None:
647
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
648
+ elif input_ids is not None:
649
+ batch_size, seq_length = input_ids.shape
650
+ elif inputs_embeds is not None:
651
+ batch_size, seq_length, _ = inputs_embeds.shape
652
+ else:
653
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
654
+
655
+ seq_length_with_past = seq_length
656
+ past_key_values_length = 0
657
+
658
+ if past_key_values is not None:
659
+ past_key_values_length = past_key_values[0][0].shape[2]
660
+ seq_length_with_past = seq_length_with_past + past_key_values_length
661
+
662
+ if position_ids is None:
663
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
664
+ position_ids = torch.arange(
665
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
666
+ )
667
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
668
+ else:
669
+ position_ids = position_ids.view(-1, seq_length).long()
670
+
671
+ if inputs_embeds is None:
672
+ inputs_embeds = self.embed_tokens(input_ids)
673
+ # embed positions
674
+ if attention_mask is None:
675
+ attention_mask = torch.ones(
676
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
677
+ )
678
+ attention_mask = self._prepare_decoder_attention_mask(
679
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
680
+ )
681
+
682
+ hidden_states = inputs_embeds
683
+
684
+ if self.gradient_checkpointing and self.training:
685
+ if use_cache:
686
+ logger.warning_once(
687
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
688
+ )
689
+ use_cache = False
690
+
691
+ # decoder layers
692
+ all_hidden_states = () if output_hidden_states else None
693
+ all_self_attns = () if output_attentions else None
694
+ next_decoder_cache = () if use_cache else None
695
+
696
+ for idx, decoder_layer in enumerate(self.layers):
697
+ if output_hidden_states:
698
+ all_hidden_states += (hidden_states,)
699
+
700
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
701
+
702
+ if self.gradient_checkpointing and self.training:
703
+
704
+ def create_custom_forward(module):
705
+ def custom_forward(*inputs):
706
+ # None for past_key_value
707
+ return module(*inputs, past_key_value, output_attentions)
708
+
709
+ return custom_forward
710
+
711
+ layer_outputs = torch.utils.checkpoint.checkpoint(
712
+ create_custom_forward(decoder_layer),
713
+ hidden_states,
714
+ attention_mask,
715
+ position_ids,
716
+ )
717
+ else:
718
+ layer_outputs = decoder_layer(
719
+ hidden_states,
720
+ attention_mask=attention_mask,
721
+ position_ids=position_ids,
722
+ past_key_value=past_key_value,
723
+ output_attentions=output_attentions,
724
+ use_cache=use_cache,
725
+ )
726
+
727
+ hidden_states = layer_outputs[0]
728
+
729
+ if use_cache:
730
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
731
+
732
+ if output_attentions:
733
+ all_self_attns += (layer_outputs[1],)
734
+
735
+ hidden_states = self.norm(hidden_states)
736
+
737
+ # add hidden states from the last decoder layer
738
+ if output_hidden_states:
739
+ all_hidden_states += (hidden_states,)
740
+
741
+ next_cache = next_decoder_cache if use_cache else None
742
+ if not return_dict:
743
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
744
+ return BaseModelOutputWithPast(
745
+ last_hidden_state=hidden_states,
746
+ past_key_values=next_cache,
747
+ hidden_states=all_hidden_states,
748
+ attentions=all_self_attns,
749
+ )
750
+
751
+
752
+ class ParamBharatGenForCausalLM(ParamBharatGenPreTrainedModel):
753
+ _tied_weights_keys = ["lm_head.weight"]
754
+
755
+ def __init__(self, config):
756
+ super().__init__(config)
757
+ self.model = ParamBharatGenModel(config)
758
+ self.vocab_size = config.vocab_size
759
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
760
+
761
+ # Initialize weights and apply final processing
762
+ self.post_init()
763
+
764
+ def get_input_embeddings(self):
765
+ return self.model.embed_tokens
766
+
767
+ def set_input_embeddings(self, value):
768
+ self.model.embed_tokens = value
769
+
770
+ def get_output_embeddings(self):
771
+ return self.lm_head
772
+
773
+ def set_output_embeddings(self, new_embeddings):
774
+ self.lm_head = new_embeddings
775
+
776
+ def set_decoder(self, decoder):
777
+ self.model = decoder
778
+
779
+ def get_decoder(self):
780
+ return self.model
781
+
782
+ @add_start_docstrings_to_model_forward(PARAMBHARATGEN_INPUTS_DOCSTRING)
783
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
784
+ def forward(
785
+ self,
786
+ input_ids: torch.LongTensor = None,
787
+ attention_mask: Optional[torch.Tensor] = None,
788
+ position_ids: Optional[torch.LongTensor] = None,
789
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
790
+ inputs_embeds: Optional[torch.FloatTensor] = None,
791
+ labels: Optional[torch.LongTensor] = None,
792
+ use_cache: Optional[bool] = None,
793
+ output_attentions: Optional[bool] = None,
794
+ output_hidden_states: Optional[bool] = None,
795
+ return_dict: Optional[bool] = None,
796
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
797
+ r"""
798
+ Args:
799
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
800
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
801
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
802
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
803
+
804
+ Returns:
805
+
806
+ Example:
807
+
808
+ ```python
809
+ >>> from transformers import AutoTokenizer, ParamBharatGenForCausalLM
810
+
811
+ >>> model = ParamBharatGenForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
812
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
813
+
814
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
815
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
816
+
817
+ >>> # Generate
818
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
819
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
820
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
821
+ ```"""
822
+
823
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
824
+ output_hidden_states = (
825
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
826
+ )
827
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
828
+
829
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
830
+ outputs = self.model(
831
+ input_ids=input_ids,
832
+ attention_mask=attention_mask,
833
+ position_ids=position_ids,
834
+ past_key_values=past_key_values,
835
+ inputs_embeds=inputs_embeds,
836
+ use_cache=use_cache,
837
+ output_attentions=output_attentions,
838
+ output_hidden_states=output_hidden_states,
839
+ return_dict=return_dict,
840
+ )
841
+
842
+ hidden_states = outputs[0]
843
+ if self.config.pretraining_tp > 1:
844
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
845
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
846
+ logits = torch.cat(logits, dim=-1)
847
+ else:
848
+ logits = self.lm_head(hidden_states)
849
+ logits = logits.float()
850
+
851
+ loss = None
852
+ if labels is not None:
853
+ # Shift so that tokens < n predict n
854
+ shift_logits = logits[..., :-1, :].contiguous()
855
+ shift_labels = labels[..., 1:].contiguous()
856
+ # Flatten the tokens
857
+ loss_fct = CrossEntropyLoss()
858
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
859
+ shift_labels = shift_labels.view(-1)
860
+ # Enable model parallelism
861
+ shift_labels = shift_labels.to(shift_logits.device)
862
+ loss = loss_fct(shift_logits, shift_labels)
863
+
864
+ if not return_dict:
865
+ output = (logits,) + outputs[1:]
866
+ return (loss,) + output if loss is not None else output
867
+
868
+ return CausalLMOutputWithPast(
869
+ loss=loss,
870
+ logits=logits,
871
+ past_key_values=outputs.past_key_values,
872
+ hidden_states=outputs.hidden_states,
873
+ attentions=outputs.attentions,
874
+ )
875
+
876
+ def prepare_inputs_for_generation(
877
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
878
+ ):
879
+ if past_key_values:
880
+ input_ids = input_ids[:, -1:]
881
+
882
+ position_ids = kwargs.get("position_ids", None)
883
+ if attention_mask is not None and position_ids is None:
884
+ # create position_ids on the fly for batch generation
885
+ position_ids = attention_mask.long().cumsum(-1) - 1
886
+ position_ids.masked_fill_(attention_mask == 0, 1)
887
+ if past_key_values:
888
+ position_ids = position_ids[:, -1].unsqueeze(-1)
889
+
890
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
891
+ if inputs_embeds is not None and past_key_values is None:
892
+ model_inputs = {"inputs_embeds": inputs_embeds}
893
+ else:
894
+ model_inputs = {"input_ids": input_ids}
895
+
896
+ model_inputs.update(
897
+ {
898
+ "position_ids": position_ids,
899
+ "past_key_values": past_key_values,
900
+ "use_cache": kwargs.get("use_cache"),
901
+ "attention_mask": attention_mask,
902
+ }
903
+ )
904
+ return model_inputs
905
+
906
+ @staticmethod
907
+ def _reorder_cache(past_key_values, beam_idx):
908
+ reordered_past = ()
909
+ for layer_past in past_key_values:
910
+ reordered_past += (
911
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
912
+ )
913
+ return reordered_past
914
+
915
+
916
+ @add_start_docstrings(
917
+ """
918
+ The ParamBharatGen Model transformer with a sequence classification head on top (linear layer).
919
+
920
+ [`ParamBharatGenForSequenceClassification`] uses the last token in order to do the classification, as other causal models
921
+ (e.g. GPT-2) do.
922
+
923
+ Since it does classification on the last token, it requires to know the position of the last token. If a
924
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
925
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
926
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
927
+ each row of the batch).
928
+ """,
929
+ PARAMBHARATGEN_START_DOCSTRING,
930
+ )
931
+ class ParamBharatGenForSequenceClassification(ParamBharatGenPreTrainedModel):
932
+ def __init__(self, config):
933
+ super().__init__(config)
934
+ self.num_labels = config.num_labels
935
+ self.model = ParamBharatGenModel(config)
936
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
937
+
938
+ # Initialize weights and apply final processing
939
+ self.post_init()
940
+
941
+ def get_input_embeddings(self):
942
+ return self.model.embed_tokens
943
+
944
+ def set_input_embeddings(self, value):
945
+ self.model.embed_tokens = value
946
+
947
+ @add_start_docstrings_to_model_forward(PARAMBHARATGEN_INPUTS_DOCSTRING)
948
+ def forward(
949
+ self,
950
+ input_ids: torch.LongTensor = None,
951
+ attention_mask: Optional[torch.Tensor] = None,
952
+ position_ids: Optional[torch.LongTensor] = None,
953
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
954
+ inputs_embeds: Optional[torch.FloatTensor] = None,
955
+ labels: Optional[torch.LongTensor] = None,
956
+ use_cache: Optional[bool] = None,
957
+ output_attentions: Optional[bool] = None,
958
+ output_hidden_states: Optional[bool] = None,
959
+ return_dict: Optional[bool] = None,
960
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
961
+ r"""
962
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
963
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
964
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
965
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
966
+ """
967
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
968
+
969
+ transformer_outputs = self.model(
970
+ input_ids,
971
+ attention_mask=attention_mask,
972
+ position_ids=position_ids,
973
+ past_key_values=past_key_values,
974
+ inputs_embeds=inputs_embeds,
975
+ use_cache=use_cache,
976
+ output_attentions=output_attentions,
977
+ output_hidden_states=output_hidden_states,
978
+ return_dict=return_dict,
979
+ )
980
+ hidden_states = transformer_outputs[0]
981
+ logits = self.score(hidden_states)
982
+
983
+ if input_ids is not None:
984
+ batch_size = input_ids.shape[0]
985
+ else:
986
+ batch_size = inputs_embeds.shape[0]
987
+
988
+ if self.config.pad_token_id is None and batch_size != 1:
989
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
990
+ if self.config.pad_token_id is None:
991
+ sequence_lengths = -1
992
+ else:
993
+ if input_ids is not None:
994
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
995
+ logits.device
996
+ )
997
+ else:
998
+ sequence_lengths = -1
999
+
1000
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1001
+
1002
+ loss = None
1003
+ if labels is not None:
1004
+ labels = labels.to(logits.device)
1005
+ if self.config.problem_type is None:
1006
+ if self.num_labels == 1:
1007
+ self.config.problem_type = "regression"
1008
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1009
+ self.config.problem_type = "single_label_classification"
1010
+ else:
1011
+ self.config.problem_type = "multi_label_classification"
1012
+
1013
+ if self.config.problem_type == "regression":
1014
+ loss_fct = MSELoss()
1015
+ if self.num_labels == 1:
1016
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1017
+ else:
1018
+ loss = loss_fct(pooled_logits, labels)
1019
+ elif self.config.problem_type == "single_label_classification":
1020
+ loss_fct = CrossEntropyLoss()
1021
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1022
+ elif self.config.problem_type == "multi_label_classification":
1023
+ loss_fct = BCEWithLogitsLoss()
1024
+ loss = loss_fct(pooled_logits, labels)
1025
+ if not return_dict:
1026
+ output = (pooled_logits,) + transformer_outputs[1:]
1027
+ return ((loss,) + output) if loss is not None else output
1028
+
1029
+ return SequenceClassifierOutputWithPast(
1030
+ loss=loss,
1031
+ logits=pooled_logits,
1032
+ past_key_values=transformer_outputs.past_key_values,
1033
+ hidden_states=transformer_outputs.hidden_states,
1034
+ attentions=transformer_outputs.attentions,
1035
+ )
1036
+
1037
+ AutoModelForCausalLM.register(ParamBharatGenConfig, ParamBharatGenForCausalLM)
1038
+ AutoModelForSequenceClassification.register(ParamBharatGenConfig, ParamBharatGenForSequenceClassification)