Recag commited on
Commit
de206fe
·
1 Parent(s): bcc760c

Upload BharataiForCausalLM

Browse files
Files changed (3) hide show
  1. config.json +6 -1
  2. model.py +1221 -0
  3. model.safetensors +1 -1
config.json CHANGED
@@ -1,8 +1,12 @@
1
  {
 
 
 
2
  "attention_bias": false,
3
  "attention_dropout": 0.0,
4
  "auto_map": {
5
- "AutoConfig": "config.BharataiConfig"
 
6
  },
7
  "bos_token_id": 1,
8
  "eos_token_id": 2,
@@ -20,6 +24,7 @@
20
  "rope_scaling": null,
21
  "rope_theta": 10000.0,
22
  "tie_word_embeddings": false,
 
23
  "transformers_version": "4.36.0.dev0",
24
  "use_cache": true,
25
  "vocab_size": 5000
 
1
  {
2
+ "architectures": [
3
+ "BharataiForCausalLM"
4
+ ],
5
  "attention_bias": false,
6
  "attention_dropout": 0.0,
7
  "auto_map": {
8
+ "AutoConfig": "config.BharataiConfig",
9
+ "AutoModelForCausalLM": "model.BharataiForCausalLM"
10
  },
11
  "bos_token_id": 1,
12
  "eos_token_id": 2,
 
24
  "rope_scaling": null,
25
  "rope_theta": 10000.0,
26
  "tie_word_embeddings": false,
27
+ "torch_dtype": "float32",
28
  "transformers_version": "4.36.0.dev0",
29
  "use_cache": true,
30
  "vocab_size": 5000
model.py ADDED
@@ -0,0 +1,1221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 BharatTech Tech Ecosystem Pvt. Ltd. and the HuggingFace Inc. team. All rights reserved.
3
+
4
+ """ PyTorch Bharatai model."""
5
+ import math
6
+ import warnings
7
+ from typing import List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint
12
+ from torch import nn
13
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
14
+
15
+ from transformers.activations import ACT2FN
16
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter, _prepare_4d_causal_attention_mask
17
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
18
+ from transformers.modeling_utils import PreTrainedModel
19
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
20
+ from transformers.utils import (
21
+ add_start_docstrings,
22
+ add_start_docstrings_to_model_forward,
23
+ is_flash_attn_2_available,
24
+ logging,
25
+ replace_return_docstrings,
26
+ )
27
+ from transformers.utils.import_utils import is_torch_fx_available
28
+ from .config import BharataiConfig
29
+
30
+
31
+ if is_flash_attn_2_available():
32
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
33
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
34
+
35
+
36
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
37
+ # It means that the function will not be traced through and simply appear as a node in the graph.
38
+ if is_torch_fx_available():
39
+ if not is_torch_greater_or_equal_than_1_13:
40
+ import torch.fx
41
+
42
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CONFIG_FOR_DOC = "BharataiConfig"
48
+
49
+
50
+ def _get_unpad_data(attention_mask):
51
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
52
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
53
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
54
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
55
+ return (
56
+ indices,
57
+ cu_seqlens,
58
+ max_seqlen_in_batch,
59
+ )
60
+
61
+
62
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
63
+ warnings.warn(
64
+ "Calling `transformers.models.Bharatai.modeling_Bharatai._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils.AttentionMaskConverter._prepare_4d_attention_mask"
65
+ )
66
+ return AttentionMaskConverter._prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
67
+
68
+
69
+ def _make_causal_mask(
70
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
71
+ ):
72
+ warnings.warn(
73
+ "Calling `transformers.models.Bharatai.modeling_Bharatai._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.Bharatai.modeling_Bharatai.AttentionMaskConverter._make_causal_mask"
74
+ )
75
+ return AttentionMaskConverter._make_causal_mask(
76
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
77
+ )
78
+
79
+
80
+ class BharataiRMSNorm(nn.Module):
81
+ def __init__(self, hidden_size, eps=1e-6):
82
+ """
83
+ BharataiRMSNorm is equivalent to T5LayerNorm
84
+ """
85
+ super().__init__()
86
+ self.weight = nn.Parameter(torch.ones(hidden_size))
87
+ self.variance_epsilon = eps
88
+
89
+ def forward(self, hidden_states):
90
+ input_dtype = hidden_states.dtype
91
+ hidden_states = hidden_states.to(torch.float32)
92
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
93
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
94
+ return self.weight * hidden_states.to(input_dtype)
95
+
96
+
97
+ ALL_LAYERNORM_LAYERS.append(BharataiRMSNorm)
98
+
99
+
100
+ class BharataiRotaryEmbedding(nn.Module):
101
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
102
+ super().__init__()
103
+
104
+ self.dim = dim
105
+ self.max_position_embeddings = max_position_embeddings
106
+ self.base = base
107
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
108
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
109
+
110
+ # Build here to make `torch.jit.trace` work.
111
+ self._set_cos_sin_cache(
112
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
113
+ )
114
+
115
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
116
+ self.max_seq_len_cached = seq_len
117
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
118
+
119
+ freqs = torch.outer(t, self.inv_freq)
120
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
121
+ emb = torch.cat((freqs, freqs), dim=-1)
122
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
123
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
124
+
125
+ def forward(self, x, seq_len=None):
126
+ # x: [bs, num_attention_heads, seq_len, head_size]
127
+ if seq_len > self.max_seq_len_cached:
128
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
129
+
130
+ return (
131
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
132
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
133
+ )
134
+
135
+
136
+ class BharataiLinearScalingRotaryEmbedding(BharataiRotaryEmbedding):
137
+ """BharataiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
138
+
139
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
140
+ self.scaling_factor = scaling_factor
141
+ super().__init__(dim, max_position_embeddings, base, device)
142
+
143
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
144
+ self.max_seq_len_cached = seq_len
145
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
146
+ t = t / self.scaling_factor
147
+
148
+ freqs = torch.outer(t, self.inv_freq)
149
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
150
+ emb = torch.cat((freqs, freqs), dim=-1)
151
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
152
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
153
+
154
+
155
+ class BharataiDynamicNTKScalingRotaryEmbedding(BharataiRotaryEmbedding):
156
+ """BharataiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
157
+
158
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
159
+ self.scaling_factor = scaling_factor
160
+ super().__init__(dim, max_position_embeddings, base, device)
161
+
162
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
163
+ self.max_seq_len_cached = seq_len
164
+
165
+ if seq_len > self.max_position_embeddings:
166
+ base = self.base * (
167
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
168
+ ) ** (self.dim / (self.dim - 2))
169
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
170
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
171
+
172
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
173
+
174
+ freqs = torch.outer(t, self.inv_freq)
175
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
176
+ emb = torch.cat((freqs, freqs), dim=-1)
177
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
178
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
179
+
180
+
181
+ def rotate_half(x):
182
+ """Rotates half the hidden dims of the input."""
183
+ x1 = x[..., : x.shape[-1] // 2]
184
+ x2 = x[..., x.shape[-1] // 2 :]
185
+ return torch.cat((-x2, x1), dim=-1)
186
+
187
+
188
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
189
+ """Applies Rotary Position Embedding to the query and key tensors.
190
+
191
+ Args:
192
+ q (`torch.Tensor`): The query tensor.
193
+ k (`torch.Tensor`): The key tensor.
194
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
195
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
196
+ position_ids (`torch.Tensor`):
197
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
198
+ used to pass offsetted position ids when working with a KV-cache.
199
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
200
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
201
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
202
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
203
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
204
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
205
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
206
+ Returns:
207
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
208
+ """
209
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
210
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
211
+ q_embed = (q * cos) + (rotate_half(q) * sin)
212
+ k_embed = (k * cos) + (rotate_half(k) * sin)
213
+ return q_embed, k_embed
214
+
215
+
216
+ class BharataiMLP(nn.Module):
217
+ def __init__(self, config):
218
+ super().__init__()
219
+ self.config = config
220
+ self.hidden_size = config.hidden_size
221
+ self.intermediate_size = config.intermediate_size
222
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
223
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
224
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
225
+ self.act_fn = ACT2FN[config.hidden_act]
226
+
227
+ def forward(self, x):
228
+ if self.config.pretraining_tp > 1:
229
+ slice = self.intermediate_size // self.config.pretraining_tp
230
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
231
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
232
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
233
+
234
+ gate_proj = torch.cat(
235
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
236
+ )
237
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
238
+
239
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
240
+ down_proj = [
241
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
242
+ ]
243
+ down_proj = sum(down_proj)
244
+ else:
245
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
246
+
247
+ return down_proj
248
+
249
+
250
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
251
+ """
252
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
253
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
254
+ """
255
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
256
+ if n_rep == 1:
257
+ return hidden_states
258
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
259
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
260
+
261
+
262
+ class BharataiAttention(nn.Module):
263
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
264
+
265
+ def __init__(self, config: BharataiConfig):
266
+ super().__init__()
267
+ self.config = config
268
+ self.attention_dropout = config.attention_dropout
269
+ self.hidden_size = config.hidden_size
270
+ self.num_heads = config.num_attention_heads
271
+ self.head_dim = self.hidden_size // self.num_heads
272
+ self.num_key_value_heads = config.num_key_value_heads
273
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
274
+ self.max_position_embeddings = config.max_position_embeddings
275
+ self.rope_theta = config.rope_theta
276
+ self.is_causal = True
277
+
278
+ if (self.head_dim * self.num_heads) != self.hidden_size:
279
+ raise ValueError(
280
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
281
+ f" and `num_heads`: {self.num_heads})."
282
+ )
283
+
284
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
285
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
286
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
287
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
288
+ self._init_rope()
289
+
290
+ def _init_rope(self):
291
+ if self.config.rope_scaling is None:
292
+ self.rotary_emb = BharataiRotaryEmbedding(
293
+ self.head_dim,
294
+ max_position_embeddings=self.max_position_embeddings,
295
+ base=self.rope_theta,
296
+ )
297
+ else:
298
+ scaling_type = self.config.rope_scaling["type"]
299
+ scaling_factor = self.config.rope_scaling["factor"]
300
+ if scaling_type == "linear":
301
+ self.rotary_emb = BharataiLinearScalingRotaryEmbedding(
302
+ self.head_dim,
303
+ max_position_embeddings=self.max_position_embeddings,
304
+ scaling_factor=scaling_factor,
305
+ base=self.rope_theta,
306
+ )
307
+ elif scaling_type == "dynamic":
308
+ self.rotary_emb = BharataiDynamicNTKScalingRotaryEmbedding(
309
+ self.head_dim,
310
+ max_position_embeddings=self.max_position_embeddings,
311
+ scaling_factor=scaling_factor,
312
+ base=self.rope_theta,
313
+ )
314
+ else:
315
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
316
+
317
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
318
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
319
+
320
+ def forward(
321
+ self,
322
+ hidden_states: torch.Tensor,
323
+ attention_mask: Optional[torch.Tensor] = None,
324
+ position_ids: Optional[torch.LongTensor] = None,
325
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
326
+ output_attentions: bool = False,
327
+ use_cache: bool = False,
328
+ **kwargs,
329
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
330
+ if "padding_mask" in kwargs:
331
+ warnings.warn(
332
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
333
+ )
334
+
335
+ bsz, q_len, _ = hidden_states.size()
336
+
337
+ if self.config.pretraining_tp > 1:
338
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
339
+ query_slices = self.q_proj.weight.split(
340
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
341
+ )
342
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
343
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
344
+
345
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
346
+ query_states = torch.cat(query_states, dim=-1)
347
+
348
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
349
+ key_states = torch.cat(key_states, dim=-1)
350
+
351
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
352
+ value_states = torch.cat(value_states, dim=-1)
353
+
354
+ else:
355
+ query_states = self.q_proj(hidden_states)
356
+ key_states = self.k_proj(hidden_states)
357
+ value_states = self.v_proj(hidden_states)
358
+
359
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
360
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
361
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
362
+
363
+ kv_seq_len = key_states.shape[-2]
364
+ if past_key_value is not None:
365
+ kv_seq_len += past_key_value[0].shape[-2]
366
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
367
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
368
+
369
+ if past_key_value is not None:
370
+ # reuse k, v, self_attention
371
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
372
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
373
+
374
+ past_key_value = (key_states, value_states) if use_cache else None
375
+
376
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
377
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
378
+
379
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
380
+
381
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
382
+ raise ValueError(
383
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
384
+ f" {attn_weights.size()}"
385
+ )
386
+
387
+ if attention_mask is not None:
388
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
389
+ raise ValueError(
390
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
391
+ )
392
+ attn_weights = attn_weights + attention_mask
393
+
394
+ # upcast attention to fp32
395
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
396
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
397
+ attn_output = torch.matmul(attn_weights, value_states)
398
+
399
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
400
+ raise ValueError(
401
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
402
+ f" {attn_output.size()}"
403
+ )
404
+
405
+ attn_output = attn_output.transpose(1, 2).contiguous()
406
+
407
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
408
+
409
+ if self.config.pretraining_tp > 1:
410
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
411
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
412
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
413
+ else:
414
+ attn_output = self.o_proj(attn_output)
415
+
416
+ if not output_attentions:
417
+ attn_weights = None
418
+
419
+ return attn_output, attn_weights, past_key_value
420
+
421
+
422
+ class BharataiFlashAttention2(BharataiAttention):
423
+ """
424
+ Bharatai flash attention module. This module inherits from `BharataiAttention` as the weights of the module stays
425
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
426
+ flash attention and deal with padding tokens in case the input contains any of them.
427
+ """
428
+
429
+ def forward(
430
+ self,
431
+ hidden_states: torch.Tensor,
432
+ attention_mask: Optional[torch.LongTensor] = None,
433
+ position_ids: Optional[torch.LongTensor] = None,
434
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
435
+ output_attentions: bool = False,
436
+ use_cache: bool = False,
437
+ **kwargs,
438
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
439
+ # BharataiFlashAttention2 attention does not support output_attentions
440
+ if "padding_mask" in kwargs:
441
+ warnings.warn(
442
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
443
+ )
444
+
445
+ # overwrite attention_mask with padding_mask
446
+ attention_mask = kwargs.pop("padding_mask")
447
+
448
+ output_attentions = False
449
+
450
+ bsz, q_len, _ = hidden_states.size()
451
+
452
+ query_states = self.q_proj(hidden_states)
453
+ key_states = self.k_proj(hidden_states)
454
+ value_states = self.v_proj(hidden_states)
455
+
456
+ # Flash attention requires the input to have the shape
457
+ # batch_size x seq_length x head_dim x hidden_dim
458
+ # therefore we just need to keep the original shape
459
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
460
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
461
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
462
+
463
+ kv_seq_len = key_states.shape[-2]
464
+ if past_key_value is not None:
465
+ kv_seq_len += past_key_value[0].shape[-2]
466
+
467
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
468
+
469
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
470
+
471
+ if past_key_value is not None:
472
+ # reuse k, v, self_attention
473
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
474
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
475
+
476
+ past_key_value = (key_states, value_states) if use_cache else None
477
+
478
+ query_states = query_states.transpose(1, 2)
479
+ key_states = key_states.transpose(1, 2)
480
+ value_states = value_states.transpose(1, 2)
481
+
482
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
483
+
484
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
485
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
486
+ # cast them back in the correct dtype just to be sure everything works as expected.
487
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
488
+ # in fp32. (BharataiRMSNorm handles it correctly)
489
+
490
+ input_dtype = query_states.dtype
491
+ if input_dtype == torch.float32:
492
+ # Handle the case where the model is quantized
493
+ if hasattr(self.config, "_pre_quantization_dtype"):
494
+ target_dtype = self.config._pre_quantization_dtype
495
+ else:
496
+ target_dtype = self.q_proj.weight.dtype
497
+
498
+ logger.warning_once(
499
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
500
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
501
+ f" {target_dtype}."
502
+ )
503
+
504
+ query_states = query_states.to(target_dtype)
505
+ key_states = key_states.to(target_dtype)
506
+ value_states = value_states.to(target_dtype)
507
+
508
+ attn_output = self._flash_attention_forward(
509
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
510
+ )
511
+
512
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
513
+ attn_output = self.o_proj(attn_output)
514
+
515
+ if not output_attentions:
516
+ attn_weights = None
517
+
518
+ return attn_output, attn_weights, past_key_value
519
+
520
+ def _flash_attention_forward(
521
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
522
+ ):
523
+ """
524
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
525
+ first unpad the input, then computes the attention scores and pad the final attention scores.
526
+
527
+ Args:
528
+ query_states (`torch.Tensor`):
529
+ Input query states to be passed to Flash Attention API
530
+ key_states (`torch.Tensor`):
531
+ Input key states to be passed to Flash Attention API
532
+ value_states (`torch.Tensor`):
533
+ Input value states to be passed to Flash Attention API
534
+ attention_mask (`torch.Tensor`):
535
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
536
+ position of padding tokens and 1 for the position of non-padding tokens.
537
+ dropout (`int`, *optional*):
538
+ Attention dropout
539
+ softmax_scale (`float`, *optional*):
540
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
541
+ """
542
+ # Contains at least one padding token in the sequence
543
+ if attention_mask is not None:
544
+ batch_size = query_states.shape[0]
545
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
546
+ query_states, key_states, value_states, attention_mask, query_length
547
+ )
548
+
549
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
550
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
551
+
552
+ attn_output_unpad = flash_attn_varlen_func(
553
+ query_states,
554
+ key_states,
555
+ value_states,
556
+ cu_seqlens_q=cu_seqlens_q,
557
+ cu_seqlens_k=cu_seqlens_k,
558
+ max_seqlen_q=max_seqlen_in_batch_q,
559
+ max_seqlen_k=max_seqlen_in_batch_k,
560
+ dropout_p=dropout,
561
+ softmax_scale=softmax_scale,
562
+ causal=self.is_causal,
563
+ )
564
+
565
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
566
+ else:
567
+ attn_output = flash_attn_func(
568
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=self.is_causal
569
+ )
570
+
571
+ return attn_output
572
+
573
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
574
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
575
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
576
+
577
+ key_layer = index_first_axis(
578
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
579
+ )
580
+ value_layer = index_first_axis(
581
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
582
+ )
583
+ if query_length == kv_seq_len:
584
+ query_layer = index_first_axis(
585
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
586
+ )
587
+ cu_seqlens_q = cu_seqlens_k
588
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
589
+ indices_q = indices_k
590
+ elif query_length == 1:
591
+ max_seqlen_in_batch_q = 1
592
+ cu_seqlens_q = torch.arange(
593
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
594
+ ) # There is a memcpy here, that is very bad.
595
+ indices_q = cu_seqlens_q[:-1]
596
+ query_layer = query_layer.squeeze(1)
597
+ else:
598
+ # The -q_len: slice assumes left padding.
599
+ attention_mask = attention_mask[:, -query_length:]
600
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
601
+
602
+ return (
603
+ query_layer,
604
+ key_layer,
605
+ value_layer,
606
+ indices_q,
607
+ (cu_seqlens_q, cu_seqlens_k),
608
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
609
+ )
610
+
611
+
612
+ class BharataiDecoderLayer(nn.Module):
613
+ def __init__(self, config: BharataiConfig):
614
+ super().__init__()
615
+ self.hidden_size = config.hidden_size
616
+ self.self_attn = (
617
+ BharataiAttention(config=config)
618
+ if not getattr(config, "_flash_attn_2_enabled", False)
619
+ else BharataiFlashAttention2(config=config)
620
+ )
621
+ self.mlp = BharataiMLP(config)
622
+ self.input_layernorm = BharataiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
623
+ self.post_attention_layernorm = BharataiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
624
+
625
+ def forward(
626
+ self,
627
+ hidden_states: torch.Tensor,
628
+ attention_mask: Optional[torch.Tensor] = None,
629
+ position_ids: Optional[torch.LongTensor] = None,
630
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
631
+ output_attentions: Optional[bool] = False,
632
+ use_cache: Optional[bool] = False,
633
+ **kwargs,
634
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
635
+ """
636
+ Args:
637
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
638
+ attention_mask (`torch.FloatTensor`, *optional*):
639
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
640
+ query_sequence_length, key_sequence_length)` if default attention is used.
641
+ output_attentions (`bool`, *optional*):
642
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
643
+ returned tensors for more detail.
644
+ use_cache (`bool`, *optional*):
645
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
646
+ (see `past_key_values`).
647
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
648
+ """
649
+ if "padding_mask" in kwargs:
650
+ warnings.warn(
651
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
652
+ )
653
+
654
+ residual = hidden_states
655
+
656
+ hidden_states = self.input_layernorm(hidden_states)
657
+
658
+ # Self Attention
659
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
660
+ hidden_states=hidden_states,
661
+ attention_mask=attention_mask,
662
+ position_ids=position_ids,
663
+ past_key_value=past_key_value,
664
+ output_attentions=output_attentions,
665
+ use_cache=use_cache,
666
+ **kwargs,
667
+ )
668
+ hidden_states = residual + hidden_states
669
+
670
+ # Fully Connected
671
+ residual = hidden_states
672
+ hidden_states = self.post_attention_layernorm(hidden_states)
673
+ hidden_states = self.mlp(hidden_states)
674
+ hidden_states = residual + hidden_states
675
+
676
+ outputs = (hidden_states,)
677
+
678
+ if output_attentions:
679
+ outputs += (self_attn_weights,)
680
+
681
+ if use_cache:
682
+ outputs += (present_key_value,)
683
+
684
+ return outputs
685
+
686
+
687
+ Bharatai_START_DOCSTRING = r"""
688
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
689
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
690
+ etc.)
691
+
692
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
693
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
694
+ and behavior.
695
+
696
+ Parameters:
697
+ config ([`BharataiConfig`]):
698
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
699
+ load the weights associated with the model, only the configuration. Check out the
700
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
701
+ """
702
+
703
+
704
+ @add_start_docstrings(
705
+
706
+ Bharatai_START_DOCSTRING,
707
+ )
708
+ class BharataiPreTrainedModel(PreTrainedModel):
709
+ config_class = BharataiConfig
710
+ base_model_prefix = "model"
711
+ supports_gradient_checkpointing = True
712
+ _no_split_modules = ["BharataiDecoderLayer"]
713
+ _skip_keys_device_placement = "past_key_values"
714
+ _supports_flash_attn_2 = True
715
+
716
+ def _init_weights(self, module):
717
+ std = self.config.initializer_range
718
+ if isinstance(module, nn.Linear):
719
+ module.weight.data.normal_(mean=0.0, std=std)
720
+ if module.bias is not None:
721
+ module.bias.data.zero_()
722
+ elif isinstance(module, nn.Embedding):
723
+ module.weight.data.normal_(mean=0.0, std=std)
724
+ if module.padding_idx is not None:
725
+ module.weight.data[module.padding_idx].zero_()
726
+
727
+
728
+ Bharatai_INPUTS_DOCSTRING = r"""
729
+ Args:
730
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
731
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
732
+ it.
733
+
734
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
735
+ [`PreTrainedTokenizer.__call__`] for details.
736
+
737
+ [What are input IDs?](../glossary#input-ids)
738
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
739
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
740
+
741
+ - 1 for tokens that are **not masked**,
742
+ - 0 for tokens that are **masked**.
743
+
744
+ [What are attention masks?](../glossary#attention-mask)
745
+
746
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
747
+ [`PreTrainedTokenizer.__call__`] for details.
748
+
749
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
750
+ `past_key_values`).
751
+
752
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
753
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
754
+ information on the default strategy.
755
+
756
+ - 1 indicates the head is **not masked**,
757
+ - 0 indicates the head is **masked**.
758
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
759
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
760
+ config.n_positions - 1]`.
761
+
762
+ [What are position IDs?](../glossary#position-ids)
763
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
764
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
765
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
766
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
767
+
768
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
769
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
770
+
771
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
772
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
773
+ of shape `(batch_size, sequence_length)`.
774
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
775
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
776
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
777
+ model's internal embedding lookup matrix.
778
+ use_cache (`bool`, *optional*):
779
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
780
+ `past_key_values`).
781
+ output_attentions (`bool`, *optional*):
782
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
783
+ tensors for more detail.
784
+ output_hidden_states (`bool`, *optional*):
785
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
786
+ more detail.
787
+ return_dict (`bool`, *optional*):
788
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
789
+ """
790
+
791
+
792
+ @add_start_docstrings(
793
+ "The bare Bharatai Model outputting raw hidden-states without any specific head on top.",
794
+ Bharatai_START_DOCSTRING,
795
+ )
796
+ class BharataiModel(BharataiPreTrainedModel):
797
+ """
798
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BharataiDecoderLayer`]
799
+
800
+ Args:
801
+ config: BharataiConfig
802
+ """
803
+
804
+ def __init__(self, config: BharataiConfig):
805
+ super().__init__(config)
806
+ self.padding_idx = config.pad_token_id
807
+ self.vocab_size = config.vocab_size
808
+
809
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
810
+ self.layers = nn.ModuleList([BharataiDecoderLayer(config) for _ in range(config.num_hidden_layers)])
811
+ self.norm = BharataiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
812
+
813
+ self.gradient_checkpointing = False
814
+ # Initialize weights and apply final processing
815
+ self.post_init()
816
+
817
+ def get_input_embeddings(self):
818
+ return self.embed_tokens
819
+
820
+ def set_input_embeddings(self, value):
821
+ self.embed_tokens = value
822
+
823
+ @add_start_docstrings_to_model_forward(Bharatai_INPUTS_DOCSTRING)
824
+ def forward(
825
+ self,
826
+ input_ids: torch.LongTensor = None,
827
+ attention_mask: Optional[torch.Tensor] = None,
828
+ position_ids: Optional[torch.LongTensor] = None,
829
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
830
+ inputs_embeds: Optional[torch.FloatTensor] = None,
831
+ use_cache: Optional[bool] = None,
832
+ output_attentions: Optional[bool] = None,
833
+ output_hidden_states: Optional[bool] = None,
834
+ return_dict: Optional[bool] = None,
835
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
836
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
837
+ output_hidden_states = (
838
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
839
+ )
840
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
841
+
842
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
843
+
844
+ # retrieve input_ids and inputs_embeds
845
+ if input_ids is not None and inputs_embeds is not None:
846
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
847
+ elif input_ids is not None:
848
+ batch_size, seq_length = input_ids.shape[:2]
849
+ elif inputs_embeds is not None:
850
+ batch_size, seq_length = inputs_embeds.shape[:2]
851
+ else:
852
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
853
+
854
+ past_key_values_length = 0
855
+ if past_key_values is not None:
856
+ past_key_values_length = past_key_values[0][0].shape[2]
857
+
858
+ if position_ids is None:
859
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
860
+ position_ids = torch.arange(
861
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
862
+ )
863
+ position_ids = position_ids.unsqueeze(0)
864
+
865
+ if inputs_embeds is None:
866
+ inputs_embeds = self.embed_tokens(input_ids)
867
+
868
+ if getattr(self.config, "_flash_attn_2_enabled", False):
869
+ # 2d mask is passed through the layers
870
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
871
+ else:
872
+ # 4d mask is passed through the layers
873
+ attention_mask = _prepare_4d_causal_attention_mask(
874
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
875
+ )
876
+
877
+ # embed positions
878
+ hidden_states = inputs_embeds
879
+
880
+ if self.gradient_checkpointing and self.training:
881
+ if use_cache:
882
+ logger.warning_once(
883
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
884
+ )
885
+ use_cache = False
886
+
887
+ # decoder layers
888
+ all_hidden_states = () if output_hidden_states else None
889
+ all_self_attns = () if output_attentions else None
890
+ next_decoder_cache = () if use_cache else None
891
+
892
+ for idx, decoder_layer in enumerate(self.layers):
893
+ if output_hidden_states:
894
+ all_hidden_states += (hidden_states,)
895
+
896
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
897
+
898
+ if self.gradient_checkpointing and self.training:
899
+ layer_outputs = self._gradient_checkpointing_func(
900
+ decoder_layer.__call__,
901
+ hidden_states,
902
+ attention_mask,
903
+ position_ids,
904
+ past_key_value,
905
+ output_attentions,
906
+ use_cache,
907
+ )
908
+ else:
909
+ layer_outputs = decoder_layer(
910
+ hidden_states,
911
+ attention_mask=attention_mask,
912
+ position_ids=position_ids,
913
+ past_key_value=past_key_value,
914
+ output_attentions=output_attentions,
915
+ use_cache=use_cache,
916
+ )
917
+
918
+ hidden_states = layer_outputs[0]
919
+
920
+ if use_cache:
921
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
922
+
923
+ if output_attentions:
924
+ all_self_attns += (layer_outputs[1],)
925
+
926
+ hidden_states = self.norm(hidden_states)
927
+
928
+ # add hidden states from the last decoder layer
929
+ if output_hidden_states:
930
+ all_hidden_states += (hidden_states,)
931
+
932
+ next_cache = next_decoder_cache if use_cache else None
933
+ if not return_dict:
934
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
935
+ return BaseModelOutputWithPast(
936
+ last_hidden_state=hidden_states,
937
+ past_key_values=next_cache,
938
+ hidden_states=all_hidden_states,
939
+ attentions=all_self_attns,
940
+ )
941
+
942
+
943
+ class BharataiForCausalLM(BharataiPreTrainedModel):
944
+ _tied_weights_keys = ["lm_head.weight"]
945
+
946
+ def __init__(self, config):
947
+ super().__init__(config)
948
+ self.model = BharataiModel(config)
949
+ self.vocab_size = config.vocab_size
950
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
951
+
952
+ # Initialize weights and apply final processing
953
+ self.post_init()
954
+
955
+ def get_input_embeddings(self):
956
+ return self.model.embed_tokens
957
+
958
+ def set_input_embeddings(self, value):
959
+ self.model.embed_tokens = value
960
+
961
+ def get_output_embeddings(self):
962
+ return self.lm_head
963
+
964
+ def set_output_embeddings(self, new_embeddings):
965
+ self.lm_head = new_embeddings
966
+
967
+ def set_decoder(self, decoder):
968
+ self.model = decoder
969
+
970
+ def get_decoder(self):
971
+ return self.model
972
+
973
+ @add_start_docstrings_to_model_forward(Bharatai_INPUTS_DOCSTRING)
974
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
975
+ def forward(
976
+ self,
977
+ input_ids: torch.LongTensor = None,
978
+ attention_mask: Optional[torch.Tensor] = None,
979
+ position_ids: Optional[torch.LongTensor] = None,
980
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
981
+ inputs_embeds: Optional[torch.FloatTensor] = None,
982
+ labels: Optional[torch.LongTensor] = None,
983
+ use_cache: Optional[bool] = None,
984
+ output_attentions: Optional[bool] = None,
985
+ output_hidden_states: Optional[bool] = None,
986
+ return_dict: Optional[bool] = None,
987
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
988
+ r"""
989
+ Args:
990
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
991
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
992
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
993
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
994
+
995
+ Returns:
996
+
997
+
998
+ ```"""
999
+
1000
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1001
+ output_hidden_states = (
1002
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1003
+ )
1004
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1005
+
1006
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1007
+ outputs = self.model(
1008
+ input_ids=input_ids,
1009
+ attention_mask=attention_mask,
1010
+ position_ids=position_ids,
1011
+ past_key_values=past_key_values,
1012
+ inputs_embeds=inputs_embeds,
1013
+ use_cache=use_cache,
1014
+ output_attentions=output_attentions,
1015
+ output_hidden_states=output_hidden_states,
1016
+ return_dict=return_dict,
1017
+ )
1018
+
1019
+ hidden_states = outputs[0]
1020
+ if self.config.pretraining_tp > 1:
1021
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1022
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1023
+ logits = torch.cat(logits, dim=-1)
1024
+ else:
1025
+ logits = self.lm_head(hidden_states)
1026
+ logits = logits.float()
1027
+
1028
+ loss = None
1029
+ if labels is not None:
1030
+ # Shift so that tokens < n predict n
1031
+ shift_logits = logits[..., :-1, :].contiguous()
1032
+ shift_labels = labels[..., 1:].contiguous()
1033
+ # Flatten the tokens
1034
+ loss_fct = CrossEntropyLoss()
1035
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1036
+ shift_labels = shift_labels.view(-1)
1037
+ # Enable model parallelism
1038
+ shift_labels = shift_labels.to(shift_logits.device)
1039
+ loss = loss_fct(shift_logits, shift_labels)
1040
+
1041
+ if not return_dict:
1042
+ output = (logits,) + outputs[1:]
1043
+ return (loss,) + output if loss is not None else output
1044
+
1045
+ return CausalLMOutputWithPast(
1046
+ loss=loss,
1047
+ logits=logits,
1048
+ past_key_values=outputs.past_key_values,
1049
+ hidden_states=outputs.hidden_states,
1050
+ attentions=outputs.attentions,
1051
+ )
1052
+
1053
+ def prepare_inputs_for_generation(
1054
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1055
+ ):
1056
+ if past_key_values is not None:
1057
+ past_length = past_key_values[0][0].shape[2]
1058
+
1059
+ # Some generation methods already pass only the last input ID
1060
+ if input_ids.shape[1] > past_length:
1061
+ remove_prefix_length = past_length
1062
+ else:
1063
+ # Default to old behavior: keep only final ID
1064
+ remove_prefix_length = input_ids.shape[1] - 1
1065
+
1066
+ input_ids = input_ids[:, remove_prefix_length:]
1067
+
1068
+ position_ids = kwargs.get("position_ids", None)
1069
+ if attention_mask is not None and position_ids is None:
1070
+ # create position_ids on the fly for batch generation
1071
+ position_ids = attention_mask.long().cumsum(-1) - 1
1072
+ position_ids.masked_fill_(attention_mask == 0, 1)
1073
+ if past_key_values:
1074
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1075
+
1076
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1077
+ if inputs_embeds is not None and past_key_values is None:
1078
+ model_inputs = {"inputs_embeds": inputs_embeds}
1079
+ else:
1080
+ model_inputs = {"input_ids": input_ids}
1081
+
1082
+ model_inputs.update(
1083
+ {
1084
+ "position_ids": position_ids,
1085
+ "past_key_values": past_key_values,
1086
+ "use_cache": kwargs.get("use_cache"),
1087
+ "attention_mask": attention_mask,
1088
+ }
1089
+ )
1090
+ return model_inputs
1091
+
1092
+ @staticmethod
1093
+ def _reorder_cache(past_key_values, beam_idx):
1094
+ reordered_past = ()
1095
+ for layer_past in past_key_values:
1096
+ reordered_past += (
1097
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1098
+ )
1099
+ return reordered_past
1100
+
1101
+
1102
+ @add_start_docstrings(
1103
+ """
1104
+ The Bharatai Model transformer with a sequence classification head on top (linear layer).
1105
+
1106
+ [`BharataiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1107
+ (e.g. GPT-2) do.
1108
+
1109
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1110
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1111
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1112
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1113
+ each row of the batch).
1114
+ """,
1115
+ Bharatai_START_DOCSTRING,
1116
+ )
1117
+ class BharataiForSequenceClassification(BharataiPreTrainedModel):
1118
+ def __init__(self, config):
1119
+ super().__init__(config)
1120
+ self.num_labels = config.num_labels
1121
+ self.model = BharataiModel(config)
1122
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1123
+
1124
+ # Initialize weights and apply final processing
1125
+ self.post_init()
1126
+
1127
+ def get_input_embeddings(self):
1128
+ return self.model.embed_tokens
1129
+
1130
+ def set_input_embeddings(self, value):
1131
+ self.model.embed_tokens = value
1132
+
1133
+ @add_start_docstrings_to_model_forward(Bharatai_INPUTS_DOCSTRING)
1134
+ def forward(
1135
+ self,
1136
+ input_ids: torch.LongTensor = None,
1137
+ attention_mask: Optional[torch.Tensor] = None,
1138
+ position_ids: Optional[torch.LongTensor] = None,
1139
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1140
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1141
+ labels: Optional[torch.LongTensor] = None,
1142
+ use_cache: Optional[bool] = None,
1143
+ output_attentions: Optional[bool] = None,
1144
+ output_hidden_states: Optional[bool] = None,
1145
+ return_dict: Optional[bool] = None,
1146
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1147
+ r"""
1148
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1149
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1150
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1151
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1152
+ """
1153
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1154
+
1155
+ transformer_outputs = self.model(
1156
+ input_ids,
1157
+ attention_mask=attention_mask,
1158
+ position_ids=position_ids,
1159
+ past_key_values=past_key_values,
1160
+ inputs_embeds=inputs_embeds,
1161
+ use_cache=use_cache,
1162
+ output_attentions=output_attentions,
1163
+ output_hidden_states=output_hidden_states,
1164
+ return_dict=return_dict,
1165
+ )
1166
+ hidden_states = transformer_outputs[0]
1167
+ logits = self.score(hidden_states)
1168
+
1169
+ if input_ids is not None:
1170
+ batch_size = input_ids.shape[0]
1171
+ else:
1172
+ batch_size = inputs_embeds.shape[0]
1173
+
1174
+ if self.config.pad_token_id is None and batch_size != 1:
1175
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1176
+ if self.config.pad_token_id is None:
1177
+ sequence_lengths = -1
1178
+ else:
1179
+ if input_ids is not None:
1180
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1181
+ logits.device
1182
+ )
1183
+ else:
1184
+ sequence_lengths = -1
1185
+
1186
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1187
+
1188
+ loss = None
1189
+ if labels is not None:
1190
+ labels = labels.to(logits.device)
1191
+ if self.config.problem_type is None:
1192
+ if self.num_labels == 1:
1193
+ self.config.problem_type = "regression"
1194
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1195
+ self.config.problem_type = "single_label_classification"
1196
+ else:
1197
+ self.config.problem_type = "multi_label_classification"
1198
+
1199
+ if self.config.problem_type == "regression":
1200
+ loss_fct = MSELoss()
1201
+ if self.num_labels == 1:
1202
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1203
+ else:
1204
+ loss = loss_fct(pooled_logits, labels)
1205
+ elif self.config.problem_type == "single_label_classification":
1206
+ loss_fct = CrossEntropyLoss()
1207
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1208
+ elif self.config.problem_type == "multi_label_classification":
1209
+ loss_fct = BCEWithLogitsLoss()
1210
+ loss = loss_fct(pooled_logits, labels)
1211
+ if not return_dict:
1212
+ output = (pooled_logits,) + transformer_outputs[1:]
1213
+ return ((loss,) + output) if loss is not None else output
1214
+
1215
+ return SequenceClassifierOutputWithPast(
1216
+ loss=loss,
1217
+ logits=pooled_logits,
1218
+ past_key_values=transformer_outputs.past_key_values,
1219
+ hidden_states=transformer_outputs.hidden_states,
1220
+ attentions=transformer_outputs.attentions,
1221
+ )
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2e9d11fa7bdc2d1e7349d53c685f938ecca3132506826923d67071cebdd8b8bc
3
  size 595142768
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a48c235e875d3f48a57004d0d6a17fa0781925cf1d1d7af0461c76118da6bda
3
  size 595142768