SatyaSriVelpuri commited on
Commit
fc6bddf
·
verified ·
1 Parent(s): 916d816

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ checkpoint-1000/tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ checkpoint-1500/tokenizer.json filter=lfs diff=lfs merge=lfs -text
checkpoint-1000/chat_template.jinja ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {{- '<|im_start|>' + message.role + '\n' + content }}
35
+ {%- if message.tool_calls %}
36
+ {%- for tool_call in message.tool_calls %}
37
+ {%- if (loop.first and content) or (not loop.first) %}
38
+ {{- '\n' }}
39
+ {%- endif %}
40
+ {%- if tool_call.function %}
41
+ {%- set tool_call = tool_call.function %}
42
+ {%- endif %}
43
+ {{- '<tool_call>\n{"name": "' }}
44
+ {{- tool_call.name }}
45
+ {{- '", "arguments": ' }}
46
+ {%- if tool_call.arguments is string %}
47
+ {{- tool_call.arguments }}
48
+ {%- else %}
49
+ {{- tool_call.arguments | tojson }}
50
+ {%- endif %}
51
+ {{- '}\n</tool_call>' }}
52
+ {%- endfor %}
53
+ {%- endif %}
54
+ {{- '<|im_end|>\n' }}
55
+ {%- elif message.role == "tool" %}
56
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
57
+ {{- '<|im_start|>user' }}
58
+ {%- endif %}
59
+ {{- '\n<tool_response>\n' }}
60
+ {{- content }}
61
+ {{- '\n</tool_response>' }}
62
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
63
+ {{- '<|im_end|>\n' }}
64
+ {%- endif %}
65
+ {%- endif %}
66
+ {%- endfor %}
67
+ {%- if add_generation_prompt %}
68
+ {{- '<|im_start|>assistant\n' }}
69
+ {%- endif %}
checkpoint-1000/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ParamBharatGenForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "config_parambharatgen.ParamBharatGenConfig",
9
+ "AutoModelForCausalLM": "modeling_parambharatgen.ParamBharatGenForCausalLM"
10
+ },
11
+ "bos_token_id": 2,
12
+ "custom_mlp_ratio": 3.5,
13
+ "dtype": "bfloat16",
14
+ "eos_token_id": 256001,
15
+ "head_dim": 128,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.01,
19
+ "intermediate_size": 7168,
20
+ "max_position_embeddings": 8192,
21
+ "mlp_bias": false,
22
+ "model_type": "parambharatgen",
23
+ "num_attention_heads": 16,
24
+ "num_hidden_layers": 32,
25
+ "num_key_value_heads": 8,
26
+ "pad_token_id": 256002,
27
+ "pretraining_tp": 1,
28
+ "rms_norm_eps": 1e-05,
29
+ "rope_parameters": {
30
+ "rope_theta": 10000.0,
31
+ "rope_type": "default"
32
+ },
33
+ "rope_theta": 10000.0,
34
+ "tie_word_embeddings": false,
35
+ "transformers_version": "5.2.0",
36
+ "use_cache": false,
37
+ "vocab_size": 256011
38
+ }
checkpoint-1000/config_parambharatgen.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class ParamBharatGenConfig(PretrainedConfig):
4
+ model_type = "parambharatgen"
5
+ keys_to_ignore_at_inference = ["past_key_values"]
6
+
7
+ def __init__(
8
+ self,
9
+ vocab_size=256000,
10
+ hidden_size=2048,
11
+ intermediate_size=7168,
12
+ num_hidden_layers=32,
13
+ num_attention_heads=16,
14
+ num_key_value_heads=8,
15
+ hidden_act="silu",
16
+ max_position_embeddings=2048,
17
+ initializer_range=0.01,
18
+ rms_norm_eps=1e-5,
19
+ use_cache=True,
20
+ pad_token_id=None,
21
+ bos_token_id=2,
22
+ eos_token_id=3,
23
+ pretraining_tp=1,
24
+ tie_word_embeddings=False,
25
+ rope_theta=10000.0,
26
+ rope_scaling=None,
27
+ attention_bias=False,
28
+ attention_dropout=0.0,
29
+ mlp_bias=False,
30
+ custom_mlp_ratio=3.5,
31
+ **kwargs,
32
+ ):
33
+ self.vocab_size = vocab_size
34
+ self.max_position_embeddings = max_position_embeddings
35
+ self.hidden_size = hidden_size
36
+ self.intermediate_size = intermediate_size
37
+ self.num_hidden_layers = num_hidden_layers
38
+ self.num_attention_heads = num_attention_heads
39
+ self.num_key_value_heads = num_key_value_heads
40
+ self.hidden_act = hidden_act
41
+ self.initializer_range = initializer_range
42
+ self.rms_norm_eps = rms_norm_eps
43
+ self.pretraining_tp = pretraining_tp
44
+ self.use_cache = use_cache
45
+ self.rope_theta = rope_theta
46
+ self.rope_scaling = rope_scaling
47
+ self.attention_bias = attention_bias
48
+ self.attention_dropout = attention_dropout
49
+ self.mlp_bias = mlp_bias
50
+ self.custom_mlp_ratio = custom_mlp_ratio
51
+
52
+ super().__init__(
53
+ pad_token_id=pad_token_id,
54
+ bos_token_id=bos_token_id,
55
+ eos_token_id=eos_token_id,
56
+ tie_word_embeddings=tie_word_embeddings,
57
+ **kwargs,
58
+ )
59
+
60
+ ParamBharatGenConfig.register_for_auto_class()
checkpoint-1000/generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 2,
4
+ "eos_token_id": [
5
+ 256001,
6
+ 3
7
+ ],
8
+ "pad_token_id": 256002,
9
+ "transformers_version": "5.2.0"
10
+ }
checkpoint-1000/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3dd2643de3733916bcb8b64b137a73ad64f6c17ea612899fde50412295ca0f3
3
+ size 5721420784
checkpoint-1000/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)
checkpoint-1000/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d716f1693897e208d1cc4ed863a55ea6b4896871f5f708f87c41074e866791f
3
+ size 11443027647
checkpoint-1000/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de69a2834426ff9ef8199d077e00892579278af31d8969d77f98235b5cfc010a
3
+ size 14645
checkpoint-1000/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16bd41a1e174bcef765cf973a8ae1147b1ef3f13fd83f53f556c55cc1a14a5cb
3
+ size 1465
checkpoint-1000/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a34c65fb3c53c0539a65958e6ef7d97a1f7a2f12c2f035768d4fed5f1b49605e
3
+ size 34812157
checkpoint-1000/tokenizer_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<s>",
4
+ "clean_up_tokenization_spaces": true,
5
+ "eos_token": "<|im_end|>",
6
+ "is_local": false,
7
+ "model_input_names": [
8
+ "input_ids",
9
+ "attention_mask"
10
+ ],
11
+ "model_max_length": 1000000000000000019884624838656,
12
+ "pad_token": "<|endoftext|>",
13
+ "tokenizer_class": "TokenizersBackend"
14
+ }
checkpoint-1000/trainer_state.json ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 1.6835016835016834,
6
+ "eval_steps": 500,
7
+ "global_step": 1000,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.04208754208754209,
14
+ "grad_norm": 44.5,
15
+ "learning_rate": 2.222222222222222e-06,
16
+ "loss": 9.708373413085937,
17
+ "step": 25
18
+ },
19
+ {
20
+ "epoch": 0.08417508417508418,
21
+ "grad_norm": 20.5,
22
+ "learning_rate": 4.537037037037038e-06,
23
+ "loss": 7.022988891601562,
24
+ "step": 50
25
+ },
26
+ {
27
+ "epoch": 0.12626262626262627,
28
+ "grad_norm": 13.375,
29
+ "learning_rate": 4.94212962962963e-06,
30
+ "loss": 4.4798516845703125,
31
+ "step": 75
32
+ },
33
+ {
34
+ "epoch": 0.16835016835016836,
35
+ "grad_norm": 35.75,
36
+ "learning_rate": 4.869791666666667e-06,
37
+ "loss": 3.579981384277344,
38
+ "step": 100
39
+ },
40
+ {
41
+ "epoch": 0.21043771043771045,
42
+ "grad_norm": 33.0,
43
+ "learning_rate": 4.797453703703704e-06,
44
+ "loss": 2.9001919555664064,
45
+ "step": 125
46
+ },
47
+ {
48
+ "epoch": 0.25252525252525254,
49
+ "grad_norm": 38.5,
50
+ "learning_rate": 4.725115740740741e-06,
51
+ "loss": 2.722982177734375,
52
+ "step": 150
53
+ },
54
+ {
55
+ "epoch": 0.2946127946127946,
56
+ "grad_norm": 98.0,
57
+ "learning_rate": 4.652777777777779e-06,
58
+ "loss": 2.658799133300781,
59
+ "step": 175
60
+ },
61
+ {
62
+ "epoch": 0.3367003367003367,
63
+ "grad_norm": 37.5,
64
+ "learning_rate": 4.580439814814815e-06,
65
+ "loss": 2.5711898803710938,
66
+ "step": 200
67
+ },
68
+ {
69
+ "epoch": 0.3787878787878788,
70
+ "grad_norm": 148.0,
71
+ "learning_rate": 4.508101851851852e-06,
72
+ "loss": 2.5608544921875,
73
+ "step": 225
74
+ },
75
+ {
76
+ "epoch": 0.4208754208754209,
77
+ "grad_norm": 100.0,
78
+ "learning_rate": 4.435763888888889e-06,
79
+ "loss": 2.5246621704101564,
80
+ "step": 250
81
+ },
82
+ {
83
+ "epoch": 0.46296296296296297,
84
+ "grad_norm": 111.0,
85
+ "learning_rate": 4.363425925925927e-06,
86
+ "loss": 2.504690399169922,
87
+ "step": 275
88
+ },
89
+ {
90
+ "epoch": 0.5050505050505051,
91
+ "grad_norm": 74.5,
92
+ "learning_rate": 4.2910879629629634e-06,
93
+ "loss": 2.456527099609375,
94
+ "step": 300
95
+ },
96
+ {
97
+ "epoch": 0.5471380471380471,
98
+ "grad_norm": 84.0,
99
+ "learning_rate": 4.21875e-06,
100
+ "loss": 2.476842498779297,
101
+ "step": 325
102
+ },
103
+ {
104
+ "epoch": 0.5892255892255892,
105
+ "grad_norm": 26.125,
106
+ "learning_rate": 4.1464120370370375e-06,
107
+ "loss": 2.447265930175781,
108
+ "step": 350
109
+ },
110
+ {
111
+ "epoch": 0.6313131313131313,
112
+ "grad_norm": 38.5,
113
+ "learning_rate": 4.074074074074074e-06,
114
+ "loss": 2.3707008361816406,
115
+ "step": 375
116
+ },
117
+ {
118
+ "epoch": 0.6734006734006734,
119
+ "grad_norm": 23.375,
120
+ "learning_rate": 4.001736111111112e-06,
121
+ "loss": 2.374063720703125,
122
+ "step": 400
123
+ },
124
+ {
125
+ "epoch": 0.7154882154882155,
126
+ "grad_norm": 21.875,
127
+ "learning_rate": 3.929398148148148e-06,
128
+ "loss": 2.3581019592285157,
129
+ "step": 425
130
+ },
131
+ {
132
+ "epoch": 0.7575757575757576,
133
+ "grad_norm": 21.25,
134
+ "learning_rate": 3.857060185185186e-06,
135
+ "loss": 2.3752615356445315,
136
+ "step": 450
137
+ },
138
+ {
139
+ "epoch": 0.7996632996632996,
140
+ "grad_norm": 48.0,
141
+ "learning_rate": 3.7847222222222224e-06,
142
+ "loss": 2.309081726074219,
143
+ "step": 475
144
+ },
145
+ {
146
+ "epoch": 0.8417508417508418,
147
+ "grad_norm": 17.375,
148
+ "learning_rate": 3.7123842592592594e-06,
149
+ "loss": 2.265882568359375,
150
+ "step": 500
151
+ },
152
+ {
153
+ "epoch": 0.8838383838383839,
154
+ "grad_norm": 38.5,
155
+ "learning_rate": 3.640046296296297e-06,
156
+ "loss": 2.245345458984375,
157
+ "step": 525
158
+ },
159
+ {
160
+ "epoch": 0.9259259259259259,
161
+ "grad_norm": 26.875,
162
+ "learning_rate": 3.5677083333333335e-06,
163
+ "loss": 2.2155528259277344,
164
+ "step": 550
165
+ },
166
+ {
167
+ "epoch": 0.968013468013468,
168
+ "grad_norm": 40.0,
169
+ "learning_rate": 3.4953703703703706e-06,
170
+ "loss": 2.2166319274902344,
171
+ "step": 575
172
+ },
173
+ {
174
+ "epoch": 1.0101010101010102,
175
+ "grad_norm": 141.0,
176
+ "learning_rate": 3.423032407407408e-06,
177
+ "loss": 2.2579159545898437,
178
+ "step": 600
179
+ },
180
+ {
181
+ "epoch": 1.0521885521885521,
182
+ "grad_norm": 19.75,
183
+ "learning_rate": 3.3506944444444447e-06,
184
+ "loss": 2.1792347717285154,
185
+ "step": 625
186
+ },
187
+ {
188
+ "epoch": 1.0942760942760943,
189
+ "grad_norm": 159.0,
190
+ "learning_rate": 3.2783564814814817e-06,
191
+ "loss": 2.1700653076171874,
192
+ "step": 650
193
+ },
194
+ {
195
+ "epoch": 1.1363636363636362,
196
+ "grad_norm": 26.125,
197
+ "learning_rate": 3.2060185185185188e-06,
198
+ "loss": 2.1729795837402346,
199
+ "step": 675
200
+ },
201
+ {
202
+ "epoch": 1.1784511784511784,
203
+ "grad_norm": 112.0,
204
+ "learning_rate": 3.1336805555555562e-06,
205
+ "loss": 2.1509564208984373,
206
+ "step": 700
207
+ },
208
+ {
209
+ "epoch": 1.2205387205387206,
210
+ "grad_norm": 18.5,
211
+ "learning_rate": 3.061342592592593e-06,
212
+ "loss": 2.1331724548339843,
213
+ "step": 725
214
+ },
215
+ {
216
+ "epoch": 1.2626262626262625,
217
+ "grad_norm": 72.0,
218
+ "learning_rate": 2.98900462962963e-06,
219
+ "loss": 2.0941813659667967,
220
+ "step": 750
221
+ },
222
+ {
223
+ "epoch": 1.3047138047138047,
224
+ "grad_norm": 56.0,
225
+ "learning_rate": 2.916666666666667e-06,
226
+ "loss": 2.122632598876953,
227
+ "step": 775
228
+ },
229
+ {
230
+ "epoch": 1.3468013468013469,
231
+ "grad_norm": 22.75,
232
+ "learning_rate": 2.8443287037037036e-06,
233
+ "loss": 2.120499572753906,
234
+ "step": 800
235
+ },
236
+ {
237
+ "epoch": 1.3888888888888888,
238
+ "grad_norm": 27.5,
239
+ "learning_rate": 2.771990740740741e-06,
240
+ "loss": 2.1208335876464846,
241
+ "step": 825
242
+ },
243
+ {
244
+ "epoch": 1.430976430976431,
245
+ "grad_norm": 19.125,
246
+ "learning_rate": 2.699652777777778e-06,
247
+ "loss": 2.1359043884277344,
248
+ "step": 850
249
+ },
250
+ {
251
+ "epoch": 1.4730639730639732,
252
+ "grad_norm": 18.5,
253
+ "learning_rate": 2.6273148148148148e-06,
254
+ "loss": 2.1154779052734374,
255
+ "step": 875
256
+ },
257
+ {
258
+ "epoch": 1.5151515151515151,
259
+ "grad_norm": 25.625,
260
+ "learning_rate": 2.554976851851852e-06,
261
+ "loss": 2.107982635498047,
262
+ "step": 900
263
+ },
264
+ {
265
+ "epoch": 1.557239057239057,
266
+ "grad_norm": 17.375,
267
+ "learning_rate": 2.4826388888888893e-06,
268
+ "loss": 2.086489410400391,
269
+ "step": 925
270
+ },
271
+ {
272
+ "epoch": 1.5993265993265995,
273
+ "grad_norm": 23.125,
274
+ "learning_rate": 2.410300925925926e-06,
275
+ "loss": 2.1238157653808596,
276
+ "step": 950
277
+ },
278
+ {
279
+ "epoch": 1.6414141414141414,
280
+ "grad_norm": 17.25,
281
+ "learning_rate": 2.3379629629629634e-06,
282
+ "loss": 2.0812089538574217,
283
+ "step": 975
284
+ },
285
+ {
286
+ "epoch": 1.6835016835016834,
287
+ "grad_norm": 19.5,
288
+ "learning_rate": 2.265625e-06,
289
+ "loss": 2.041307220458984,
290
+ "step": 1000
291
+ }
292
+ ],
293
+ "logging_steps": 25,
294
+ "max_steps": 1782,
295
+ "num_input_tokens_seen": 0,
296
+ "num_train_epochs": 3,
297
+ "save_steps": 500,
298
+ "stateful_callbacks": {
299
+ "TrainerControl": {
300
+ "args": {
301
+ "should_epoch_stop": false,
302
+ "should_evaluate": false,
303
+ "should_log": false,
304
+ "should_save": true,
305
+ "should_training_stop": false
306
+ },
307
+ "attributes": {}
308
+ }
309
+ },
310
+ "total_flos": 9.185883303947796e+17,
311
+ "train_batch_size": 8,
312
+ "trial_name": null,
313
+ "trial_params": null
314
+ }
checkpoint-1000/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e25d938f6b6e7079164fe4ac0abf1b15c1d5d3f52336cde2eb648d428957543
3
+ size 5265
checkpoint-1500/chat_template.jinja ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {{- '<|im_start|>' + message.role + '\n' + content }}
35
+ {%- if message.tool_calls %}
36
+ {%- for tool_call in message.tool_calls %}
37
+ {%- if (loop.first and content) or (not loop.first) %}
38
+ {{- '\n' }}
39
+ {%- endif %}
40
+ {%- if tool_call.function %}
41
+ {%- set tool_call = tool_call.function %}
42
+ {%- endif %}
43
+ {{- '<tool_call>\n{"name": "' }}
44
+ {{- tool_call.name }}
45
+ {{- '", "arguments": ' }}
46
+ {%- if tool_call.arguments is string %}
47
+ {{- tool_call.arguments }}
48
+ {%- else %}
49
+ {{- tool_call.arguments | tojson }}
50
+ {%- endif %}
51
+ {{- '}\n</tool_call>' }}
52
+ {%- endfor %}
53
+ {%- endif %}
54
+ {{- '<|im_end|>\n' }}
55
+ {%- elif message.role == "tool" %}
56
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
57
+ {{- '<|im_start|>user' }}
58
+ {%- endif %}
59
+ {{- '\n<tool_response>\n' }}
60
+ {{- content }}
61
+ {{- '\n</tool_response>' }}
62
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
63
+ {{- '<|im_end|>\n' }}
64
+ {%- endif %}
65
+ {%- endif %}
66
+ {%- endfor %}
67
+ {%- if add_generation_prompt %}
68
+ {{- '<|im_start|>assistant\n' }}
69
+ {%- endif %}
checkpoint-1500/config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ParamBharatGenForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "config_parambharatgen.ParamBharatGenConfig",
9
+ "AutoModelForCausalLM": "modeling_parambharatgen.ParamBharatGenForCausalLM"
10
+ },
11
+ "bos_token_id": 2,
12
+ "custom_mlp_ratio": 3.5,
13
+ "dtype": "bfloat16",
14
+ "eos_token_id": 256001,
15
+ "head_dim": 128,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.01,
19
+ "intermediate_size": 7168,
20
+ "max_position_embeddings": 8192,
21
+ "mlp_bias": false,
22
+ "model_type": "parambharatgen",
23
+ "num_attention_heads": 16,
24
+ "num_hidden_layers": 32,
25
+ "num_key_value_heads": 8,
26
+ "pad_token_id": 256002,
27
+ "pretraining_tp": 1,
28
+ "rms_norm_eps": 1e-05,
29
+ "rope_parameters": {
30
+ "rope_theta": 10000.0,
31
+ "rope_type": "default"
32
+ },
33
+ "rope_theta": 10000.0,
34
+ "tie_word_embeddings": false,
35
+ "transformers_version": "5.2.0",
36
+ "use_cache": false,
37
+ "vocab_size": 256011
38
+ }
checkpoint-1500/config_parambharatgen.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class ParamBharatGenConfig(PretrainedConfig):
4
+ model_type = "parambharatgen"
5
+ keys_to_ignore_at_inference = ["past_key_values"]
6
+
7
+ def __init__(
8
+ self,
9
+ vocab_size=256000,
10
+ hidden_size=2048,
11
+ intermediate_size=7168,
12
+ num_hidden_layers=32,
13
+ num_attention_heads=16,
14
+ num_key_value_heads=8,
15
+ hidden_act="silu",
16
+ max_position_embeddings=2048,
17
+ initializer_range=0.01,
18
+ rms_norm_eps=1e-5,
19
+ use_cache=True,
20
+ pad_token_id=None,
21
+ bos_token_id=2,
22
+ eos_token_id=3,
23
+ pretraining_tp=1,
24
+ tie_word_embeddings=False,
25
+ rope_theta=10000.0,
26
+ rope_scaling=None,
27
+ attention_bias=False,
28
+ attention_dropout=0.0,
29
+ mlp_bias=False,
30
+ custom_mlp_ratio=3.5,
31
+ **kwargs,
32
+ ):
33
+ self.vocab_size = vocab_size
34
+ self.max_position_embeddings = max_position_embeddings
35
+ self.hidden_size = hidden_size
36
+ self.intermediate_size = intermediate_size
37
+ self.num_hidden_layers = num_hidden_layers
38
+ self.num_attention_heads = num_attention_heads
39
+ self.num_key_value_heads = num_key_value_heads
40
+ self.hidden_act = hidden_act
41
+ self.initializer_range = initializer_range
42
+ self.rms_norm_eps = rms_norm_eps
43
+ self.pretraining_tp = pretraining_tp
44
+ self.use_cache = use_cache
45
+ self.rope_theta = rope_theta
46
+ self.rope_scaling = rope_scaling
47
+ self.attention_bias = attention_bias
48
+ self.attention_dropout = attention_dropout
49
+ self.mlp_bias = mlp_bias
50
+ self.custom_mlp_ratio = custom_mlp_ratio
51
+
52
+ super().__init__(
53
+ pad_token_id=pad_token_id,
54
+ bos_token_id=bos_token_id,
55
+ eos_token_id=eos_token_id,
56
+ tie_word_embeddings=tie_word_embeddings,
57
+ **kwargs,
58
+ )
59
+
60
+ ParamBharatGenConfig.register_for_auto_class()
checkpoint-1500/generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 2,
4
+ "eos_token_id": [
5
+ 256001,
6
+ 3
7
+ ],
8
+ "pad_token_id": 256002,
9
+ "transformers_version": "5.2.0"
10
+ }
checkpoint-1500/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:545b23e7cf899531082ffe5d55907154e027ce5b0e923b21233b132c886e8ba2
3
+ size 5721420784
checkpoint-1500/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)
checkpoint-1500/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f36bcfbd7adc98db257d4177032e0c6840128bb9d96558693eccf59fbe3fa5ef
3
+ size 11443027647
checkpoint-1500/rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2534e434cd5abbb8f7668d3eab0549db0ef95d6a797a3efa86b712e8e32266a7
3
+ size 14645
checkpoint-1500/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e48f7334d270029af00d5592d1e9fc63c8d6865a1c56cf834a06f4059a7626cb
3
+ size 1465
checkpoint-1500/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a34c65fb3c53c0539a65958e6ef7d97a1f7a2f12c2f035768d4fed5f1b49605e
3
+ size 34812157
checkpoint-1500/tokenizer_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<s>",
4
+ "clean_up_tokenization_spaces": true,
5
+ "eos_token": "<|im_end|>",
6
+ "is_local": false,
7
+ "model_input_names": [
8
+ "input_ids",
9
+ "attention_mask"
10
+ ],
11
+ "model_max_length": 1000000000000000019884624838656,
12
+ "pad_token": "<|endoftext|>",
13
+ "tokenizer_class": "TokenizersBackend"
14
+ }
checkpoint-1500/trainer_state.json ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 2.525252525252525,
6
+ "eval_steps": 500,
7
+ "global_step": 1500,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.04208754208754209,
14
+ "grad_norm": 44.5,
15
+ "learning_rate": 2.222222222222222e-06,
16
+ "loss": 9.708373413085937,
17
+ "step": 25
18
+ },
19
+ {
20
+ "epoch": 0.08417508417508418,
21
+ "grad_norm": 20.5,
22
+ "learning_rate": 4.537037037037038e-06,
23
+ "loss": 7.022988891601562,
24
+ "step": 50
25
+ },
26
+ {
27
+ "epoch": 0.12626262626262627,
28
+ "grad_norm": 13.375,
29
+ "learning_rate": 4.94212962962963e-06,
30
+ "loss": 4.4798516845703125,
31
+ "step": 75
32
+ },
33
+ {
34
+ "epoch": 0.16835016835016836,
35
+ "grad_norm": 35.75,
36
+ "learning_rate": 4.869791666666667e-06,
37
+ "loss": 3.579981384277344,
38
+ "step": 100
39
+ },
40
+ {
41
+ "epoch": 0.21043771043771045,
42
+ "grad_norm": 33.0,
43
+ "learning_rate": 4.797453703703704e-06,
44
+ "loss": 2.9001919555664064,
45
+ "step": 125
46
+ },
47
+ {
48
+ "epoch": 0.25252525252525254,
49
+ "grad_norm": 38.5,
50
+ "learning_rate": 4.725115740740741e-06,
51
+ "loss": 2.722982177734375,
52
+ "step": 150
53
+ },
54
+ {
55
+ "epoch": 0.2946127946127946,
56
+ "grad_norm": 98.0,
57
+ "learning_rate": 4.652777777777779e-06,
58
+ "loss": 2.658799133300781,
59
+ "step": 175
60
+ },
61
+ {
62
+ "epoch": 0.3367003367003367,
63
+ "grad_norm": 37.5,
64
+ "learning_rate": 4.580439814814815e-06,
65
+ "loss": 2.5711898803710938,
66
+ "step": 200
67
+ },
68
+ {
69
+ "epoch": 0.3787878787878788,
70
+ "grad_norm": 148.0,
71
+ "learning_rate": 4.508101851851852e-06,
72
+ "loss": 2.5608544921875,
73
+ "step": 225
74
+ },
75
+ {
76
+ "epoch": 0.4208754208754209,
77
+ "grad_norm": 100.0,
78
+ "learning_rate": 4.435763888888889e-06,
79
+ "loss": 2.5246621704101564,
80
+ "step": 250
81
+ },
82
+ {
83
+ "epoch": 0.46296296296296297,
84
+ "grad_norm": 111.0,
85
+ "learning_rate": 4.363425925925927e-06,
86
+ "loss": 2.504690399169922,
87
+ "step": 275
88
+ },
89
+ {
90
+ "epoch": 0.5050505050505051,
91
+ "grad_norm": 74.5,
92
+ "learning_rate": 4.2910879629629634e-06,
93
+ "loss": 2.456527099609375,
94
+ "step": 300
95
+ },
96
+ {
97
+ "epoch": 0.5471380471380471,
98
+ "grad_norm": 84.0,
99
+ "learning_rate": 4.21875e-06,
100
+ "loss": 2.476842498779297,
101
+ "step": 325
102
+ },
103
+ {
104
+ "epoch": 0.5892255892255892,
105
+ "grad_norm": 26.125,
106
+ "learning_rate": 4.1464120370370375e-06,
107
+ "loss": 2.447265930175781,
108
+ "step": 350
109
+ },
110
+ {
111
+ "epoch": 0.6313131313131313,
112
+ "grad_norm": 38.5,
113
+ "learning_rate": 4.074074074074074e-06,
114
+ "loss": 2.3707008361816406,
115
+ "step": 375
116
+ },
117
+ {
118
+ "epoch": 0.6734006734006734,
119
+ "grad_norm": 23.375,
120
+ "learning_rate": 4.001736111111112e-06,
121
+ "loss": 2.374063720703125,
122
+ "step": 400
123
+ },
124
+ {
125
+ "epoch": 0.7154882154882155,
126
+ "grad_norm": 21.875,
127
+ "learning_rate": 3.929398148148148e-06,
128
+ "loss": 2.3581019592285157,
129
+ "step": 425
130
+ },
131
+ {
132
+ "epoch": 0.7575757575757576,
133
+ "grad_norm": 21.25,
134
+ "learning_rate": 3.857060185185186e-06,
135
+ "loss": 2.3752615356445315,
136
+ "step": 450
137
+ },
138
+ {
139
+ "epoch": 0.7996632996632996,
140
+ "grad_norm": 48.0,
141
+ "learning_rate": 3.7847222222222224e-06,
142
+ "loss": 2.309081726074219,
143
+ "step": 475
144
+ },
145
+ {
146
+ "epoch": 0.8417508417508418,
147
+ "grad_norm": 17.375,
148
+ "learning_rate": 3.7123842592592594e-06,
149
+ "loss": 2.265882568359375,
150
+ "step": 500
151
+ },
152
+ {
153
+ "epoch": 0.8838383838383839,
154
+ "grad_norm": 38.5,
155
+ "learning_rate": 3.640046296296297e-06,
156
+ "loss": 2.245345458984375,
157
+ "step": 525
158
+ },
159
+ {
160
+ "epoch": 0.9259259259259259,
161
+ "grad_norm": 26.875,
162
+ "learning_rate": 3.5677083333333335e-06,
163
+ "loss": 2.2155528259277344,
164
+ "step": 550
165
+ },
166
+ {
167
+ "epoch": 0.968013468013468,
168
+ "grad_norm": 40.0,
169
+ "learning_rate": 3.4953703703703706e-06,
170
+ "loss": 2.2166319274902344,
171
+ "step": 575
172
+ },
173
+ {
174
+ "epoch": 1.0101010101010102,
175
+ "grad_norm": 141.0,
176
+ "learning_rate": 3.423032407407408e-06,
177
+ "loss": 2.2579159545898437,
178
+ "step": 600
179
+ },
180
+ {
181
+ "epoch": 1.0521885521885521,
182
+ "grad_norm": 19.75,
183
+ "learning_rate": 3.3506944444444447e-06,
184
+ "loss": 2.1792347717285154,
185
+ "step": 625
186
+ },
187
+ {
188
+ "epoch": 1.0942760942760943,
189
+ "grad_norm": 159.0,
190
+ "learning_rate": 3.2783564814814817e-06,
191
+ "loss": 2.1700653076171874,
192
+ "step": 650
193
+ },
194
+ {
195
+ "epoch": 1.1363636363636362,
196
+ "grad_norm": 26.125,
197
+ "learning_rate": 3.2060185185185188e-06,
198
+ "loss": 2.1729795837402346,
199
+ "step": 675
200
+ },
201
+ {
202
+ "epoch": 1.1784511784511784,
203
+ "grad_norm": 112.0,
204
+ "learning_rate": 3.1336805555555562e-06,
205
+ "loss": 2.1509564208984373,
206
+ "step": 700
207
+ },
208
+ {
209
+ "epoch": 1.2205387205387206,
210
+ "grad_norm": 18.5,
211
+ "learning_rate": 3.061342592592593e-06,
212
+ "loss": 2.1331724548339843,
213
+ "step": 725
214
+ },
215
+ {
216
+ "epoch": 1.2626262626262625,
217
+ "grad_norm": 72.0,
218
+ "learning_rate": 2.98900462962963e-06,
219
+ "loss": 2.0941813659667967,
220
+ "step": 750
221
+ },
222
+ {
223
+ "epoch": 1.3047138047138047,
224
+ "grad_norm": 56.0,
225
+ "learning_rate": 2.916666666666667e-06,
226
+ "loss": 2.122632598876953,
227
+ "step": 775
228
+ },
229
+ {
230
+ "epoch": 1.3468013468013469,
231
+ "grad_norm": 22.75,
232
+ "learning_rate": 2.8443287037037036e-06,
233
+ "loss": 2.120499572753906,
234
+ "step": 800
235
+ },
236
+ {
237
+ "epoch": 1.3888888888888888,
238
+ "grad_norm": 27.5,
239
+ "learning_rate": 2.771990740740741e-06,
240
+ "loss": 2.1208335876464846,
241
+ "step": 825
242
+ },
243
+ {
244
+ "epoch": 1.430976430976431,
245
+ "grad_norm": 19.125,
246
+ "learning_rate": 2.699652777777778e-06,
247
+ "loss": 2.1359043884277344,
248
+ "step": 850
249
+ },
250
+ {
251
+ "epoch": 1.4730639730639732,
252
+ "grad_norm": 18.5,
253
+ "learning_rate": 2.6273148148148148e-06,
254
+ "loss": 2.1154779052734374,
255
+ "step": 875
256
+ },
257
+ {
258
+ "epoch": 1.5151515151515151,
259
+ "grad_norm": 25.625,
260
+ "learning_rate": 2.554976851851852e-06,
261
+ "loss": 2.107982635498047,
262
+ "step": 900
263
+ },
264
+ {
265
+ "epoch": 1.557239057239057,
266
+ "grad_norm": 17.375,
267
+ "learning_rate": 2.4826388888888893e-06,
268
+ "loss": 2.086489410400391,
269
+ "step": 925
270
+ },
271
+ {
272
+ "epoch": 1.5993265993265995,
273
+ "grad_norm": 23.125,
274
+ "learning_rate": 2.410300925925926e-06,
275
+ "loss": 2.1238157653808596,
276
+ "step": 950
277
+ },
278
+ {
279
+ "epoch": 1.6414141414141414,
280
+ "grad_norm": 17.25,
281
+ "learning_rate": 2.3379629629629634e-06,
282
+ "loss": 2.0812089538574217,
283
+ "step": 975
284
+ },
285
+ {
286
+ "epoch": 1.6835016835016834,
287
+ "grad_norm": 19.5,
288
+ "learning_rate": 2.265625e-06,
289
+ "loss": 2.041307220458984,
290
+ "step": 1000
291
+ },
292
+ {
293
+ "epoch": 1.7255892255892256,
294
+ "grad_norm": 24.125,
295
+ "learning_rate": 2.193287037037037e-06,
296
+ "loss": 2.044098205566406,
297
+ "step": 1025
298
+ },
299
+ {
300
+ "epoch": 1.7676767676767677,
301
+ "grad_norm": 21.875,
302
+ "learning_rate": 2.120949074074074e-06,
303
+ "loss": 2.1019331359863282,
304
+ "step": 1050
305
+ },
306
+ {
307
+ "epoch": 1.8097643097643097,
308
+ "grad_norm": 21.25,
309
+ "learning_rate": 2.048611111111111e-06,
310
+ "loss": 2.048153839111328,
311
+ "step": 1075
312
+ },
313
+ {
314
+ "epoch": 1.8518518518518519,
315
+ "grad_norm": 26.0,
316
+ "learning_rate": 1.9762731481481482e-06,
317
+ "loss": 2.011888427734375,
318
+ "step": 1100
319
+ },
320
+ {
321
+ "epoch": 1.893939393939394,
322
+ "grad_norm": 17.5,
323
+ "learning_rate": 1.9039351851851853e-06,
324
+ "loss": 2.103341369628906,
325
+ "step": 1125
326
+ },
327
+ {
328
+ "epoch": 1.936026936026936,
329
+ "grad_norm": 21.5,
330
+ "learning_rate": 1.8315972222222223e-06,
331
+ "loss": 2.0502833557128906,
332
+ "step": 1150
333
+ },
334
+ {
335
+ "epoch": 1.9781144781144782,
336
+ "grad_norm": 18.375,
337
+ "learning_rate": 1.7592592592592594e-06,
338
+ "loss": 2.0501133728027345,
339
+ "step": 1175
340
+ },
341
+ {
342
+ "epoch": 2.0202020202020203,
343
+ "grad_norm": 20.0,
344
+ "learning_rate": 1.6869212962962964e-06,
345
+ "loss": 2.0467076110839844,
346
+ "step": 1200
347
+ },
348
+ {
349
+ "epoch": 2.0622895622895623,
350
+ "grad_norm": 17.75,
351
+ "learning_rate": 1.6145833333333335e-06,
352
+ "loss": 2.06115478515625,
353
+ "step": 1225
354
+ },
355
+ {
356
+ "epoch": 2.1043771043771042,
357
+ "grad_norm": 30.75,
358
+ "learning_rate": 1.5422453703703705e-06,
359
+ "loss": 2.088555908203125,
360
+ "step": 1250
361
+ },
362
+ {
363
+ "epoch": 2.1464646464646466,
364
+ "grad_norm": 25.25,
365
+ "learning_rate": 1.4699074074074074e-06,
366
+ "loss": 2.0032412719726564,
367
+ "step": 1275
368
+ },
369
+ {
370
+ "epoch": 2.1885521885521886,
371
+ "grad_norm": 22.75,
372
+ "learning_rate": 1.3975694444444446e-06,
373
+ "loss": 2.0343482971191404,
374
+ "step": 1300
375
+ },
376
+ {
377
+ "epoch": 2.2306397306397305,
378
+ "grad_norm": 14.875,
379
+ "learning_rate": 1.3252314814814815e-06,
380
+ "loss": 2.0316773986816408,
381
+ "step": 1325
382
+ },
383
+ {
384
+ "epoch": 2.2727272727272725,
385
+ "grad_norm": 17.25,
386
+ "learning_rate": 1.2528935185185187e-06,
387
+ "loss": 2.059365692138672,
388
+ "step": 1350
389
+ },
390
+ {
391
+ "epoch": 2.314814814814815,
392
+ "grad_norm": 15.625,
393
+ "learning_rate": 1.1805555555555556e-06,
394
+ "loss": 2.0488226318359377,
395
+ "step": 1375
396
+ },
397
+ {
398
+ "epoch": 2.356902356902357,
399
+ "grad_norm": 17.0,
400
+ "learning_rate": 1.1082175925925926e-06,
401
+ "loss": 2.025330810546875,
402
+ "step": 1400
403
+ },
404
+ {
405
+ "epoch": 2.398989898989899,
406
+ "grad_norm": 17.75,
407
+ "learning_rate": 1.0358796296296297e-06,
408
+ "loss": 2.031147155761719,
409
+ "step": 1425
410
+ },
411
+ {
412
+ "epoch": 2.441077441077441,
413
+ "grad_norm": 70.5,
414
+ "learning_rate": 9.635416666666667e-07,
415
+ "loss": 2.0263748168945312,
416
+ "step": 1450
417
+ },
418
+ {
419
+ "epoch": 2.483164983164983,
420
+ "grad_norm": 16.5,
421
+ "learning_rate": 8.912037037037037e-07,
422
+ "loss": 1.9904652404785157,
423
+ "step": 1475
424
+ },
425
+ {
426
+ "epoch": 2.525252525252525,
427
+ "grad_norm": 20.0,
428
+ "learning_rate": 8.188657407407407e-07,
429
+ "loss": 1.9979853820800781,
430
+ "step": 1500
431
+ }
432
+ ],
433
+ "logging_steps": 25,
434
+ "max_steps": 1782,
435
+ "num_input_tokens_seen": 0,
436
+ "num_train_epochs": 3,
437
+ "save_steps": 500,
438
+ "stateful_callbacks": {
439
+ "TrainerControl": {
440
+ "args": {
441
+ "should_epoch_stop": false,
442
+ "should_evaluate": false,
443
+ "should_log": false,
444
+ "should_save": true,
445
+ "should_training_stop": false
446
+ },
447
+ "attributes": {}
448
+ }
449
+ },
450
+ "total_flos": 1.3778250766441513e+18,
451
+ "train_batch_size": 8,
452
+ "trial_name": null,
453
+ "trial_params": null
454
+ }
checkpoint-1500/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e25d938f6b6e7079164fe4ac0abf1b15c1d5d3f52336cde2eb648d428957543
3
+ size 5265
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ParamBharatGenForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "config_parambharatgen.ParamBharatGenConfig",
9
+ "AutoModelForCausalLM": "modeling_parambharatgen.ParamBharatGenForCausalLM"
10
+ },
11
+ "bos_token_id": 2,
12
+ "custom_mlp_ratio": 3.5,
13
+ "dtype": "bfloat16",
14
+ "eos_token_id": 256001,
15
+ "head_dim": 128,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.01,
19
+ "intermediate_size": 7168,
20
+ "max_position_embeddings": 8192,
21
+ "mlp_bias": false,
22
+ "model_type": "parambharatgen",
23
+ "num_attention_heads": 16,
24
+ "num_hidden_layers": 32,
25
+ "num_key_value_heads": 8,
26
+ "pad_token_id": 256002,
27
+ "pretraining_tp": 1,
28
+ "rms_norm_eps": 1e-05,
29
+ "rope_parameters": {
30
+ "rope_theta": 10000.0,
31
+ "rope_type": "default"
32
+ },
33
+ "rope_theta": 10000.0,
34
+ "tie_word_embeddings": false,
35
+ "transformers_version": "5.2.0",
36
+ "use_cache": false,
37
+ "vocab_size": 256011
38
+ }
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 2,
4
+ "eos_token_id": [
5
+ 256001,
6
+ 3
7
+ ],
8
+ "pad_token_id": 256002,
9
+ "transformers_version": "5.2.0"
10
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:545b23e7cf899531082ffe5d55907154e027ce5b0e923b21233b132c886e8ba2
3
+ size 5721420784
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e25d938f6b6e7079164fe4ac0abf1b15c1d5d3f52336cde2eb648d428957543
3
+ size 5265