benjamin commited on
Commit
c4b099e
·
1 Parent(s): a4ffd71
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ config.json filter=lfs diff=lfs merge=lfs -text
README.md DELETED
@@ -1,199 +0,0 @@
1
- ---
2
- library_name: transformers
3
- tags: []
4
- ---
5
-
6
- # Model Card for Model ID
7
-
8
- <!-- Provide a quick summary of what the model is/does. -->
9
-
10
-
11
-
12
- ## Model Details
13
-
14
- ### Model Description
15
-
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "<unk>": 263
3
+ }
config.json CHANGED
@@ -1,38 +1,3 @@
1
- {
2
- "_name_or_path": ".",
3
- "architectures": [
4
- "Gemma2ForCausalLM"
5
- ],
6
- "attention_bias": false,
7
- "attention_dropout": 0.0,
8
- "attn_logit_softcapping": 50.0,
9
- "bos_token_id": 2,
10
- "cache_implementation": "hybrid",
11
- "eos_token_id": [
12
- 1,
13
- 107
14
- ],
15
- "final_logit_softcapping": 30.0,
16
- "head_dim": 256,
17
- "hidden_act": "gelu_pytorch_tanh",
18
- "hidden_activation": "gelu_pytorch_tanh",
19
- "hidden_size": 2304,
20
- "initializer_range": 0.02,
21
- "intermediate_size": 9216,
22
- "max_length": 2048,
23
- "max_position_embeddings": 8192,
24
- "model_type": "gemma2",
25
- "num_attention_heads": 8,
26
- "num_hidden_layers": 26,
27
- "num_key_value_heads": 4,
28
- "pad_token_id": 0,
29
- "query_pre_attn_scalar": 256,
30
- "rms_norm_eps": 1e-06,
31
- "rope_theta": 10000.0,
32
- "sliding_window": 4096,
33
- "tie_word_embeddings": false,
34
- "torch_dtype": "float32",
35
- "transformers_version": "4.46.0.dev0",
36
- "use_cache": true,
37
- "vocab_size": 264
38
- }
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9ac5bd8092c38bc347c3e2ee1cdc4fb082fca72d8031443d65755636b181087
3
+ size 10543100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
configuration_tpu_gemma2.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TPU Gemma2 model configuration"""
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+
5
+
6
+ class TPUGemma2Config(PretrainedConfig):
7
+ r"""
8
+ This is the configuration class to store the configuration of a [`Gemma2Model`]. It is used to instantiate an Gemma2
9
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
10
+ defaults will yield a similar configuration to that of the Gemma2-7B.
11
+ e.g. [google/gemma2-7b](https://huggingface.co/google/gemma2-7b)
12
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
13
+ documentation from [`PretrainedConfig`] for more information.
14
+ Args:
15
+ vocab_size (`int`, *optional*, defaults to 256000):
16
+ Vocabulary size of the Gemma2 model. Defines the number of different tokens that can be represented by the
17
+ `inputs_ids` passed when calling [`Gemma2Model`]
18
+ hidden_size (`int`, *optional*, defaults to 3072):
19
+ Dimension of the hidden representations.
20
+ intermediate_size (`int`, *optional*, defaults to 24576):
21
+ Dimension of the MLP representations.
22
+ num_hidden_layers (`int`, *optional*, defaults to 28):
23
+ Number of hidden layers in the Transformer decoder.
24
+ num_attention_heads (`int`, *optional*, defaults to 16):
25
+ Number of attention heads for each attention layer in the Transformer decoder.
26
+ num_key_value_heads (`int`, *optional*, defaults to 16):
27
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
28
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
29
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
30
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
31
+ by meanpooling all the original heads within that group. For more details checkout [this
32
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
33
+ `num_attention_heads`.
34
+ head_dim (`int`, *optional*, defaults to 256):
35
+ The attention head dimension.
36
+ hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
37
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
38
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
39
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
40
+ The maximum sequence length that this model might ever be used with.
41
+ initializer_range (`float`, *optional*, defaults to 0.02):
42
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
43
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
44
+ The epsilon used by the rms normalization layers.
45
+ use_cache (`bool`, *optional*, defaults to `True`):
46
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
47
+ relevant if `config.is_decoder=True`.
48
+ pad_token_id (`int`, *optional*, defaults to 0):
49
+ Padding token id.
50
+ eos_token_id (`int`, *optional*, defaults to 1):
51
+ End of stream token id.
52
+ bos_token_id (`int`, *optional*, defaults to 2):
53
+ Beginning of stream token id.
54
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
55
+ Whether to tie weight embeddings
56
+ rope_theta (`float`, *optional*, defaults to 10000.0):
57
+ The base period of the RoPE embeddings.
58
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
59
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
60
+ attention_dropout (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio for the attention probabilities.
62
+ query_pre_attn_scalar (`float`, *optional*, defaults to 224): scaling factor used on the attention scores
63
+ sliding_window (`int`, *optional*, defaults to 4096): in Gemma2, every other layer uses sliding window attention. This is the
64
+ size of the sliding window.
65
+ final_logit_softcapping (`float`, *optional*, defaults to 30.0): scaling factor when applying tanh softcapping on the logits.
66
+ attn_logit_softcapping (`float`, *optional*, defaults to 50.0): scaling factor when applying tanh softcapping on the attention scores.
67
+ cache_implementation (`str`, *optional*, defaults to `"hybrid"`): the cache type to be used with `generate`.
68
+
69
+ ```python
70
+ >>> from transformers import Gemma2Model, Gemma2Config
71
+ >>> # Initializing a Gemma2 gemma2-7b style configuration
72
+ >>> configuration = Gemma2Config()
73
+ >>> # Initializing a model from the gemma2-7b style configuration
74
+ >>> model = Gemma2Model(configuration)
75
+ >>> # Accessing the model configuration
76
+ >>> configuration = model.config
77
+ ```"""
78
+
79
+ model_type = "tpu_gemma2"
80
+ keys_to_ignore_at_inference = ["past_key_values"]
81
+
82
+ def __init__(
83
+ self,
84
+ vocab_size=256000,
85
+ hidden_size=3072,
86
+ intermediate_size=24576,
87
+ num_hidden_layers=28,
88
+ num_attention_heads=16,
89
+ num_key_value_heads=16,
90
+ head_dim=256,
91
+ hidden_activation="gelu_pytorch_tanh",
92
+ max_position_embeddings=8192,
93
+ initializer_range=0.02,
94
+ rms_norm_eps=1e-6,
95
+ use_cache=True,
96
+ pad_token_id=0,
97
+ eos_token_id=1,
98
+ bos_token_id=2,
99
+ tie_word_embeddings=True,
100
+ rope_theta=10000.0,
101
+ attention_bias=False,
102
+ attention_dropout=0.0,
103
+ query_pre_attn_scalar=224,
104
+ sliding_window=4096,
105
+ final_logit_softcapping=30.0,
106
+ attn_logit_softcapping=50.0,
107
+ cache_implementation="hybrid",
108
+ expand_input_ids=False, # Transformers-native PyTorch generation support
109
+ expand_input_ids_maxlen=None,
110
+ expand_input_ids_vocab_size=None,
111
+ expand_input_ids_dict=None,
112
+ **kwargs,
113
+ ):
114
+ super().__init__(
115
+ pad_token_id=pad_token_id,
116
+ bos_token_id=bos_token_id,
117
+ eos_token_id=eos_token_id,
118
+ tie_word_embeddings=tie_word_embeddings,
119
+ **kwargs,
120
+ )
121
+ self.vocab_size = vocab_size
122
+ self.max_position_embeddings = max_position_embeddings
123
+ self.hidden_size = hidden_size
124
+ self.intermediate_size = intermediate_size
125
+ self.num_hidden_layers = num_hidden_layers
126
+ self.num_attention_heads = num_attention_heads
127
+ self.head_dim = head_dim
128
+ self.num_key_value_heads = num_key_value_heads
129
+ self.initializer_range = initializer_range
130
+ self.rms_norm_eps = rms_norm_eps
131
+ self.use_cache = use_cache
132
+ self.rope_theta = rope_theta
133
+ self.attention_bias = attention_bias
134
+ self.attention_dropout = attention_dropout
135
+ self.hidden_activation = hidden_activation
136
+ self.query_pre_attn_scalar = query_pre_attn_scalar
137
+ self.sliding_window = sliding_window
138
+ self.final_logit_softcapping = final_logit_softcapping
139
+ self.attn_logit_softcapping = attn_logit_softcapping
140
+ self.cache_implementation = cache_implementation
141
+
142
+ self.expand_input_ids = expand_input_ids
143
+ self.expand_input_ids_maxlen = expand_input_ids_maxlen
144
+ self.expand_input_ids_vocab_size = expand_input_ids_vocab_size
145
+ self.expand_input_ids_dict = expand_input_ids_dict
flax_model-00001-of-00002.msgpack → flax_model.msgpack RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:a43a044a3e281de0d2f9423d3a49ae9bbf9f88e1801393b4c21cc5e407fe61d6
3
- size 4988306829
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d0e0c94f8ba94eae022591d612844797c600b3bd150bda26ff972b416b229ca
3
+ size 8124185158
flax_model.msgpack.index.json DELETED
@@ -1,296 +0,0 @@
1
- {
2
- "metadata": {
3
- "total_size": 8102937600
4
- },
5
- "weight_map": {
6
- "lm_head/kernel": "flax_model-00001-of-00002.msgpack",
7
- "model/embed_tokens/embedding": "flax_model-00001-of-00002.msgpack",
8
- "model/layers/0/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
9
- "model/layers/0/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
10
- "model/layers/0/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
11
- "model/layers/0/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
12
- "model/layers/0/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
13
- "model/layers/0/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
14
- "model/layers/0/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
15
- "model/layers/0/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
16
- "model/layers/0/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
17
- "model/layers/0/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
18
- "model/layers/0/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
19
- "model/layers/1/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
20
- "model/layers/1/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
21
- "model/layers/1/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
22
- "model/layers/1/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
23
- "model/layers/1/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
24
- "model/layers/1/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
25
- "model/layers/1/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
26
- "model/layers/1/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
27
- "model/layers/1/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
28
- "model/layers/1/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
29
- "model/layers/1/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
30
- "model/layers/10/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
31
- "model/layers/10/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
32
- "model/layers/10/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
33
- "model/layers/10/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
34
- "model/layers/10/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
35
- "model/layers/10/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
36
- "model/layers/10/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
37
- "model/layers/10/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
38
- "model/layers/10/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
39
- "model/layers/10/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
40
- "model/layers/10/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
41
- "model/layers/11/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
42
- "model/layers/11/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
43
- "model/layers/11/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
44
- "model/layers/11/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
45
- "model/layers/11/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
46
- "model/layers/11/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
47
- "model/layers/11/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
48
- "model/layers/11/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
49
- "model/layers/11/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
50
- "model/layers/11/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
51
- "model/layers/11/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
52
- "model/layers/12/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
53
- "model/layers/12/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
54
- "model/layers/12/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
55
- "model/layers/12/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
56
- "model/layers/12/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
57
- "model/layers/12/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
58
- "model/layers/12/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
59
- "model/layers/12/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
60
- "model/layers/12/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
61
- "model/layers/12/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
62
- "model/layers/12/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
63
- "model/layers/13/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
64
- "model/layers/13/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
65
- "model/layers/13/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
66
- "model/layers/13/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
67
- "model/layers/13/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
68
- "model/layers/13/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
69
- "model/layers/13/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
70
- "model/layers/13/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
71
- "model/layers/13/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
72
- "model/layers/13/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
73
- "model/layers/13/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
74
- "model/layers/14/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
75
- "model/layers/14/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
76
- "model/layers/14/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
77
- "model/layers/14/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
78
- "model/layers/14/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
79
- "model/layers/14/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
80
- "model/layers/14/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
81
- "model/layers/14/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
82
- "model/layers/14/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
83
- "model/layers/14/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
84
- "model/layers/14/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
85
- "model/layers/15/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
86
- "model/layers/15/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
87
- "model/layers/15/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
88
- "model/layers/15/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
89
- "model/layers/15/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
90
- "model/layers/15/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
91
- "model/layers/15/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
92
- "model/layers/15/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
93
- "model/layers/15/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
94
- "model/layers/15/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
95
- "model/layers/15/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
96
- "model/layers/16/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
97
- "model/layers/16/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
98
- "model/layers/16/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
99
- "model/layers/16/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
100
- "model/layers/16/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
101
- "model/layers/16/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
102
- "model/layers/16/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
103
- "model/layers/16/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
104
- "model/layers/16/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
105
- "model/layers/16/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
106
- "model/layers/16/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
107
- "model/layers/17/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
108
- "model/layers/17/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
109
- "model/layers/17/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
110
- "model/layers/17/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
111
- "model/layers/17/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
112
- "model/layers/17/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
113
- "model/layers/17/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
114
- "model/layers/17/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
115
- "model/layers/17/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
116
- "model/layers/17/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
117
- "model/layers/17/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
118
- "model/layers/18/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
119
- "model/layers/18/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
120
- "model/layers/18/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
121
- "model/layers/18/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
122
- "model/layers/18/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
123
- "model/layers/18/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
124
- "model/layers/18/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
125
- "model/layers/18/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
126
- "model/layers/18/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
127
- "model/layers/18/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
128
- "model/layers/18/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
129
- "model/layers/19/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
130
- "model/layers/19/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
131
- "model/layers/19/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
132
- "model/layers/19/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
133
- "model/layers/19/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
134
- "model/layers/19/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
135
- "model/layers/19/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
136
- "model/layers/19/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
137
- "model/layers/19/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
138
- "model/layers/19/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
139
- "model/layers/19/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
140
- "model/layers/2/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
141
- "model/layers/2/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
142
- "model/layers/2/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
143
- "model/layers/2/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
144
- "model/layers/2/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
145
- "model/layers/2/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
146
- "model/layers/2/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
147
- "model/layers/2/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
148
- "model/layers/2/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
149
- "model/layers/2/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
150
- "model/layers/2/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
151
- "model/layers/20/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
152
- "model/layers/20/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
153
- "model/layers/20/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
154
- "model/layers/20/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
155
- "model/layers/20/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
156
- "model/layers/20/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
157
- "model/layers/20/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
158
- "model/layers/20/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
159
- "model/layers/20/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
160
- "model/layers/20/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
161
- "model/layers/20/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
162
- "model/layers/21/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
163
- "model/layers/21/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
164
- "model/layers/21/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
165
- "model/layers/21/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
166
- "model/layers/21/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
167
- "model/layers/21/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
168
- "model/layers/21/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
169
- "model/layers/21/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
170
- "model/layers/21/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
171
- "model/layers/21/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
172
- "model/layers/21/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
173
- "model/layers/22/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
174
- "model/layers/22/mlp/down_proj/kernel": "flax_model-00001-of-00002.msgpack",
175
- "model/layers/22/mlp/gate_proj/kernel": "flax_model-00001-of-00002.msgpack",
176
- "model/layers/22/mlp/up_proj/kernel": "flax_model-00001-of-00002.msgpack",
177
- "model/layers/22/post_attention_layernorm/weight": "flax_model-00001-of-00002.msgpack",
178
- "model/layers/22/post_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
179
- "model/layers/22/pre_feedforward_layernorm/weight": "flax_model-00001-of-00002.msgpack",
180
- "model/layers/22/self_attn/k_proj/kernel": "flax_model-00001-of-00002.msgpack",
181
- "model/layers/22/self_attn/o_proj/kernel": "flax_model-00001-of-00002.msgpack",
182
- "model/layers/22/self_attn/q_proj/kernel": "flax_model-00001-of-00002.msgpack",
183
- "model/layers/22/self_attn/v_proj/kernel": "flax_model-00001-of-00002.msgpack",
184
- "model/layers/23/input_layernorm/weight": "flax_model-00001-of-00002.msgpack",
185
- "model/layers/23/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
186
- "model/layers/23/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
187
- "model/layers/23/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
188
- "model/layers/23/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
189
- "model/layers/23/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
190
- "model/layers/23/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
191
- "model/layers/23/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
192
- "model/layers/23/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
193
- "model/layers/23/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
194
- "model/layers/23/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
195
- "model/layers/24/input_layernorm/weight": "flax_model-00002-of-00002.msgpack",
196
- "model/layers/24/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
197
- "model/layers/24/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
198
- "model/layers/24/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
199
- "model/layers/24/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
200
- "model/layers/24/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
201
- "model/layers/24/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
202
- "model/layers/24/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
203
- "model/layers/24/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
204
- "model/layers/24/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
205
- "model/layers/24/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
206
- "model/layers/25/input_layernorm/weight": "flax_model-00002-of-00002.msgpack",
207
- "model/layers/25/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
208
- "model/layers/25/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
209
- "model/layers/25/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
210
- "model/layers/25/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
211
- "model/layers/25/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
212
- "model/layers/25/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
213
- "model/layers/25/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
214
- "model/layers/25/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
215
- "model/layers/25/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
216
- "model/layers/25/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
217
- "model/layers/3/input_layernorm/weight": "flax_model-00002-of-00002.msgpack",
218
- "model/layers/3/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
219
- "model/layers/3/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
220
- "model/layers/3/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
221
- "model/layers/3/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
222
- "model/layers/3/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
223
- "model/layers/3/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
224
- "model/layers/3/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
225
- "model/layers/3/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
226
- "model/layers/3/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
227
- "model/layers/3/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
228
- "model/layers/4/input_layernorm/weight": "flax_model-00002-of-00002.msgpack",
229
- "model/layers/4/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
230
- "model/layers/4/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
231
- "model/layers/4/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
232
- "model/layers/4/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
233
- "model/layers/4/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
234
- "model/layers/4/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
235
- "model/layers/4/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
236
- "model/layers/4/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
237
- "model/layers/4/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
238
- "model/layers/4/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
239
- "model/layers/5/input_layernorm/weight": "flax_model-00002-of-00002.msgpack",
240
- "model/layers/5/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
241
- "model/layers/5/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
242
- "model/layers/5/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
243
- "model/layers/5/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
244
- "model/layers/5/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
245
- "model/layers/5/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
246
- "model/layers/5/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
247
- "model/layers/5/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
248
- "model/layers/5/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
249
- "model/layers/5/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
250
- "model/layers/6/input_layernorm/weight": "flax_model-00002-of-00002.msgpack",
251
- "model/layers/6/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
252
- "model/layers/6/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
253
- "model/layers/6/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
254
- "model/layers/6/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
255
- "model/layers/6/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
256
- "model/layers/6/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
257
- "model/layers/6/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
258
- "model/layers/6/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
259
- "model/layers/6/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
260
- "model/layers/6/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
261
- "model/layers/7/input_layernorm/weight": "flax_model-00002-of-00002.msgpack",
262
- "model/layers/7/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
263
- "model/layers/7/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
264
- "model/layers/7/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
265
- "model/layers/7/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
266
- "model/layers/7/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
267
- "model/layers/7/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
268
- "model/layers/7/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
269
- "model/layers/7/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
270
- "model/layers/7/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
271
- "model/layers/7/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
272
- "model/layers/8/input_layernorm/weight": "flax_model-00002-of-00002.msgpack",
273
- "model/layers/8/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
274
- "model/layers/8/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
275
- "model/layers/8/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
276
- "model/layers/8/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
277
- "model/layers/8/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
278
- "model/layers/8/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
279
- "model/layers/8/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
280
- "model/layers/8/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
281
- "model/layers/8/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
282
- "model/layers/8/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
283
- "model/layers/9/input_layernorm/weight": "flax_model-00002-of-00002.msgpack",
284
- "model/layers/9/mlp/down_proj/kernel": "flax_model-00002-of-00002.msgpack",
285
- "model/layers/9/mlp/gate_proj/kernel": "flax_model-00002-of-00002.msgpack",
286
- "model/layers/9/mlp/up_proj/kernel": "flax_model-00002-of-00002.msgpack",
287
- "model/layers/9/post_attention_layernorm/weight": "flax_model-00002-of-00002.msgpack",
288
- "model/layers/9/post_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
289
- "model/layers/9/pre_feedforward_layernorm/weight": "flax_model-00002-of-00002.msgpack",
290
- "model/layers/9/self_attn/k_proj/kernel": "flax_model-00002-of-00002.msgpack",
291
- "model/layers/9/self_attn/o_proj/kernel": "flax_model-00002-of-00002.msgpack",
292
- "model/layers/9/self_attn/q_proj/kernel": "flax_model-00002-of-00002.msgpack",
293
- "model/layers/9/self_attn/v_proj/kernel": "flax_model-00002-of-00002.msgpack",
294
- "model/norm/weight": "flax_model-00002-of-00002.msgpack"
295
- }
296
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 2,
4
+ "cache_implementation": "hybrid",
5
+ "eos_token_id": [
6
+ 1,
7
+ 107
8
+ ],
9
+ "max_length": 2048,
10
+ "pad_token_id": 0,
11
+ "transformers_version": "4.46.0"
12
+ }
flax_model-00002-of-00002.msgpack → model-00001-of-00003.safetensors RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:b58f03c5921a31ce5a74f31b2dae884c84e3f771d7c5794e7056899345427b0f
3
- size 3114644628
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eded117d7c79a43e33e458bd386194dd4baeb8df70ca673a16c4d195ee858676
3
+ size 4995009256
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:388a34bae7384f1d9b24babfcc9e446e93b8c3f07460567bcaafb1e404c7d759
3
+ size 4983443424
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d105ad43da46a3da2d83ce41f8ffef826dd5cf00475aa3c61c755a3e40f2cd86
3
+ size 483814504
model.safetensors.index.json ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 10462233600
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00003-of-00003.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00003.safetensors",
8
+ "model.expand_embed_tokens.weight": "model-00001-of-00003.safetensors",
9
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00003.safetensors",
10
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
11
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
12
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
13
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
14
+ "model.layers.0.post_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
15
+ "model.layers.0.pre_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
16
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
17
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
18
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
19
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
20
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00003.safetensors",
21
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
22
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
23
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
24
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
25
+ "model.layers.1.post_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
26
+ "model.layers.1.pre_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
27
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
28
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
29
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
30
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
31
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00003.safetensors",
32
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
33
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
34
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
35
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
36
+ "model.layers.10.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
37
+ "model.layers.10.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
38
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
39
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
40
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
41
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
42
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00003.safetensors",
43
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
44
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
45
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
46
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
47
+ "model.layers.11.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
48
+ "model.layers.11.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
49
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
50
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
51
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
52
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
53
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00003.safetensors",
54
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
55
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
56
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
57
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
58
+ "model.layers.12.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
59
+ "model.layers.12.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
60
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
61
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
62
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
63
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
64
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00003.safetensors",
65
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
66
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
67
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
68
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
69
+ "model.layers.13.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
70
+ "model.layers.13.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
71
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
72
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
73
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
74
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
75
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00003.safetensors",
76
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
77
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
78
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
79
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
80
+ "model.layers.14.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
81
+ "model.layers.14.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
82
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
83
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
84
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
85
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
86
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00003.safetensors",
87
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
88
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
89
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
90
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
91
+ "model.layers.15.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
92
+ "model.layers.15.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
93
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
94
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
95
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
96
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
97
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00003.safetensors",
98
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
99
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
100
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
101
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
102
+ "model.layers.16.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
103
+ "model.layers.16.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
104
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
105
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
106
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
107
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
108
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00003.safetensors",
109
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
110
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
111
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
112
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
113
+ "model.layers.17.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
114
+ "model.layers.17.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
115
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
116
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
117
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
118
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
119
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00003.safetensors",
120
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
121
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
122
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
123
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
124
+ "model.layers.18.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
125
+ "model.layers.18.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
126
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
127
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
128
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
129
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
130
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00003.safetensors",
131
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
132
+ "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
133
+ "model.layers.19.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
134
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
135
+ "model.layers.19.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
136
+ "model.layers.19.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
137
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
138
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
139
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
140
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
141
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00003.safetensors",
142
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
143
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
144
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
145
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
146
+ "model.layers.2.post_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
147
+ "model.layers.2.pre_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
148
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
149
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
150
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
151
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
152
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00003.safetensors",
153
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
154
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
155
+ "model.layers.20.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
156
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
157
+ "model.layers.20.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
158
+ "model.layers.20.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
159
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
160
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
161
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
162
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
163
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00003.safetensors",
164
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
165
+ "model.layers.21.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
166
+ "model.layers.21.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
167
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
168
+ "model.layers.21.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
169
+ "model.layers.21.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
170
+ "model.layers.21.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
171
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
172
+ "model.layers.21.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
173
+ "model.layers.21.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
174
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00003.safetensors",
175
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
176
+ "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
177
+ "model.layers.22.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
178
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
179
+ "model.layers.22.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
180
+ "model.layers.22.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
181
+ "model.layers.22.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
182
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
183
+ "model.layers.22.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
184
+ "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
185
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00003.safetensors",
186
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
187
+ "model.layers.23.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
188
+ "model.layers.23.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
189
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
190
+ "model.layers.23.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
191
+ "model.layers.23.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
192
+ "model.layers.23.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
193
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
194
+ "model.layers.23.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
195
+ "model.layers.23.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
196
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00003.safetensors",
197
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
198
+ "model.layers.24.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
199
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
200
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
201
+ "model.layers.24.post_feedforward_layernorm.weight": "model-00003-of-00003.safetensors",
202
+ "model.layers.24.pre_feedforward_layernorm.weight": "model-00003-of-00003.safetensors",
203
+ "model.layers.24.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
204
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
205
+ "model.layers.24.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
206
+ "model.layers.24.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
207
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00003.safetensors",
208
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
209
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
210
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
211
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
212
+ "model.layers.25.post_feedforward_layernorm.weight": "model-00003-of-00003.safetensors",
213
+ "model.layers.25.pre_feedforward_layernorm.weight": "model-00003-of-00003.safetensors",
214
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
215
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
216
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
217
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
218
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00003.safetensors",
219
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
220
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
221
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
222
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
223
+ "model.layers.3.post_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
224
+ "model.layers.3.pre_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
225
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
226
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
227
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
228
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
229
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00003.safetensors",
230
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
231
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
232
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
233
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
234
+ "model.layers.4.post_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
235
+ "model.layers.4.pre_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
236
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
237
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
238
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
239
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
240
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00003.safetensors",
241
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
242
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
243
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
244
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
245
+ "model.layers.5.post_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
246
+ "model.layers.5.pre_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
247
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
248
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
249
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
250
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
251
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00003.safetensors",
252
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
253
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
254
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
255
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
256
+ "model.layers.6.post_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
257
+ "model.layers.6.pre_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
258
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
259
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
260
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
261
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
262
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00003.safetensors",
263
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
264
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
265
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
266
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
267
+ "model.layers.7.post_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
268
+ "model.layers.7.pre_feedforward_layernorm.weight": "model-00001-of-00003.safetensors",
269
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
270
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
271
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
272
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
273
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00003.safetensors",
274
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
275
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
276
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
277
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
278
+ "model.layers.8.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
279
+ "model.layers.8.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
280
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
281
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
282
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
283
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
284
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00003.safetensors",
285
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
286
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
287
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
288
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
289
+ "model.layers.9.post_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
290
+ "model.layers.9.pre_feedforward_layernorm.weight": "model-00002-of-00003.safetensors",
291
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
292
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
293
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
294
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
295
+ "model.norm.weight": "model-00003-of-00003.safetensors"
296
+ }
297
+ }
modelling_flax_tpu_gemma2.py ADDED
@@ -0,0 +1,830 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Flax TPU Gemma2 model."""
2
+
3
+ from typing import Optional, Tuple
4
+
5
+ import flax.linen as nn
6
+ import jax
7
+ import jax.numpy as jnp
8
+ import numpy as np
9
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
10
+ from flax.linen import combine_masks, make_causal_mask
11
+ from flax.linen.attention import dot_product_attention_weights
12
+ from flax.linen import partitioning as nn_partitioning
13
+ from flax.traverse_util import flatten_dict, unflatten_dict
14
+ from jax import lax
15
+ from jax.sharding import PartitionSpec as P
16
+
17
+ from transformers.modeling_flax_outputs import FlaxBaseModelOutput, FlaxCausalLMOutput
18
+ from transformers.modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring
19
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
20
+ from .configuration_tpu_gemma2 import TPUGemma2Config
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ _CONFIG_FOR_DOC = "TPUGemma2Config"
26
+ _CHECKPOINT_FOR_DOC = "google/gemma-2-2b"
27
+ _REAL_CHECKPOINT_FOR_DOC = "openlm-research/open_llama_3b_v2"
28
+
29
+ TPU_GEMMA2_START_DOCSTRING = r"""
30
+
31
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
32
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
33
+ etc.)
34
+
35
+ This model is also a Flax Linen
36
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
37
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
38
+
39
+ Finally, this model supports inherent JAX features such as:
40
+
41
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
42
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
43
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
44
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
45
+
46
+ Parameters:
47
+ config ([`GemmaConfig`]): Model configuration class with all the parameters of the model.
48
+ Initializing with a config file does not load the weights associated with the model, only the
49
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
50
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
51
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16`, or
52
+ `jax.numpy.bfloat16`.
53
+
54
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
55
+ specified all the computation will be performed with the given `dtype`.
56
+
57
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
58
+ parameters.**
59
+
60
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
61
+ [`~FlaxPreTrainedModel.to_bf16`].
62
+ """
63
+
64
+ TPU_GEMMA2_INPUTS_DOCSTRING = r"""
65
+ Args:
66
+ input_ids (`numpy.ndarray` of shape `(batch_size, input_ids_length)`):
67
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
68
+ it.
69
+
70
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
71
+ [`PreTrainedTokenizer.__call__`] for details.
72
+
73
+ [What are input IDs?](../glossary#input-ids)
74
+ attention_mask (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
75
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
76
+
77
+ - 1 for tokens that are **not masked**,
78
+ - 0 for tokens that are **masked**.
79
+
80
+ [What are attention masks?](../glossary#attention-mask)
81
+
82
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
83
+ [`PreTrainedTokenizer.__call__`] for details.
84
+
85
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
86
+ `past_key_values`).
87
+
88
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
89
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
90
+ information on the default strategy.
91
+
92
+ - 1 indicates the head is **not masked**,
93
+ - 0 indicates the head is **masked**.
94
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
95
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
96
+ config.n_positions - 1]`.
97
+
98
+ [What are position IDs?](../glossary#position-ids)
99
+ past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
100
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
101
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
102
+ output_attentions (`bool`, *optional*):
103
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
104
+ tensors for more detail.
105
+ output_hidden_states (`bool`, *optional*):
106
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
107
+ more detail.
108
+ return_dict (`bool`, *optional*):
109
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
110
+ """
111
+
112
+ remat = nn_partitioning.remat
113
+
114
+ def create_sinusoidal_positions(num_pos, dim):
115
+ inv_freq = 1.0 / (10000 ** (np.arange(0, dim, 2)[: (dim // 2)] / dim))
116
+ freqs = np.einsum("i , j -> i j", np.arange(num_pos), inv_freq).astype("float32")
117
+
118
+ emb = np.concatenate((freqs, freqs), axis=-1)
119
+ out = np.concatenate((np.sin(emb)[:, None, :], np.cos(emb)[:, None, :]), axis=-1)
120
+ return jnp.array(out[:, :, :num_pos])
121
+
122
+
123
+ # Copied from transformers.models.llama.modeling_flax_llama.rotate_half
124
+ def rotate_half(tensor):
125
+ """Rotates half the hidden dims of the input."""
126
+ rotate_half_tensor = jnp.concatenate(
127
+ (-tensor[..., tensor.shape[-1] // 2 :], tensor[..., : tensor.shape[-1] // 2]), axis=-1
128
+ )
129
+ return rotate_half_tensor
130
+
131
+
132
+ # Copied from transformers.models.llama.modeling_flax_llama.apply_rotary_pos_emb
133
+ def apply_rotary_pos_emb(tensor, sin_pos, cos_pos):
134
+ return (tensor * cos_pos) + (rotate_half(tensor) * sin_pos)
135
+
136
+
137
+ class FlaxTPUGemma2RMSNorm(nn.Module):
138
+ config: TPUGemma2Config
139
+ dtype: jnp.dtype = jnp.float32
140
+
141
+ def setup(self):
142
+ self.epsilon = self.config.rms_norm_eps
143
+ self.weight = self.param("weight", lambda _, shape: jnp.ones(shape), self.config.hidden_size)
144
+
145
+ def __call__(self, hidden_states):
146
+ variance = jnp.asarray(hidden_states, dtype=jnp.float32)
147
+ variance = jnp.power(variance, 2)
148
+ variance = variance.mean(-1, keepdims=True)
149
+ # use `jax.numpy.sqrt` as `jax.lax.rsqrt` does not match `torch.rsqrt`
150
+ hidden_states = hidden_states / jnp.sqrt(variance + self.epsilon)
151
+
152
+ return (1 + self.weight) * jnp.asarray(hidden_states, dtype=self.dtype)
153
+
154
+
155
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaRotaryEmbedding with Llama->Gemma2
156
+ class FlaxTPUGemma2RotaryEmbedding(nn.Module):
157
+ config: TPUGemma2Config
158
+ dtype: jnp.dtype = jnp.float32
159
+
160
+ # Ignore copy
161
+ def setup(self):
162
+ head_dim = self.config.head_dim
163
+ self.sincos = create_sinusoidal_positions(self.config.max_position_embeddings, head_dim)
164
+
165
+ def __call__(self, key, query, position_ids):
166
+ sincos = self.sincos[position_ids]
167
+ sin_pos, cos_pos = jnp.split(sincos, 2, axis=-1)
168
+
169
+ key = apply_rotary_pos_emb(key, sin_pos, cos_pos)
170
+ query = apply_rotary_pos_emb(query, sin_pos, cos_pos)
171
+
172
+ key = jnp.asarray(key, dtype=self.dtype)
173
+ query = jnp.asarray(query, dtype=self.dtype)
174
+
175
+ return key, query
176
+
177
+
178
+ class FlaxTPUGemma2Attention(nn.Module):
179
+ config: TPUGemma2Config
180
+ layer_idx: int
181
+ dtype: jnp.dtype = jnp.float32
182
+ causal: bool = True
183
+ is_cross_attention: bool = False
184
+
185
+ def setup(self):
186
+ config = self.config
187
+ self.embed_dim = config.hidden_size
188
+ self.num_heads = config.num_attention_heads
189
+ self.head_dim = config.head_dim
190
+
191
+ # otherwise we would manually have to scale attn weights
192
+ assert config.query_pre_attn_scalar == config.head_dim
193
+
194
+ self.attention_softmax_in_fp32 = self.dtype is not jnp.float32
195
+
196
+ self.num_key_value_heads = config.num_key_value_heads
197
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
198
+
199
+ kernel = jax.nn.initializers.normal(self.config.initializer_range)
200
+ self.q_proj = nn.Dense(
201
+ self.num_heads * self.head_dim, use_bias=config.attention_bias, dtype=self.dtype, kernel_init=kernel
202
+ )
203
+ self.k_proj = nn.Dense(
204
+ self.num_key_value_heads * self.head_dim,
205
+ use_bias=config.attention_bias,
206
+ dtype=self.dtype,
207
+ kernel_init=kernel,
208
+ )
209
+ self.v_proj = nn.Dense(
210
+ self.num_key_value_heads * self.head_dim,
211
+ use_bias=config.attention_bias,
212
+ dtype=self.dtype,
213
+ kernel_init=kernel,
214
+ )
215
+ self.o_proj = nn.Dense(self.embed_dim, use_bias=config.attention_bias, dtype=self.dtype, kernel_init=kernel)
216
+ self.sliding_window = config.sliding_window if not bool(self.layer_idx % 2) else None
217
+
218
+ self.causal_mask = make_causal_mask(jnp.ones((1, config.max_position_embeddings), dtype="bool"), dtype="bool")
219
+ self.rotary_emb = FlaxTPUGemma2RotaryEmbedding(config, dtype=self.dtype)
220
+
221
+ def _split_heads(self, hidden_states, num_heads):
222
+ return hidden_states.reshape(hidden_states.shape[:2] + (num_heads, self.head_dim))
223
+
224
+ def _merge_heads(self, hidden_states):
225
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads * self.head_dim,))
226
+
227
+ @nn.compact
228
+ # Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoSelfAttention._concatenate_to_cache
229
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
230
+ """
231
+ This function takes projected key, value states from a single input token and concatenates the states to cached
232
+ states from previous steps. This function is slighly adapted from the official Flax repository:
233
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
234
+ """
235
+ # detect if we're initializing by absence of existing cache data.
236
+ is_initialized = self.has_variable("cache", "cached_key")
237
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
238
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
239
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
240
+
241
+ if is_initialized:
242
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
243
+ # update key, value caches with our new 1d spatial slices
244
+ cur_index = cache_index.value
245
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
246
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
247
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
248
+ cached_key.value = key
249
+ cached_value.value = value
250
+ num_updated_cache_vectors = query.shape[1]
251
+ cache_index.value = cache_index.value + num_updated_cache_vectors
252
+ # causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
253
+ pad_mask = jnp.broadcast_to(
254
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
255
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
256
+ )
257
+ attention_mask = combine_masks(pad_mask, attention_mask)
258
+ return key, value, attention_mask
259
+
260
+ def __call__(
261
+ self,
262
+ hidden_states,
263
+ attention_mask,
264
+ position_ids,
265
+ deterministic: bool = True,
266
+ init_cache: bool = False,
267
+ output_attentions: bool = False,
268
+ ):
269
+ raw_query = self.q_proj(hidden_states)
270
+ raw_key = self.k_proj(hidden_states)
271
+ raw_value = self.v_proj(hidden_states)
272
+
273
+ query = self._split_heads(raw_query, self.num_heads)
274
+ key = self._split_heads(raw_key, self.num_key_value_heads)
275
+ value = self._split_heads(raw_value, self.num_key_value_heads)
276
+
277
+ key, query = self.rotary_emb(key, query, position_ids)
278
+
279
+ query_length, key_length = query.shape[1], key.shape[1]
280
+
281
+ if self.has_variable("cache", "cached_key"):
282
+ mask_shift = self.variables["cache"]["cache_index"]
283
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
284
+ causal_mask = lax.dynamic_slice(
285
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
286
+ )
287
+ else:
288
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
289
+
290
+ batch_size = hidden_states.shape[0]
291
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
292
+
293
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
294
+ attention_mask = combine_masks(attention_mask, causal_mask)
295
+
296
+ if self.sliding_window is not None:
297
+ min_dtype = jnp.finfo(hidden_states.dtype).min
298
+ sliding_window_mask = jnp.tril(
299
+ jnp.ones_like(attention_mask, dtype=bool), k=-self.sliding_window
300
+ )
301
+ attention_mask = jnp.where(sliding_window_mask, min_dtype, attention_mask)
302
+ if attention_mask.shape[-1] <= 1: # when decoding
303
+ attention_mask = attention_mask[:, :, :, -self.sliding_window :]
304
+
305
+ dropout_rng = None
306
+ if not deterministic and self.config.attention_dropout > 0.0:
307
+ dropout_rng = self.make_rng("dropout")
308
+
309
+ # During fast autoregressive decoding, we feed one position at a time,
310
+ # and cache the keys and values step by step.
311
+ if self.has_variable("cache", "cached_key") or init_cache:
312
+ key, value, attention_mask = self._concatenate_to_cache(key, value, query, attention_mask)
313
+
314
+ # transform boolean mask into float mask
315
+ attention_bias = lax.select(
316
+ attention_mask > 0,
317
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
318
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
319
+ )
320
+
321
+ key = jnp.repeat(key, repeats=self.num_key_value_groups, axis=2)
322
+ value = jnp.repeat(value, repeats=self.num_key_value_groups, axis=2)
323
+
324
+ # usual dot product attention
325
+ attention_dtype = jnp.float32 if self.attention_softmax_in_fp32 else self.dtype
326
+ attn_weights = dot_product_attention_weights(
327
+ query,
328
+ key,
329
+ bias=attention_bias,
330
+ dropout_rng=dropout_rng,
331
+ dropout_rate=self.config.attention_dropout,
332
+ deterministic=deterministic,
333
+ dtype=attention_dtype,
334
+ )
335
+
336
+ if self.config.attn_logit_softcapping is not None:
337
+ attn_weights = attn_weights / self.config.attn_logit_softcapping
338
+ attn_weights = jnp.tanh(attn_weights)
339
+ attn_weights = attn_weights * self.config.attn_logit_softcapping
340
+
341
+ if self.attention_softmax_in_fp32:
342
+ attn_weights = attn_weights.astype(self.dtype)
343
+
344
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value)
345
+ attn_output = self._merge_heads(attn_output)
346
+ attn_output = self.o_proj(attn_output)
347
+
348
+ outputs = (attn_output, (raw_query, raw_key, raw_value)) if output_attentions else (attn_output,)
349
+ return outputs
350
+
351
+
352
+ class FlaxTPUGemma2MLP(nn.Module):
353
+ config: TPUGemma2Config
354
+ dtype: jnp.dtype = jnp.float32
355
+
356
+ def setup(self):
357
+ embed_dim = self.config.hidden_size
358
+ inner_dim = self.config.intermediate_size if self.config.intermediate_size is not None else 4 * embed_dim
359
+
360
+ kernel_init = jax.nn.initializers.normal(self.config.initializer_range)
361
+ if self.config.hidden_activation is None:
362
+ logger.warning_once(
363
+ "Gemma2's activation function should be approximate GeLU and not exact GeLU. "
364
+ "Changing the activation function to `gelu_pytorch_tanh`."
365
+ f"if you want to use the legacy `{self.config.hidden_act}`, "
366
+ f"edit the `model.config` to set `hidden_activation={self.config.hidden_act}` "
367
+ " instead of `hidden_act`. See https://github.com/huggingface/transformers/pull/29402 for more details."
368
+ )
369
+ hidden_activation = "gelu_pytorch_tanh"
370
+ else:
371
+ hidden_activation = self.config.hidden_activation
372
+ self.act = ACT2FN[hidden_activation]
373
+
374
+ self.gate_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
375
+ self.down_proj = nn.Dense(embed_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
376
+ self.up_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
377
+
378
+ def __call__(self, hidden_states):
379
+ up_proj_states = self.up_proj(hidden_states)
380
+ gate_states = self.act(self.gate_proj(hidden_states))
381
+
382
+ hidden_states = self.down_proj(up_proj_states * gate_states)
383
+ return hidden_states
384
+
385
+
386
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaDecoderLayer with Llama->Gemma2
387
+ class FlaxTPUGemma2DecoderLayer(nn.Module):
388
+ config: TPUGemma2Config
389
+ layer_idx: int
390
+ dtype: jnp.dtype = jnp.float32
391
+
392
+ def setup(self):
393
+ self.input_layernorm = FlaxTPUGemma2RMSNorm(self.config, dtype=self.dtype)
394
+ self.self_attn = FlaxTPUGemma2Attention(self.config, self.layer_idx, dtype=self.dtype)
395
+ self.pre_feedforward_layernorm = FlaxTPUGemma2RMSNorm(self.config, dtype=self.dtype)
396
+ self.post_feedforward_layernorm = FlaxTPUGemma2RMSNorm(self.config, dtype=self.dtype)
397
+ self.post_attention_layernorm = FlaxTPUGemma2RMSNorm(self.config, dtype=self.dtype)
398
+ self.mlp = FlaxTPUGemma2MLP(self.config, dtype=self.dtype)
399
+
400
+ def __call__(
401
+ self,
402
+ hidden_states,
403
+ attention_mask=None,
404
+ position_ids=None,
405
+ deterministic: bool = True,
406
+ init_cache: bool = False,
407
+ output_attentions: bool = False,
408
+ ):
409
+ mesh = getattr(self.config, "mesh", None)
410
+ if mesh is not None:
411
+ hidden_states = jax.lax.with_sharding_constraint(
412
+ hidden_states, jax.sharding.NamedSharding(mesh, P("data", None, "model"))
413
+ )
414
+ residual = hidden_states
415
+ hidden_states = self.input_layernorm(hidden_states)
416
+ outputs = self.self_attn(
417
+ hidden_states,
418
+ attention_mask=attention_mask,
419
+ position_ids=position_ids,
420
+ deterministic=deterministic,
421
+ init_cache=init_cache,
422
+ output_attentions=output_attentions,
423
+ )
424
+ # residual connection
425
+ attn_output = self.post_attention_layernorm(outputs[0])
426
+ hidden_states = residual + attn_output
427
+
428
+ residual = hidden_states
429
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
430
+ hidden_states = self.mlp(hidden_states)
431
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
432
+ # residual connection
433
+ hidden_states = residual + hidden_states
434
+
435
+ return (hidden_states,) + outputs[1:]
436
+
437
+
438
+ # Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoPreTrainedModel with GPTNeo->Gemma2, GPT_NEO->Gemma2, transformer->model
439
+ class FlaxTPUGemma2PreTrainedModel(FlaxPreTrainedModel):
440
+ """
441
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
442
+ models.
443
+ """
444
+
445
+ config_class = TPUGemma2Config
446
+ base_model_prefix = "model"
447
+ module_class: nn.Module = None
448
+
449
+ def __init__(
450
+ self,
451
+ config: TPUGemma2Config,
452
+ input_shape: Tuple = (1, 1),
453
+ seed: int = 0,
454
+ dtype: jnp.dtype = jnp.float32,
455
+ _do_init: bool = True,
456
+ gradient_checkpointing: bool = False,
457
+ **kwargs,
458
+ ):
459
+ module = self.module_class(config=config, dtype=dtype, gradient_checkpointing=gradient_checkpointing, **kwargs)
460
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
461
+
462
+ def enable_gradient_checkpointing(self):
463
+ self._module = self.module_class(
464
+ config=self.config,
465
+ dtype=self.dtype,
466
+ gradient_checkpointing=True,
467
+ )
468
+
469
+ @classmethod
470
+ def can_generate(cls) -> bool:
471
+ # disable generation, handled separately
472
+ # this is convenient since GenerationConfig.from_model_config(config) needs a pickleable config
473
+ return False
474
+
475
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
476
+ # init input tensors
477
+ input_ids = jnp.zeros(input_shape, dtype="i4")
478
+ attention_mask = jnp.ones_like(input_ids)
479
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
480
+ params_rng, dropout_rng = jax.random.split(rng)
481
+ rngs = {"params": params_rng, "dropout": dropout_rng}
482
+
483
+ random_params = self.module.init(rngs, input_ids, None, attention_mask, position_ids, return_dict=False)["params"]
484
+
485
+ if params is not None:
486
+ random_params = flatten_dict(unfreeze(random_params))
487
+ params = flatten_dict(unfreeze(params))
488
+ for missing_key in self._missing_keys:
489
+ params[missing_key] = random_params[missing_key]
490
+ self._missing_keys = set()
491
+ return freeze(unflatten_dict(params))
492
+ else:
493
+ return random_params
494
+
495
+ def init_cache(self, batch_size, max_length):
496
+ r"""
497
+ Args:
498
+ batch_size (`int`):
499
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
500
+ max_length (`int`):
501
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
502
+ cache.
503
+ """
504
+ # init input variables to retrieve cache
505
+ input_ids = jnp.ones((batch_size, max_length))
506
+ attention_mask = jnp.ones_like(input_ids)
507
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
508
+
509
+ init_variables = self.module.init(
510
+ jax.random.PRNGKey(0), input_ids, None, attention_mask, position_ids, return_dict=False, init_cache=True
511
+ )
512
+ return unfreeze(init_variables["cache"])
513
+
514
+ @add_start_docstrings_to_model_forward(TPU_GEMMA2_INPUTS_DOCSTRING)
515
+ def __call__(
516
+ self,
517
+ input_ids,
518
+ inputs_embeds=None,
519
+ attention_mask=None,
520
+ position_ids=None,
521
+ params: dict = None,
522
+ past_key_values: dict = None,
523
+ dropout_rng: jax.random.PRNGKey = None,
524
+ train: bool = False,
525
+ output_attentions: Optional[bool] = None,
526
+ output_hidden_states: Optional[bool] = None,
527
+ return_dict: Optional[bool] = None,
528
+ ):
529
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
530
+ output_hidden_states = (
531
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
532
+ )
533
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
534
+
535
+ if input_ids is not None:
536
+ batch_size, sequence_length = input_ids.shape
537
+ else:
538
+ batch_size, sequence_length, _ = inputs_embeds.shape
539
+
540
+ if position_ids is None:
541
+ if past_key_values is not None:
542
+ raise ValueError("Make sure to provide `position_ids` when passing `past_key_values`.")
543
+
544
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
545
+
546
+ if attention_mask is None:
547
+ attention_mask = jnp.ones((batch_size, sequence_length))
548
+
549
+ # Handle any PRNG if needed
550
+ rngs = {}
551
+ if dropout_rng is not None:
552
+ rngs["dropout"] = dropout_rng
553
+
554
+ inputs = {"params": params or self.params}
555
+
556
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be changed by FlaxGemma2Attention module
557
+ if past_key_values:
558
+ inputs["cache"] = past_key_values
559
+ mutable = ["cache"]
560
+ else:
561
+ mutable = False
562
+
563
+ outputs = self.module.apply(
564
+ inputs,
565
+ jnp.array(input_ids, dtype="i4") if input_ids is not None else None,
566
+ inputs_embeds if inputs_embeds is not None else None,
567
+ jnp.array(attention_mask, dtype="i4"),
568
+ jnp.array(position_ids, dtype="i4"),
569
+ not train,
570
+ False,
571
+ output_attentions,
572
+ output_hidden_states,
573
+ return_dict,
574
+ rngs=rngs,
575
+ mutable=mutable,
576
+ )
577
+
578
+ # add updated cache to model output
579
+ if past_key_values is not None and return_dict:
580
+ outputs, past_key_values = outputs
581
+ outputs["past_key_values"] = unfreeze(past_key_values["cache"])
582
+ return outputs
583
+ elif past_key_values is not None and not return_dict:
584
+ outputs, past_key_values = outputs
585
+ outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
586
+
587
+ return outputs
588
+
589
+
590
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaLayerCollection with Llama->Gemma2
591
+ class FlaxTPUGemma2LayerCollection(nn.Module):
592
+ config: TPUGemma2Config
593
+ dtype: jnp.dtype = jnp.float32
594
+ gradient_checkpointing: bool = False
595
+
596
+ def setup(self):
597
+ if self.gradient_checkpointing:
598
+ FlaxTPUGemma2DecoderCheckpointLayer = remat(FlaxTPUGemma2DecoderLayer, static_argnums=(3, 4, 5))
599
+ self.blocks = [
600
+ FlaxTPUGemma2DecoderCheckpointLayer(self.config, layer_idx, dtype=self.dtype, name=str(layer_idx))
601
+ for layer_idx in range(self.config.num_hidden_layers)
602
+ ]
603
+ else:
604
+ self.blocks = [
605
+ FlaxTPUGemma2DecoderLayer(self.config, layer_idx, dtype=self.dtype, name=str(layer_idx))
606
+ for layer_idx in range(self.config.num_hidden_layers)
607
+ ]
608
+
609
+ def __call__(
610
+ self,
611
+ hidden_states,
612
+ attention_mask=None,
613
+ position_ids=None,
614
+ deterministic: bool = True,
615
+ init_cache: bool = False,
616
+ output_attentions: bool = False,
617
+ output_hidden_states: bool = False,
618
+ return_dict: bool = False,
619
+ ):
620
+ all_attentions = () if output_attentions else None
621
+ all_hidden_states = () if output_hidden_states else None
622
+
623
+ for block in self.blocks:
624
+ if output_hidden_states:
625
+ all_hidden_states += (hidden_states,)
626
+ layer_outputs = block(
627
+ hidden_states,
628
+ attention_mask,
629
+ position_ids,
630
+ deterministic,
631
+ init_cache,
632
+ output_attentions,
633
+ )
634
+ hidden_states = layer_outputs[0]
635
+
636
+ if output_attentions:
637
+ all_attentions += (layer_outputs[1],)
638
+
639
+ # this contains possible `None` values - `FlaxGemma2Module` will filter them out
640
+ outputs = (hidden_states, all_hidden_states, all_attentions)
641
+
642
+ return outputs
643
+
644
+
645
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaModule with Llama->Gemma2
646
+ class FlaxTPUGemma2Module(nn.Module):
647
+ config: TPUGemma2Config
648
+ dtype: jnp.dtype = jnp.float32
649
+ gradient_checkpointing: bool = False
650
+
651
+ def setup(self):
652
+ self.hidden_size = self.config.hidden_size
653
+ embedding_init = jax.nn.initializers.normal(stddev=self.config.initializer_range)
654
+ self.embed_tokens = nn.Embed(
655
+ self.config.vocab_size,
656
+ self.hidden_size,
657
+ embedding_init=embedding_init,
658
+ dtype=self.dtype,
659
+ )
660
+ self.layers = FlaxTPUGemma2LayerCollection(self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing)
661
+ self.norm = FlaxTPUGemma2RMSNorm(self.config, dtype=self.dtype)
662
+
663
+ # Ignore copy
664
+ def __call__(
665
+ self,
666
+ input_ids,
667
+ inputs_embeds=None,
668
+ attention_mask=None,
669
+ position_ids=None,
670
+ deterministic=True,
671
+ init_cache: bool = False,
672
+ output_attentions: bool = False,
673
+ output_hidden_states: bool = False,
674
+ return_dict: bool = True,
675
+ ):
676
+ if inputs_embeds is None:
677
+ inputs_embeds = self.embed_tokens(input_ids.astype("i4"))
678
+
679
+ inputs_embeds = inputs_embeds * (self.config.hidden_size**0.5)
680
+
681
+ outputs = self.layers(
682
+ inputs_embeds,
683
+ position_ids=position_ids,
684
+ attention_mask=attention_mask,
685
+ deterministic=deterministic,
686
+ init_cache=init_cache,
687
+ output_attentions=output_attentions,
688
+ output_hidden_states=output_hidden_states,
689
+ return_dict=return_dict,
690
+ )
691
+
692
+ hidden_states = outputs[0]
693
+ hidden_states = self.norm(hidden_states)
694
+
695
+ if output_hidden_states:
696
+ all_hidden_states = outputs[1] + (hidden_states,)
697
+ outputs = (hidden_states, all_hidden_states) + outputs[2:]
698
+ else:
699
+ outputs = (hidden_states,) + outputs[1:]
700
+
701
+ if not return_dict:
702
+ return tuple(v for v in outputs if v is not None)
703
+
704
+ return FlaxBaseModelOutput(
705
+ last_hidden_state=hidden_states,
706
+ hidden_states=outputs[1],
707
+ attentions=outputs[-1],
708
+ )
709
+
710
+
711
+ @add_start_docstrings(
712
+ "The bare Gemma2 Model transformer outputting raw hidden-states without any specific head on top.",
713
+ TPU_GEMMA2_START_DOCSTRING,
714
+ )
715
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaModel with Llama->Gemma2
716
+ class FlaxTPUGemma2Model(FlaxTPUGemma2PreTrainedModel):
717
+ module_class = FlaxTPUGemma2Module
718
+
719
+
720
+ append_call_sample_docstring(
721
+ FlaxTPUGemma2Model,
722
+ _CHECKPOINT_FOR_DOC,
723
+ FlaxBaseModelOutput,
724
+ _CONFIG_FOR_DOC,
725
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
726
+ )
727
+
728
+
729
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaForCausalLMModule with Llama->Gemma2
730
+ class FlaxTPUGemma2ForCausalLMModule(nn.Module):
731
+ config: TPUGemma2Config
732
+ dtype: jnp.dtype = jnp.float32
733
+ gradient_checkpointing: bool = False
734
+
735
+ def setup(self):
736
+ self.model = FlaxTPUGemma2Module(self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing)
737
+ self.lm_head = nn.Dense(
738
+ self.config.vocab_size,
739
+ use_bias=False,
740
+ dtype=self.dtype,
741
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
742
+ )
743
+
744
+ # Ignore copy
745
+ def __call__(
746
+ self,
747
+ input_ids,
748
+ inputs_embeds=None,
749
+ attention_mask=None,
750
+ position_ids=None,
751
+ deterministic: bool = True,
752
+ init_cache: bool = False,
753
+ output_attentions: bool = False,
754
+ output_hidden_states: bool = False,
755
+ return_dict: bool = True,
756
+ ):
757
+ outputs = self.model(
758
+ input_ids,
759
+ inputs_embeds=inputs_embeds,
760
+ position_ids=position_ids,
761
+ attention_mask=attention_mask,
762
+ deterministic=deterministic,
763
+ init_cache=init_cache,
764
+ output_attentions=output_attentions,
765
+ output_hidden_states=output_hidden_states,
766
+ return_dict=return_dict,
767
+ )
768
+
769
+ hidden_states = outputs[0]
770
+ if self.config.tie_word_embeddings:
771
+ shared_kernel = self.model.variables["params"]["embed_tokens"]["embedding"].T
772
+ lm_logits = self.lm_head.apply({"params": {"kernel": shared_kernel}}, hidden_states)
773
+ else:
774
+ lm_logits = self.lm_head(hidden_states)
775
+
776
+ if self.config.final_logit_softcapping is not None:
777
+ lm_logits = lm_logits / self.config.final_logit_softcapping
778
+ lm_logits = jnp.tanh(lm_logits)
779
+ lm_logits = lm_logits * self.config.final_logit_softcapping
780
+
781
+ if not return_dict:
782
+ return (lm_logits,) + outputs[1:]
783
+
784
+ return FlaxCausalLMOutput(logits=lm_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
785
+
786
+
787
+ @add_start_docstrings(
788
+ """
789
+ The Gemma2 Model transformer with a language modeling head (linear layer) on top.
790
+ """,
791
+ TPU_GEMMA2_START_DOCSTRING,
792
+ )
793
+ # Copied from transformers.models.gptj.modeling_flax_gptj.FlaxGPTJForCausalLM with GPTJ->Gemma2
794
+ class FlaxTPUGemma2ForCausalLM(FlaxTPUGemma2PreTrainedModel):
795
+ module_class = FlaxTPUGemma2ForCausalLMModule
796
+
797
+ def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
798
+ # initializing the cache
799
+ batch_size, seq_length = input_ids.shape
800
+
801
+ past_key_values = self.init_cache(batch_size, max_length)
802
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
803
+ # But since Gemma2 uses a causal mask, those positions are masked anyways.
804
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
805
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
806
+ if attention_mask is not None:
807
+ position_ids = attention_mask.cumsum(axis=-1) - 1
808
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
809
+ else:
810
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
811
+
812
+ return {
813
+ "past_key_values": past_key_values,
814
+ "attention_mask": extended_attention_mask,
815
+ "position_ids": position_ids,
816
+ }
817
+
818
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
819
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
820
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
821
+ return model_kwargs
822
+
823
+
824
+ append_call_sample_docstring(
825
+ FlaxTPUGemma2ForCausalLM,
826
+ _CHECKPOINT_FOR_DOC,
827
+ FlaxCausalLMOutput,
828
+ _CONFIG_FOR_DOC,
829
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
830
+ )
modelling_tpu_gemma2.py ADDED
@@ -0,0 +1,1417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TPU Gemma2 model with support for expanding input ids (used in byte-level models)."""
2
+
3
+ from typing import List, Optional, Tuple, Union
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.utils.checkpoint
8
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
9
+
10
+ from transformers.activations import ACT2FN
11
+ from transformers.cache_utils import Cache, HybridCache
12
+ from transformers.generation import GenerationMixin
13
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
14
+ from transformers.modeling_outputs import (
15
+ BaseModelOutputWithPast,
16
+ CausalLMOutputWithPast,
17
+ SequenceClassifierOutputWithPast,
18
+ TokenClassifierOutput,
19
+ )
20
+ from transformers.modeling_utils import PreTrainedModel
21
+ from transformers.utils import (
22
+ add_start_docstrings,
23
+ add_start_docstrings_to_model_forward,
24
+ is_flash_attn_greater_or_equal,
25
+ is_flash_attn_greater_or_equal_2_10,
26
+ logging,
27
+ replace_return_docstrings,
28
+ )
29
+ from .configuration_tpu_gemma2 import TPUGemma2Config
30
+
31
+ def torch_expand_input_ids(
32
+ input_ids,
33
+ expand_input_ids_dict,
34
+ maxlen,
35
+ last_n=None,
36
+ ):
37
+ expanded_input_ids = torch.zeros_like(input_ids)
38
+
39
+ for example_idx in range(len(input_ids)):
40
+ last_maxlen_ids = []
41
+
42
+ for i in range(len(input_ids[example_idx])):
43
+ last_maxlen_ids.insert(0, int(input_ids[example_idx][i] + 1))
44
+ if len(last_maxlen_ids) > maxlen:
45
+ last_maxlen_ids.pop()
46
+
47
+ if last_n is not None and i < len(input_ids[example_idx]) - last_n:
48
+ continue
49
+
50
+ if last_maxlen_ids[0] in expand_input_ids_dict[1]:
51
+ expanded_input_ids[example_idx][i] = expand_input_ids_dict[0][(last_maxlen_ids[0],)] - 1
52
+ else:
53
+ found = False
54
+ last_maxlen_up_to = len(last_maxlen_ids)
55
+
56
+ while not found and last_maxlen_up_to > 0:
57
+ try:
58
+ expanded_input_ids[example_idx][i] = expand_input_ids_dict[0][tuple(last_maxlen_ids[:last_maxlen_up_to])] - 1
59
+ found = True
60
+ except KeyError:
61
+ last_maxlen_up_to -= 1
62
+
63
+ return expanded_input_ids
64
+
65
+ class TPUGemma2RMSNorm(nn.Module):
66
+ def __init__(self, dim: int, eps: float = 1e-6):
67
+ super().__init__()
68
+ self.eps = eps
69
+ self.weight = nn.Parameter(torch.zeros(dim))
70
+
71
+ def _norm(self, x):
72
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
73
+
74
+ def forward(self, x):
75
+ output = self._norm(x.float())
76
+ # Llama does x.to(float16) * w whilst Gemma2 is (x * w).to(float16)
77
+ # See https://github.com/huggingface/transformers/pull/29402
78
+ output = output * (1.0 + self.weight.float())
79
+ return output.type_as(x)
80
+
81
+ def extra_repr(self):
82
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
83
+
84
+
85
+ class TPUGemma2MLP(nn.Module):
86
+ def __init__(self, config):
87
+ super().__init__()
88
+ self.config = config
89
+ self.hidden_size = config.hidden_size
90
+ self.intermediate_size = config.intermediate_size
91
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
92
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
93
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
94
+ self.act_fn = ACT2FN[config.hidden_activation]
95
+
96
+ def forward(self, x):
97
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
98
+
99
+
100
+ logger = logging.get_logger(__name__)
101
+
102
+
103
+ class TPUGemma2RotaryEmbedding(nn.Module):
104
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
105
+ super().__init__()
106
+
107
+ self.dim = dim
108
+ self.max_position_embeddings = max_position_embeddings
109
+ self.base = base
110
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
111
+ self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
112
+
113
+ @torch.no_grad()
114
+ def forward(self, x, position_ids, seq_len=None):
115
+ # x: [bs, num_attention_heads, seq_len, head_size]
116
+ self.inv_freq.to(x.device)
117
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
118
+ position_ids_expanded = position_ids[:, None, :].float()
119
+ # Force float32 since bfloat16 loses precision on long contexts
120
+ # See https://github.com/huggingface/transformers/pull/29285
121
+ device_type = x.device.type
122
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
123
+ with torch.autocast(device_type=device_type, enabled=False):
124
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
125
+ emb = torch.cat((freqs, freqs), dim=-1)
126
+ cos = emb.cos()
127
+ sin = emb.sin()
128
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
129
+
130
+
131
+ def rotate_half(x):
132
+ """Rotates half the hidden dims of the input."""
133
+ x1 = x[..., : x.shape[-1] // 2]
134
+ x2 = x[..., x.shape[-1] // 2 :]
135
+ return torch.cat((-x2, x1), dim=-1)
136
+
137
+
138
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
139
+ """Applies Rotary Position Embedding to the query and key tensors.
140
+
141
+ Args:
142
+ q (`torch.Tensor`): The query tensor.
143
+ k (`torch.Tensor`): The key tensor.
144
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
145
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
146
+ position_ids (`torch.Tensor`, *optional*):
147
+ Deprecated and unused.
148
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
149
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
150
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
151
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
152
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
153
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
154
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
155
+ Returns:
156
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
157
+ """
158
+ cos = cos.unsqueeze(unsqueeze_dim)
159
+ sin = sin.unsqueeze(unsqueeze_dim)
160
+ q_embed = (q * cos) + (rotate_half(q) * sin)
161
+ k_embed = (k * cos) + (rotate_half(k) * sin)
162
+ return q_embed, k_embed
163
+
164
+
165
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
166
+ """
167
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
168
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
169
+ """
170
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
171
+ if n_rep == 1:
172
+ return hidden_states
173
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
174
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
175
+
176
+
177
+ class TPUGemma2Attention(nn.Module):
178
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
179
+
180
+ def __init__(self, config: TPUGemma2Config, layer_idx: Optional[int] = None):
181
+ super().__init__()
182
+ self.config = config
183
+ self.layer_idx = layer_idx
184
+ if layer_idx is None:
185
+ logger.warning_once(
186
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
187
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
188
+ "when creating this class."
189
+ )
190
+
191
+ self.attention_dropout = config.attention_dropout
192
+ self.hidden_size = config.hidden_size
193
+ self.num_heads = config.num_attention_heads
194
+ self.head_dim = config.head_dim
195
+ self.num_key_value_heads = config.num_key_value_heads
196
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
197
+ self.max_position_embeddings = config.max_position_embeddings
198
+ self.rope_theta = config.rope_theta
199
+ self.is_causal = True
200
+ self.scaling = config.query_pre_attn_scalar**-0.5
201
+
202
+ if self.hidden_size % self.num_heads != 0:
203
+ raise ValueError(
204
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
205
+ f" and `num_heads`: {self.num_heads})."
206
+ )
207
+
208
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
209
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
210
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
211
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
212
+ self.sliding_window = config.sliding_window if not bool(layer_idx % 2) else None
213
+ self.rotary_emb = TPUGemma2RotaryEmbedding(
214
+ self.head_dim,
215
+ max_position_embeddings=self.max_position_embeddings,
216
+ base=self.rope_theta,
217
+ )
218
+
219
+ def forward(
220
+ self,
221
+ hidden_states: torch.Tensor,
222
+ attention_mask: Optional[torch.Tensor] = None,
223
+ position_ids: Optional[torch.LongTensor] = None,
224
+ past_key_value: Optional[Cache] = None,
225
+ output_attentions: bool = False,
226
+ use_cache: bool = False,
227
+ cache_position: Optional[torch.LongTensor] = None,
228
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
229
+ bsz, q_len, _ = hidden_states.size()
230
+
231
+ query_states = self.q_proj(hidden_states)
232
+ key_states = self.k_proj(hidden_states)
233
+ value_states = self.v_proj(hidden_states)
234
+
235
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
236
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
237
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
238
+
239
+ cos, sin = self.rotary_emb(value_states, position_ids)
240
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
241
+
242
+ if past_key_value is not None:
243
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
244
+ cache_kwargs = {
245
+ "sin": sin,
246
+ "cos": cos,
247
+ "sliding_window": self.sliding_window,
248
+ "cache_position": cache_position,
249
+ }
250
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
251
+
252
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
253
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
254
+
255
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
256
+
257
+ if self.config.attn_logit_softcapping is not None:
258
+ attn_weights = attn_weights / self.config.attn_logit_softcapping
259
+ attn_weights = torch.tanh(attn_weights)
260
+ attn_weights = attn_weights * self.config.attn_logit_softcapping
261
+ if attention_mask is not None: # no matter the length, we just slice it
262
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
263
+ attn_weights = attn_weights + causal_mask
264
+
265
+ # upcast attention to fp32
266
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
267
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
268
+ attn_output = torch.matmul(attn_weights, value_states)
269
+
270
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
271
+ raise ValueError(
272
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
273
+ f" {attn_output.size()}"
274
+ )
275
+
276
+ attn_output = attn_output.transpose(1, 2).contiguous()
277
+
278
+ attn_output = attn_output.view(bsz, q_len, -1)
279
+ attn_output = self.o_proj(attn_output)
280
+
281
+ if not output_attentions:
282
+ attn_weights = None
283
+
284
+ return attn_output, attn_weights, past_key_value
285
+
286
+
287
+ class TPUGemma2FlashAttention2(TPUGemma2Attention):
288
+ """
289
+ Gemma2 flash attention module. This module inherits from `Gemma2Attention` as the weights of the module stays
290
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
291
+ flash attention and deal with padding tokens in case the input contains any of them.
292
+ """
293
+
294
+ def __init__(self, *args, **kwargs):
295
+ super().__init__(*args, **kwargs)
296
+
297
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
298
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
299
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
300
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
301
+
302
+ def forward(
303
+ self,
304
+ hidden_states: torch.Tensor,
305
+ attention_mask: Optional[torch.LongTensor] = None,
306
+ position_ids: Optional[torch.LongTensor] = None,
307
+ past_key_value: Optional[Cache] = None,
308
+ output_attentions: bool = False,
309
+ use_cache: bool = False,
310
+ cache_position: Optional[torch.LongTensor] = None,
311
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
312
+ output_attentions = False
313
+
314
+ bsz, q_len, _ = hidden_states.size()
315
+
316
+ query_states = self.q_proj(hidden_states)
317
+ key_states = self.k_proj(hidden_states)
318
+ value_states = self.v_proj(hidden_states)
319
+
320
+ # Flash attention requires the input to have the shape
321
+ # batch_size x seq_length x head_dim x hidden_dim
322
+ # therefore we just need to keep the original shape
323
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
324
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
325
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
326
+
327
+ cos, sin = self.rotary_emb(value_states, position_ids)
328
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
329
+
330
+ if past_key_value is not None:
331
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
332
+ cache_kwargs = {
333
+ "sin": sin,
334
+ "cos": cos,
335
+ "sliding_window": self.sliding_window,
336
+ "cache_position": cache_position,
337
+ }
338
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
339
+
340
+ if attention_mask is not None:
341
+ seq_len = attention_mask.shape[1]
342
+ key_states = key_states[:, :, :seq_len]
343
+ value_states = value_states[:, :, :seq_len]
344
+
345
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
346
+ # to be able to avoid many of these transpose/reshape/view.
347
+ query_states = query_states.transpose(1, 2)
348
+ key_states = key_states.transpose(1, 2)
349
+ value_states = value_states.transpose(1, 2)
350
+
351
+ dropout_rate = self.attention_dropout if self.training else 0.0
352
+
353
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
354
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
355
+ # cast them back in the correct dtype just to be sure everything works as expected.
356
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
357
+ # in fp32. (Gemma2RMSNorm handles it correctly)
358
+
359
+ input_dtype = query_states.dtype
360
+ if input_dtype == torch.float32:
361
+ if torch.is_autocast_enabled():
362
+ target_dtype = torch.get_autocast_gpu_dtype()
363
+ # Handle the case where the model is quantized
364
+ elif hasattr(self.config, "_pre_quantization_dtype"):
365
+ target_dtype = self.config._pre_quantization_dtype
366
+ else:
367
+ target_dtype = self.q_proj.weight.dtype
368
+
369
+ logger.warning_once(
370
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
371
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
372
+ f" {target_dtype}."
373
+ )
374
+
375
+ query_states = query_states.to(target_dtype)
376
+ key_states = key_states.to(target_dtype)
377
+ value_states = value_states.to(target_dtype)
378
+
379
+ attn_output = _flash_attention_forward(
380
+ query_states,
381
+ key_states,
382
+ value_states,
383
+ attention_mask,
384
+ q_len,
385
+ dropout=dropout_rate,
386
+ softmax_scale=self.scaling,
387
+ is_causal=self.is_causal,
388
+ sliding_window=self.sliding_window,
389
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
390
+ softcap=self.config.attn_logit_softcapping if is_flash_attn_greater_or_equal("2.6.0") else None,
391
+ )
392
+
393
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
394
+ attn_output = self.o_proj(attn_output)
395
+
396
+ if not output_attentions:
397
+ attn_weights = None
398
+
399
+ return attn_output, attn_weights, past_key_value
400
+
401
+
402
+ class TPUGemma2SdpaAttention(TPUGemma2Attention):
403
+ """
404
+ Gemma2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
405
+ `Gemma2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
406
+ SDPA API.
407
+ """
408
+
409
+ # Adapted from Gemma2Attention.forward
410
+ def forward(
411
+ self,
412
+ hidden_states: torch.Tensor,
413
+ attention_mask: Optional[torch.Tensor] = None,
414
+ position_ids: Optional[torch.LongTensor] = None,
415
+ past_key_value: Optional[Cache] = None,
416
+ output_attentions: bool = False,
417
+ use_cache: bool = False,
418
+ cache_position: Optional[torch.LongTensor] = None,
419
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
420
+ if output_attentions:
421
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
422
+ logger.warning_once(
423
+ "Gemma2Model is using Gemma2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
424
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
425
+ )
426
+ return super().forward(
427
+ hidden_states=hidden_states,
428
+ attention_mask=attention_mask,
429
+ position_ids=position_ids,
430
+ past_key_value=past_key_value,
431
+ output_attentions=output_attentions,
432
+ use_cache=use_cache,
433
+ cache_position=cache_position,
434
+ )
435
+
436
+ bsz, q_len, _ = hidden_states.size()
437
+
438
+ query_states = self.q_proj(hidden_states)
439
+ key_states = self.k_proj(hidden_states)
440
+ value_states = self.v_proj(hidden_states)
441
+
442
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
443
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
444
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
445
+
446
+ cos, sin = self.rotary_emb(value_states, position_ids)
447
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
448
+
449
+ if past_key_value is not None:
450
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
451
+ cache_kwargs = {
452
+ "sin": sin,
453
+ "cos": cos,
454
+ "sliding_window": self.sliding_window,
455
+ "cache_position": cache_position,
456
+ }
457
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
458
+
459
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
460
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
461
+
462
+ causal_mask = attention_mask
463
+ if attention_mask is not None:
464
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
465
+
466
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
467
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
468
+ if query_states.device.type == "cuda" and causal_mask is not None:
469
+ query_states = query_states.contiguous()
470
+ key_states = key_states.contiguous()
471
+ value_states = value_states.contiguous()
472
+
473
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
474
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
475
+ is_causal = True if causal_mask is None and q_len > 1 else False
476
+
477
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
478
+ query_states,
479
+ key_states,
480
+ value_states,
481
+ attn_mask=causal_mask,
482
+ dropout_p=self.attention_dropout if self.training else 0.0,
483
+ is_causal=is_causal,
484
+ scale=self.scaling,
485
+ )
486
+
487
+ attn_output = attn_output.transpose(1, 2).contiguous()
488
+ attn_output = attn_output.view(bsz, q_len, -1)
489
+
490
+ attn_output = self.o_proj(attn_output)
491
+
492
+ return attn_output, None, past_key_value
493
+
494
+
495
+ TPU_GEMMA2_ATTENTION_CLASSES = {
496
+ "eager": TPUGemma2Attention,
497
+ "flash_attention_2": TPUGemma2FlashAttention2,
498
+ "sdpa": TPUGemma2SdpaAttention,
499
+ }
500
+
501
+
502
+ class TPUGemma2DecoderLayer(nn.Module):
503
+ def __init__(self, config: TPUGemma2Config, layer_idx: int):
504
+ super().__init__()
505
+ self.hidden_size = config.hidden_size
506
+ self.self_attn = TPU_GEMMA2_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
507
+ self.mlp = TPUGemma2MLP(config)
508
+ self.input_layernorm = TPUGemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
509
+ self.config = config
510
+ self.is_sliding = not bool(layer_idx % 2)
511
+ self.pre_feedforward_layernorm = TPUGemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
512
+ self.post_feedforward_layernorm = TPUGemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
513
+ self.sliding_window = config.sliding_window
514
+ self.post_attention_layernorm = TPUGemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
515
+
516
+ def forward(
517
+ self,
518
+ hidden_states: torch.Tensor,
519
+ attention_mask: Optional[torch.Tensor] = None,
520
+ position_ids: Optional[torch.LongTensor] = None,
521
+ past_key_value: Optional[Cache] = None,
522
+ output_attentions: Optional[bool] = False,
523
+ use_cache: Optional[bool] = False,
524
+ cache_position: Optional[torch.LongTensor] = None,
525
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
526
+ """
527
+ Args:
528
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
529
+ attention_mask (`torch.FloatTensor`, *optional*):
530
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
531
+ query_sequence_length, key_sequence_length)` if default attention is used.
532
+ output_attentions (`bool`, *optional*):
533
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
534
+ returned tensors for more detail.
535
+ use_cache (`bool`, *optional*):
536
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
537
+ (see `past_key_values`).
538
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
539
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
540
+ Indices depicting the position of the input sequence tokens in the sequence
541
+ kwargs (`dict`, *optional*):
542
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
543
+ into the model
544
+ """
545
+ if self.is_sliding and attention_mask is not None: # efficient SDPA and no padding
546
+ # Flash-attn is a 2D tensor
547
+ if self.config._attn_implementation == "flash_attention_2":
548
+ if past_key_value is not None: # when decoding
549
+ attention_mask = attention_mask[:, -self.sliding_window :]
550
+ else:
551
+ min_dtype = torch.finfo(hidden_states.dtype).min
552
+ sliding_window_mask = torch.tril(
553
+ torch.ones_like(attention_mask, dtype=torch.bool), diagonal=-self.sliding_window
554
+ )
555
+ attention_mask = torch.where(sliding_window_mask, min_dtype, attention_mask)
556
+ if attention_mask.shape[-1] <= 1: # when decoding
557
+ attention_mask = attention_mask[:, :, :, -self.sliding_window :]
558
+
559
+ residual = hidden_states
560
+
561
+ hidden_states = self.input_layernorm(hidden_states)
562
+
563
+ # Self Attention
564
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
565
+ hidden_states=hidden_states,
566
+ attention_mask=attention_mask,
567
+ position_ids=position_ids,
568
+ past_key_value=past_key_value,
569
+ output_attentions=output_attentions,
570
+ use_cache=use_cache,
571
+ cache_position=cache_position,
572
+ )
573
+ hidden_states = self.post_attention_layernorm(hidden_states)
574
+ hidden_states = residual + hidden_states
575
+
576
+ residual = hidden_states
577
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
578
+ hidden_states = self.mlp(hidden_states)
579
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
580
+ hidden_states = residual + hidden_states
581
+
582
+ outputs = (hidden_states,)
583
+
584
+ if output_attentions:
585
+ outputs += (self_attn_weights,)
586
+
587
+ if use_cache:
588
+ outputs += (present_key_value,)
589
+
590
+ return outputs
591
+
592
+
593
+ TPU_GEMMA2_START_DOCSTRING = r"""
594
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
595
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
596
+ etc.)
597
+
598
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
599
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
600
+ and behavior.
601
+
602
+ Parameters:
603
+ config ([`Gemma2Config`]):
604
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
605
+ load the weights associated with the model, only the configuration. Check out the
606
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
607
+ """
608
+
609
+
610
+ @add_start_docstrings(
611
+ "The bare Gemma2 Model outputting raw hidden-states without any specific head on top.",
612
+ TPU_GEMMA2_START_DOCSTRING,
613
+ )
614
+ class TPUGemma2PreTrainedModel(PreTrainedModel):
615
+ config_class = TPUGemma2Config
616
+ base_model_prefix = "model"
617
+ supports_gradient_checkpointing = True
618
+ _no_split_modules = ["TPUGemma2DecoderLayer"]
619
+ _skip_keys_device_placement = ["past_key_values"]
620
+ _supports_flash_attn_2 = True
621
+ _supports_sdpa = True
622
+ _supports_cache_class = True
623
+ _supports_quantized_cache = False
624
+ _supports_static_cache = True
625
+
626
+ def _init_weights(self, module):
627
+ std = self.config.initializer_range
628
+ if isinstance(module, nn.Linear):
629
+ module.weight.data.normal_(mean=0.0, std=std)
630
+ if module.bias is not None:
631
+ module.bias.data.zero_()
632
+ elif isinstance(module, nn.Embedding):
633
+ module.weight.data.normal_(mean=0.0, std=std)
634
+ if module.padding_idx is not None:
635
+ module.weight.data[module.padding_idx].zero_()
636
+
637
+ @classmethod
638
+ def _check_and_enable_sdpa(cls, config, hard_check_only: bool = False):
639
+ """
640
+ Overloads `PreTrainedModel._check_and_enable_sdpa` so as to DISABLE torch SDPA by default on Gemma2 models.
641
+ SDPA reduces the model performance on Gemma2 because of the logits softcapping.
642
+ """
643
+ config = super()._check_and_enable_sdpa(config, hard_check_only=hard_check_only)
644
+
645
+ # if using the default path -> swap sdpa by eager
646
+ if not hard_check_only and config._attn_implementation == "sdpa":
647
+ config._attn_implementation = "eager"
648
+
649
+ return config
650
+
651
+
652
+ _CONFIG_FOR_DOC = "TPUGemma2Config"
653
+
654
+
655
+ TPU_GEMMA2_INPUTS_DOCSTRING = r"""
656
+ Args:
657
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
658
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
659
+ it.
660
+
661
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
662
+ [`PreTrainedTokenizer.__call__`] for details.
663
+
664
+ [What are input IDs?](../glossary#input-ids)
665
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
666
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
667
+
668
+ - 1 for tokens that are **not masked**,
669
+ - 0 for tokens that are **masked**.
670
+
671
+ [What are attention masks?](../glossary#attention-mask)
672
+
673
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
674
+ [`PreTrainedTokenizer.__call__`] for details.
675
+
676
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
677
+ `past_key_values`).
678
+
679
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
680
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
681
+ information on the default strategy.
682
+
683
+ - 1 indicates the head is **not masked**,
684
+ - 0 indicates the head is **masked**.
685
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
686
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
687
+ config.n_positions - 1]`.
688
+
689
+ [What are position IDs?](../glossary#position-ids)
690
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
691
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
692
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
693
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
694
+
695
+ Two formats are allowed:
696
+ - a [`~cache_utils.Cache`] instance, see our
697
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
698
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
699
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
700
+ cache format.
701
+
702
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
703
+ legacy cache format will be returned.
704
+
705
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
706
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
707
+ of shape `(batch_size, sequence_length)`.
708
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
709
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
710
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
711
+ model's internal embedding lookup matrix.
712
+ use_cache (`bool`, *optional*):
713
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
714
+ `past_key_values`).
715
+ output_attentions (`bool`, *optional*):
716
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
717
+ tensors for more detail.
718
+ output_hidden_states (`bool`, *optional*):
719
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
720
+ more detail.
721
+ return_dict (`bool`, *optional*):
722
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
723
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
724
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
725
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
726
+ the complete sequence length.
727
+ """
728
+
729
+
730
+ @add_start_docstrings(
731
+ "The bare Gemma2 Model outputting raw hidden-states without any specific head on top.",
732
+ TPU_GEMMA2_START_DOCSTRING,
733
+ )
734
+ class TPUGemma2Model(TPUGemma2PreTrainedModel):
735
+ """
736
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Gemma2DecoderLayer`]
737
+
738
+ Args:
739
+ config: TPUGemma2Config
740
+ """
741
+
742
+ def __init__(self, config: TPUGemma2Config):
743
+ super().__init__(config)
744
+ self.padding_idx = config.pad_token_id
745
+ self.vocab_size = config.vocab_size
746
+
747
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
748
+ if config.expand_input_ids:
749
+ self.expand_embed_tokens = nn.Embedding(config.expand_input_ids_vocab_size, config.hidden_size)
750
+ self.expand_input_ids_dict = (
751
+ {tuple(int(n) for n in k.split(",")) if len(k) > 0 else (): v for k, v in config.expand_input_ids_dict[0].items()},
752
+ set(int(n) for n in config.expand_input_ids_dict[1]),
753
+ )
754
+ else:
755
+ self.expand_embed_tokens = None
756
+
757
+ self.layers = nn.ModuleList(
758
+ [TPUGemma2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
759
+ )
760
+ self.norm = TPUGemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
761
+ self.gradient_checkpointing = False
762
+
763
+ # Initialize weights and apply final processing
764
+ self.post_init()
765
+
766
+ def get_input_embeddings(self):
767
+ return self.embed_tokens
768
+
769
+ def set_input_embeddings(self, value):
770
+ self.embed_tokens = value
771
+
772
+ @add_start_docstrings_to_model_forward(TPU_GEMMA2_INPUTS_DOCSTRING)
773
+ def forward(
774
+ self,
775
+ input_ids: torch.LongTensor = None,
776
+ attention_mask: Optional[torch.Tensor] = None,
777
+ position_ids: Optional[torch.LongTensor] = None,
778
+ past_key_values: Optional[HybridCache] = None,
779
+ inputs_embeds: Optional[torch.FloatTensor] = None,
780
+ use_cache: Optional[bool] = None,
781
+ output_attentions: Optional[bool] = None,
782
+ output_hidden_states: Optional[bool] = None,
783
+ return_dict: Optional[bool] = None,
784
+ cache_position: Optional[torch.LongTensor] = None,
785
+ past_input_ids: Optional[torch.LongTensor] = None,
786
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
787
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
788
+ output_hidden_states = (
789
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
790
+ )
791
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
792
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
793
+
794
+ if (input_ids is None) ^ (inputs_embeds is not None):
795
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
796
+
797
+ if self.gradient_checkpointing and self.training and use_cache:
798
+ logger.warning_once(
799
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
800
+ )
801
+ use_cache = False
802
+
803
+ if inputs_embeds is None:
804
+
805
+ if self.config.expand_input_ids:
806
+ input_ids_to_expand = past_input_ids if past_input_ids is not None else input_ids
807
+
808
+ expanded_input_ids = torch_expand_input_ids(
809
+ input_ids_to_expand,
810
+ self.expand_input_ids_dict,
811
+ self.config.expand_input_ids_maxlen,
812
+ last_n=input_ids.shape[1],
813
+ )[:, -input_ids.shape[1]:]
814
+ inputs_embeds = self.embed_tokens(input_ids) + self.expand_embed_tokens(expanded_input_ids)
815
+ else:
816
+ inputs_embeds = self.embed_tokens(input_ids)
817
+
818
+ if use_cache and past_key_values is None and not self.training:
819
+ batch_size, seq_len, _ = inputs_embeds.shape
820
+ past_key_values = HybridCache(
821
+ self.config,
822
+ batch_size=batch_size,
823
+ max_cache_len=seq_len,
824
+ device=self.device,
825
+ dtype=inputs_embeds.dtype,
826
+ )
827
+
828
+ if cache_position is None:
829
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
830
+ cache_position = torch.arange(
831
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
832
+ )
833
+
834
+ if position_ids is None:
835
+ position_ids = cache_position.unsqueeze(0)
836
+
837
+ causal_mask = self._update_causal_mask(
838
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
839
+ )
840
+
841
+ # embed positions
842
+ hidden_states = inputs_embeds
843
+
844
+ # normalized
845
+ # Gemma2 downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
846
+ # See https://github.com/huggingface/transformers/pull/29402
847
+ normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype)
848
+ hidden_states = hidden_states * normalizer
849
+
850
+ # decoder layers
851
+ all_hidden_states = () if output_hidden_states else None
852
+ all_self_attns = () if output_attentions else None
853
+
854
+ for decoder_layer in self.layers:
855
+ if output_hidden_states:
856
+ all_hidden_states += (hidden_states,)
857
+
858
+ if self.gradient_checkpointing and self.training:
859
+ layer_outputs = self._gradient_checkpointing_func(
860
+ decoder_layer.__call__,
861
+ hidden_states,
862
+ causal_mask,
863
+ position_ids,
864
+ past_key_values,
865
+ output_attentions,
866
+ use_cache,
867
+ cache_position,
868
+ )
869
+ else:
870
+ layer_outputs = decoder_layer(
871
+ hidden_states,
872
+ attention_mask=causal_mask,
873
+ position_ids=position_ids,
874
+ past_key_value=past_key_values,
875
+ output_attentions=output_attentions,
876
+ use_cache=use_cache,
877
+ cache_position=cache_position,
878
+ )
879
+
880
+ hidden_states = layer_outputs[0]
881
+
882
+ if output_attentions:
883
+ all_self_attns += (layer_outputs[1],)
884
+
885
+ hidden_states = self.norm(hidden_states)
886
+
887
+ if output_hidden_states:
888
+ all_hidden_states += (hidden_states,)
889
+
890
+ next_cache = past_key_values if use_cache else None
891
+
892
+ if not return_dict:
893
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
894
+ return BaseModelOutputWithPast(
895
+ last_hidden_state=hidden_states,
896
+ past_key_values=next_cache,
897
+ hidden_states=all_hidden_states,
898
+ attentions=all_self_attns,
899
+ )
900
+
901
+ def _update_causal_mask(
902
+ self,
903
+ attention_mask: torch.Tensor,
904
+ input_tensor: torch.Tensor,
905
+ cache_position: torch.Tensor,
906
+ past_key_values: HybridCache,
907
+ output_attentions: bool,
908
+ ):
909
+ # Flash Attention currently doesn't support static cache but Gemma2 work only with static cache.
910
+ # So we will pass in attention mask as is in any case, not only when ther's padding. Then we'll use its shape
911
+ # to cut out keys/values trailing 0 used in static cache. This workaround should be compile compatible
912
+ # as it doesn't cause dynamic control issues.
913
+ if self.config._attn_implementation == "flash_attention_2":
914
+ return attention_mask
915
+
916
+ dtype, device = input_tensor.dtype, input_tensor.device
917
+ sequence_length = input_tensor.shape[1]
918
+ if isinstance(past_key_values, HybridCache):
919
+ target_length = past_key_values.get_max_cache_shape()
920
+ else:
921
+ target_length = attention_mask.shape[-1] if attention_mask is not None else input_tensor.shape[1]
922
+
923
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
924
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
925
+ attention_mask,
926
+ sequence_length=sequence_length,
927
+ target_length=target_length,
928
+ dtype=dtype,
929
+ device=device,
930
+ cache_position=cache_position,
931
+ batch_size=input_tensor.shape[0],
932
+ )
933
+ return causal_mask
934
+
935
+ @staticmethod
936
+ def _prepare_4d_causal_attention_mask_with_cache_position(
937
+ attention_mask: torch.Tensor,
938
+ sequence_length: int,
939
+ target_length: int,
940
+ dtype: torch.dtype,
941
+ device: torch.device,
942
+ cache_position: torch.Tensor,
943
+ batch_size: int,
944
+ ):
945
+ """
946
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
947
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
948
+
949
+ Args:
950
+ attention_mask (`torch.Tensor`):
951
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
952
+ `(batch_size, 1, query_length, key_value_length)`.
953
+ sequence_length (`int`):
954
+ The sequence length being processed.
955
+ target_length (`int`):
956
+ The target length: when generating with static cache, the mask should be as long as the static cache,
957
+ to account for the 0 padding, the part of the cache that is not filled yet.
958
+ dtype (`torch.dtype`):
959
+ The dtype to use for the 4D attention mask.
960
+ device (`torch.device`):
961
+ The device to plcae the 4D attention mask on.
962
+ cache_position (`torch.Tensor`):
963
+ Indices depicting the position of the input sequence tokens in the sequence.
964
+ batch_size (`torch.Tensor`):
965
+ Batch size.
966
+ """
967
+ if attention_mask is not None and attention_mask.dim() == 4:
968
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
969
+ causal_mask = attention_mask
970
+ else:
971
+ min_dtype = torch.finfo(dtype).min
972
+ causal_mask = torch.full(
973
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
974
+ )
975
+ if sequence_length != 1:
976
+ causal_mask = torch.triu(causal_mask, diagonal=1)
977
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
978
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
979
+ if attention_mask is not None:
980
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
981
+ mask_length = attention_mask.shape[-1]
982
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
983
+ padding_mask = padding_mask == 0
984
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
985
+ padding_mask, min_dtype
986
+ )
987
+
988
+ return causal_mask
989
+
990
+
991
+ class TPUGemma2ForCausalLM(TPUGemma2PreTrainedModel, GenerationMixin):
992
+ _tied_weights_keys = ["lm_head.weight"]
993
+
994
+ def __init__(self, config):
995
+ super().__init__(config)
996
+ self.model = TPUGemma2Model(config)
997
+ self.vocab_size = config.vocab_size
998
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
999
+
1000
+ # Initialize weights and apply final processing
1001
+ self.post_init()
1002
+
1003
+ def get_input_embeddings(self):
1004
+ return self.model.embed_tokens
1005
+
1006
+ def set_input_embeddings(self, value):
1007
+ self.model.embed_tokens = value
1008
+
1009
+ def get_output_embeddings(self):
1010
+ return self.lm_head
1011
+
1012
+ def set_output_embeddings(self, new_embeddings):
1013
+ self.lm_head = new_embeddings
1014
+
1015
+ def set_decoder(self, decoder):
1016
+ self.model = decoder
1017
+
1018
+ def get_decoder(self):
1019
+ return self.model
1020
+
1021
+ @add_start_docstrings_to_model_forward(TPU_GEMMA2_INPUTS_DOCSTRING)
1022
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1023
+ def forward(
1024
+ self,
1025
+ input_ids: torch.LongTensor = None,
1026
+ attention_mask: Optional[torch.Tensor] = None,
1027
+ position_ids: Optional[torch.LongTensor] = None,
1028
+ past_key_values: Optional[HybridCache] = None,
1029
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1030
+ labels: Optional[torch.LongTensor] = None,
1031
+ use_cache: Optional[bool] = None,
1032
+ output_attentions: Optional[bool] = None,
1033
+ output_hidden_states: Optional[bool] = None,
1034
+ return_dict: Optional[bool] = None,
1035
+ cache_position: Optional[torch.LongTensor] = None,
1036
+ num_logits_to_keep: int = 0,
1037
+ past_input_ids: Optional[torch.LongTensor] = None,
1038
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1039
+ r"""
1040
+ Args:
1041
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1042
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1043
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1044
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1045
+
1046
+ num_logits_to_keep (`int`, *optional*):
1047
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1048
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1049
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1050
+
1051
+ Returns:
1052
+
1053
+ Example:
1054
+
1055
+ ```python
1056
+ >>> from transformers import AutoTokenizer, GemmaForCausalLM
1057
+
1058
+ >>> model = GemmaForCausalLM.from_pretrained("google/gemma-2-9b")
1059
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
1060
+
1061
+ >>> prompt = "What is your favorite condiment?"
1062
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1063
+
1064
+ >>> # Generate
1065
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1066
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1067
+ "What is your favorite condiment?"
1068
+ ```"""
1069
+
1070
+ if self.training and self.config._attn_implementation != "eager":
1071
+ logger.warning_once(
1072
+ "It is strongly recommended to train Gemma2 models with the `eager` attention implementation "
1073
+ f"instead of `{self.config._attn_implementation}`. Use `eager` with `AutoModelForCausalLM.from_pretrained('<path-to-checkpoint>', attn_implementation='eager')`."
1074
+ )
1075
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1076
+ output_hidden_states = (
1077
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1078
+ )
1079
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1080
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1081
+ outputs = self.model(
1082
+ input_ids=input_ids,
1083
+ attention_mask=attention_mask,
1084
+ position_ids=position_ids,
1085
+ past_key_values=past_key_values,
1086
+ inputs_embeds=inputs_embeds,
1087
+ use_cache=use_cache,
1088
+ output_attentions=output_attentions,
1089
+ output_hidden_states=output_hidden_states,
1090
+ return_dict=return_dict,
1091
+ cache_position=cache_position,
1092
+ past_input_ids=past_input_ids,
1093
+ )
1094
+
1095
+ hidden_states = outputs[0]
1096
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1097
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1098
+ if self.config.final_logit_softcapping is not None:
1099
+ logits = logits / self.config.final_logit_softcapping
1100
+ logits = torch.tanh(logits)
1101
+ logits = logits * self.config.final_logit_softcapping
1102
+
1103
+ loss = None
1104
+ if labels is not None:
1105
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1106
+ logits = logits.float()
1107
+ # Shift so that tokens < n predict n
1108
+ shift_logits = logits[..., :-1, :].contiguous()
1109
+ shift_labels = labels[..., 1:].contiguous()
1110
+ # Flatten the tokens
1111
+ loss_fct = CrossEntropyLoss()
1112
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1113
+ shift_labels = shift_labels.view(-1)
1114
+ # Enable model parallelism
1115
+ shift_labels = shift_labels.to(shift_logits.device)
1116
+ loss = loss_fct(shift_logits, shift_labels)
1117
+
1118
+ if not return_dict:
1119
+ output = (logits,) + outputs[1:]
1120
+ return (loss,) + output if loss is not None else output
1121
+
1122
+ return CausalLMOutputWithPast(
1123
+ loss=loss,
1124
+ logits=logits,
1125
+ past_key_values=outputs.past_key_values,
1126
+ hidden_states=outputs.hidden_states,
1127
+ attentions=outputs.attentions,
1128
+ )
1129
+
1130
+ def prepare_inputs_for_generation(
1131
+ self,
1132
+ input_ids,
1133
+ past_key_values=None,
1134
+ attention_mask=None,
1135
+ inputs_embeds=None,
1136
+ cache_position=None,
1137
+ position_ids=None,
1138
+ use_cache=True,
1139
+ num_logits_to_keep=None,
1140
+ **kwargs,
1141
+ ):
1142
+ # Overwritten: has a special cache type, `HybridCache`
1143
+
1144
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1145
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1146
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1147
+ if past_key_values is not None:
1148
+ if inputs_embeds is not None: # Exception 1
1149
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1150
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1151
+ input_ids = input_ids[:, cache_position]
1152
+ if attention_mask is not None and position_ids is None:
1153
+ # create position_ids on the fly for batch generation
1154
+ position_ids = attention_mask.long().cumsum(-1) - 1
1155
+ position_ids.masked_fill_(attention_mask == 0, 1)
1156
+ if past_key_values:
1157
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1158
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s
1159
+ # `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride
1160
+ # during the decoding. Here, simply using `.contiguous()` is not sufficient as in the
1161
+ # batch size = 1 case, `position_ids` is already contiguous but with varying stride
1162
+ # which retriggers a capture.
1163
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1164
+
1165
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1166
+ if inputs_embeds is not None and cache_position[0] == 0:
1167
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1168
+ else:
1169
+ # The clone here is for the same reason as for `position_ids`.
1170
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1171
+
1172
+ if (
1173
+ isinstance(past_key_values, HybridCache)
1174
+ and attention_mask.ndim == 2
1175
+ and not self.config._attn_implementation == "flash_attention_2"
1176
+ ):
1177
+ if model_inputs["inputs_embeds"] is not None:
1178
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1179
+ device = model_inputs["inputs_embeds"].device
1180
+ else:
1181
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1182
+ device = model_inputs["input_ids"].device
1183
+
1184
+ attention_mask = self.model._prepare_4d_causal_attention_mask_with_cache_position(
1185
+ attention_mask,
1186
+ sequence_length=sequence_length,
1187
+ target_length=past_key_values.get_max_cache_shape(),
1188
+ dtype=self.lm_head.weight.dtype,
1189
+ device=device,
1190
+ cache_position=cache_position,
1191
+ batch_size=batch_size,
1192
+ )
1193
+
1194
+ if num_logits_to_keep is not None:
1195
+ model_inputs["num_logits_to_keep"] = num_logits_to_keep
1196
+
1197
+ model_inputs.update(
1198
+ {
1199
+ "position_ids": position_ids,
1200
+ "cache_position": cache_position,
1201
+ "past_key_values": past_key_values,
1202
+ "use_cache": use_cache,
1203
+ "attention_mask": attention_mask,
1204
+ }
1205
+ )
1206
+
1207
+ if self.config.expand_input_ids:
1208
+ model_inputs["past_input_ids"] = input_ids
1209
+
1210
+ return model_inputs
1211
+
1212
+
1213
+ @add_start_docstrings(
1214
+ """
1215
+ The Gemma2 Model transformer with a sequence classification head on top (linear layer).
1216
+
1217
+ [`Gemma2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1218
+ (e.g. GPT-2) do.
1219
+
1220
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1221
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1222
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1223
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1224
+ each row of the batch).
1225
+ """,
1226
+ TPU_GEMMA2_START_DOCSTRING,
1227
+ )
1228
+ class TPUGemma2ForSequenceClassification(TPUGemma2PreTrainedModel):
1229
+ def __init__(self, config):
1230
+ super().__init__(config)
1231
+ self.num_labels = config.num_labels
1232
+ self.model = TPUGemma2Model(config)
1233
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1234
+
1235
+ # Initialize weights and apply final processing
1236
+ self.post_init()
1237
+
1238
+ def get_input_embeddings(self):
1239
+ return self.model.embed_tokens
1240
+
1241
+ def set_input_embeddings(self, value):
1242
+ self.model.embed_tokens = value
1243
+
1244
+ @add_start_docstrings_to_model_forward(TPU_GEMMA2_INPUTS_DOCSTRING)
1245
+ def forward(
1246
+ self,
1247
+ input_ids: Optional[torch.LongTensor] = None,
1248
+ attention_mask: Optional[torch.Tensor] = None,
1249
+ position_ids: Optional[torch.LongTensor] = None,
1250
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1251
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1252
+ labels: Optional[torch.LongTensor] = None,
1253
+ use_cache: Optional[bool] = None,
1254
+ output_attentions: Optional[bool] = None,
1255
+ output_hidden_states: Optional[bool] = None,
1256
+ return_dict: Optional[bool] = None,
1257
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1258
+ r"""
1259
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1260
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1261
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1262
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1263
+ """
1264
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1265
+
1266
+ transformer_outputs = self.model(
1267
+ input_ids,
1268
+ attention_mask=attention_mask,
1269
+ position_ids=position_ids,
1270
+ past_key_values=past_key_values,
1271
+ inputs_embeds=inputs_embeds,
1272
+ use_cache=use_cache,
1273
+ output_attentions=output_attentions,
1274
+ output_hidden_states=output_hidden_states,
1275
+ return_dict=return_dict,
1276
+ )
1277
+ hidden_states = transformer_outputs[0]
1278
+ logits = self.score(hidden_states)
1279
+
1280
+ if input_ids is not None:
1281
+ batch_size = input_ids.shape[0]
1282
+ else:
1283
+ batch_size = inputs_embeds.shape[0]
1284
+
1285
+ if self.config.pad_token_id is None and batch_size != 1:
1286
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1287
+ if self.config.pad_token_id is None:
1288
+ sequence_lengths = -1
1289
+ else:
1290
+ if input_ids is not None:
1291
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1292
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1293
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1294
+ sequence_lengths = sequence_lengths.to(logits.device)
1295
+ else:
1296
+ sequence_lengths = -1
1297
+
1298
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1299
+
1300
+ loss = None
1301
+ if labels is not None:
1302
+ labels = labels.to(logits.device)
1303
+ if self.config.problem_type is None:
1304
+ if self.num_labels == 1:
1305
+ self.config.problem_type = "regression"
1306
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1307
+ self.config.problem_type = "single_label_classification"
1308
+ else:
1309
+ self.config.problem_type = "multi_label_classification"
1310
+
1311
+ if self.config.problem_type == "regression":
1312
+ loss_fct = MSELoss()
1313
+ if self.num_labels == 1:
1314
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1315
+ else:
1316
+ loss = loss_fct(pooled_logits, labels)
1317
+ elif self.config.problem_type == "single_label_classification":
1318
+ loss_fct = CrossEntropyLoss()
1319
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1320
+ elif self.config.problem_type == "multi_label_classification":
1321
+ loss_fct = BCEWithLogitsLoss()
1322
+ loss = loss_fct(pooled_logits, labels)
1323
+ if not return_dict:
1324
+ output = (pooled_logits,) + transformer_outputs[1:]
1325
+ return ((loss,) + output) if loss is not None else output
1326
+
1327
+ return SequenceClassifierOutputWithPast(
1328
+ loss=loss,
1329
+ logits=pooled_logits,
1330
+ past_key_values=transformer_outputs.past_key_values,
1331
+ hidden_states=transformer_outputs.hidden_states,
1332
+ attentions=transformer_outputs.attentions,
1333
+ )
1334
+
1335
+
1336
+ @add_start_docstrings(
1337
+ """
1338
+ The Gemma2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1339
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1340
+ """,
1341
+ TPU_GEMMA2_START_DOCSTRING,
1342
+ )
1343
+ class TPUGemma2ForTokenClassification(TPUGemma2PreTrainedModel):
1344
+ def __init__(self, config):
1345
+ super().__init__(config)
1346
+ self.num_labels = config.num_labels
1347
+ self.model = TPUGemma2Model(config)
1348
+ if getattr(config, "classifier_dropout", None) is not None:
1349
+ classifier_dropout = config.classifier_dropout
1350
+ elif getattr(config, "hidden_dropout", None) is not None:
1351
+ classifier_dropout = config.hidden_dropout
1352
+ else:
1353
+ classifier_dropout = 0.1
1354
+ self.dropout = nn.Dropout(classifier_dropout)
1355
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1356
+
1357
+ # Initialize weights and apply final processing
1358
+ self.post_init()
1359
+
1360
+ def get_input_embeddings(self):
1361
+ return self.model.embed_tokens
1362
+
1363
+ def set_input_embeddings(self, value):
1364
+ self.model.embed_tokens = value
1365
+
1366
+ @add_start_docstrings_to_model_forward(TPU_GEMMA2_INPUTS_DOCSTRING)
1367
+ def forward(
1368
+ self,
1369
+ input_ids: Optional[torch.LongTensor] = None,
1370
+ attention_mask: Optional[torch.Tensor] = None,
1371
+ position_ids: Optional[torch.LongTensor] = None,
1372
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1373
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1374
+ labels: Optional[torch.LongTensor] = None,
1375
+ use_cache: Optional[bool] = None,
1376
+ output_attentions: Optional[bool] = None,
1377
+ output_hidden_states: Optional[bool] = None,
1378
+ return_dict: Optional[bool] = None,
1379
+ ) -> Union[Tuple, TokenClassifierOutput]:
1380
+ r"""
1381
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1382
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1383
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1384
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1385
+ """
1386
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1387
+
1388
+ outputs = self.model(
1389
+ input_ids,
1390
+ attention_mask=attention_mask,
1391
+ position_ids=position_ids,
1392
+ past_key_values=past_key_values,
1393
+ inputs_embeds=inputs_embeds,
1394
+ use_cache=use_cache,
1395
+ output_attentions=output_attentions,
1396
+ output_hidden_states=output_hidden_states,
1397
+ return_dict=return_dict,
1398
+ )
1399
+ sequence_output = outputs[0]
1400
+ sequence_output = self.dropout(sequence_output)
1401
+ logits = self.score(sequence_output)
1402
+
1403
+ loss = None
1404
+ if labels is not None:
1405
+ loss_fct = CrossEntropyLoss()
1406
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1407
+
1408
+ if not return_dict:
1409
+ output = (logits,) + outputs[2:]
1410
+ return ((loss,) + output) if loss is not None else output
1411
+
1412
+ return TokenClassifierOutput(
1413
+ loss=loss,
1414
+ logits=logits,
1415
+ hidden_states=outputs.hidden_states,
1416
+ attentions=outputs.attentions,
1417
+ )
special_tokens_map.json CHANGED
@@ -3,32 +3,8 @@
3
  "<start_of_turn>",
4
  "<end_of_turn>"
5
  ],
6
- "bos_token": {
7
- "content": "<bos>",
8
- "lstrip": false,
9
- "normalized": false,
10
- "rstrip": false,
11
- "single_word": false
12
- },
13
- "eos_token": {
14
- "content": "<eos>",
15
- "lstrip": false,
16
- "normalized": false,
17
- "rstrip": false,
18
- "single_word": false
19
- },
20
- "pad_token": {
21
- "content": "<pad>",
22
- "lstrip": false,
23
- "normalized": false,
24
- "rstrip": false,
25
- "single_word": false
26
- },
27
- "unk_token": {
28
- "content": "<unk>",
29
- "lstrip": false,
30
- "normalized": false,
31
- "rstrip": false,
32
- "single_word": false
33
- }
34
  }
 
3
  "<start_of_turn>",
4
  "<end_of_turn>"
5
  ],
6
+ "bos_token": "<bos>",
7
+ "eos_token": "<eos>",
8
+ "pad_token": "<pad>",
9
+ "unk_token": "<unk>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  }
tokenizer.json CHANGED
@@ -5,7 +5,7 @@
5
  "added_tokens": [
6
  {
7
  "id": 256,
8
- "content": "<pad>",
9
  "single_word": false,
10
  "lstrip": false,
11
  "rstrip": false,
@@ -14,7 +14,7 @@
14
  },
15
  {
16
  "id": 257,
17
- "content": "<eos>",
18
  "single_word": false,
19
  "lstrip": false,
20
  "rstrip": false,
@@ -23,7 +23,7 @@
23
  },
24
  {
25
  "id": 258,
26
- "content": "<bos>",
27
  "single_word": false,
28
  "lstrip": false,
29
  "rstrip": false,
@@ -32,7 +32,7 @@
32
  },
33
  {
34
  "id": 259,
35
- "content": "<unk>",
36
  "single_word": false,
37
  "lstrip": false,
38
  "rstrip": false,
@@ -49,52 +49,21 @@
49
  "special": true
50
  },
51
  {
52
- "id": 261,
53
- "content": "<end_of_turn>",
54
  "single_word": false,
55
  "lstrip": false,
56
  "rstrip": false,
57
  "normalized": false,
58
  "special": true
59
- },
60
- {
61
- "id": 262,
62
- "content": "user",
63
- "single_word": false,
64
- "lstrip": false,
65
- "rstrip": false,
66
- "normalized": true,
67
- "special": false
68
- },
69
- {
70
- "id": 263,
71
- "content": "model",
72
- "single_word": false,
73
- "lstrip": false,
74
- "rstrip": false,
75
- "normalized": true,
76
- "special": false
77
  }
78
  ],
79
  "normalizer": null,
80
  "pre_tokenizer": {
81
- "type": "Sequence",
82
- "pretokenizers": [
83
- {
84
- "type": "Split",
85
- "pattern": {
86
- "Regex": "\\s*[\\p{L}\\p{M}]+|\\s*\\p{N}+|\\s*[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+"
87
- },
88
- "behavior": "Removed",
89
- "invert": true
90
- },
91
- {
92
- "type": "ByteLevel",
93
- "add_prefix_space": false,
94
- "trim_offsets": true,
95
- "use_regex": false
96
- }
97
- ]
98
  },
99
  "post_processor": {
100
  "type": "TemplateProcessing",
@@ -142,7 +111,7 @@
142
  "<bos>": {
143
  "id": "<bos>",
144
  "ids": [
145
- 258
146
  ],
147
  "tokens": [
148
  "<bos>"
@@ -157,273 +126,1062 @@
157
  "use_regex": true
158
  },
159
  "model": {
160
- "type": "WordPiece",
161
- "unk_token": "<unk>",
162
- "continuing_subword_prefix": "",
163
- "max_input_chars_per_word": 1000000,
164
- "vocab": {
165
- "Ā": 0,
166
- "ā": 1,
167
- "Ă": 2,
168
- "ă": 3,
169
- "Ą": 4,
170
- "ą": 5,
171
- "Ć": 6,
172
- "ć": 7,
173
- "Ĉ": 8,
174
- "ĉ": 9,
175
- "Ċ": 10,
176
- "ċ": 11,
177
- "Č": 12,
178
- "č": 13,
179
- "Ď": 14,
180
- "ď": 15,
181
- "Đ": 16,
182
- "đ": 17,
183
- "Ē": 18,
184
- "ē": 19,
185
- "Ĕ": 20,
186
- "ĕ": 21,
187
- "Ė": 22,
188
- "ė": 23,
189
- "Ę": 24,
190
- "ę": 25,
191
- "Ě": 26,
192
- "ě": 27,
193
- "Ĝ": 28,
194
- "ĝ": 29,
195
- "Ğ": 30,
196
- "ğ": 31,
197
- "Ġ": 32,
198
- "!": 33,
199
- "\"": 34,
200
- "#": 35,
201
- "$": 36,
202
- "%": 37,
203
- "&": 38,
204
- "'": 39,
205
- "(": 40,
206
- ")": 41,
207
- "*": 42,
208
- "+": 43,
209
- ",": 44,
210
- "-": 45,
211
- ".": 46,
212
- "/": 47,
213
- "0": 48,
214
- "1": 49,
215
- "2": 50,
216
- "3": 51,
217
- "4": 52,
218
- "5": 53,
219
- "6": 54,
220
- "7": 55,
221
- "8": 56,
222
- "9": 57,
223
- ":": 58,
224
- ";": 59,
225
- "<": 60,
226
- "=": 61,
227
- ">": 62,
228
- "?": 63,
229
- "@": 64,
230
- "A": 65,
231
- "B": 66,
232
- "C": 67,
233
- "D": 68,
234
- "E": 69,
235
- "F": 70,
236
- "G": 71,
237
- "H": 72,
238
- "I": 73,
239
- "J": 74,
240
- "K": 75,
241
- "L": 76,
242
- "M": 77,
243
- "N": 78,
244
- "O": 79,
245
- "P": 80,
246
- "Q": 81,
247
- "R": 82,
248
- "S": 83,
249
- "T": 84,
250
- "U": 85,
251
- "V": 86,
252
- "W": 87,
253
- "X": 88,
254
- "Y": 89,
255
- "Z": 90,
256
- "[": 91,
257
- "\\": 92,
258
- "]": 93,
259
- "^": 94,
260
- "_": 95,
261
- "`": 96,
262
- "a": 97,
263
- "b": 98,
264
- "c": 99,
265
- "d": 100,
266
- "e": 101,
267
- "f": 102,
268
- "g": 103,
269
- "h": 104,
270
- "i": 105,
271
- "j": 106,
272
- "k": 107,
273
- "l": 108,
274
- "m": 109,
275
- "n": 110,
276
- "o": 111,
277
- "p": 112,
278
- "q": 113,
279
- "r": 114,
280
- "s": 115,
281
- "t": 116,
282
- "u": 117,
283
- "v": 118,
284
- "w": 119,
285
- "x": 120,
286
- "y": 121,
287
- "z": 122,
288
- "{": 123,
289
- "|": 124,
290
- "}": 125,
291
- "~": 126,
292
- "ġ": 127,
293
- "Ģ": 128,
294
- "ģ": 129,
295
- "Ĥ": 130,
296
- "ĥ": 131,
297
- "Ħ": 132,
298
- "ħ": 133,
299
- "Ĩ": 134,
300
- "ĩ": 135,
301
- "Ī": 136,
302
- "ī": 137,
303
- "Ĭ": 138,
304
- "ĭ": 139,
305
- "Į": 140,
306
- "į": 141,
307
- "İ": 142,
308
- "ı": 143,
309
- "IJ": 144,
310
- "ij": 145,
311
- "Ĵ": 146,
312
- "ĵ": 147,
313
- "Ķ": 148,
314
- "ķ": 149,
315
- "ĸ": 150,
316
- "Ĺ": 151,
317
- "ĺ": 152,
318
- "Ļ": 153,
319
- "ļ": 154,
320
- "Ľ": 155,
321
- "ľ": 156,
322
- "Ŀ": 157,
323
- "ŀ": 158,
324
- "Ł": 159,
325
- "ł": 160,
326
- "¡": 161,
327
- "¢": 162,
328
- "£": 163,
329
- "¤": 164,
330
- "¥": 165,
331
- "¦": 166,
332
- "§": 167,
333
- "¨": 168,
334
- "©": 169,
335
- "ª": 170,
336
- "«": 171,
337
- "¬": 172,
338
- "Ń": 173,
339
- "®": 174,
340
- "¯": 175,
341
- "°": 176,
342
- "±": 177,
343
- "²": 178,
344
- "³": 179,
345
- "´": 180,
346
- "µ": 181,
347
- "¶": 182,
348
- "·": 183,
349
- "¸": 184,
350
- "¹": 185,
351
- "º": 186,
352
- "»": 187,
353
- "¼": 188,
354
- "½": 189,
355
- "¾": 190,
356
- "¿": 191,
357
- "À": 192,
358
- "Á": 193,
359
- "Â": 194,
360
- "Ã": 195,
361
- "Ä": 196,
362
- "Å": 197,
363
- "Æ": 198,
364
- "Ç": 199,
365
- "È": 200,
366
- "É": 201,
367
- "Ê": 202,
368
- "Ë": 203,
369
- "Ì": 204,
370
- "Í": 205,
371
- "Î": 206,
372
- "Ï": 207,
373
- "Ð": 208,
374
- "Ñ": 209,
375
- "Ò": 210,
376
- "Ó": 211,
377
- "Ô": 212,
378
- "Õ": 213,
379
- "Ö": 214,
380
- "×": 215,
381
- "Ø": 216,
382
- "Ù": 217,
383
- "Ú": 218,
384
- "Û": 219,
385
- "Ü": 220,
386
- "Ý": 221,
387
- "Þ": 222,
388
- "ß": 223,
389
- "à": 224,
390
- "á": 225,
391
- "â": 226,
392
- "ã": 227,
393
- "ä": 228,
394
- "å": 229,
395
- "æ": 230,
396
- "ç": 231,
397
- "è": 232,
398
- "é": 233,
399
- "ê": 234,
400
- "ë": 235,
401
- "ì": 236,
402
- "í": 237,
403
- "î": 238,
404
- "ï": 239,
405
- "ð": 240,
406
- "ñ": 241,
407
- "ò": 242,
408
- "ó": 243,
409
- "ô": 244,
410
- "õ": 245,
411
- "ö": 246,
412
- "÷": 247,
413
- "ø": 248,
414
- "ù": 249,
415
- "ú": 250,
416
- "û": 251,
417
- "ü": 252,
418
- "ý": 253,
419
- "þ": 254,
420
- "ÿ": 255,
421
- "<pad>": 256,
422
- "<eos>": 257,
423
- "<bos>": 258,
424
- "<unk>": 259,
425
- "<start_of_turn>": 260,
426
- "<end_of_turn>": 261
427
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  }
429
  }
 
5
  "added_tokens": [
6
  {
7
  "id": 256,
8
+ "content": "<bos>",
9
  "single_word": false,
10
  "lstrip": false,
11
  "rstrip": false,
 
14
  },
15
  {
16
  "id": 257,
17
+ "content": "<end_of_turn>",
18
  "single_word": false,
19
  "lstrip": false,
20
  "rstrip": false,
 
23
  },
24
  {
25
  "id": 258,
26
+ "content": "<eos>",
27
  "single_word": false,
28
  "lstrip": false,
29
  "rstrip": false,
 
32
  },
33
  {
34
  "id": 259,
35
+ "content": "<pad>",
36
  "single_word": false,
37
  "lstrip": false,
38
  "rstrip": false,
 
49
  "special": true
50
  },
51
  {
52
+ "id": 263,
53
+ "content": "<unk>",
54
  "single_word": false,
55
  "lstrip": false,
56
  "rstrip": false,
57
  "normalized": false,
58
  "special": true
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  }
60
  ],
61
  "normalizer": null,
62
  "pre_tokenizer": {
63
+ "type": "ByteLevel",
64
+ "add_prefix_space": false,
65
+ "trim_offsets": true,
66
+ "use_regex": false
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  },
68
  "post_processor": {
69
  "type": "TemplateProcessing",
 
111
  "<bos>": {
112
  "id": "<bos>",
113
  "ids": [
114
+ 256
115
  ],
116
  "tokens": [
117
  "<bos>"
 
126
  "use_regex": true
127
  },
128
  "model": {
129
+ "type": "Unigram",
130
+ "unk_id": null,
131
+ "vocab": [
132
+ [
133
+ "Ā",
134
+ 0.0
135
+ ],
136
+ [
137
+ "ā",
138
+ 0.0
139
+ ],
140
+ [
141
+ "Ă",
142
+ 0.0
143
+ ],
144
+ [
145
+ "ă",
146
+ 0.0
147
+ ],
148
+ [
149
+ "Ą",
150
+ 0.0
151
+ ],
152
+ [
153
+ "ą",
154
+ 0.0
155
+ ],
156
+ [
157
+ "Ć",
158
+ 0.0
159
+ ],
160
+ [
161
+ "ć",
162
+ 0.0
163
+ ],
164
+ [
165
+ "Ĉ",
166
+ 0.0
167
+ ],
168
+ [
169
+ "ĉ",
170
+ 0.0
171
+ ],
172
+ [
173
+ "Ċ",
174
+ 0.0
175
+ ],
176
+ [
177
+ "ċ",
178
+ 0.0
179
+ ],
180
+ [
181
+ "Č",
182
+ 0.0
183
+ ],
184
+ [
185
+ "č",
186
+ 0.0
187
+ ],
188
+ [
189
+ "Ď",
190
+ 0.0
191
+ ],
192
+ [
193
+ "ď",
194
+ 0.0
195
+ ],
196
+ [
197
+ "Đ",
198
+ 0.0
199
+ ],
200
+ [
201
+ "đ",
202
+ 0.0
203
+ ],
204
+ [
205
+ "Ē",
206
+ 0.0
207
+ ],
208
+ [
209
+ "ē",
210
+ 0.0
211
+ ],
212
+ [
213
+ "Ĕ",
214
+ 0.0
215
+ ],
216
+ [
217
+ "ĕ",
218
+ 0.0
219
+ ],
220
+ [
221
+ "Ė",
222
+ 0.0
223
+ ],
224
+ [
225
+ "ė",
226
+ 0.0
227
+ ],
228
+ [
229
+ "Ę",
230
+ 0.0
231
+ ],
232
+ [
233
+ "ę",
234
+ 0.0
235
+ ],
236
+ [
237
+ "Ě",
238
+ 0.0
239
+ ],
240
+ [
241
+ "ě",
242
+ 0.0
243
+ ],
244
+ [
245
+ "Ĝ",
246
+ 0.0
247
+ ],
248
+ [
249
+ "ĝ",
250
+ 0.0
251
+ ],
252
+ [
253
+ "Ğ",
254
+ 0.0
255
+ ],
256
+ [
257
+ "ğ",
258
+ 0.0
259
+ ],
260
+ [
261
+ "Ġ",
262
+ 0.0
263
+ ],
264
+ [
265
+ "!",
266
+ 0.0
267
+ ],
268
+ [
269
+ "\"",
270
+ 0.0
271
+ ],
272
+ [
273
+ "#",
274
+ 0.0
275
+ ],
276
+ [
277
+ "$",
278
+ 0.0
279
+ ],
280
+ [
281
+ "%",
282
+ 0.0
283
+ ],
284
+ [
285
+ "&",
286
+ 0.0
287
+ ],
288
+ [
289
+ "'",
290
+ 0.0
291
+ ],
292
+ [
293
+ "(",
294
+ 0.0
295
+ ],
296
+ [
297
+ ")",
298
+ 0.0
299
+ ],
300
+ [
301
+ "*",
302
+ 0.0
303
+ ],
304
+ [
305
+ "+",
306
+ 0.0
307
+ ],
308
+ [
309
+ ",",
310
+ 0.0
311
+ ],
312
+ [
313
+ "-",
314
+ 0.0
315
+ ],
316
+ [
317
+ ".",
318
+ 0.0
319
+ ],
320
+ [
321
+ "/",
322
+ 0.0
323
+ ],
324
+ [
325
+ "0",
326
+ 0.0
327
+ ],
328
+ [
329
+ "1",
330
+ 0.0
331
+ ],
332
+ [
333
+ "2",
334
+ 0.0
335
+ ],
336
+ [
337
+ "3",
338
+ 0.0
339
+ ],
340
+ [
341
+ "4",
342
+ 0.0
343
+ ],
344
+ [
345
+ "5",
346
+ 0.0
347
+ ],
348
+ [
349
+ "6",
350
+ 0.0
351
+ ],
352
+ [
353
+ "7",
354
+ 0.0
355
+ ],
356
+ [
357
+ "8",
358
+ 0.0
359
+ ],
360
+ [
361
+ "9",
362
+ 0.0
363
+ ],
364
+ [
365
+ ":",
366
+ 0.0
367
+ ],
368
+ [
369
+ ";",
370
+ 0.0
371
+ ],
372
+ [
373
+ "<",
374
+ 0.0
375
+ ],
376
+ [
377
+ "=",
378
+ 0.0
379
+ ],
380
+ [
381
+ ">",
382
+ 0.0
383
+ ],
384
+ [
385
+ "?",
386
+ 0.0
387
+ ],
388
+ [
389
+ "@",
390
+ 0.0
391
+ ],
392
+ [
393
+ "A",
394
+ 0.0
395
+ ],
396
+ [
397
+ "B",
398
+ 0.0
399
+ ],
400
+ [
401
+ "C",
402
+ 0.0
403
+ ],
404
+ [
405
+ "D",
406
+ 0.0
407
+ ],
408
+ [
409
+ "E",
410
+ 0.0
411
+ ],
412
+ [
413
+ "F",
414
+ 0.0
415
+ ],
416
+ [
417
+ "G",
418
+ 0.0
419
+ ],
420
+ [
421
+ "H",
422
+ 0.0
423
+ ],
424
+ [
425
+ "I",
426
+ 0.0
427
+ ],
428
+ [
429
+ "J",
430
+ 0.0
431
+ ],
432
+ [
433
+ "K",
434
+ 0.0
435
+ ],
436
+ [
437
+ "L",
438
+ 0.0
439
+ ],
440
+ [
441
+ "M",
442
+ 0.0
443
+ ],
444
+ [
445
+ "N",
446
+ 0.0
447
+ ],
448
+ [
449
+ "O",
450
+ 0.0
451
+ ],
452
+ [
453
+ "P",
454
+ 0.0
455
+ ],
456
+ [
457
+ "Q",
458
+ 0.0
459
+ ],
460
+ [
461
+ "R",
462
+ 0.0
463
+ ],
464
+ [
465
+ "S",
466
+ 0.0
467
+ ],
468
+ [
469
+ "T",
470
+ 0.0
471
+ ],
472
+ [
473
+ "U",
474
+ 0.0
475
+ ],
476
+ [
477
+ "V",
478
+ 0.0
479
+ ],
480
+ [
481
+ "W",
482
+ 0.0
483
+ ],
484
+ [
485
+ "X",
486
+ 0.0
487
+ ],
488
+ [
489
+ "Y",
490
+ 0.0
491
+ ],
492
+ [
493
+ "Z",
494
+ 0.0
495
+ ],
496
+ [
497
+ "[",
498
+ 0.0
499
+ ],
500
+ [
501
+ "\\",
502
+ 0.0
503
+ ],
504
+ [
505
+ "]",
506
+ 0.0
507
+ ],
508
+ [
509
+ "^",
510
+ 0.0
511
+ ],
512
+ [
513
+ "_",
514
+ 0.0
515
+ ],
516
+ [
517
+ "`",
518
+ 0.0
519
+ ],
520
+ [
521
+ "a",
522
+ 0.0
523
+ ],
524
+ [
525
+ "b",
526
+ 0.0
527
+ ],
528
+ [
529
+ "c",
530
+ 0.0
531
+ ],
532
+ [
533
+ "d",
534
+ 0.0
535
+ ],
536
+ [
537
+ "e",
538
+ 0.0
539
+ ],
540
+ [
541
+ "f",
542
+ 0.0
543
+ ],
544
+ [
545
+ "g",
546
+ 0.0
547
+ ],
548
+ [
549
+ "h",
550
+ 0.0
551
+ ],
552
+ [
553
+ "i",
554
+ 0.0
555
+ ],
556
+ [
557
+ "j",
558
+ 0.0
559
+ ],
560
+ [
561
+ "k",
562
+ 0.0
563
+ ],
564
+ [
565
+ "l",
566
+ 0.0
567
+ ],
568
+ [
569
+ "m",
570
+ 0.0
571
+ ],
572
+ [
573
+ "n",
574
+ 0.0
575
+ ],
576
+ [
577
+ "o",
578
+ 0.0
579
+ ],
580
+ [
581
+ "p",
582
+ 0.0
583
+ ],
584
+ [
585
+ "q",
586
+ 0.0
587
+ ],
588
+ [
589
+ "r",
590
+ 0.0
591
+ ],
592
+ [
593
+ "s",
594
+ 0.0
595
+ ],
596
+ [
597
+ "t",
598
+ 0.0
599
+ ],
600
+ [
601
+ "u",
602
+ 0.0
603
+ ],
604
+ [
605
+ "v",
606
+ 0.0
607
+ ],
608
+ [
609
+ "w",
610
+ 0.0
611
+ ],
612
+ [
613
+ "x",
614
+ 0.0
615
+ ],
616
+ [
617
+ "y",
618
+ 0.0
619
+ ],
620
+ [
621
+ "z",
622
+ 0.0
623
+ ],
624
+ [
625
+ "{",
626
+ 0.0
627
+ ],
628
+ [
629
+ "|",
630
+ 0.0
631
+ ],
632
+ [
633
+ "}",
634
+ 0.0
635
+ ],
636
+ [
637
+ "~",
638
+ 0.0
639
+ ],
640
+ [
641
+ "ġ",
642
+ 0.0
643
+ ],
644
+ [
645
+ "Ģ",
646
+ 0.0
647
+ ],
648
+ [
649
+ "ģ",
650
+ 0.0
651
+ ],
652
+ [
653
+ "Ĥ",
654
+ 0.0
655
+ ],
656
+ [
657
+ "ĥ",
658
+ 0.0
659
+ ],
660
+ [
661
+ "Ħ",
662
+ 0.0
663
+ ],
664
+ [
665
+ "ħ",
666
+ 0.0
667
+ ],
668
+ [
669
+ "Ĩ",
670
+ 0.0
671
+ ],
672
+ [
673
+ "ĩ",
674
+ 0.0
675
+ ],
676
+ [
677
+ "Ī",
678
+ 0.0
679
+ ],
680
+ [
681
+ "ī",
682
+ 0.0
683
+ ],
684
+ [
685
+ "Ĭ",
686
+ 0.0
687
+ ],
688
+ [
689
+ "ĭ",
690
+ 0.0
691
+ ],
692
+ [
693
+ "Į",
694
+ 0.0
695
+ ],
696
+ [
697
+ "į",
698
+ 0.0
699
+ ],
700
+ [
701
+ "İ",
702
+ 0.0
703
+ ],
704
+ [
705
+ "ı",
706
+ 0.0
707
+ ],
708
+ [
709
+ "IJ",
710
+ 0.0
711
+ ],
712
+ [
713
+ "ij",
714
+ 0.0
715
+ ],
716
+ [
717
+ "Ĵ",
718
+ 0.0
719
+ ],
720
+ [
721
+ "ĵ",
722
+ 0.0
723
+ ],
724
+ [
725
+ "Ķ",
726
+ 0.0
727
+ ],
728
+ [
729
+ "ķ",
730
+ 0.0
731
+ ],
732
+ [
733
+ "ĸ",
734
+ 0.0
735
+ ],
736
+ [
737
+ "Ĺ",
738
+ 0.0
739
+ ],
740
+ [
741
+ "ĺ",
742
+ 0.0
743
+ ],
744
+ [
745
+ "Ļ",
746
+ 0.0
747
+ ],
748
+ [
749
+ "ļ",
750
+ 0.0
751
+ ],
752
+ [
753
+ "Ľ",
754
+ 0.0
755
+ ],
756
+ [
757
+ "ľ",
758
+ 0.0
759
+ ],
760
+ [
761
+ "Ŀ",
762
+ 0.0
763
+ ],
764
+ [
765
+ "ŀ",
766
+ 0.0
767
+ ],
768
+ [
769
+ "Ł",
770
+ 0.0
771
+ ],
772
+ [
773
+ "ł",
774
+ 0.0
775
+ ],
776
+ [
777
+ "¡",
778
+ 0.0
779
+ ],
780
+ [
781
+ "¢",
782
+ 0.0
783
+ ],
784
+ [
785
+ "£",
786
+ 0.0
787
+ ],
788
+ [
789
+ "¤",
790
+ 0.0
791
+ ],
792
+ [
793
+ "¥",
794
+ 0.0
795
+ ],
796
+ [
797
+ "¦",
798
+ 0.0
799
+ ],
800
+ [
801
+ "§",
802
+ 0.0
803
+ ],
804
+ [
805
+ "¨",
806
+ 0.0
807
+ ],
808
+ [
809
+ "©",
810
+ 0.0
811
+ ],
812
+ [
813
+ "ª",
814
+ 0.0
815
+ ],
816
+ [
817
+ "«",
818
+ 0.0
819
+ ],
820
+ [
821
+ "¬",
822
+ 0.0
823
+ ],
824
+ [
825
+ "Ń",
826
+ 0.0
827
+ ],
828
+ [
829
+ "®",
830
+ 0.0
831
+ ],
832
+ [
833
+ "¯",
834
+ 0.0
835
+ ],
836
+ [
837
+ "°",
838
+ 0.0
839
+ ],
840
+ [
841
+ "±",
842
+ 0.0
843
+ ],
844
+ [
845
+ "²",
846
+ 0.0
847
+ ],
848
+ [
849
+ "³",
850
+ 0.0
851
+ ],
852
+ [
853
+ "´",
854
+ 0.0
855
+ ],
856
+ [
857
+ "µ",
858
+ 0.0
859
+ ],
860
+ [
861
+ "¶",
862
+ 0.0
863
+ ],
864
+ [
865
+ "·",
866
+ 0.0
867
+ ],
868
+ [
869
+ "¸",
870
+ 0.0
871
+ ],
872
+ [
873
+ "¹",
874
+ 0.0
875
+ ],
876
+ [
877
+ "º",
878
+ 0.0
879
+ ],
880
+ [
881
+ "»",
882
+ 0.0
883
+ ],
884
+ [
885
+ "¼",
886
+ 0.0
887
+ ],
888
+ [
889
+ "½",
890
+ 0.0
891
+ ],
892
+ [
893
+ "¾",
894
+ 0.0
895
+ ],
896
+ [
897
+ "¿",
898
+ 0.0
899
+ ],
900
+ [
901
+ "À",
902
+ 0.0
903
+ ],
904
+ [
905
+ "Á",
906
+ 0.0
907
+ ],
908
+ [
909
+ "Â",
910
+ 0.0
911
+ ],
912
+ [
913
+ "Ã",
914
+ 0.0
915
+ ],
916
+ [
917
+ "Ä",
918
+ 0.0
919
+ ],
920
+ [
921
+ "Å",
922
+ 0.0
923
+ ],
924
+ [
925
+ "Æ",
926
+ 0.0
927
+ ],
928
+ [
929
+ "Ç",
930
+ 0.0
931
+ ],
932
+ [
933
+ "È",
934
+ 0.0
935
+ ],
936
+ [
937
+ "É",
938
+ 0.0
939
+ ],
940
+ [
941
+ "Ê",
942
+ 0.0
943
+ ],
944
+ [
945
+ "Ë",
946
+ 0.0
947
+ ],
948
+ [
949
+ "Ì",
950
+ 0.0
951
+ ],
952
+ [
953
+ "Í",
954
+ 0.0
955
+ ],
956
+ [
957
+ "Î",
958
+ 0.0
959
+ ],
960
+ [
961
+ "Ï",
962
+ 0.0
963
+ ],
964
+ [
965
+ "Ð",
966
+ 0.0
967
+ ],
968
+ [
969
+ "Ñ",
970
+ 0.0
971
+ ],
972
+ [
973
+ "Ò",
974
+ 0.0
975
+ ],
976
+ [
977
+ "Ó",
978
+ 0.0
979
+ ],
980
+ [
981
+ "Ô",
982
+ 0.0
983
+ ],
984
+ [
985
+ "Õ",
986
+ 0.0
987
+ ],
988
+ [
989
+ "Ö",
990
+ 0.0
991
+ ],
992
+ [
993
+ "×",
994
+ 0.0
995
+ ],
996
+ [
997
+ "Ø",
998
+ 0.0
999
+ ],
1000
+ [
1001
+ "Ù",
1002
+ 0.0
1003
+ ],
1004
+ [
1005
+ "Ú",
1006
+ 0.0
1007
+ ],
1008
+ [
1009
+ "Û",
1010
+ 0.0
1011
+ ],
1012
+ [
1013
+ "Ü",
1014
+ 0.0
1015
+ ],
1016
+ [
1017
+ "Ý",
1018
+ 0.0
1019
+ ],
1020
+ [
1021
+ "Þ",
1022
+ 0.0
1023
+ ],
1024
+ [
1025
+ "ß",
1026
+ 0.0
1027
+ ],
1028
+ [
1029
+ "à",
1030
+ 0.0
1031
+ ],
1032
+ [
1033
+ "á",
1034
+ 0.0
1035
+ ],
1036
+ [
1037
+ "â",
1038
+ 0.0
1039
+ ],
1040
+ [
1041
+ "ã",
1042
+ 0.0
1043
+ ],
1044
+ [
1045
+ "ä",
1046
+ 0.0
1047
+ ],
1048
+ [
1049
+ "å",
1050
+ 0.0
1051
+ ],
1052
+ [
1053
+ "æ",
1054
+ 0.0
1055
+ ],
1056
+ [
1057
+ "ç",
1058
+ 0.0
1059
+ ],
1060
+ [
1061
+ "è",
1062
+ 0.0
1063
+ ],
1064
+ [
1065
+ "é",
1066
+ 0.0
1067
+ ],
1068
+ [
1069
+ "ê",
1070
+ 0.0
1071
+ ],
1072
+ [
1073
+ "ë",
1074
+ 0.0
1075
+ ],
1076
+ [
1077
+ "ì",
1078
+ 0.0
1079
+ ],
1080
+ [
1081
+ "í",
1082
+ 0.0
1083
+ ],
1084
+ [
1085
+ "î",
1086
+ 0.0
1087
+ ],
1088
+ [
1089
+ "ï",
1090
+ 0.0
1091
+ ],
1092
+ [
1093
+ "ð",
1094
+ 0.0
1095
+ ],
1096
+ [
1097
+ "ñ",
1098
+ 0.0
1099
+ ],
1100
+ [
1101
+ "ò",
1102
+ 0.0
1103
+ ],
1104
+ [
1105
+ "ó",
1106
+ 0.0
1107
+ ],
1108
+ [
1109
+ "ô",
1110
+ 0.0
1111
+ ],
1112
+ [
1113
+ "õ",
1114
+ 0.0
1115
+ ],
1116
+ [
1117
+ "ö",
1118
+ 0.0
1119
+ ],
1120
+ [
1121
+ "÷",
1122
+ 0.0
1123
+ ],
1124
+ [
1125
+ "ø",
1126
+ 0.0
1127
+ ],
1128
+ [
1129
+ "ù",
1130
+ 0.0
1131
+ ],
1132
+ [
1133
+ "ú",
1134
+ 0.0
1135
+ ],
1136
+ [
1137
+ "û",
1138
+ 0.0
1139
+ ],
1140
+ [
1141
+ "ü",
1142
+ 0.0
1143
+ ],
1144
+ [
1145
+ "ý",
1146
+ 0.0
1147
+ ],
1148
+ [
1149
+ "þ",
1150
+ 0.0
1151
+ ],
1152
+ [
1153
+ "ÿ",
1154
+ 0.0
1155
+ ],
1156
+ [
1157
+ "<bos>",
1158
+ 0.0
1159
+ ],
1160
+ [
1161
+ "<end_of_turn>",
1162
+ 0.0
1163
+ ],
1164
+ [
1165
+ "<eos>",
1166
+ 0.0
1167
+ ],
1168
+ [
1169
+ "<pad>",
1170
+ 0.0
1171
+ ],
1172
+ [
1173
+ "<start_of_turn>",
1174
+ 0.0
1175
+ ],
1176
+ [
1177
+ "model",
1178
+ 0.0
1179
+ ],
1180
+ [
1181
+ "user",
1182
+ 0.0
1183
+ ]
1184
+ ],
1185
+ "byte_fallback": false
1186
  }
1187
  }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2
3
+ size 4241003
tokenizer_config.json CHANGED
@@ -3,7 +3,7 @@
3
  "add_eos_token": false,
4
  "added_tokens_decoder": {
5
  "256": {
6
- "content": "<pad>",
7
  "lstrip": false,
8
  "normalized": false,
9
  "rstrip": false,
@@ -11,7 +11,7 @@
11
  "special": true
12
  },
13
  "257": {
14
- "content": "<eos>",
15
  "lstrip": false,
16
  "normalized": false,
17
  "rstrip": false,
@@ -19,7 +19,7 @@
19
  "special": true
20
  },
21
  "258": {
22
- "content": "<bos>",
23
  "lstrip": false,
24
  "normalized": false,
25
  "rstrip": false,
@@ -27,7 +27,7 @@
27
  "special": true
28
  },
29
  "259": {
30
- "content": "<unk>",
31
  "lstrip": false,
32
  "normalized": false,
33
  "rstrip": false,
@@ -42,29 +42,13 @@
42
  "single_word": false,
43
  "special": true
44
  },
45
- "261": {
46
- "content": "<end_of_turn>",
47
  "lstrip": false,
48
  "normalized": false,
49
  "rstrip": false,
50
  "single_word": false,
51
  "special": true
52
- },
53
- "262": {
54
- "content": "user",
55
- "lstrip": false,
56
- "normalized": true,
57
- "rstrip": false,
58
- "single_word": false,
59
- "special": false
60
- },
61
- "263": {
62
- "content": "model",
63
- "lstrip": false,
64
- "normalized": true,
65
- "rstrip": false,
66
- "single_word": false,
67
- "special": false
68
  }
69
  },
70
  "additional_special_tokens": [
@@ -72,6 +56,7 @@
72
  "<end_of_turn>"
73
  ],
74
  "bos_token": "<bos>",
 
75
  "clean_up_tokenization_spaces": false,
76
  "eos_token": "<eos>",
77
  "model_max_length": 1000000000000000019884624838656,
 
3
  "add_eos_token": false,
4
  "added_tokens_decoder": {
5
  "256": {
6
+ "content": "<bos>",
7
  "lstrip": false,
8
  "normalized": false,
9
  "rstrip": false,
 
11
  "special": true
12
  },
13
  "257": {
14
+ "content": "<end_of_turn>",
15
  "lstrip": false,
16
  "normalized": false,
17
  "rstrip": false,
 
19
  "special": true
20
  },
21
  "258": {
22
+ "content": "<eos>",
23
  "lstrip": false,
24
  "normalized": false,
25
  "rstrip": false,
 
27
  "special": true
28
  },
29
  "259": {
30
+ "content": "<pad>",
31
  "lstrip": false,
32
  "normalized": false,
33
  "rstrip": false,
 
42
  "single_word": false,
43
  "special": true
44
  },
45
+ "263": {
46
+ "content": "<unk>",
47
  "lstrip": false,
48
  "normalized": false,
49
  "rstrip": false,
50
  "single_word": false,
51
  "special": true
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  }
53
  },
54
  "additional_special_tokens": [
 
56
  "<end_of_turn>"
57
  ],
58
  "bos_token": "<bos>",
59
+ "chat_template": "{{ bos_token }}{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}{% endfor %}{% if add_generation_prompt %}{{'<start_of_turn>model\n'}}{% endif %}",
60
  "clean_up_tokenization_spaces": false,
61
  "eos_token": "<eos>",
62
  "model_max_length": 1000000000000000019884624838656,