update
Browse files- README.md +0 -199
- config.json +0 -0
- configuration_tpu_llama.py +215 -0
- flax_model.msgpack +3 -0
- flax_model.msgpack.index.json +0 -262
- generation_config.json +11 -0
- flax_model-00001-of-00003.msgpack → model-00001-of-00003.safetensors +2 -2
- flax_model-00002-of-00003.msgpack → model-00002-of-00003.safetensors +2 -2
- flax_model-00003-of-00003.msgpack → model-00003-of-00003.safetensors +2 -2
- model.safetensors.index.json +263 -0
- modelling_flax_tpu_llama.py +1112 -0
- modelling_tpu_llama.py +1607 -0
- special_tokens_map.json +3 -21
- tokenizer.json +1070 -591
- tokenizer_config.json +2 -51
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]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
config.json
CHANGED
The diff for this file is too large to render.
See raw diff
|
|
configuration_tpu_llama.py
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
"""LLaMA model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
24 |
+
|
25 |
+
|
26 |
+
class TPULlamaConfig(PretrainedConfig):
|
27 |
+
r"""
|
28 |
+
This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
|
29 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
30 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
31 |
+
|
32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
33 |
+
documentation from [`PretrainedConfig`] for more information.
|
34 |
+
|
35 |
+
|
36 |
+
Args:
|
37 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
38 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
39 |
+
`inputs_ids` passed when calling [`TPULlamaModel`]
|
40 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
41 |
+
Dimension of the hidden representations.
|
42 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
43 |
+
Dimension of the MLP representations.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
45 |
+
Number of hidden layers in the Transformer decoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
47 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
48 |
+
num_key_value_heads (`int`, *optional*):
|
49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
51 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
54 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
55 |
+
`num_attention_heads`.
|
56 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
57 |
+
The non-linear activation function (function or string) in the decoder.
|
58 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
59 |
+
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
60 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
64 |
+
The epsilon used by the rms normalization layers.
|
65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
67 |
+
relevant if `config.is_decoder=True`.
|
68 |
+
pad_token_id (`int`, *optional*):
|
69 |
+
Padding token id.
|
70 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
71 |
+
Beginning of stream token id.
|
72 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
73 |
+
End of stream token id.
|
74 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
75 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
76 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
|
77 |
+
understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
|
78 |
+
results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
|
79 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
80 |
+
Whether to tie weight embeddings
|
81 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
82 |
+
The base period of the RoPE embeddings.
|
83 |
+
rope_scaling (`Dict`, *optional*):
|
84 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
85 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
86 |
+
accordingly.
|
87 |
+
Expected contents:
|
88 |
+
`rope_type` (`str`):
|
89 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
90 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
91 |
+
`factor` (`float`, *optional*):
|
92 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
93 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
94 |
+
original maximum pre-trained length.
|
95 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
96 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
97 |
+
pretraining.
|
98 |
+
`attention_factor` (`float`, *optional*):
|
99 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
100 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
101 |
+
`factor` field to infer the suggested value.
|
102 |
+
`beta_fast` (`float`, *optional*):
|
103 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
104 |
+
ramp function. If unspecified, it defaults to 32.
|
105 |
+
`beta_slow` (`float`, *optional*):
|
106 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
107 |
+
ramp function. If unspecified, it defaults to 1.
|
108 |
+
`short_factor` (`List[float]`, *optional*):
|
109 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
110 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
111 |
+
size divided by the number of attention heads divided by 2
|
112 |
+
`long_factor` (`List[float]`, *optional*):
|
113 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
114 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
115 |
+
size divided by the number of attention heads divided by 2
|
116 |
+
`low_freq_factor` (`float`, *optional*):
|
117 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
118 |
+
`high_freq_factor` (`float`, *optional*):
|
119 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
120 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
121 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
122 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
123 |
+
The dropout ratio for the attention probabilities.
|
124 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
125 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
126 |
+
head_dim (`int`, *optional*):
|
127 |
+
The attention head dimension. If None, it will default to hidden_size // num_heads
|
128 |
+
|
129 |
+
```python
|
130 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
131 |
+
|
132 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
133 |
+
>>> configuration = LlamaConfig()
|
134 |
+
|
135 |
+
>>> # Initializing a model from the llama-7b style configuration
|
136 |
+
>>> model = LlamaModel(configuration)
|
137 |
+
|
138 |
+
>>> # Accessing the model configuration
|
139 |
+
>>> configuration = model.config
|
140 |
+
```"""
|
141 |
+
|
142 |
+
model_type = "tpu_llama"
|
143 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
144 |
+
|
145 |
+
def __init__(
|
146 |
+
self,
|
147 |
+
vocab_size=32000,
|
148 |
+
hidden_size=4096,
|
149 |
+
intermediate_size=11008,
|
150 |
+
num_hidden_layers=32,
|
151 |
+
num_attention_heads=32,
|
152 |
+
num_key_value_heads=None,
|
153 |
+
hidden_act="silu",
|
154 |
+
max_position_embeddings=2048,
|
155 |
+
initializer_range=0.02,
|
156 |
+
rms_norm_eps=1e-6,
|
157 |
+
use_cache=True,
|
158 |
+
pad_token_id=None,
|
159 |
+
bos_token_id=1,
|
160 |
+
eos_token_id=2,
|
161 |
+
pretraining_tp=1,
|
162 |
+
tie_word_embeddings=False,
|
163 |
+
rope_theta=10000.0,
|
164 |
+
rope_scaling=None,
|
165 |
+
attention_bias=False,
|
166 |
+
attention_dropout=0.0,
|
167 |
+
mlp_bias=False,
|
168 |
+
head_dim=None,
|
169 |
+
expand_input_ids=False, # Transformers-native PyTorch generation support
|
170 |
+
expand_input_ids_maxlen=None,
|
171 |
+
expand_input_ids_vocab_size=None,
|
172 |
+
expand_input_ids_dict=None,
|
173 |
+
**kwargs,
|
174 |
+
):
|
175 |
+
self.vocab_size = vocab_size
|
176 |
+
self.max_position_embeddings = max_position_embeddings
|
177 |
+
self.hidden_size = hidden_size
|
178 |
+
self.intermediate_size = intermediate_size
|
179 |
+
self.num_hidden_layers = num_hidden_layers
|
180 |
+
self.num_attention_heads = num_attention_heads
|
181 |
+
|
182 |
+
# for backward compatibility
|
183 |
+
if num_key_value_heads is None:
|
184 |
+
num_key_value_heads = num_attention_heads
|
185 |
+
|
186 |
+
self.num_key_value_heads = num_key_value_heads
|
187 |
+
self.hidden_act = hidden_act
|
188 |
+
self.initializer_range = initializer_range
|
189 |
+
self.rms_norm_eps = rms_norm_eps
|
190 |
+
self.pretraining_tp = pretraining_tp
|
191 |
+
self.use_cache = use_cache
|
192 |
+
self.rope_theta = rope_theta
|
193 |
+
self.rope_scaling = rope_scaling
|
194 |
+
self.attention_bias = attention_bias
|
195 |
+
self.attention_dropout = attention_dropout
|
196 |
+
self.mlp_bias = mlp_bias
|
197 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
198 |
+
# Validate the correctness of rotary position embeddings parameters
|
199 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
200 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
201 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
202 |
+
rope_config_validation(self)
|
203 |
+
|
204 |
+
self.expand_input_ids = expand_input_ids
|
205 |
+
self.expand_input_ids_maxlen = expand_input_ids_maxlen
|
206 |
+
self.expand_input_ids_vocab_size = expand_input_ids_vocab_size
|
207 |
+
self.expand_input_ids_dict = expand_input_ids_dict
|
208 |
+
|
209 |
+
super().__init__(
|
210 |
+
pad_token_id=pad_token_id,
|
211 |
+
bos_token_id=bos_token_id,
|
212 |
+
eos_token_id=eos_token_id,
|
213 |
+
tie_word_embeddings=tie_word_embeddings,
|
214 |
+
**kwargs,
|
215 |
+
)
|
flax_model.msgpack
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fac95617b354832a8235523ebbe6b881395032501d245342b1e60a30e7e7156b
|
3 |
+
size 11319336568
|
flax_model.msgpack.index.json
DELETED
@@ -1,262 +0,0 @@
|
|
1 |
-
{
|
2 |
-
"metadata": {
|
3 |
-
"total_size": 11287670784
|
4 |
-
},
|
5 |
-
"weight_map": {
|
6 |
-
"lm_head/kernel": "flax_model-00001-of-00003.msgpack",
|
7 |
-
"model/embed_tokens/embedding": "flax_model-00001-of-00003.msgpack",
|
8 |
-
"model/layers/0/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
9 |
-
"model/layers/0/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
10 |
-
"model/layers/0/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
11 |
-
"model/layers/0/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
12 |
-
"model/layers/0/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
13 |
-
"model/layers/0/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
14 |
-
"model/layers/0/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
15 |
-
"model/layers/0/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
16 |
-
"model/layers/0/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
17 |
-
"model/layers/1/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
18 |
-
"model/layers/1/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
19 |
-
"model/layers/1/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
20 |
-
"model/layers/1/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
21 |
-
"model/layers/1/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
22 |
-
"model/layers/1/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
23 |
-
"model/layers/1/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
24 |
-
"model/layers/1/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
25 |
-
"model/layers/1/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
26 |
-
"model/layers/10/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
27 |
-
"model/layers/10/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
28 |
-
"model/layers/10/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
29 |
-
"model/layers/10/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
30 |
-
"model/layers/10/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
31 |
-
"model/layers/10/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
32 |
-
"model/layers/10/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
33 |
-
"model/layers/10/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
34 |
-
"model/layers/10/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
35 |
-
"model/layers/11/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
36 |
-
"model/layers/11/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
37 |
-
"model/layers/11/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
38 |
-
"model/layers/11/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
39 |
-
"model/layers/11/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
40 |
-
"model/layers/11/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
41 |
-
"model/layers/11/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
42 |
-
"model/layers/11/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
43 |
-
"model/layers/11/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
44 |
-
"model/layers/12/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
45 |
-
"model/layers/12/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
46 |
-
"model/layers/12/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
47 |
-
"model/layers/12/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
48 |
-
"model/layers/12/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
49 |
-
"model/layers/12/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
50 |
-
"model/layers/12/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
51 |
-
"model/layers/12/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
52 |
-
"model/layers/12/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
53 |
-
"model/layers/13/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
54 |
-
"model/layers/13/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
55 |
-
"model/layers/13/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
56 |
-
"model/layers/13/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
57 |
-
"model/layers/13/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
58 |
-
"model/layers/13/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
59 |
-
"model/layers/13/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
60 |
-
"model/layers/13/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
61 |
-
"model/layers/13/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
62 |
-
"model/layers/14/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
63 |
-
"model/layers/14/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
64 |
-
"model/layers/14/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
65 |
-
"model/layers/14/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
66 |
-
"model/layers/14/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
67 |
-
"model/layers/14/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
68 |
-
"model/layers/14/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
69 |
-
"model/layers/14/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
70 |
-
"model/layers/14/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
71 |
-
"model/layers/15/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
72 |
-
"model/layers/15/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
73 |
-
"model/layers/15/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
74 |
-
"model/layers/15/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
75 |
-
"model/layers/15/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
76 |
-
"model/layers/15/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
77 |
-
"model/layers/15/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
78 |
-
"model/layers/15/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
79 |
-
"model/layers/15/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
80 |
-
"model/layers/16/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
81 |
-
"model/layers/16/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
82 |
-
"model/layers/16/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
83 |
-
"model/layers/16/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
84 |
-
"model/layers/16/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
85 |
-
"model/layers/16/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
86 |
-
"model/layers/16/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
87 |
-
"model/layers/16/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
88 |
-
"model/layers/16/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
89 |
-
"model/layers/17/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
90 |
-
"model/layers/17/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
91 |
-
"model/layers/17/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
92 |
-
"model/layers/17/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
93 |
-
"model/layers/17/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
94 |
-
"model/layers/17/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
95 |
-
"model/layers/17/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
96 |
-
"model/layers/17/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
97 |
-
"model/layers/17/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
98 |
-
"model/layers/18/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
99 |
-
"model/layers/18/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
100 |
-
"model/layers/18/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
101 |
-
"model/layers/18/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
102 |
-
"model/layers/18/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
103 |
-
"model/layers/18/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
104 |
-
"model/layers/18/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
105 |
-
"model/layers/18/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
106 |
-
"model/layers/18/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
107 |
-
"model/layers/19/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
108 |
-
"model/layers/19/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
109 |
-
"model/layers/19/mlp/gate_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
110 |
-
"model/layers/19/mlp/up_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
111 |
-
"model/layers/19/post_attention_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
112 |
-
"model/layers/19/self_attn/k_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
113 |
-
"model/layers/19/self_attn/o_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
114 |
-
"model/layers/19/self_attn/q_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
115 |
-
"model/layers/19/self_attn/v_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
116 |
-
"model/layers/2/input_layernorm/weight": "flax_model-00001-of-00003.msgpack",
|
117 |
-
"model/layers/2/mlp/down_proj/kernel": "flax_model-00001-of-00003.msgpack",
|
118 |
-
"model/layers/2/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
119 |
-
"model/layers/2/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
120 |
-
"model/layers/2/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
121 |
-
"model/layers/2/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
122 |
-
"model/layers/2/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
123 |
-
"model/layers/2/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
124 |
-
"model/layers/2/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
125 |
-
"model/layers/20/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
126 |
-
"model/layers/20/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
127 |
-
"model/layers/20/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
128 |
-
"model/layers/20/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
129 |
-
"model/layers/20/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
130 |
-
"model/layers/20/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
131 |
-
"model/layers/20/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
132 |
-
"model/layers/20/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
133 |
-
"model/layers/20/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
134 |
-
"model/layers/21/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
135 |
-
"model/layers/21/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
136 |
-
"model/layers/21/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
137 |
-
"model/layers/21/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
138 |
-
"model/layers/21/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
139 |
-
"model/layers/21/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
140 |
-
"model/layers/21/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
141 |
-
"model/layers/21/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
142 |
-
"model/layers/21/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
143 |
-
"model/layers/22/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
144 |
-
"model/layers/22/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
145 |
-
"model/layers/22/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
146 |
-
"model/layers/22/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
147 |
-
"model/layers/22/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
148 |
-
"model/layers/22/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
149 |
-
"model/layers/22/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
150 |
-
"model/layers/22/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
151 |
-
"model/layers/22/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
152 |
-
"model/layers/23/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
153 |
-
"model/layers/23/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
154 |
-
"model/layers/23/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
155 |
-
"model/layers/23/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
156 |
-
"model/layers/23/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
157 |
-
"model/layers/23/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
158 |
-
"model/layers/23/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
159 |
-
"model/layers/23/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
160 |
-
"model/layers/23/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
161 |
-
"model/layers/24/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
162 |
-
"model/layers/24/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
163 |
-
"model/layers/24/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
164 |
-
"model/layers/24/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
165 |
-
"model/layers/24/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
166 |
-
"model/layers/24/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
167 |
-
"model/layers/24/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
168 |
-
"model/layers/24/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
169 |
-
"model/layers/24/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
170 |
-
"model/layers/25/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
171 |
-
"model/layers/25/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
172 |
-
"model/layers/25/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
173 |
-
"model/layers/25/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
174 |
-
"model/layers/25/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
175 |
-
"model/layers/25/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
176 |
-
"model/layers/25/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
177 |
-
"model/layers/25/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
178 |
-
"model/layers/25/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
179 |
-
"model/layers/26/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
180 |
-
"model/layers/26/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
181 |
-
"model/layers/26/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
182 |
-
"model/layers/26/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
183 |
-
"model/layers/26/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
184 |
-
"model/layers/26/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
185 |
-
"model/layers/26/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
186 |
-
"model/layers/26/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
187 |
-
"model/layers/26/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
188 |
-
"model/layers/27/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
189 |
-
"model/layers/27/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
190 |
-
"model/layers/27/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
191 |
-
"model/layers/27/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
192 |
-
"model/layers/27/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
193 |
-
"model/layers/27/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
194 |
-
"model/layers/27/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
195 |
-
"model/layers/27/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
196 |
-
"model/layers/27/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
197 |
-
"model/layers/3/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
198 |
-
"model/layers/3/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
199 |
-
"model/layers/3/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
200 |
-
"model/layers/3/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
201 |
-
"model/layers/3/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
202 |
-
"model/layers/3/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
203 |
-
"model/layers/3/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
204 |
-
"model/layers/3/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
205 |
-
"model/layers/3/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
206 |
-
"model/layers/4/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
207 |
-
"model/layers/4/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
208 |
-
"model/layers/4/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
209 |
-
"model/layers/4/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
210 |
-
"model/layers/4/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
211 |
-
"model/layers/4/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
212 |
-
"model/layers/4/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
213 |
-
"model/layers/4/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
214 |
-
"model/layers/4/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
215 |
-
"model/layers/5/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
216 |
-
"model/layers/5/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
217 |
-
"model/layers/5/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
218 |
-
"model/layers/5/mlp/up_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
219 |
-
"model/layers/5/post_attention_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
220 |
-
"model/layers/5/self_attn/k_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
221 |
-
"model/layers/5/self_attn/o_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
222 |
-
"model/layers/5/self_attn/q_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
223 |
-
"model/layers/5/self_attn/v_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
224 |
-
"model/layers/6/input_layernorm/weight": "flax_model-00002-of-00003.msgpack",
|
225 |
-
"model/layers/6/mlp/down_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
226 |
-
"model/layers/6/mlp/gate_proj/kernel": "flax_model-00002-of-00003.msgpack",
|
227 |
-
"model/layers/6/mlp/up_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
228 |
-
"model/layers/6/post_attention_layernorm/weight": "flax_model-00003-of-00003.msgpack",
|
229 |
-
"model/layers/6/self_attn/k_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
230 |
-
"model/layers/6/self_attn/o_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
231 |
-
"model/layers/6/self_attn/q_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
232 |
-
"model/layers/6/self_attn/v_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
233 |
-
"model/layers/7/input_layernorm/weight": "flax_model-00003-of-00003.msgpack",
|
234 |
-
"model/layers/7/mlp/down_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
235 |
-
"model/layers/7/mlp/gate_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
236 |
-
"model/layers/7/mlp/up_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
237 |
-
"model/layers/7/post_attention_layernorm/weight": "flax_model-00003-of-00003.msgpack",
|
238 |
-
"model/layers/7/self_attn/k_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
239 |
-
"model/layers/7/self_attn/o_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
240 |
-
"model/layers/7/self_attn/q_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
241 |
-
"model/layers/7/self_attn/v_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
242 |
-
"model/layers/8/input_layernorm/weight": "flax_model-00003-of-00003.msgpack",
|
243 |
-
"model/layers/8/mlp/down_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
244 |
-
"model/layers/8/mlp/gate_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
245 |
-
"model/layers/8/mlp/up_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
246 |
-
"model/layers/8/post_attention_layernorm/weight": "flax_model-00003-of-00003.msgpack",
|
247 |
-
"model/layers/8/self_attn/k_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
248 |
-
"model/layers/8/self_attn/o_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
249 |
-
"model/layers/8/self_attn/q_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
250 |
-
"model/layers/8/self_attn/v_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
251 |
-
"model/layers/9/input_layernorm/weight": "flax_model-00003-of-00003.msgpack",
|
252 |
-
"model/layers/9/mlp/down_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
253 |
-
"model/layers/9/mlp/gate_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
254 |
-
"model/layers/9/mlp/up_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
255 |
-
"model/layers/9/post_attention_layernorm/weight": "flax_model-00003-of-00003.msgpack",
|
256 |
-
"model/layers/9/self_attn/k_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
257 |
-
"model/layers/9/self_attn/o_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
258 |
-
"model/layers/9/self_attn/q_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
259 |
-
"model/layers/9/self_attn/v_proj/kernel": "flax_model-00003-of-00003.msgpack",
|
260 |
-
"model/norm/weight": "flax_model-00003-of-00003.msgpack"
|
261 |
-
}
|
262 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
generation_config.json
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 128000,
|
4 |
+
"eos_token_id": [
|
5 |
+
128001,
|
6 |
+
128008,
|
7 |
+
128009
|
8 |
+
],
|
9 |
+
"max_length": 2048,
|
10 |
+
"transformers_version": "4.46.0.dev0"
|
11 |
+
}
|
flax_model-00001-of-00003.msgpack → model-00001-of-00003.safetensors
RENAMED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8aaf0d2d9acfaea34c863147685c9cf783ec1f830d7d9eab29e564a56a62041d
|
3 |
+
size 4901397232
|
flax_model-00002-of-00003.msgpack → model-00002-of-00003.safetensors
RENAMED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:489398be1c2a1221de417815f98b3682de255748bee2f38ece6c9ca8ecf28c65
|
3 |
+
size 4932808968
|
flax_model-00003-of-00003.msgpack → model-00003-of-00003.safetensors
RENAMED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b32106a41daab0866a82e8338519582c221df8f4f3f8c992fe8c968445a315ae
|
3 |
+
size 3023408856
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 12857585664
|
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.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
15 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
16 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
17 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
18 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
19 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
20 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
21 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
22 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
23 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
24 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
25 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
26 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
27 |
+
"model.layers.10.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
28 |
+
"model.layers.10.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
29 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
30 |
+
"model.layers.10.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
31 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
32 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
33 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
34 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
35 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
36 |
+
"model.layers.11.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
37 |
+
"model.layers.11.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
38 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
39 |
+
"model.layers.11.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
40 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
41 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
42 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
43 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
44 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
45 |
+
"model.layers.12.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
46 |
+
"model.layers.12.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
47 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
48 |
+
"model.layers.12.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
49 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
50 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
51 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
52 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
53 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
54 |
+
"model.layers.13.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
55 |
+
"model.layers.13.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
56 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
57 |
+
"model.layers.13.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
58 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
59 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
60 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
61 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
62 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
63 |
+
"model.layers.14.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
64 |
+
"model.layers.14.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
65 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
66 |
+
"model.layers.14.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
67 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
68 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
69 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
70 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
71 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
72 |
+
"model.layers.15.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
73 |
+
"model.layers.15.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
74 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
75 |
+
"model.layers.15.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
76 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
77 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
78 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
79 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
80 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
81 |
+
"model.layers.16.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
82 |
+
"model.layers.16.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
83 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
84 |
+
"model.layers.16.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
85 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
86 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
87 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
88 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
89 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
90 |
+
"model.layers.17.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
91 |
+
"model.layers.17.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
92 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
93 |
+
"model.layers.17.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
94 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
95 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
96 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
97 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
98 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
99 |
+
"model.layers.18.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
100 |
+
"model.layers.18.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
101 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
102 |
+
"model.layers.18.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
103 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
104 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
105 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
106 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
107 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
108 |
+
"model.layers.19.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
109 |
+
"model.layers.19.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
110 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
111 |
+
"model.layers.19.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
112 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
113 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
114 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
115 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
116 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
117 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
118 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
119 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
120 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
121 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
122 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
123 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
124 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
125 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
126 |
+
"model.layers.20.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
127 |
+
"model.layers.20.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
128 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
129 |
+
"model.layers.20.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
130 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
131 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
132 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
133 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
134 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
135 |
+
"model.layers.21.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
136 |
+
"model.layers.21.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
137 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
138 |
+
"model.layers.21.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
139 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
140 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
141 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
142 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
143 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
144 |
+
"model.layers.22.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
145 |
+
"model.layers.22.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
146 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
147 |
+
"model.layers.22.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
148 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
149 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
150 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
151 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
152 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
153 |
+
"model.layers.23.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
154 |
+
"model.layers.23.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
155 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
156 |
+
"model.layers.23.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
157 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
158 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
159 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
160 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
161 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
162 |
+
"model.layers.24.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
163 |
+
"model.layers.24.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
164 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
165 |
+
"model.layers.24.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
166 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
167 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
168 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
169 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
170 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
171 |
+
"model.layers.25.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
172 |
+
"model.layers.25.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
173 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
174 |
+
"model.layers.25.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
175 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
176 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
177 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
178 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
179 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
180 |
+
"model.layers.26.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
181 |
+
"model.layers.26.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
182 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
183 |
+
"model.layers.26.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
184 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
185 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
186 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
187 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
188 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
189 |
+
"model.layers.27.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
190 |
+
"model.layers.27.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
191 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
192 |
+
"model.layers.27.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
193 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
194 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
195 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
196 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
197 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
198 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
199 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
200 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
201 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
202 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
203 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
204 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
205 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
206 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
207 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
208 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
209 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
210 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
211 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
212 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
213 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
214 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
215 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
216 |
+
"model.layers.5.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
217 |
+
"model.layers.5.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
218 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
219 |
+
"model.layers.5.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
220 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
221 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
222 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
223 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
224 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
225 |
+
"model.layers.6.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
226 |
+
"model.layers.6.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
227 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
228 |
+
"model.layers.6.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
229 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
230 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
231 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
232 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
233 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
234 |
+
"model.layers.7.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
235 |
+
"model.layers.7.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
236 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
237 |
+
"model.layers.7.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
238 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
239 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
240 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
241 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
242 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
243 |
+
"model.layers.8.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
244 |
+
"model.layers.8.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
245 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
246 |
+
"model.layers.8.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
247 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
248 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
249 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
250 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
251 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
252 |
+
"model.layers.9.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
253 |
+
"model.layers.9.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
254 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
255 |
+
"model.layers.9.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
256 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
257 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
258 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
259 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
260 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
261 |
+
"model.norm.weight": "model-00003-of-00003.safetensors"
|
262 |
+
}
|
263 |
+
}
|
modelling_flax_tpu_llama.py
ADDED
@@ -0,0 +1,1112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 Meta AI, EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
"""Flax LLaMA model."""
|
21 |
+
|
22 |
+
import math
|
23 |
+
from functools import partial
|
24 |
+
from typing import Optional, Tuple
|
25 |
+
|
26 |
+
import flax.linen as nn
|
27 |
+
import jax
|
28 |
+
import jax.numpy as jnp
|
29 |
+
import numpy as np
|
30 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
31 |
+
from flax.linen import combine_masks, make_causal_mask
|
32 |
+
from flax.linen.attention import dot_product_attention_weights
|
33 |
+
from flax.linen import partitioning as nn_partitioning
|
34 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
35 |
+
from jax import lax
|
36 |
+
from jax.experimental.pallas.ops.tpu.flash_attention import (
|
37 |
+
flash_attention as pallas_flash_attention,
|
38 |
+
)
|
39 |
+
from jax.experimental.shard_map import shard_map
|
40 |
+
from jax.sharding import PartitionSpec as P
|
41 |
+
|
42 |
+
from transformers.modeling_flax_outputs import FlaxBaseModelOutput, FlaxCausalLMOutput
|
43 |
+
from transformers.modeling_flax_utils import (
|
44 |
+
ACT2FN,
|
45 |
+
FlaxPreTrainedModel,
|
46 |
+
append_call_sample_docstring,
|
47 |
+
)
|
48 |
+
from transformers.utils import (
|
49 |
+
add_start_docstrings,
|
50 |
+
add_start_docstrings_to_model_forward,
|
51 |
+
logging,
|
52 |
+
)
|
53 |
+
from .configuration_tpu_llama import TPULlamaConfig
|
54 |
+
|
55 |
+
logger = logging.get_logger(__name__)
|
56 |
+
|
57 |
+
_CONFIG_FOR_DOC = "TPULlamaConfig"
|
58 |
+
_CHECKPOINT_FOR_DOC = "afmck/testing-llama-tiny"
|
59 |
+
_REAL_CHECKPOINT_FOR_DOC = "openlm-research/open_llama_3b_v2"
|
60 |
+
|
61 |
+
LLAMA_START_DOCSTRING = r"""
|
62 |
+
|
63 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
64 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
65 |
+
etc.)
|
66 |
+
|
67 |
+
This model is also a Flax Linen
|
68 |
+
[flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
|
69 |
+
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
|
70 |
+
|
71 |
+
Finally, this model supports inherent JAX features such as:
|
72 |
+
|
73 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
74 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
75 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
76 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
77 |
+
|
78 |
+
Parameters:
|
79 |
+
config ([`LlamaConfig`]): Model configuration class with all the parameters of the model.
|
80 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
81 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
82 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
83 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16`, or
|
84 |
+
`jax.numpy.bfloat16`.
|
85 |
+
|
86 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
87 |
+
specified all the computation will be performed with the given `dtype`.
|
88 |
+
|
89 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
90 |
+
parameters.**
|
91 |
+
|
92 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
93 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
94 |
+
"""
|
95 |
+
|
96 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
97 |
+
Args:
|
98 |
+
input_ids (`numpy.ndarray` of shape `(batch_size, input_ids_length)`):
|
99 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
100 |
+
it.
|
101 |
+
|
102 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
103 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
104 |
+
|
105 |
+
[What are input IDs?](../glossary#input-ids)
|
106 |
+
attention_mask (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
107 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
108 |
+
|
109 |
+
- 1 for tokens that are **not masked**,
|
110 |
+
- 0 for tokens that are **masked**.
|
111 |
+
|
112 |
+
[What are attention masks?](../glossary#attention-mask)
|
113 |
+
|
114 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
115 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
116 |
+
|
117 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
118 |
+
`past_key_values`).
|
119 |
+
|
120 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
121 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
122 |
+
information on the default strategy.
|
123 |
+
|
124 |
+
- 1 indicates the head is **not masked**,
|
125 |
+
- 0 indicates the head is **masked**.
|
126 |
+
position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
127 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
128 |
+
config.n_positions - 1]`.
|
129 |
+
|
130 |
+
[What are position IDs?](../glossary#position-ids)
|
131 |
+
past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
|
132 |
+
Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
|
133 |
+
auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
|
134 |
+
output_attentions (`bool`, *optional*):
|
135 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
136 |
+
tensors for more detail.
|
137 |
+
output_hidden_states (`bool`, *optional*):
|
138 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
139 |
+
more detail.
|
140 |
+
return_dict (`bool`, *optional*):
|
141 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
142 |
+
"""
|
143 |
+
|
144 |
+
remat = nn_partitioning.remat
|
145 |
+
|
146 |
+
# adapted from modeling_rope_utils
|
147 |
+
def _compute_default_rope_parameters(
|
148 |
+
config=None,
|
149 |
+
seq_len: Optional[int] = None,
|
150 |
+
**rope_kwargs,
|
151 |
+
):
|
152 |
+
if config is not None and len(rope_kwargs) > 0:
|
153 |
+
raise ValueError(
|
154 |
+
"Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in "
|
155 |
+
f"`_compute_default_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}"
|
156 |
+
)
|
157 |
+
if len(rope_kwargs) > 0:
|
158 |
+
base = rope_kwargs["base"]
|
159 |
+
dim = rope_kwargs["dim"]
|
160 |
+
elif config is not None:
|
161 |
+
base = config.rope_theta
|
162 |
+
partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
|
163 |
+
head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
164 |
+
dim = int(head_dim * partial_rotary_factor)
|
165 |
+
|
166 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
167 |
+
|
168 |
+
# Compute the inverse frequencies
|
169 |
+
inv_freq = 1.0 / (base ** (jnp.arange(0, dim, 2, dtype=jnp.int32).astype(jnp.float32) / dim))
|
170 |
+
return inv_freq, attention_factor
|
171 |
+
|
172 |
+
|
173 |
+
def _compute_longrope_parameters(
|
174 |
+
config, seq_len: Optional[int] = None, **rope_kwargs
|
175 |
+
):
|
176 |
+
# TODO (joao): use the new `original_max_position_embeddings` from rope_scaling
|
177 |
+
# No need to keep BC with longrope, unreleased when this new pattern was created.
|
178 |
+
if len(rope_kwargs) > 0:
|
179 |
+
raise ValueError(
|
180 |
+
"Unexpected arguments: `**rope_kwargs` should be unset in `_compute_longrope_parameters`, got "
|
181 |
+
f"{rope_kwargs}"
|
182 |
+
)
|
183 |
+
|
184 |
+
base = config.rope_theta
|
185 |
+
partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
|
186 |
+
head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
187 |
+
dim = int(head_dim * partial_rotary_factor)
|
188 |
+
long_factor = config.rope_scaling["long_factor"]
|
189 |
+
short_factor = config.rope_scaling["short_factor"]
|
190 |
+
factor = config.rope_scaling.get("factor")
|
191 |
+
attention_factor = config.rope_scaling.get("attention_factor")
|
192 |
+
|
193 |
+
# NOTE: Phi3 (and potentially other models) modify `max_position_embeddings` and have a
|
194 |
+
# `original_max_position_embeddings` field containing the pretrained value. They use the ratio between these two
|
195 |
+
# values to compute the default attention scaling factor, instead of using `factor`.
|
196 |
+
if hasattr(config, "original_max_position_embeddings"):
|
197 |
+
if seq_len and seq_len < config.original_max_position_embeddings:
|
198 |
+
expanded_max_position_embeddings = config.original_max_position_embeddings
|
199 |
+
else:
|
200 |
+
expanded_max_position_embeddings = config.max_position_embeddings
|
201 |
+
max_position_embeddings = config.original_max_position_embeddings
|
202 |
+
factor = expanded_max_position_embeddings / max_position_embeddings
|
203 |
+
else:
|
204 |
+
max_position_embeddings = config.max_position_embeddings
|
205 |
+
expanded_max_position_embeddings = max_position_embeddings * factor
|
206 |
+
|
207 |
+
# Sets the attention factor as suggested in the paper
|
208 |
+
if attention_factor is None:
|
209 |
+
if factor <= 1.0:
|
210 |
+
attention_factor = 1.0
|
211 |
+
else:
|
212 |
+
attention_factor = math.sqrt(1 + math.log(factor) / math.log(max_position_embeddings))
|
213 |
+
|
214 |
+
# Compute the inverse frequencies -- scaled based on the target sequence length
|
215 |
+
if expanded_max_position_embeddings > max_position_embeddings:
|
216 |
+
ext_factors = jnp.array(long_factor, dtype=jnp.float32)
|
217 |
+
else:
|
218 |
+
ext_factors = jnp.array(short_factor, dtype=jnp.float32)
|
219 |
+
inv_freq_shape = jnp.arange(0, dim, 2, dtype=jnp.int64).astype(jnp.float32) / dim
|
220 |
+
inv_freq = 1.0 / (ext_factors * base**inv_freq_shape)
|
221 |
+
|
222 |
+
return inv_freq, attention_factor
|
223 |
+
|
224 |
+
|
225 |
+
def _compute_llama3_parameters(config, seq_len: Optional[int] = None, **rope_kwargs):
|
226 |
+
# Gets the default RoPE parameters
|
227 |
+
inv_freq, attention_factor = _compute_default_rope_parameters(config, seq_len, **rope_kwargs)
|
228 |
+
|
229 |
+
factor = config.rope_scaling["factor"] # `8` in the original implementation
|
230 |
+
low_freq_factor = config.rope_scaling["low_freq_factor"] # `1` in the original implementation
|
231 |
+
high_freq_factor = config.rope_scaling["high_freq_factor"] # `4` in the original implementation
|
232 |
+
old_context_len = config.rope_scaling["original_max_position_embeddings"] # `8192` in the original implementation
|
233 |
+
|
234 |
+
low_freq_wavelen = old_context_len / low_freq_factor
|
235 |
+
high_freq_wavelen = old_context_len / high_freq_factor
|
236 |
+
|
237 |
+
wavelen = 2 * math.pi / inv_freq
|
238 |
+
# wavelen < high_freq_wavelen: do nothing
|
239 |
+
# wavelen > low_freq_wavelen: divide by factor
|
240 |
+
inv_freq_llama = jnp.where(wavelen > low_freq_wavelen, inv_freq / factor, inv_freq)
|
241 |
+
# otherwise: interpolate between the two, using a smooth factor
|
242 |
+
smooth_factor = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)
|
243 |
+
smoothed_inv_freq = (1 - smooth_factor) * inv_freq_llama / factor + smooth_factor * inv_freq_llama
|
244 |
+
is_medium_freq = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen)
|
245 |
+
inv_freq_llama = jnp.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama)
|
246 |
+
|
247 |
+
return inv_freq_llama, attention_factor
|
248 |
+
|
249 |
+
|
250 |
+
ROPE_INIT_FUNCTIONS = {
|
251 |
+
"default": _compute_default_rope_parameters,
|
252 |
+
"llama3": _compute_llama3_parameters,
|
253 |
+
"longrope": _compute_longrope_parameters,
|
254 |
+
}
|
255 |
+
|
256 |
+
|
257 |
+
def create_sinusoidal_positions(num_pos, dim):
|
258 |
+
inv_freq = 1.0 / (10000 ** (np.arange(0, dim, 2) / dim))
|
259 |
+
freqs = np.einsum("i , j -> i j", np.arange(num_pos), inv_freq).astype("float32")
|
260 |
+
|
261 |
+
emb = np.concatenate((freqs, freqs), axis=-1)
|
262 |
+
out = np.concatenate((np.sin(emb)[:, None, :], np.cos(emb)[:, None, :]), axis=-1)
|
263 |
+
return jnp.array(out[:, :, :num_pos])
|
264 |
+
|
265 |
+
|
266 |
+
def rotate_half(tensor):
|
267 |
+
"""Rotates half the hidden dims of the input."""
|
268 |
+
rotate_half_tensor = jnp.concatenate(
|
269 |
+
(-tensor[..., tensor.shape[-1] // 2 :], tensor[..., : tensor.shape[-1] // 2]),
|
270 |
+
axis=-1,
|
271 |
+
)
|
272 |
+
return rotate_half_tensor
|
273 |
+
|
274 |
+
|
275 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
276 |
+
# TODO: get rid of swapaxes?
|
277 |
+
q = jnp.swapaxes(q, 2, 1)
|
278 |
+
k = jnp.swapaxes(k, 2, 1)
|
279 |
+
|
280 |
+
cos = jnp.expand_dims(cos, axis=unsqueeze_dim)
|
281 |
+
sin = jnp.expand_dims(sin, axis=unsqueeze_dim)
|
282 |
+
|
283 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
284 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
285 |
+
|
286 |
+
q_embed = jnp.swapaxes(q_embed, 2, 1)
|
287 |
+
k_embed = jnp.swapaxes(k_embed, 2, 1)
|
288 |
+
|
289 |
+
return q_embed, k_embed
|
290 |
+
|
291 |
+
|
292 |
+
class FlaxTPULlamaRMSNorm(nn.Module):
|
293 |
+
config: TPULlamaConfig
|
294 |
+
dtype: jnp.dtype = jnp.float32
|
295 |
+
|
296 |
+
def setup(self):
|
297 |
+
self.epsilon = self.config.rms_norm_eps
|
298 |
+
self.weight = self.param("weight", lambda _, shape: jnp.ones(shape), self.config.hidden_size)
|
299 |
+
|
300 |
+
def __call__(self, hidden_states):
|
301 |
+
variance = jnp.asarray(hidden_states, dtype=jnp.float32)
|
302 |
+
variance = jnp.power(variance, 2)
|
303 |
+
variance = variance.mean(-1, keepdims=True)
|
304 |
+
# use `jax.numpy.sqrt` as `jax.lax.rsqrt` does not match `torch.rsqrt`
|
305 |
+
hidden_states = hidden_states / jnp.sqrt(variance + self.epsilon)
|
306 |
+
|
307 |
+
return self.weight * jnp.asarray(hidden_states, dtype=self.dtype)
|
308 |
+
|
309 |
+
|
310 |
+
class FlaxTPULlamaRotaryEmbedding(nn.Module):
|
311 |
+
config: TPULlamaConfig
|
312 |
+
dtype: jnp.dtype = jnp.float32
|
313 |
+
|
314 |
+
def setup(self):
|
315 |
+
self.rope_kwargs = {}
|
316 |
+
|
317 |
+
if self.config.rope_scaling is not None:
|
318 |
+
self.rope_type = self.config.rope_scaling.get("rope_type", self.config.rope_scaling.get("type"))
|
319 |
+
else:
|
320 |
+
self.rope_type = "default"
|
321 |
+
self.max_seq_len_cached = self.config.max_position_embeddings
|
322 |
+
self.original_max_seq_len = self.config.max_position_embeddings
|
323 |
+
|
324 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
325 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, **self.rope_kwargs)
|
326 |
+
self.inv_freq = self.original_inv_freq = inv_freq
|
327 |
+
|
328 |
+
def __call__(self, x, position_ids):
|
329 |
+
inv_freq_expanded = jnp.tile(
|
330 |
+
self.inv_freq[None, :, None].astype(jnp.float32),
|
331 |
+
(position_ids.shape[0], 1, 1),
|
332 |
+
)
|
333 |
+
position_ids_expanded = position_ids[:, None, :].astype(jnp.float32)
|
334 |
+
|
335 |
+
freqs = jnp.swapaxes(jnp.matmul(inv_freq_expanded, position_ids_expanded), 1, 2)
|
336 |
+
emb = jnp.concatenate([freqs, freqs], axis=-1)
|
337 |
+
cos = jnp.cos(emb)
|
338 |
+
sin = jnp.sin(emb)
|
339 |
+
|
340 |
+
cos = cos * self.attention_scaling
|
341 |
+
sin = sin * self.attention_scaling
|
342 |
+
|
343 |
+
return cos.astype(x.dtype), sin.astype(x.dtype)
|
344 |
+
|
345 |
+
|
346 |
+
class FlaxTPULlamaAttention(nn.Module):
|
347 |
+
config: TPULlamaConfig
|
348 |
+
dtype: jnp.dtype = jnp.float32
|
349 |
+
causal: bool = True
|
350 |
+
is_cross_attention: bool = False
|
351 |
+
|
352 |
+
def setup(self):
|
353 |
+
config = self.config
|
354 |
+
self.embed_dim = config.hidden_size
|
355 |
+
self.num_heads = config.num_attention_heads
|
356 |
+
self.head_dim = self.embed_dim // self.num_heads
|
357 |
+
self.num_key_value_heads = config.num_key_value_heads
|
358 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
359 |
+
self.attention_softmax_in_fp32 = self.dtype is not jnp.float32
|
360 |
+
|
361 |
+
dense = partial(
|
362 |
+
nn.Dense,
|
363 |
+
use_bias=config.attention_bias,
|
364 |
+
dtype=self.dtype,
|
365 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
366 |
+
)
|
367 |
+
|
368 |
+
self.q_proj = dense(self.num_heads * self.head_dim)
|
369 |
+
self.k_proj = dense(self.num_key_value_heads * self.head_dim)
|
370 |
+
self.v_proj = dense(self.num_key_value_heads * self.head_dim)
|
371 |
+
self.o_proj = dense(self.embed_dim)
|
372 |
+
self.causal_mask = make_causal_mask(
|
373 |
+
jnp.ones(
|
374 |
+
(1, getattr(config, "max_length", config.max_position_embeddings)),
|
375 |
+
dtype="bool",
|
376 |
+
),
|
377 |
+
dtype="bool",
|
378 |
+
)
|
379 |
+
self.rotary_emb = FlaxTPULlamaRotaryEmbedding(config, dtype=self.dtype)
|
380 |
+
|
381 |
+
def _split_heads(self, hidden_states, num_heads):
|
382 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (num_heads, self.head_dim))
|
383 |
+
|
384 |
+
def _merge_heads(self, hidden_states):
|
385 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
|
386 |
+
|
387 |
+
@nn.compact
|
388 |
+
# Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoSelfAttention._concatenate_to_cache
|
389 |
+
def _concatenate_to_cache(self, key, value, query, attention_mask):
|
390 |
+
"""
|
391 |
+
This function takes projected key, value states from a single input token and concatenates the states to cached
|
392 |
+
states from previous steps. This function is slighly adapted from the official Flax repository:
|
393 |
+
https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
|
394 |
+
"""
|
395 |
+
# detect if we're initializing by absence of existing cache data.
|
396 |
+
is_initialized = self.has_variable("cache", "cached_key")
|
397 |
+
cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
|
398 |
+
cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
|
399 |
+
cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
|
400 |
+
|
401 |
+
if is_initialized:
|
402 |
+
*batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
|
403 |
+
# update key, value caches with our new 1d spatial slices
|
404 |
+
cur_index = cache_index.value
|
405 |
+
indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
|
406 |
+
key = lax.dynamic_update_slice(cached_key.value, key, indices)
|
407 |
+
value = lax.dynamic_update_slice(cached_value.value, value, indices)
|
408 |
+
cached_key.value = key
|
409 |
+
cached_value.value = value
|
410 |
+
num_updated_cache_vectors = query.shape[1]
|
411 |
+
cache_index.value = cache_index.value + num_updated_cache_vectors
|
412 |
+
# 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.
|
413 |
+
pad_mask = jnp.broadcast_to(
|
414 |
+
jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
|
415 |
+
tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
|
416 |
+
)
|
417 |
+
attention_mask = combine_masks(pad_mask, attention_mask)
|
418 |
+
return key, value, attention_mask
|
419 |
+
|
420 |
+
def __call__(
|
421 |
+
self,
|
422 |
+
hidden_states,
|
423 |
+
attention_mask,
|
424 |
+
position_ids,
|
425 |
+
deterministic: bool = True,
|
426 |
+
init_cache: bool = False,
|
427 |
+
output_attentions: bool = False,
|
428 |
+
):
|
429 |
+
raw_query = self.q_proj(hidden_states)
|
430 |
+
raw_key = self.k_proj(hidden_states)
|
431 |
+
raw_value = self.v_proj(hidden_states)
|
432 |
+
|
433 |
+
query = self._split_heads(raw_query, self.num_heads)
|
434 |
+
key = self._split_heads(raw_key, self.num_key_value_heads)
|
435 |
+
value = self._split_heads(raw_value, self.num_key_value_heads)
|
436 |
+
|
437 |
+
cos, sin = self.rotary_emb(value, position_ids)
|
438 |
+
query, key = apply_rotary_pos_emb(query, key, cos, sin)
|
439 |
+
|
440 |
+
query_length, key_length = query.shape[1], key.shape[1]
|
441 |
+
|
442 |
+
if self.has_variable("cache", "cached_key"):
|
443 |
+
mask_shift = self.variables["cache"]["cache_index"]
|
444 |
+
max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
|
445 |
+
causal_mask = lax.dynamic_slice(
|
446 |
+
self.causal_mask,
|
447 |
+
(0, 0, mask_shift, 0),
|
448 |
+
(1, 1, query_length, max_decoder_length),
|
449 |
+
)
|
450 |
+
else:
|
451 |
+
causal_mask = self.causal_mask[:, :, :query_length, :key_length]
|
452 |
+
|
453 |
+
batch_size = hidden_states.shape[0]
|
454 |
+
causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
|
455 |
+
|
456 |
+
if attention_mask.ndim == 2:
|
457 |
+
attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
|
458 |
+
else:
|
459 |
+
assert attention_mask.ndim == 4
|
460 |
+
|
461 |
+
attention_mask = jnp.broadcast_to(attention_mask, causal_mask.shape)
|
462 |
+
attention_mask = combine_masks(attention_mask, causal_mask)
|
463 |
+
|
464 |
+
dropout_rng = None
|
465 |
+
if not deterministic and self.config.attention_dropout > 0.0:
|
466 |
+
dropout_rng = self.make_rng("dropout")
|
467 |
+
|
468 |
+
# During fast autoregressive decoding, we feed one position at a time,
|
469 |
+
# and cache the keys and values step by step.
|
470 |
+
if self.has_variable("cache", "cached_key") or init_cache:
|
471 |
+
key, value, attention_mask = self._concatenate_to_cache(key, value, query, attention_mask)
|
472 |
+
|
473 |
+
key = jnp.repeat(key, self.num_key_value_groups, axis=2)
|
474 |
+
value = jnp.repeat(value, self.num_key_value_groups, axis=2)
|
475 |
+
|
476 |
+
# transform boolean mask into float mask
|
477 |
+
attention_bias = lax.select(
|
478 |
+
attention_mask > 0,
|
479 |
+
jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
480 |
+
jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
|
481 |
+
)
|
482 |
+
|
483 |
+
# usual dot product attention
|
484 |
+
attention_dtype = jnp.float32 if self.attention_softmax_in_fp32 else self.dtype
|
485 |
+
attn_weights = dot_product_attention_weights(
|
486 |
+
query,
|
487 |
+
key,
|
488 |
+
bias=attention_bias,
|
489 |
+
dropout_rng=dropout_rng,
|
490 |
+
dropout_rate=self.config.attention_dropout,
|
491 |
+
deterministic=deterministic,
|
492 |
+
dtype=attention_dtype,
|
493 |
+
)
|
494 |
+
|
495 |
+
if self.attention_softmax_in_fp32:
|
496 |
+
attn_weights = attn_weights.astype(self.dtype)
|
497 |
+
|
498 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value)
|
499 |
+
attn_output = self._merge_heads(attn_output)
|
500 |
+
attn_output = self.o_proj(attn_output)
|
501 |
+
|
502 |
+
outputs = (attn_output, (raw_query, raw_key, raw_value)) if output_attentions else (attn_output,)
|
503 |
+
return outputs
|
504 |
+
|
505 |
+
|
506 |
+
class FlaxTPULlamaFlashAttention(FlaxTPULlamaAttention):
|
507 |
+
def setup(self):
|
508 |
+
super().setup()
|
509 |
+
|
510 |
+
if self.num_heads % len(jax.devices()) != 0:
|
511 |
+
# TODO: warn or pad attention heads or neither or both?
|
512 |
+
shard_across_model = False
|
513 |
+
else:
|
514 |
+
shard_across_model = True
|
515 |
+
|
516 |
+
model_partition = "model" if shard_across_model else None
|
517 |
+
data_partition = "data"
|
518 |
+
|
519 |
+
self.flash_attn_fn = shard_map(
|
520 |
+
partial(
|
521 |
+
pallas_flash_attention,
|
522 |
+
sm_scale=1 / math.sqrt(self.head_dim),
|
523 |
+
causal=True,
|
524 |
+
),
|
525 |
+
mesh=getattr(self.config, "mesh"),
|
526 |
+
in_specs=(
|
527 |
+
# bnlh
|
528 |
+
P(data_partition, model_partition, None, None),
|
529 |
+
P(data_partition, model_partition, None, None),
|
530 |
+
P(data_partition, model_partition, None, None),
|
531 |
+
# P(),
|
532 |
+
),
|
533 |
+
# bnlh
|
534 |
+
out_specs=P(data_partition, model_partition, None, None),
|
535 |
+
check_rep=False,
|
536 |
+
)
|
537 |
+
|
538 |
+
def __call__(
|
539 |
+
self,
|
540 |
+
hidden_states,
|
541 |
+
attention_mask,
|
542 |
+
position_ids,
|
543 |
+
deterministic: bool = True,
|
544 |
+
init_cache: bool = False,
|
545 |
+
output_attentions: bool = False,
|
546 |
+
):
|
547 |
+
raw_query = self.q_proj(hidden_states)
|
548 |
+
raw_key = self.k_proj(hidden_states)
|
549 |
+
raw_value = self.v_proj(hidden_states)
|
550 |
+
|
551 |
+
query = self._split_heads(raw_query, self.num_heads)
|
552 |
+
key = self._split_heads(raw_key, self.num_key_value_heads)
|
553 |
+
value = self._split_heads(raw_value, self.num_key_value_heads)
|
554 |
+
|
555 |
+
cos, sin = self.rotary_emb(value, position_ids)
|
556 |
+
query, key = apply_rotary_pos_emb(query, key, cos, sin)
|
557 |
+
|
558 |
+
query_length, key_length = query.shape[1], key.shape[1]
|
559 |
+
|
560 |
+
if self.has_variable("cache", "cached_key"):
|
561 |
+
mask_shift = self.variables["cache"]["cache_index"]
|
562 |
+
max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
|
563 |
+
causal_mask = lax.dynamic_slice(
|
564 |
+
self.causal_mask,
|
565 |
+
(0, 0, mask_shift, 0),
|
566 |
+
(1, 1, query_length, max_decoder_length),
|
567 |
+
)
|
568 |
+
else:
|
569 |
+
causal_mask = self.causal_mask[:, :, :query_length, :key_length]
|
570 |
+
|
571 |
+
batch_size = hidden_states.shape[0]
|
572 |
+
causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
|
573 |
+
|
574 |
+
if attention_mask.ndim == 2:
|
575 |
+
attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
|
576 |
+
else:
|
577 |
+
assert attention_mask.ndim == 4
|
578 |
+
|
579 |
+
attention_mask = jnp.broadcast_to(attention_mask, causal_mask.shape)
|
580 |
+
attention_mask = combine_masks(attention_mask, causal_mask)
|
581 |
+
|
582 |
+
# During fast autoregressive decoding, we feed one position at a time,
|
583 |
+
# and cache the keys and values step by step.
|
584 |
+
if self.has_variable("cache", "cached_key") or init_cache:
|
585 |
+
key, value, attention_mask = self._concatenate_to_cache(key, value, query, attention_mask)
|
586 |
+
|
587 |
+
key = jnp.repeat(key, self.num_key_value_groups, axis=2)
|
588 |
+
value = jnp.repeat(value, self.num_key_value_groups, axis=2)
|
589 |
+
|
590 |
+
# transform boolean mask into float mask
|
591 |
+
# attention_bias = lax.select(
|
592 |
+
# attention_mask > 0,
|
593 |
+
# jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
594 |
+
# jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(
|
595 |
+
# self.dtype
|
596 |
+
# ),
|
597 |
+
# )
|
598 |
+
|
599 |
+
query = jnp.swapaxes(query, 1, 2)
|
600 |
+
key = jnp.swapaxes(key, 1, 2)
|
601 |
+
value = jnp.swapaxes(value, 1, 2)
|
602 |
+
|
603 |
+
# TODO: revisit attention_bias when implementing packing
|
604 |
+
# attention_bias = jnp.broadcast_to(
|
605 |
+
# attention_bias, (batch_size, self.num_heads, query_length, key_length)
|
606 |
+
# )
|
607 |
+
|
608 |
+
# flash attn needs fp32
|
609 |
+
query = query.astype(jnp.float32)
|
610 |
+
key = key.astype(jnp.float32)
|
611 |
+
value = value.astype(jnp.float32)
|
612 |
+
|
613 |
+
# usual dot product attention
|
614 |
+
attn_output = self.flash_attn_fn(
|
615 |
+
query,
|
616 |
+
key,
|
617 |
+
value,
|
618 |
+
).astype(hidden_states.dtype)
|
619 |
+
attn_output = jnp.swapaxes(attn_output, 1, 2)
|
620 |
+
attn_output = self._merge_heads(attn_output)
|
621 |
+
attn_output = self.o_proj(attn_output)
|
622 |
+
|
623 |
+
outputs = (attn_output, (raw_query, raw_key, raw_value)) if output_attentions else (attn_output,)
|
624 |
+
return outputs
|
625 |
+
|
626 |
+
|
627 |
+
class FlaxTPULlamaMLP(nn.Module):
|
628 |
+
config: TPULlamaConfig
|
629 |
+
dtype: jnp.dtype = jnp.float32
|
630 |
+
|
631 |
+
def setup(self):
|
632 |
+
embed_dim = self.config.hidden_size
|
633 |
+
inner_dim = self.config.intermediate_size if self.config.intermediate_size is not None else 4 * embed_dim
|
634 |
+
|
635 |
+
kernel_init = jax.nn.initializers.normal(self.config.initializer_range)
|
636 |
+
self.act = ACT2FN[self.config.hidden_act]
|
637 |
+
|
638 |
+
self.gate_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
|
639 |
+
self.down_proj = nn.Dense(embed_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
|
640 |
+
self.up_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
|
641 |
+
|
642 |
+
def __call__(self, hidden_states):
|
643 |
+
up_proj_states = self.up_proj(hidden_states)
|
644 |
+
gate_states = self.act(self.gate_proj(hidden_states))
|
645 |
+
|
646 |
+
hidden_states = self.down_proj(up_proj_states * gate_states)
|
647 |
+
return hidden_states
|
648 |
+
|
649 |
+
|
650 |
+
LLAMA_ATTENTION_CLASSES = {
|
651 |
+
"eager": FlaxTPULlamaAttention,
|
652 |
+
"pallas_flash_attention": FlaxTPULlamaFlashAttention,
|
653 |
+
}
|
654 |
+
|
655 |
+
|
656 |
+
class FlaxTPULlamaDecoderLayer(nn.Module):
|
657 |
+
config: TPULlamaConfig
|
658 |
+
dtype: jnp.dtype = jnp.float32
|
659 |
+
|
660 |
+
def setup(self):
|
661 |
+
self.input_layernorm = FlaxTPULlamaRMSNorm(self.config, dtype=self.dtype)
|
662 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[self.config._attn_implementation](self.config, dtype=self.dtype)
|
663 |
+
self.post_attention_layernorm = FlaxTPULlamaRMSNorm(self.config, dtype=self.dtype)
|
664 |
+
self.mlp = FlaxTPULlamaMLP(self.config, dtype=self.dtype)
|
665 |
+
|
666 |
+
def __call__(
|
667 |
+
self,
|
668 |
+
hidden_states,
|
669 |
+
attention_mask=None,
|
670 |
+
position_ids=None,
|
671 |
+
deterministic: bool = True,
|
672 |
+
init_cache: bool = False,
|
673 |
+
output_attentions: bool = False,
|
674 |
+
):
|
675 |
+
hidden_states = jax.lax.with_sharding_constraint(
|
676 |
+
hidden_states, jax.sharding.NamedSharding(getattr(self.config, "mesh"), P("data", None, "model"))
|
677 |
+
)
|
678 |
+
residual = hidden_states
|
679 |
+
hidden_states = self.input_layernorm(hidden_states)
|
680 |
+
outputs = self.self_attn(
|
681 |
+
hidden_states,
|
682 |
+
attention_mask=attention_mask,
|
683 |
+
position_ids=position_ids,
|
684 |
+
deterministic=deterministic,
|
685 |
+
init_cache=init_cache,
|
686 |
+
output_attentions=output_attentions,
|
687 |
+
)
|
688 |
+
# residual connection
|
689 |
+
attn_output = outputs[0]
|
690 |
+
hidden_states = residual + attn_output
|
691 |
+
|
692 |
+
residual = hidden_states
|
693 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
694 |
+
|
695 |
+
hidden_states = jax.lax.with_sharding_constraint(
|
696 |
+
hidden_states, jax.sharding.NamedSharding(getattr(self.config, "mesh"), P("data", None, "model"))
|
697 |
+
)
|
698 |
+
|
699 |
+
hidden_states = self.mlp(hidden_states)
|
700 |
+
# residual connection
|
701 |
+
hidden_states = residual + hidden_states
|
702 |
+
|
703 |
+
return (hidden_states,) + outputs[1:]
|
704 |
+
|
705 |
+
|
706 |
+
# Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoPreTrainedModel with GPTNeo->Llama, GPT_NEO->LLAMA, transformer->model
|
707 |
+
class FlaxTPULlamaPreTrainedModel(FlaxPreTrainedModel):
|
708 |
+
"""
|
709 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
710 |
+
models.
|
711 |
+
"""
|
712 |
+
|
713 |
+
config_class = TPULlamaConfig
|
714 |
+
base_model_prefix = "model"
|
715 |
+
module_class: nn.Module = None
|
716 |
+
|
717 |
+
def __init__(
|
718 |
+
self,
|
719 |
+
config: TPULlamaConfig,
|
720 |
+
input_shape: Tuple = (1, 1),
|
721 |
+
seed: int = 0,
|
722 |
+
dtype: jnp.dtype = jnp.float32,
|
723 |
+
_do_init: bool = True,
|
724 |
+
gradient_checkpointing: bool = False,
|
725 |
+
**kwargs,
|
726 |
+
):
|
727 |
+
module = self.module_class(
|
728 |
+
config=config,
|
729 |
+
dtype=dtype,
|
730 |
+
gradient_checkpointing=gradient_checkpointing,
|
731 |
+
**kwargs
|
732 |
+
)
|
733 |
+
super().__init__(
|
734 |
+
config,
|
735 |
+
module,
|
736 |
+
input_shape=input_shape,
|
737 |
+
seed=seed,
|
738 |
+
dtype=dtype,
|
739 |
+
_do_init=_do_init,
|
740 |
+
)
|
741 |
+
|
742 |
+
def enable_gradient_checkpointing(self):
|
743 |
+
self._module = self.module_class(
|
744 |
+
config=self.config,
|
745 |
+
dtype=self.dtype,
|
746 |
+
gradient_checkpointing=True,
|
747 |
+
)
|
748 |
+
|
749 |
+
@classmethod
|
750 |
+
def can_generate(cls) -> bool:
|
751 |
+
# disable generation, handled separately
|
752 |
+
# this is convenient since GenerationConfig.from_model_config(config) needs a pickleable config
|
753 |
+
return False
|
754 |
+
|
755 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
756 |
+
# init input tensors
|
757 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
758 |
+
attention_mask = jnp.ones_like(input_ids)
|
759 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
|
760 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
761 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
762 |
+
|
763 |
+
random_params = self.module.init(rngs, input_ids, None, attention_mask, position_ids, return_dict=False)[
|
764 |
+
"params"
|
765 |
+
]
|
766 |
+
|
767 |
+
if params is not None:
|
768 |
+
random_params = flatten_dict(unfreeze(random_params))
|
769 |
+
params = flatten_dict(unfreeze(params))
|
770 |
+
for missing_key in self._missing_keys:
|
771 |
+
params[missing_key] = random_params[missing_key]
|
772 |
+
self._missing_keys = set()
|
773 |
+
return freeze(unflatten_dict(params))
|
774 |
+
else:
|
775 |
+
return random_params
|
776 |
+
|
777 |
+
def init_cache(self, batch_size, max_length):
|
778 |
+
r"""
|
779 |
+
Args:
|
780 |
+
batch_size (`int`):
|
781 |
+
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
|
782 |
+
max_length (`int`):
|
783 |
+
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
|
784 |
+
cache.
|
785 |
+
"""
|
786 |
+
# init input variables to retrieve cache
|
787 |
+
input_ids = jnp.ones((batch_size, max_length))
|
788 |
+
attention_mask = jnp.ones_like(input_ids)
|
789 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
790 |
+
|
791 |
+
init_variables = self.module.init(
|
792 |
+
jax.random.PRNGKey(0),
|
793 |
+
input_ids,
|
794 |
+
None,
|
795 |
+
attention_mask,
|
796 |
+
position_ids,
|
797 |
+
return_dict=False,
|
798 |
+
init_cache=True,
|
799 |
+
)
|
800 |
+
return unfreeze(init_variables["cache"])
|
801 |
+
|
802 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
803 |
+
def __call__(
|
804 |
+
self,
|
805 |
+
input_ids,
|
806 |
+
inputs_embeds=None,
|
807 |
+
attention_mask=None,
|
808 |
+
position_ids=None,
|
809 |
+
params: dict = None,
|
810 |
+
past_key_values: dict = None,
|
811 |
+
dropout_rng: jax.random.PRNGKey = None,
|
812 |
+
train: bool = False,
|
813 |
+
output_attentions: Optional[bool] = None,
|
814 |
+
output_hidden_states: Optional[bool] = None,
|
815 |
+
return_dict: Optional[bool] = None,
|
816 |
+
):
|
817 |
+
if (input_ids is None) == (inputs_embeds is None):
|
818 |
+
raise ValueError("Need to provide either input_ids or inputs_embeds (and not both)")
|
819 |
+
|
820 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
821 |
+
output_hidden_states = (
|
822 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
823 |
+
)
|
824 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
825 |
+
|
826 |
+
if input_ids is not None:
|
827 |
+
batch_size, sequence_length = input_ids.shape
|
828 |
+
else:
|
829 |
+
batch_size, sequence_length, _ = inputs_embeds.shape
|
830 |
+
|
831 |
+
if position_ids is None:
|
832 |
+
if past_key_values is not None:
|
833 |
+
raise ValueError("Make sure to provide `position_ids` when passing `past_key_values`.")
|
834 |
+
|
835 |
+
position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
836 |
+
|
837 |
+
if attention_mask is None:
|
838 |
+
attention_mask = jnp.ones((batch_size, sequence_length))
|
839 |
+
|
840 |
+
# Handle any PRNG if needed
|
841 |
+
rngs = {}
|
842 |
+
if dropout_rng is not None:
|
843 |
+
rngs["dropout"] = dropout_rng
|
844 |
+
|
845 |
+
inputs = {"params": params or self.params}
|
846 |
+
|
847 |
+
# 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 FlaxTPULlamaAttention module
|
848 |
+
if past_key_values:
|
849 |
+
inputs["cache"] = past_key_values
|
850 |
+
mutable = ["cache"]
|
851 |
+
else:
|
852 |
+
mutable = False
|
853 |
+
|
854 |
+
outputs = self.module.apply(
|
855 |
+
inputs,
|
856 |
+
jnp.array(input_ids, dtype="i4") if input_ids is not None else None,
|
857 |
+
inputs_embeds if inputs_embeds is not None else None,
|
858 |
+
jnp.array(attention_mask, dtype="i4"),
|
859 |
+
jnp.array(position_ids, dtype="i4"),
|
860 |
+
not train,
|
861 |
+
False,
|
862 |
+
output_attentions,
|
863 |
+
output_hidden_states,
|
864 |
+
return_dict,
|
865 |
+
rngs=rngs,
|
866 |
+
mutable=mutable,
|
867 |
+
)
|
868 |
+
|
869 |
+
# add updated cache to model output
|
870 |
+
if past_key_values is not None and return_dict:
|
871 |
+
outputs, past_key_values = outputs
|
872 |
+
outputs["past_key_values"] = unfreeze(past_key_values["cache"])
|
873 |
+
return outputs
|
874 |
+
elif past_key_values is not None and not return_dict:
|
875 |
+
outputs, past_key_values = outputs
|
876 |
+
outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
|
877 |
+
|
878 |
+
return outputs
|
879 |
+
|
880 |
+
|
881 |
+
class FlaxTPULlamaLayerCollection(nn.Module):
|
882 |
+
config: TPULlamaConfig
|
883 |
+
dtype: jnp.dtype = jnp.float32
|
884 |
+
gradient_checkpointing: bool = False
|
885 |
+
|
886 |
+
def setup(self):
|
887 |
+
if self.gradient_checkpointing:
|
888 |
+
FlaxTPULlamaDecoderCheckpointLayer = remat(FlaxTPULlamaDecoderLayer, static_argnums=(3, 4, 5))
|
889 |
+
self.blocks = [
|
890 |
+
FlaxTPULlamaDecoderCheckpointLayer(self.config, dtype=self.dtype, name=str(i))
|
891 |
+
for i in range(self.config.num_hidden_layers)
|
892 |
+
]
|
893 |
+
else:
|
894 |
+
self.blocks = [
|
895 |
+
FlaxTPULlamaDecoderLayer(self.config, dtype=self.dtype, name=str(i))
|
896 |
+
for i in range(self.config.num_hidden_layers)
|
897 |
+
]
|
898 |
+
|
899 |
+
def __call__(
|
900 |
+
self,
|
901 |
+
hidden_states,
|
902 |
+
attention_mask=None,
|
903 |
+
position_ids=None,
|
904 |
+
deterministic: bool = True,
|
905 |
+
init_cache: bool = False,
|
906 |
+
output_attentions: bool = False,
|
907 |
+
output_hidden_states: bool = False,
|
908 |
+
return_dict: bool = False,
|
909 |
+
):
|
910 |
+
all_attentions = () if output_attentions else None
|
911 |
+
all_hidden_states = () if output_hidden_states else None
|
912 |
+
|
913 |
+
for block in self.blocks:
|
914 |
+
if output_hidden_states:
|
915 |
+
all_hidden_states += (hidden_states,)
|
916 |
+
layer_outputs = block(
|
917 |
+
hidden_states,
|
918 |
+
attention_mask,
|
919 |
+
position_ids,
|
920 |
+
deterministic,
|
921 |
+
init_cache,
|
922 |
+
output_attentions,
|
923 |
+
)
|
924 |
+
hidden_states = layer_outputs[0]
|
925 |
+
|
926 |
+
if output_attentions:
|
927 |
+
all_attentions += (layer_outputs[1],)
|
928 |
+
|
929 |
+
# this contains possible `None` values - `FlaxTPULlamaModule` will filter them out
|
930 |
+
outputs = (hidden_states, all_hidden_states, all_attentions)
|
931 |
+
|
932 |
+
return outputs
|
933 |
+
|
934 |
+
|
935 |
+
class FlaxTPULlamaModule(nn.Module):
|
936 |
+
config: TPULlamaConfig
|
937 |
+
dtype: jnp.dtype = jnp.float32
|
938 |
+
gradient_checkpointing: bool = False
|
939 |
+
|
940 |
+
def setup(self):
|
941 |
+
self.hidden_size = self.config.hidden_size
|
942 |
+
embedding_init = jax.nn.initializers.normal(stddev=self.config.initializer_range)
|
943 |
+
self.embed_tokens = nn.Embed(
|
944 |
+
self.config.vocab_size,
|
945 |
+
self.hidden_size,
|
946 |
+
embedding_init=embedding_init,
|
947 |
+
dtype=self.dtype,
|
948 |
+
)
|
949 |
+
self.layers = FlaxTPULlamaLayerCollection(self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing)
|
950 |
+
self.norm = FlaxTPULlamaRMSNorm(self.config, dtype=self.dtype)
|
951 |
+
|
952 |
+
def __call__(
|
953 |
+
self,
|
954 |
+
input_ids,
|
955 |
+
inputs_embeds=None,
|
956 |
+
attention_mask=None,
|
957 |
+
position_ids=None,
|
958 |
+
deterministic=True,
|
959 |
+
init_cache: bool = False,
|
960 |
+
output_attentions: bool = False,
|
961 |
+
output_hidden_states: bool = False,
|
962 |
+
return_dict: bool = True,
|
963 |
+
):
|
964 |
+
if inputs_embeds is None:
|
965 |
+
inputs_embeds = self.embed_tokens(input_ids.astype("i4"))
|
966 |
+
|
967 |
+
outputs = self.layers(
|
968 |
+
inputs_embeds,
|
969 |
+
position_ids=position_ids,
|
970 |
+
attention_mask=attention_mask,
|
971 |
+
deterministic=deterministic,
|
972 |
+
init_cache=init_cache,
|
973 |
+
output_attentions=output_attentions,
|
974 |
+
output_hidden_states=output_hidden_states,
|
975 |
+
return_dict=return_dict,
|
976 |
+
)
|
977 |
+
|
978 |
+
hidden_states = outputs[0]
|
979 |
+
hidden_states = self.norm(hidden_states)
|
980 |
+
|
981 |
+
if output_hidden_states:
|
982 |
+
all_hidden_states = outputs[1] + (hidden_states,)
|
983 |
+
outputs = (hidden_states, all_hidden_states) + outputs[2:]
|
984 |
+
else:
|
985 |
+
outputs = (hidden_states,) + outputs[1:]
|
986 |
+
|
987 |
+
if not return_dict:
|
988 |
+
return tuple(v for v in outputs if v is not None)
|
989 |
+
|
990 |
+
return FlaxBaseModelOutput(
|
991 |
+
last_hidden_state=hidden_states,
|
992 |
+
hidden_states=outputs[1],
|
993 |
+
attentions=outputs[-1],
|
994 |
+
)
|
995 |
+
|
996 |
+
|
997 |
+
@add_start_docstrings(
|
998 |
+
"The bare Llama Model transformer outputting raw hidden-states without any specific head on top.",
|
999 |
+
LLAMA_START_DOCSTRING,
|
1000 |
+
)
|
1001 |
+
class FlaxTPULlamaModel(FlaxTPULlamaPreTrainedModel):
|
1002 |
+
module_class = FlaxTPULlamaModule
|
1003 |
+
|
1004 |
+
|
1005 |
+
append_call_sample_docstring(
|
1006 |
+
FlaxTPULlamaModel,
|
1007 |
+
_CHECKPOINT_FOR_DOC,
|
1008 |
+
FlaxBaseModelOutput,
|
1009 |
+
_CONFIG_FOR_DOC,
|
1010 |
+
real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
|
1011 |
+
)
|
1012 |
+
|
1013 |
+
|
1014 |
+
class FlaxTPULlamaForCausalLMModule(nn.Module):
|
1015 |
+
config: TPULlamaConfig
|
1016 |
+
dtype: jnp.dtype = jnp.float32
|
1017 |
+
gradient_checkpointing: bool = False
|
1018 |
+
|
1019 |
+
def setup(self):
|
1020 |
+
self.model = FlaxTPULlamaModule(self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing)
|
1021 |
+
self.lm_head = nn.Dense(
|
1022 |
+
self.config.vocab_size,
|
1023 |
+
use_bias=False,
|
1024 |
+
dtype=self.dtype,
|
1025 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
1026 |
+
)
|
1027 |
+
|
1028 |
+
def __call__(
|
1029 |
+
self,
|
1030 |
+
input_ids,
|
1031 |
+
inputs_embeds=None,
|
1032 |
+
attention_mask=None,
|
1033 |
+
position_ids=None,
|
1034 |
+
deterministic: bool = True,
|
1035 |
+
init_cache: bool = False,
|
1036 |
+
output_attentions: bool = False,
|
1037 |
+
output_hidden_states: bool = False,
|
1038 |
+
return_dict: bool = True,
|
1039 |
+
):
|
1040 |
+
outputs = self.model(
|
1041 |
+
input_ids,
|
1042 |
+
inputs_embeds=inputs_embeds,
|
1043 |
+
position_ids=position_ids,
|
1044 |
+
attention_mask=attention_mask,
|
1045 |
+
deterministic=deterministic,
|
1046 |
+
init_cache=init_cache,
|
1047 |
+
output_attentions=output_attentions,
|
1048 |
+
output_hidden_states=output_hidden_states,
|
1049 |
+
return_dict=return_dict,
|
1050 |
+
)
|
1051 |
+
|
1052 |
+
hidden_states = outputs[0]
|
1053 |
+
if self.config.tie_word_embeddings:
|
1054 |
+
shared_kernel = self.model.variables["params"]["embed_tokens"]["embedding"].T
|
1055 |
+
lm_logits = self.lm_head.apply({"params": {"kernel": shared_kernel}}, hidden_states)
|
1056 |
+
else:
|
1057 |
+
lm_logits = self.lm_head(hidden_states)
|
1058 |
+
|
1059 |
+
if not return_dict:
|
1060 |
+
return (lm_logits,) + outputs[1:]
|
1061 |
+
|
1062 |
+
return FlaxCausalLMOutput(
|
1063 |
+
logits=lm_logits,
|
1064 |
+
hidden_states=outputs.hidden_states,
|
1065 |
+
attentions=outputs.attentions,
|
1066 |
+
)
|
1067 |
+
|
1068 |
+
|
1069 |
+
@add_start_docstrings(
|
1070 |
+
"""
|
1071 |
+
The Llama Model transformer with a language modeling head (linear layer) on top.
|
1072 |
+
""",
|
1073 |
+
LLAMA_START_DOCSTRING,
|
1074 |
+
)
|
1075 |
+
# Copied from transformers.models.gptj.modeling_flax_gptj.FlaxGPTJForCausalLM with GPTJ->Llama
|
1076 |
+
class FlaxTPULlamaForCausalLM(FlaxTPULlamaPreTrainedModel):
|
1077 |
+
module_class = FlaxTPULlamaForCausalLMModule
|
1078 |
+
|
1079 |
+
def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
|
1080 |
+
# initializing the cache
|
1081 |
+
batch_size, seq_length = input_ids.shape
|
1082 |
+
|
1083 |
+
past_key_values = self.init_cache(batch_size, max_length)
|
1084 |
+
# Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
|
1085 |
+
# But since Llama uses a causal mask, those positions are masked anyways.
|
1086 |
+
# Thus we can create a single static attention_mask here, which is more efficient for compilation
|
1087 |
+
extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
|
1088 |
+
if attention_mask is not None:
|
1089 |
+
position_ids = attention_mask.cumsum(axis=-1) - 1
|
1090 |
+
extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
|
1091 |
+
else:
|
1092 |
+
position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
|
1093 |
+
|
1094 |
+
return {
|
1095 |
+
"past_key_values": past_key_values,
|
1096 |
+
"attention_mask": extended_attention_mask,
|
1097 |
+
"position_ids": position_ids,
|
1098 |
+
}
|
1099 |
+
|
1100 |
+
def update_inputs_for_generation(self, model_outputs, model_kwargs):
|
1101 |
+
model_kwargs["past_key_values"] = model_outputs.past_key_values
|
1102 |
+
model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
|
1103 |
+
return model_kwargs
|
1104 |
+
|
1105 |
+
|
1106 |
+
append_call_sample_docstring(
|
1107 |
+
FlaxTPULlamaForCausalLM,
|
1108 |
+
_CHECKPOINT_FOR_DOC,
|
1109 |
+
FlaxCausalLMOutput,
|
1110 |
+
_CONFIG_FOR_DOC,
|
1111 |
+
real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
|
1112 |
+
)
|
modelling_tpu_llama.py
ADDED
@@ -0,0 +1,1607 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
import math
|
21 |
+
from typing import List, Optional, Tuple, Union
|
22 |
+
|
23 |
+
import torch
|
24 |
+
import torch.nn.functional as F
|
25 |
+
import torch.utils.checkpoint
|
26 |
+
from torch import nn
|
27 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
28 |
+
|
29 |
+
from transformers.activations import ACT2FN
|
30 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
31 |
+
from transformers.generation import GenerationMixin
|
32 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
33 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
34 |
+
from transformers.modeling_outputs import (
|
35 |
+
BaseModelOutputWithPast,
|
36 |
+
CausalLMOutputWithPast,
|
37 |
+
QuestionAnsweringModelOutput,
|
38 |
+
SequenceClassifierOutputWithPast,
|
39 |
+
TokenClassifierOutput,
|
40 |
+
)
|
41 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
42 |
+
from transformers.modeling_utils import PreTrainedModel
|
43 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
44 |
+
from transformers.utils import (
|
45 |
+
add_start_docstrings,
|
46 |
+
add_start_docstrings_to_model_forward,
|
47 |
+
is_flash_attn_greater_or_equal_2_10,
|
48 |
+
logging,
|
49 |
+
replace_return_docstrings,
|
50 |
+
)
|
51 |
+
from .configuration_tpu_llama import TPULlamaConfig
|
52 |
+
|
53 |
+
|
54 |
+
logger = logging.get_logger(__name__)
|
55 |
+
|
56 |
+
_CONFIG_FOR_DOC = "TPULlamaConfig"
|
57 |
+
|
58 |
+
|
59 |
+
def torch_expand_input_ids(
|
60 |
+
input_ids,
|
61 |
+
expand_input_ids_dict,
|
62 |
+
maxlen,
|
63 |
+
last_n=None,
|
64 |
+
):
|
65 |
+
expanded_input_ids = torch.zeros_like(input_ids)
|
66 |
+
|
67 |
+
for example_idx in range(len(input_ids)):
|
68 |
+
last_maxlen_ids = []
|
69 |
+
|
70 |
+
for i in range(len(input_ids[example_idx])):
|
71 |
+
last_maxlen_ids.insert(0, int(input_ids[example_idx][i] + 1))
|
72 |
+
if len(last_maxlen_ids) > maxlen:
|
73 |
+
last_maxlen_ids.pop()
|
74 |
+
|
75 |
+
if last_n is not None and i < len(input_ids[example_idx]) - last_n:
|
76 |
+
continue
|
77 |
+
|
78 |
+
if last_maxlen_ids[0] in expand_input_ids_dict[1]:
|
79 |
+
expanded_input_ids[example_idx][i] = expand_input_ids_dict[0][(last_maxlen_ids[0],)] - 1
|
80 |
+
else:
|
81 |
+
found = False
|
82 |
+
last_maxlen_up_to = len(last_maxlen_ids)
|
83 |
+
|
84 |
+
while not found and last_maxlen_up_to > 0:
|
85 |
+
try:
|
86 |
+
expanded_input_ids[example_idx][i] = expand_input_ids_dict[0][tuple(last_maxlen_ids[:last_maxlen_up_to])] - 1
|
87 |
+
found = True
|
88 |
+
except KeyError:
|
89 |
+
last_maxlen_up_to -= 1
|
90 |
+
|
91 |
+
return expanded_input_ids
|
92 |
+
|
93 |
+
|
94 |
+
class TPULlamaRMSNorm(nn.Module):
|
95 |
+
def __init__(self, hidden_size, eps=1e-6):
|
96 |
+
"""
|
97 |
+
TPULlamaRMSNorm is equivalent to T5LayerNorm
|
98 |
+
"""
|
99 |
+
super().__init__()
|
100 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
101 |
+
self.variance_epsilon = eps
|
102 |
+
|
103 |
+
def forward(self, hidden_states):
|
104 |
+
input_dtype = hidden_states.dtype
|
105 |
+
hidden_states = hidden_states.to(torch.float32)
|
106 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
107 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
108 |
+
return self.weight * hidden_states.to(input_dtype)
|
109 |
+
|
110 |
+
def extra_repr(self):
|
111 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
112 |
+
|
113 |
+
|
114 |
+
ALL_LAYERNORM_LAYERS.append(TPULlamaRMSNorm)
|
115 |
+
|
116 |
+
|
117 |
+
class TPULlamaRotaryEmbedding(nn.Module):
|
118 |
+
def __init__(
|
119 |
+
self,
|
120 |
+
dim=None,
|
121 |
+
max_position_embeddings=2048,
|
122 |
+
base=10000,
|
123 |
+
device=None,
|
124 |
+
scaling_factor=1.0,
|
125 |
+
rope_type="default",
|
126 |
+
config: Optional[TPULlamaConfig] = None,
|
127 |
+
):
|
128 |
+
super().__init__()
|
129 |
+
# TODO (joao): remove the `if` below, only used for BC
|
130 |
+
self.rope_kwargs = {}
|
131 |
+
if config is None:
|
132 |
+
logger.warning_once(
|
133 |
+
"`TPULlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
|
134 |
+
"`config` argument. All other arguments will be removed in v4.46"
|
135 |
+
)
|
136 |
+
self.rope_kwargs = {
|
137 |
+
"rope_type": rope_type,
|
138 |
+
"factor": scaling_factor,
|
139 |
+
"dim": dim,
|
140 |
+
"base": base,
|
141 |
+
"max_position_embeddings": max_position_embeddings,
|
142 |
+
}
|
143 |
+
self.rope_type = rope_type
|
144 |
+
self.max_seq_len_cached = max_position_embeddings
|
145 |
+
self.original_max_seq_len = max_position_embeddings
|
146 |
+
else:
|
147 |
+
# BC: "rope_type" was originally "type"
|
148 |
+
if config.rope_scaling is not None:
|
149 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
150 |
+
else:
|
151 |
+
self.rope_type = "default"
|
152 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
153 |
+
self.original_max_seq_len = config.max_position_embeddings
|
154 |
+
|
155 |
+
self.config = config
|
156 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
157 |
+
|
158 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
|
159 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
160 |
+
self.original_inv_freq = self.inv_freq
|
161 |
+
|
162 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
163 |
+
"""
|
164 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
165 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
166 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
167 |
+
"""
|
168 |
+
seq_len = torch.max(position_ids) + 1
|
169 |
+
if seq_len > self.max_seq_len_cached: # growth
|
170 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(
|
171 |
+
self.config, device, seq_len=seq_len, **self.rope_kwargs
|
172 |
+
)
|
173 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
174 |
+
self.max_seq_len_cached = seq_len
|
175 |
+
|
176 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
177 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
178 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
179 |
+
|
180 |
+
@torch.no_grad()
|
181 |
+
def forward(self, x, position_ids):
|
182 |
+
if "dynamic" in self.rope_type:
|
183 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
184 |
+
|
185 |
+
# Core RoPE block
|
186 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
187 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
188 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
189 |
+
device_type = x.device.type
|
190 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
191 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
192 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
193 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
194 |
+
cos = emb.cos()
|
195 |
+
sin = emb.sin()
|
196 |
+
|
197 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
198 |
+
cos = cos * self.attention_scaling
|
199 |
+
sin = sin * self.attention_scaling
|
200 |
+
|
201 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
202 |
+
|
203 |
+
|
204 |
+
class TPULlamaLinearScalingRotaryEmbedding(TPULlamaRotaryEmbedding):
|
205 |
+
"""TPULlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
206 |
+
|
207 |
+
def __init__(self, *args, **kwargs):
|
208 |
+
logger.warning_once(
|
209 |
+
"`TPULlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
|
210 |
+
"`TPULlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
|
211 |
+
)
|
212 |
+
kwargs["rope_type"] = "linear"
|
213 |
+
super().__init__(*args, **kwargs)
|
214 |
+
|
215 |
+
|
216 |
+
class TPULlamaDynamicNTKScalingRotaryEmbedding(TPULlamaRotaryEmbedding):
|
217 |
+
"""TPULlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
218 |
+
|
219 |
+
def __init__(self, *args, **kwargs):
|
220 |
+
logger.warning_once(
|
221 |
+
"`TPULlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
|
222 |
+
"`TPULlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
|
223 |
+
"__init__)."
|
224 |
+
)
|
225 |
+
kwargs["rope_type"] = "dynamic"
|
226 |
+
super().__init__(*args, **kwargs)
|
227 |
+
|
228 |
+
|
229 |
+
def rotate_half(x):
|
230 |
+
"""Rotates half the hidden dims of the input."""
|
231 |
+
x1 = x[..., : x.shape[-1] // 2]
|
232 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
233 |
+
return torch.cat((-x2, x1), dim=-1)
|
234 |
+
|
235 |
+
|
236 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
237 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
238 |
+
|
239 |
+
Args:
|
240 |
+
q (`torch.Tensor`): The query tensor.
|
241 |
+
k (`torch.Tensor`): The key tensor.
|
242 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
243 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
244 |
+
position_ids (`torch.Tensor`, *optional*):
|
245 |
+
Deprecated and unused.
|
246 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
247 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
248 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
249 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
250 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
251 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
252 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
253 |
+
Returns:
|
254 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
255 |
+
"""
|
256 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
257 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
258 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
259 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
260 |
+
return q_embed, k_embed
|
261 |
+
|
262 |
+
|
263 |
+
class TPULlamaMLP(nn.Module):
|
264 |
+
def __init__(self, config):
|
265 |
+
super().__init__()
|
266 |
+
self.config = config
|
267 |
+
self.hidden_size = config.hidden_size
|
268 |
+
self.intermediate_size = config.intermediate_size
|
269 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
270 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
271 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
272 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
273 |
+
|
274 |
+
def forward(self, x):
|
275 |
+
if self.config.pretraining_tp > 1:
|
276 |
+
slice = self.intermediate_size // self.config.pretraining_tp
|
277 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
278 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
279 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
280 |
+
|
281 |
+
gate_proj = torch.cat(
|
282 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
283 |
+
)
|
284 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
285 |
+
|
286 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
287 |
+
down_proj = [
|
288 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
289 |
+
]
|
290 |
+
down_proj = sum(down_proj)
|
291 |
+
else:
|
292 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
293 |
+
|
294 |
+
return down_proj
|
295 |
+
|
296 |
+
|
297 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
298 |
+
"""
|
299 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
300 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
301 |
+
"""
|
302 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
303 |
+
if n_rep == 1:
|
304 |
+
return hidden_states
|
305 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
306 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
307 |
+
|
308 |
+
|
309 |
+
class TPULlamaAttention(nn.Module):
|
310 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
311 |
+
|
312 |
+
def __init__(self, config: TPULlamaConfig, layer_idx: Optional[int] = None):
|
313 |
+
super().__init__()
|
314 |
+
self.config = config
|
315 |
+
self.layer_idx = layer_idx
|
316 |
+
if layer_idx is None:
|
317 |
+
logger.warning_once(
|
318 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
319 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
320 |
+
"when creating this class."
|
321 |
+
)
|
322 |
+
|
323 |
+
self.attention_dropout = config.attention_dropout
|
324 |
+
self.hidden_size = config.hidden_size
|
325 |
+
self.num_heads = config.num_attention_heads
|
326 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
327 |
+
self.num_key_value_heads = config.num_key_value_heads
|
328 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
329 |
+
self.max_position_embeddings = config.max_position_embeddings
|
330 |
+
self.rope_theta = config.rope_theta
|
331 |
+
self.is_causal = True
|
332 |
+
|
333 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
334 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
335 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
336 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
|
337 |
+
|
338 |
+
# TODO (joao): remove in v4.46 (RoPE is computed in the model, not in the decoder layers)
|
339 |
+
self.rotary_emb = TPULlamaRotaryEmbedding(config=self.config)
|
340 |
+
|
341 |
+
def forward(
|
342 |
+
self,
|
343 |
+
hidden_states: torch.Tensor,
|
344 |
+
attention_mask: Optional[torch.Tensor] = None,
|
345 |
+
position_ids: Optional[torch.LongTensor] = None,
|
346 |
+
past_key_value: Optional[Cache] = None,
|
347 |
+
output_attentions: bool = False,
|
348 |
+
use_cache: bool = False,
|
349 |
+
cache_position: Optional[torch.LongTensor] = None,
|
350 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
351 |
+
**kwargs,
|
352 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
353 |
+
bsz, q_len, _ = hidden_states.size()
|
354 |
+
|
355 |
+
if self.config.pretraining_tp > 1:
|
356 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
357 |
+
query_slices = self.q_proj.weight.split(
|
358 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
359 |
+
)
|
360 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
361 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
362 |
+
|
363 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
364 |
+
query_states = torch.cat(query_states, dim=-1)
|
365 |
+
|
366 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
367 |
+
key_states = torch.cat(key_states, dim=-1)
|
368 |
+
|
369 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
370 |
+
value_states = torch.cat(value_states, dim=-1)
|
371 |
+
|
372 |
+
else:
|
373 |
+
query_states = self.q_proj(hidden_states)
|
374 |
+
key_states = self.k_proj(hidden_states)
|
375 |
+
value_states = self.v_proj(hidden_states)
|
376 |
+
|
377 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
378 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
379 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
380 |
+
|
381 |
+
if position_embeddings is None:
|
382 |
+
logger.warning_once(
|
383 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
384 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
385 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
386 |
+
"removed and `position_embeddings` will be mandatory."
|
387 |
+
)
|
388 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
389 |
+
else:
|
390 |
+
cos, sin = position_embeddings
|
391 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
392 |
+
|
393 |
+
if past_key_value is not None:
|
394 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
395 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
396 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
397 |
+
|
398 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
399 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
400 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
401 |
+
|
402 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
403 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
404 |
+
attn_weights = attn_weights + causal_mask
|
405 |
+
|
406 |
+
# upcast attention to fp32
|
407 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
408 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
409 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
410 |
+
|
411 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
412 |
+
raise ValueError(
|
413 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
414 |
+
f" {attn_output.size()}"
|
415 |
+
)
|
416 |
+
|
417 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
418 |
+
|
419 |
+
attn_output = attn_output.reshape(bsz, q_len, -1)
|
420 |
+
|
421 |
+
if self.config.pretraining_tp > 1:
|
422 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
423 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
424 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
425 |
+
else:
|
426 |
+
attn_output = self.o_proj(attn_output)
|
427 |
+
|
428 |
+
if not output_attentions:
|
429 |
+
attn_weights = None
|
430 |
+
|
431 |
+
return attn_output, attn_weights, past_key_value
|
432 |
+
|
433 |
+
|
434 |
+
class TPULlamaFlashAttention2(TPULlamaAttention):
|
435 |
+
"""
|
436 |
+
TPULlama flash attention module. This module inherits from `TPULlamaAttention` as the weights of the module stays
|
437 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
438 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
439 |
+
"""
|
440 |
+
|
441 |
+
def __init__(self, *args, **kwargs):
|
442 |
+
super().__init__(*args, **kwargs)
|
443 |
+
|
444 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
445 |
+
# 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.
|
446 |
+
# 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).
|
447 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
448 |
+
|
449 |
+
def forward(
|
450 |
+
self,
|
451 |
+
hidden_states: torch.Tensor,
|
452 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
453 |
+
position_ids: Optional[torch.LongTensor] = None,
|
454 |
+
past_key_value: Optional[Cache] = None,
|
455 |
+
output_attentions: bool = False,
|
456 |
+
use_cache: bool = False,
|
457 |
+
cache_position: Optional[torch.LongTensor] = None,
|
458 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
459 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
460 |
+
if isinstance(past_key_value, StaticCache):
|
461 |
+
raise ValueError(
|
462 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
463 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
464 |
+
)
|
465 |
+
|
466 |
+
output_attentions = False
|
467 |
+
|
468 |
+
bsz, q_len, _ = hidden_states.size()
|
469 |
+
|
470 |
+
query_states = self.q_proj(hidden_states)
|
471 |
+
key_states = self.k_proj(hidden_states)
|
472 |
+
value_states = self.v_proj(hidden_states)
|
473 |
+
|
474 |
+
# Flash attention requires the input to have the shape
|
475 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
476 |
+
# therefore we just need to keep the original shape
|
477 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
478 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
479 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
480 |
+
|
481 |
+
if position_embeddings is None:
|
482 |
+
logger.warning_once(
|
483 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
484 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
485 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
486 |
+
"removed and `position_embeddings` will be mandatory."
|
487 |
+
)
|
488 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
489 |
+
else:
|
490 |
+
cos, sin = position_embeddings
|
491 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
492 |
+
|
493 |
+
if past_key_value is not None:
|
494 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
495 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
496 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
497 |
+
|
498 |
+
# 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
|
499 |
+
# to be able to avoid many of these transpose/reshape/view.
|
500 |
+
query_states = query_states.transpose(1, 2)
|
501 |
+
key_states = key_states.transpose(1, 2)
|
502 |
+
value_states = value_states.transpose(1, 2)
|
503 |
+
|
504 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
505 |
+
|
506 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
507 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
508 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
509 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
510 |
+
# in fp32. (TPULlamaRMSNorm handles it correctly)
|
511 |
+
|
512 |
+
input_dtype = query_states.dtype
|
513 |
+
if input_dtype == torch.float32:
|
514 |
+
if torch.is_autocast_enabled():
|
515 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
516 |
+
# Handle the case where the model is quantized
|
517 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
518 |
+
target_dtype = self.config._pre_quantization_dtype
|
519 |
+
else:
|
520 |
+
target_dtype = self.q_proj.weight.dtype
|
521 |
+
|
522 |
+
logger.warning_once(
|
523 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
524 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
525 |
+
f" {target_dtype}."
|
526 |
+
)
|
527 |
+
|
528 |
+
query_states = query_states.to(target_dtype)
|
529 |
+
key_states = key_states.to(target_dtype)
|
530 |
+
value_states = value_states.to(target_dtype)
|
531 |
+
|
532 |
+
attn_output = _flash_attention_forward(
|
533 |
+
query_states,
|
534 |
+
key_states,
|
535 |
+
value_states,
|
536 |
+
attention_mask,
|
537 |
+
q_len,
|
538 |
+
position_ids=position_ids,
|
539 |
+
dropout=dropout_rate,
|
540 |
+
sliding_window=getattr(self, "sliding_window", None),
|
541 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
542 |
+
is_causal=self.is_causal,
|
543 |
+
)
|
544 |
+
|
545 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
546 |
+
attn_output = self.o_proj(attn_output)
|
547 |
+
|
548 |
+
if not output_attentions:
|
549 |
+
attn_weights = None
|
550 |
+
|
551 |
+
return attn_output, attn_weights, past_key_value
|
552 |
+
|
553 |
+
|
554 |
+
class TPULlamaSdpaAttention(TPULlamaAttention):
|
555 |
+
"""
|
556 |
+
TPULlama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
557 |
+
`TPULlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
558 |
+
SDPA API.
|
559 |
+
"""
|
560 |
+
|
561 |
+
# Adapted from TPULlamaAttention.forward
|
562 |
+
def forward(
|
563 |
+
self,
|
564 |
+
hidden_states: torch.Tensor,
|
565 |
+
attention_mask: Optional[torch.Tensor] = None,
|
566 |
+
position_ids: Optional[torch.LongTensor] = None,
|
567 |
+
past_key_value: Optional[Cache] = None,
|
568 |
+
output_attentions: bool = False,
|
569 |
+
use_cache: bool = False,
|
570 |
+
cache_position: Optional[torch.LongTensor] = None,
|
571 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
572 |
+
**kwargs,
|
573 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
574 |
+
if output_attentions:
|
575 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
576 |
+
logger.warning_once(
|
577 |
+
"TPULlamaModel is using TPULlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
578 |
+
'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.'
|
579 |
+
)
|
580 |
+
return super().forward(
|
581 |
+
hidden_states=hidden_states,
|
582 |
+
attention_mask=attention_mask,
|
583 |
+
position_ids=position_ids,
|
584 |
+
past_key_value=past_key_value,
|
585 |
+
output_attentions=output_attentions,
|
586 |
+
use_cache=use_cache,
|
587 |
+
cache_position=cache_position,
|
588 |
+
position_embeddings=position_embeddings,
|
589 |
+
)
|
590 |
+
|
591 |
+
bsz, q_len, _ = hidden_states.size()
|
592 |
+
|
593 |
+
query_states = self.q_proj(hidden_states)
|
594 |
+
key_states = self.k_proj(hidden_states)
|
595 |
+
value_states = self.v_proj(hidden_states)
|
596 |
+
|
597 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
598 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
599 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
600 |
+
|
601 |
+
if position_embeddings is None:
|
602 |
+
logger.warning_once(
|
603 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
604 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
605 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
606 |
+
"removed and `position_embeddings` will be mandatory."
|
607 |
+
)
|
608 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
609 |
+
else:
|
610 |
+
cos, sin = position_embeddings
|
611 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
612 |
+
|
613 |
+
if past_key_value is not None:
|
614 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
615 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
616 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
617 |
+
|
618 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
619 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
620 |
+
|
621 |
+
causal_mask = attention_mask
|
622 |
+
if attention_mask is not None:
|
623 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
624 |
+
|
625 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
626 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
627 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
628 |
+
query_states = query_states.contiguous()
|
629 |
+
key_states = key_states.contiguous()
|
630 |
+
value_states = value_states.contiguous()
|
631 |
+
|
632 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
633 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
634 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
635 |
+
|
636 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
637 |
+
query_states,
|
638 |
+
key_states,
|
639 |
+
value_states,
|
640 |
+
attn_mask=causal_mask,
|
641 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
642 |
+
is_causal=is_causal,
|
643 |
+
)
|
644 |
+
|
645 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
646 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
647 |
+
|
648 |
+
attn_output = self.o_proj(attn_output)
|
649 |
+
|
650 |
+
return attn_output, None, past_key_value
|
651 |
+
|
652 |
+
|
653 |
+
LLAMA_ATTENTION_CLASSES = {
|
654 |
+
"eager": TPULlamaAttention,
|
655 |
+
"flash_attention_2": TPULlamaFlashAttention2,
|
656 |
+
"sdpa": TPULlamaSdpaAttention,
|
657 |
+
}
|
658 |
+
|
659 |
+
|
660 |
+
class TPULlamaDecoderLayer(nn.Module):
|
661 |
+
def __init__(self, config: TPULlamaConfig, layer_idx: int):
|
662 |
+
super().__init__()
|
663 |
+
self.hidden_size = config.hidden_size
|
664 |
+
|
665 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
666 |
+
|
667 |
+
self.mlp = TPULlamaMLP(config)
|
668 |
+
self.input_layernorm = TPULlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
669 |
+
self.post_attention_layernorm = TPULlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
670 |
+
|
671 |
+
def forward(
|
672 |
+
self,
|
673 |
+
hidden_states: torch.Tensor,
|
674 |
+
attention_mask: Optional[torch.Tensor] = None,
|
675 |
+
position_ids: Optional[torch.LongTensor] = None,
|
676 |
+
past_key_value: Optional[Cache] = None,
|
677 |
+
output_attentions: Optional[bool] = False,
|
678 |
+
use_cache: Optional[bool] = False,
|
679 |
+
cache_position: Optional[torch.LongTensor] = None,
|
680 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
681 |
+
**kwargs,
|
682 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
683 |
+
"""
|
684 |
+
Args:
|
685 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
686 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
687 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
688 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
689 |
+
output_attentions (`bool`, *optional*):
|
690 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
691 |
+
returned tensors for more detail.
|
692 |
+
use_cache (`bool`, *optional*):
|
693 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
694 |
+
(see `past_key_values`).
|
695 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
696 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
697 |
+
Indices depicting the position of the input sequence tokens in the sequence
|
698 |
+
position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
699 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
700 |
+
with `head_dim` being the embedding dimension of each attention head.
|
701 |
+
kwargs (`dict`, *optional*):
|
702 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
703 |
+
into the model
|
704 |
+
"""
|
705 |
+
residual = hidden_states
|
706 |
+
|
707 |
+
hidden_states = self.input_layernorm(hidden_states)
|
708 |
+
|
709 |
+
# Self Attention
|
710 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
711 |
+
hidden_states=hidden_states,
|
712 |
+
attention_mask=attention_mask,
|
713 |
+
position_ids=position_ids,
|
714 |
+
past_key_value=past_key_value,
|
715 |
+
output_attentions=output_attentions,
|
716 |
+
use_cache=use_cache,
|
717 |
+
cache_position=cache_position,
|
718 |
+
position_embeddings=position_embeddings,
|
719 |
+
**kwargs,
|
720 |
+
)
|
721 |
+
hidden_states = residual + hidden_states
|
722 |
+
|
723 |
+
# Fully Connected
|
724 |
+
residual = hidden_states
|
725 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
726 |
+
hidden_states = self.mlp(hidden_states)
|
727 |
+
hidden_states = residual + hidden_states
|
728 |
+
|
729 |
+
outputs = (hidden_states,)
|
730 |
+
|
731 |
+
if output_attentions:
|
732 |
+
outputs += (self_attn_weights,)
|
733 |
+
|
734 |
+
if use_cache:
|
735 |
+
outputs += (present_key_value,)
|
736 |
+
|
737 |
+
return outputs
|
738 |
+
|
739 |
+
|
740 |
+
LLAMA_START_DOCSTRING = r"""
|
741 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
742 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
743 |
+
etc.)
|
744 |
+
|
745 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
746 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
747 |
+
and behavior.
|
748 |
+
|
749 |
+
Parameters:
|
750 |
+
config ([`TPULlamaConfig`]):
|
751 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
752 |
+
load the weights associated with the model, only the configuration. Check out the
|
753 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
754 |
+
"""
|
755 |
+
|
756 |
+
|
757 |
+
@add_start_docstrings(
|
758 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
759 |
+
LLAMA_START_DOCSTRING,
|
760 |
+
)
|
761 |
+
class TPULlamaPreTrainedModel(PreTrainedModel):
|
762 |
+
config_class = TPULlamaConfig
|
763 |
+
base_model_prefix = "model"
|
764 |
+
supports_gradient_checkpointing = True
|
765 |
+
_no_split_modules = ["TPULlamaDecoderLayer"]
|
766 |
+
_skip_keys_device_placement = ["past_key_values"]
|
767 |
+
_supports_flash_attn_2 = True
|
768 |
+
_supports_sdpa = True
|
769 |
+
_supports_cache_class = True
|
770 |
+
_supports_quantized_cache = True
|
771 |
+
_supports_static_cache = True
|
772 |
+
|
773 |
+
def _init_weights(self, module):
|
774 |
+
std = self.config.initializer_range
|
775 |
+
if isinstance(module, nn.Linear):
|
776 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
777 |
+
if module.bias is not None:
|
778 |
+
module.bias.data.zero_()
|
779 |
+
elif isinstance(module, nn.Embedding):
|
780 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
781 |
+
if module.padding_idx is not None:
|
782 |
+
module.weight.data[module.padding_idx].zero_()
|
783 |
+
|
784 |
+
|
785 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
786 |
+
Args:
|
787 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
788 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
789 |
+
it.
|
790 |
+
|
791 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
792 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
793 |
+
|
794 |
+
[What are input IDs?](../glossary#input-ids)
|
795 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
796 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
797 |
+
|
798 |
+
- 1 for tokens that are **not masked**,
|
799 |
+
- 0 for tokens that are **masked**.
|
800 |
+
|
801 |
+
[What are attention masks?](../glossary#attention-mask)
|
802 |
+
|
803 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
804 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
805 |
+
|
806 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
807 |
+
`past_key_values`).
|
808 |
+
|
809 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
810 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
811 |
+
information on the default strategy.
|
812 |
+
|
813 |
+
- 1 indicates the head is **not masked**,
|
814 |
+
- 0 indicates the head is **masked**.
|
815 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
816 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
817 |
+
config.n_positions - 1]`.
|
818 |
+
|
819 |
+
[What are position IDs?](../glossary#position-ids)
|
820 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
821 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
822 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
823 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
824 |
+
|
825 |
+
Two formats are allowed:
|
826 |
+
- a [`~cache_utils.Cache`] instance, see our
|
827 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
828 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
829 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
830 |
+
cache format.
|
831 |
+
|
832 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
833 |
+
legacy cache format will be returned.
|
834 |
+
|
835 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
836 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
837 |
+
of shape `(batch_size, sequence_length)`.
|
838 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
839 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
840 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
841 |
+
model's internal embedding lookup matrix.
|
842 |
+
use_cache (`bool`, *optional*):
|
843 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
844 |
+
`past_key_values`).
|
845 |
+
output_attentions (`bool`, *optional*):
|
846 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
847 |
+
tensors for more detail.
|
848 |
+
output_hidden_states (`bool`, *optional*):
|
849 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
850 |
+
more detail.
|
851 |
+
return_dict (`bool`, *optional*):
|
852 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
853 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
854 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
855 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
856 |
+
the complete sequence length.
|
857 |
+
"""
|
858 |
+
|
859 |
+
|
860 |
+
@add_start_docstrings(
|
861 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
862 |
+
LLAMA_START_DOCSTRING,
|
863 |
+
)
|
864 |
+
class TPULlamaModel(TPULlamaPreTrainedModel):
|
865 |
+
"""
|
866 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TPULlamaDecoderLayer`]
|
867 |
+
|
868 |
+
Args:
|
869 |
+
config: TPULlamaConfig
|
870 |
+
"""
|
871 |
+
|
872 |
+
def __init__(self, config: TPULlamaConfig):
|
873 |
+
super().__init__(config)
|
874 |
+
self.padding_idx = config.pad_token_id
|
875 |
+
self.vocab_size = config.vocab_size
|
876 |
+
|
877 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
878 |
+
if config.expand_input_ids:
|
879 |
+
self.expand_embed_tokens = nn.Embedding(config.expand_input_ids_vocab_size, config.hidden_size)
|
880 |
+
self.expand_input_ids_dict = (
|
881 |
+
{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()},
|
882 |
+
set(int(n) for n in config.expand_input_ids_dict[1]),
|
883 |
+
)
|
884 |
+
else:
|
885 |
+
self.expand_embed_tokens = None
|
886 |
+
|
887 |
+
self.layers = nn.ModuleList(
|
888 |
+
[TPULlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
889 |
+
)
|
890 |
+
self.norm = TPULlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
891 |
+
self.rotary_emb = TPULlamaRotaryEmbedding(config=config)
|
892 |
+
self.gradient_checkpointing = False
|
893 |
+
|
894 |
+
# Initialize weights and apply final processing
|
895 |
+
self.post_init()
|
896 |
+
|
897 |
+
def get_input_embeddings(self):
|
898 |
+
return self.embed_tokens
|
899 |
+
|
900 |
+
def set_input_embeddings(self, value):
|
901 |
+
self.embed_tokens = value
|
902 |
+
|
903 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
904 |
+
def forward(
|
905 |
+
self,
|
906 |
+
input_ids: torch.LongTensor = None,
|
907 |
+
attention_mask: Optional[torch.Tensor] = None,
|
908 |
+
position_ids: Optional[torch.LongTensor] = None,
|
909 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
910 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
911 |
+
use_cache: Optional[bool] = None,
|
912 |
+
output_attentions: Optional[bool] = None,
|
913 |
+
output_hidden_states: Optional[bool] = None,
|
914 |
+
return_dict: Optional[bool] = None,
|
915 |
+
cache_position: Optional[torch.LongTensor] = None,
|
916 |
+
past_input_ids: Optional[torch.LongTensor] = None,
|
917 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
918 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
919 |
+
output_hidden_states = (
|
920 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
921 |
+
)
|
922 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
923 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
924 |
+
|
925 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
926 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
927 |
+
|
928 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
929 |
+
logger.warning_once(
|
930 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
931 |
+
)
|
932 |
+
use_cache = False
|
933 |
+
|
934 |
+
if inputs_embeds is None:
|
935 |
+
|
936 |
+
if self.config.expand_input_ids:
|
937 |
+
input_ids_to_expand = past_input_ids if past_input_ids is not None else input_ids
|
938 |
+
|
939 |
+
expanded_input_ids = torch_expand_input_ids(
|
940 |
+
input_ids_to_expand,
|
941 |
+
self.expand_input_ids_dict,
|
942 |
+
self.config.expand_input_ids_maxlen,
|
943 |
+
last_n=input_ids.shape[1],
|
944 |
+
)[:, -input_ids.shape[1]:]
|
945 |
+
inputs_embeds = self.embed_tokens(input_ids) + self.expand_embed_tokens(expanded_input_ids)
|
946 |
+
else:
|
947 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
948 |
+
|
949 |
+
# kept for BC (non `Cache` `past_key_values` inputs)
|
950 |
+
return_legacy_cache = False
|
951 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
952 |
+
return_legacy_cache = True
|
953 |
+
if past_key_values is None:
|
954 |
+
past_key_values = DynamicCache()
|
955 |
+
else:
|
956 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
957 |
+
logger.warning_once(
|
958 |
+
"We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
|
959 |
+
"will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
|
960 |
+
"(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
|
961 |
+
)
|
962 |
+
|
963 |
+
if cache_position is None:
|
964 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
965 |
+
cache_position = torch.arange(
|
966 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
967 |
+
)
|
968 |
+
if position_ids is None:
|
969 |
+
position_ids = cache_position.unsqueeze(0)
|
970 |
+
|
971 |
+
causal_mask = self._update_causal_mask(
|
972 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
973 |
+
)
|
974 |
+
hidden_states = inputs_embeds
|
975 |
+
|
976 |
+
# create position embeddings to be shared across the decoder layers
|
977 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
978 |
+
|
979 |
+
# decoder layers
|
980 |
+
all_hidden_states = () if output_hidden_states else None
|
981 |
+
all_self_attns = () if output_attentions else None
|
982 |
+
next_decoder_cache = None
|
983 |
+
|
984 |
+
for decoder_layer in self.layers:
|
985 |
+
if output_hidden_states:
|
986 |
+
all_hidden_states += (hidden_states,)
|
987 |
+
|
988 |
+
if self.gradient_checkpointing and self.training:
|
989 |
+
layer_outputs = self._gradient_checkpointing_func(
|
990 |
+
decoder_layer.__call__,
|
991 |
+
hidden_states,
|
992 |
+
causal_mask,
|
993 |
+
position_ids,
|
994 |
+
past_key_values,
|
995 |
+
output_attentions,
|
996 |
+
use_cache,
|
997 |
+
cache_position,
|
998 |
+
position_embeddings,
|
999 |
+
)
|
1000 |
+
else:
|
1001 |
+
layer_outputs = decoder_layer(
|
1002 |
+
hidden_states,
|
1003 |
+
attention_mask=causal_mask,
|
1004 |
+
position_ids=position_ids,
|
1005 |
+
past_key_value=past_key_values,
|
1006 |
+
output_attentions=output_attentions,
|
1007 |
+
use_cache=use_cache,
|
1008 |
+
cache_position=cache_position,
|
1009 |
+
position_embeddings=position_embeddings,
|
1010 |
+
)
|
1011 |
+
|
1012 |
+
hidden_states = layer_outputs[0]
|
1013 |
+
|
1014 |
+
if use_cache:
|
1015 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1016 |
+
|
1017 |
+
if output_attentions:
|
1018 |
+
all_self_attns += (layer_outputs[1],)
|
1019 |
+
|
1020 |
+
hidden_states = self.norm(hidden_states)
|
1021 |
+
|
1022 |
+
# add hidden states from the last decoder layer
|
1023 |
+
if output_hidden_states:
|
1024 |
+
all_hidden_states += (hidden_states,)
|
1025 |
+
|
1026 |
+
next_cache = next_decoder_cache if use_cache else None
|
1027 |
+
if return_legacy_cache:
|
1028 |
+
next_cache = next_cache.to_legacy_cache()
|
1029 |
+
|
1030 |
+
if not return_dict:
|
1031 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
1032 |
+
return BaseModelOutputWithPast(
|
1033 |
+
last_hidden_state=hidden_states,
|
1034 |
+
past_key_values=next_cache,
|
1035 |
+
hidden_states=all_hidden_states,
|
1036 |
+
attentions=all_self_attns,
|
1037 |
+
)
|
1038 |
+
|
1039 |
+
def _update_causal_mask(
|
1040 |
+
self,
|
1041 |
+
attention_mask: torch.Tensor,
|
1042 |
+
input_tensor: torch.Tensor,
|
1043 |
+
cache_position: torch.Tensor,
|
1044 |
+
past_key_values: Cache,
|
1045 |
+
output_attentions: bool,
|
1046 |
+
):
|
1047 |
+
if self.config._attn_implementation == "flash_attention_2":
|
1048 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
1049 |
+
return attention_mask
|
1050 |
+
return None
|
1051 |
+
|
1052 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
1053 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
1054 |
+
# to infer the attention mask.
|
1055 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
1056 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
1057 |
+
|
1058 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
1059 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
1060 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
1061 |
+
attention_mask,
|
1062 |
+
inputs_embeds=input_tensor,
|
1063 |
+
past_key_values_length=past_seen_tokens,
|
1064 |
+
is_training=self.training,
|
1065 |
+
):
|
1066 |
+
return None
|
1067 |
+
|
1068 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
1069 |
+
sequence_length = input_tensor.shape[1]
|
1070 |
+
if using_static_cache:
|
1071 |
+
target_length = past_key_values.get_max_cache_shape()
|
1072 |
+
else:
|
1073 |
+
target_length = (
|
1074 |
+
attention_mask.shape[-1]
|
1075 |
+
if isinstance(attention_mask, torch.Tensor)
|
1076 |
+
else past_seen_tokens + sequence_length + 1
|
1077 |
+
)
|
1078 |
+
|
1079 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
1080 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
1081 |
+
attention_mask,
|
1082 |
+
sequence_length=sequence_length,
|
1083 |
+
target_length=target_length,
|
1084 |
+
dtype=dtype,
|
1085 |
+
device=device,
|
1086 |
+
cache_position=cache_position,
|
1087 |
+
batch_size=input_tensor.shape[0],
|
1088 |
+
)
|
1089 |
+
|
1090 |
+
if (
|
1091 |
+
self.config._attn_implementation == "sdpa"
|
1092 |
+
and attention_mask is not None
|
1093 |
+
and attention_mask.device.type == "cuda"
|
1094 |
+
and not output_attentions
|
1095 |
+
):
|
1096 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
1097 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
1098 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1099 |
+
min_dtype = torch.finfo(dtype).min
|
1100 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
1101 |
+
|
1102 |
+
return causal_mask
|
1103 |
+
|
1104 |
+
@staticmethod
|
1105 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
1106 |
+
attention_mask: torch.Tensor,
|
1107 |
+
sequence_length: int,
|
1108 |
+
target_length: int,
|
1109 |
+
dtype: torch.dtype,
|
1110 |
+
device: torch.device,
|
1111 |
+
cache_position: torch.Tensor,
|
1112 |
+
batch_size: int,
|
1113 |
+
):
|
1114 |
+
"""
|
1115 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
1116 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
1117 |
+
|
1118 |
+
Args:
|
1119 |
+
attention_mask (`torch.Tensor`):
|
1120 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
1121 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
1122 |
+
sequence_length (`int`):
|
1123 |
+
The sequence length being processed.
|
1124 |
+
target_length (`int`):
|
1125 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
1126 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
1127 |
+
dtype (`torch.dtype`):
|
1128 |
+
The dtype to use for the 4D attention mask.
|
1129 |
+
device (`torch.device`):
|
1130 |
+
The device to plcae the 4D attention mask on.
|
1131 |
+
cache_position (`torch.Tensor`):
|
1132 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
1133 |
+
batch_size (`torch.Tensor`):
|
1134 |
+
Batch size.
|
1135 |
+
"""
|
1136 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
1137 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
1138 |
+
causal_mask = attention_mask
|
1139 |
+
else:
|
1140 |
+
min_dtype = torch.finfo(dtype).min
|
1141 |
+
causal_mask = torch.full(
|
1142 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
1143 |
+
)
|
1144 |
+
if sequence_length != 1:
|
1145 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
1146 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
1147 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
1148 |
+
if attention_mask is not None:
|
1149 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
1150 |
+
mask_length = attention_mask.shape[-1]
|
1151 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
1152 |
+
padding_mask = padding_mask == 0
|
1153 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
1154 |
+
padding_mask, min_dtype
|
1155 |
+
)
|
1156 |
+
|
1157 |
+
return causal_mask
|
1158 |
+
|
1159 |
+
|
1160 |
+
class TPULlamaForCausalLM(TPULlamaPreTrainedModel, GenerationMixin):
|
1161 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1162 |
+
|
1163 |
+
def __init__(self, config):
|
1164 |
+
super().__init__(config)
|
1165 |
+
self.model = TPULlamaModel(config)
|
1166 |
+
self.vocab_size = config.vocab_size
|
1167 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1168 |
+
|
1169 |
+
# Initialize weights and apply final processing
|
1170 |
+
self.post_init()
|
1171 |
+
|
1172 |
+
def get_input_embeddings(self):
|
1173 |
+
return self.model.embed_tokens
|
1174 |
+
|
1175 |
+
def set_input_embeddings(self, value):
|
1176 |
+
self.model.embed_tokens = value
|
1177 |
+
|
1178 |
+
def get_output_embeddings(self):
|
1179 |
+
return self.lm_head
|
1180 |
+
|
1181 |
+
def set_output_embeddings(self, new_embeddings):
|
1182 |
+
self.lm_head = new_embeddings
|
1183 |
+
|
1184 |
+
def set_decoder(self, decoder):
|
1185 |
+
self.model = decoder
|
1186 |
+
|
1187 |
+
def get_decoder(self):
|
1188 |
+
return self.model
|
1189 |
+
|
1190 |
+
def prepare_inputs_for_generation(self, input_ids, **model_kwargs):
|
1191 |
+
out = super().prepare_inputs_for_generation(input_ids, **model_kwargs)
|
1192 |
+
|
1193 |
+
if self.config.expand_input_ids:
|
1194 |
+
out["past_input_ids"] = input_ids
|
1195 |
+
|
1196 |
+
return out
|
1197 |
+
|
1198 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1199 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1200 |
+
def forward(
|
1201 |
+
self,
|
1202 |
+
input_ids: torch.LongTensor = None,
|
1203 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1204 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1205 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1206 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1207 |
+
labels: Optional[torch.LongTensor] = None,
|
1208 |
+
use_cache: Optional[bool] = None,
|
1209 |
+
output_attentions: Optional[bool] = None,
|
1210 |
+
output_hidden_states: Optional[bool] = None,
|
1211 |
+
return_dict: Optional[bool] = None,
|
1212 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1213 |
+
num_logits_to_keep: int = 0,
|
1214 |
+
past_input_ids: Optional[torch.LongTensor] = None,
|
1215 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1216 |
+
r"""
|
1217 |
+
Args:
|
1218 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1219 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1220 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1221 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1222 |
+
|
1223 |
+
num_logits_to_keep (`int`, *optional*):
|
1224 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
1225 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
1226 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
1227 |
+
|
1228 |
+
Returns:
|
1229 |
+
|
1230 |
+
Example:
|
1231 |
+
|
1232 |
+
```python
|
1233 |
+
>>> from transformers import AutoTokenizer, TPULlamaForCausalLM
|
1234 |
+
|
1235 |
+
>>> model = TPULlamaForCausalLM.from_pretrained("meta-llama/TPULlama-2-7b-hf")
|
1236 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/TPULlama-2-7b-hf")
|
1237 |
+
|
1238 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1239 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1240 |
+
|
1241 |
+
>>> # Generate
|
1242 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1243 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1244 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1245 |
+
```"""
|
1246 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1247 |
+
output_hidden_states = (
|
1248 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1249 |
+
)
|
1250 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1251 |
+
|
1252 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1253 |
+
outputs = self.model(
|
1254 |
+
input_ids=input_ids,
|
1255 |
+
attention_mask=attention_mask,
|
1256 |
+
position_ids=position_ids,
|
1257 |
+
past_key_values=past_key_values,
|
1258 |
+
inputs_embeds=inputs_embeds,
|
1259 |
+
use_cache=use_cache,
|
1260 |
+
output_attentions=output_attentions,
|
1261 |
+
output_hidden_states=output_hidden_states,
|
1262 |
+
return_dict=return_dict,
|
1263 |
+
cache_position=cache_position,
|
1264 |
+
past_input_ids=past_input_ids,
|
1265 |
+
)
|
1266 |
+
|
1267 |
+
hidden_states = outputs[0]
|
1268 |
+
if self.config.pretraining_tp > 1:
|
1269 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
1270 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
1271 |
+
logits = torch.cat(logits, dim=-1)
|
1272 |
+
else:
|
1273 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
1274 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
1275 |
+
|
1276 |
+
loss = None
|
1277 |
+
if labels is not None:
|
1278 |
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
1279 |
+
logits = logits.float()
|
1280 |
+
# Shift so that tokens < n predict n
|
1281 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1282 |
+
shift_labels = labels[..., 1:].contiguous()
|
1283 |
+
# Flatten the tokens
|
1284 |
+
loss_fct = CrossEntropyLoss()
|
1285 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1286 |
+
shift_labels = shift_labels.view(-1)
|
1287 |
+
# Enable model parallelism
|
1288 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1289 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1290 |
+
|
1291 |
+
if not return_dict:
|
1292 |
+
output = (logits,) + outputs[1:]
|
1293 |
+
return (loss,) + output if loss is not None else output
|
1294 |
+
|
1295 |
+
return CausalLMOutputWithPast(
|
1296 |
+
loss=loss,
|
1297 |
+
logits=logits,
|
1298 |
+
past_key_values=outputs.past_key_values,
|
1299 |
+
hidden_states=outputs.hidden_states,
|
1300 |
+
attentions=outputs.attentions,
|
1301 |
+
)
|
1302 |
+
|
1303 |
+
|
1304 |
+
@add_start_docstrings(
|
1305 |
+
"""
|
1306 |
+
The LLaMa Model transformer with a sequence classification head on top (linear layer).
|
1307 |
+
|
1308 |
+
[`TPULlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1309 |
+
(e.g. GPT-2) do.
|
1310 |
+
|
1311 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1312 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1313 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1314 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1315 |
+
each row of the batch).
|
1316 |
+
""",
|
1317 |
+
LLAMA_START_DOCSTRING,
|
1318 |
+
)
|
1319 |
+
class TPULlamaForSequenceClassification(TPULlamaPreTrainedModel):
|
1320 |
+
def __init__(self, config):
|
1321 |
+
super().__init__(config)
|
1322 |
+
self.num_labels = config.num_labels
|
1323 |
+
self.model = TPULlamaModel(config)
|
1324 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1325 |
+
|
1326 |
+
# Initialize weights and apply final processing
|
1327 |
+
self.post_init()
|
1328 |
+
|
1329 |
+
def get_input_embeddings(self):
|
1330 |
+
return self.model.embed_tokens
|
1331 |
+
|
1332 |
+
def set_input_embeddings(self, value):
|
1333 |
+
self.model.embed_tokens = value
|
1334 |
+
|
1335 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1336 |
+
def forward(
|
1337 |
+
self,
|
1338 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1339 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1340 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1341 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1342 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1343 |
+
labels: Optional[torch.LongTensor] = None,
|
1344 |
+
use_cache: Optional[bool] = None,
|
1345 |
+
output_attentions: Optional[bool] = None,
|
1346 |
+
output_hidden_states: Optional[bool] = None,
|
1347 |
+
return_dict: Optional[bool] = None,
|
1348 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1349 |
+
r"""
|
1350 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1351 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1352 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1353 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1354 |
+
"""
|
1355 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1356 |
+
|
1357 |
+
transformer_outputs = self.model(
|
1358 |
+
input_ids,
|
1359 |
+
attention_mask=attention_mask,
|
1360 |
+
position_ids=position_ids,
|
1361 |
+
past_key_values=past_key_values,
|
1362 |
+
inputs_embeds=inputs_embeds,
|
1363 |
+
use_cache=use_cache,
|
1364 |
+
output_attentions=output_attentions,
|
1365 |
+
output_hidden_states=output_hidden_states,
|
1366 |
+
return_dict=return_dict,
|
1367 |
+
)
|
1368 |
+
hidden_states = transformer_outputs[0]
|
1369 |
+
logits = self.score(hidden_states)
|
1370 |
+
|
1371 |
+
if input_ids is not None:
|
1372 |
+
batch_size = input_ids.shape[0]
|
1373 |
+
else:
|
1374 |
+
batch_size = inputs_embeds.shape[0]
|
1375 |
+
|
1376 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1377 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1378 |
+
if self.config.pad_token_id is None:
|
1379 |
+
sequence_lengths = -1
|
1380 |
+
else:
|
1381 |
+
if input_ids is not None:
|
1382 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1383 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1384 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1385 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1386 |
+
else:
|
1387 |
+
sequence_lengths = -1
|
1388 |
+
|
1389 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1390 |
+
|
1391 |
+
loss = None
|
1392 |
+
if labels is not None:
|
1393 |
+
labels = labels.to(logits.device)
|
1394 |
+
if self.config.problem_type is None:
|
1395 |
+
if self.num_labels == 1:
|
1396 |
+
self.config.problem_type = "regression"
|
1397 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1398 |
+
self.config.problem_type = "single_label_classification"
|
1399 |
+
else:
|
1400 |
+
self.config.problem_type = "multi_label_classification"
|
1401 |
+
|
1402 |
+
if self.config.problem_type == "regression":
|
1403 |
+
loss_fct = MSELoss()
|
1404 |
+
if self.num_labels == 1:
|
1405 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1406 |
+
else:
|
1407 |
+
loss = loss_fct(pooled_logits, labels)
|
1408 |
+
elif self.config.problem_type == "single_label_classification":
|
1409 |
+
loss_fct = CrossEntropyLoss()
|
1410 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1411 |
+
elif self.config.problem_type == "multi_label_classification":
|
1412 |
+
loss_fct = BCEWithLogitsLoss()
|
1413 |
+
loss = loss_fct(pooled_logits, labels)
|
1414 |
+
if not return_dict:
|
1415 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1416 |
+
return ((loss,) + output) if loss is not None else output
|
1417 |
+
|
1418 |
+
return SequenceClassifierOutputWithPast(
|
1419 |
+
loss=loss,
|
1420 |
+
logits=pooled_logits,
|
1421 |
+
past_key_values=transformer_outputs.past_key_values,
|
1422 |
+
hidden_states=transformer_outputs.hidden_states,
|
1423 |
+
attentions=transformer_outputs.attentions,
|
1424 |
+
)
|
1425 |
+
|
1426 |
+
|
1427 |
+
@add_start_docstrings(
|
1428 |
+
"""
|
1429 |
+
The TPULlama Model transformer with a span classification head on top for extractive question-answering tasks like
|
1430 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1431 |
+
""",
|
1432 |
+
LLAMA_START_DOCSTRING,
|
1433 |
+
)
|
1434 |
+
class TPULlamaForQuestionAnswering(TPULlamaPreTrainedModel):
|
1435 |
+
base_model_prefix = "transformer"
|
1436 |
+
|
1437 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->TPULlama
|
1438 |
+
def __init__(self, config):
|
1439 |
+
super().__init__(config)
|
1440 |
+
self.transformer = TPULlamaModel(config)
|
1441 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1442 |
+
|
1443 |
+
# Initialize weights and apply final processing
|
1444 |
+
self.post_init()
|
1445 |
+
|
1446 |
+
def get_input_embeddings(self):
|
1447 |
+
return self.transformer.embed_tokens
|
1448 |
+
|
1449 |
+
def set_input_embeddings(self, value):
|
1450 |
+
self.transformer.embed_tokens = value
|
1451 |
+
|
1452 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1453 |
+
def forward(
|
1454 |
+
self,
|
1455 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1456 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1457 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1458 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1459 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1460 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1461 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1462 |
+
output_attentions: Optional[bool] = None,
|
1463 |
+
output_hidden_states: Optional[bool] = None,
|
1464 |
+
return_dict: Optional[bool] = None,
|
1465 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1466 |
+
r"""
|
1467 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1468 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1469 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1470 |
+
are not taken into account for computing the loss.
|
1471 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1472 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1473 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1474 |
+
are not taken into account for computing the loss.
|
1475 |
+
"""
|
1476 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1477 |
+
|
1478 |
+
outputs = self.transformer(
|
1479 |
+
input_ids,
|
1480 |
+
attention_mask=attention_mask,
|
1481 |
+
position_ids=position_ids,
|
1482 |
+
past_key_values=past_key_values,
|
1483 |
+
inputs_embeds=inputs_embeds,
|
1484 |
+
output_attentions=output_attentions,
|
1485 |
+
output_hidden_states=output_hidden_states,
|
1486 |
+
return_dict=return_dict,
|
1487 |
+
)
|
1488 |
+
|
1489 |
+
sequence_output = outputs[0]
|
1490 |
+
|
1491 |
+
logits = self.qa_outputs(sequence_output)
|
1492 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1493 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1494 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1495 |
+
|
1496 |
+
total_loss = None
|
1497 |
+
if start_positions is not None and end_positions is not None:
|
1498 |
+
# If we are on multi-GPU, split add a dimension
|
1499 |
+
if len(start_positions.size()) > 1:
|
1500 |
+
start_positions = start_positions.squeeze(-1).to(start_logits.device)
|
1501 |
+
if len(end_positions.size()) > 1:
|
1502 |
+
end_positions = end_positions.squeeze(-1).to(end_logits.device)
|
1503 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
1504 |
+
ignored_index = start_logits.size(1)
|
1505 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
1506 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
1507 |
+
|
1508 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
1509 |
+
start_loss = loss_fct(start_logits, start_positions)
|
1510 |
+
end_loss = loss_fct(end_logits, end_positions)
|
1511 |
+
total_loss = (start_loss + end_loss) / 2
|
1512 |
+
|
1513 |
+
if not return_dict:
|
1514 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1515 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1516 |
+
|
1517 |
+
return QuestionAnsweringModelOutput(
|
1518 |
+
loss=total_loss,
|
1519 |
+
start_logits=start_logits,
|
1520 |
+
end_logits=end_logits,
|
1521 |
+
hidden_states=outputs.hidden_states,
|
1522 |
+
attentions=outputs.attentions,
|
1523 |
+
)
|
1524 |
+
|
1525 |
+
|
1526 |
+
@add_start_docstrings(
|
1527 |
+
"""
|
1528 |
+
The TPULlama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
1529 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
1530 |
+
""",
|
1531 |
+
LLAMA_START_DOCSTRING,
|
1532 |
+
)
|
1533 |
+
class TPULlamaForTokenClassification(TPULlamaPreTrainedModel):
|
1534 |
+
def __init__(self, config):
|
1535 |
+
super().__init__(config)
|
1536 |
+
self.num_labels = config.num_labels
|
1537 |
+
self.model = TPULlamaModel(config)
|
1538 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
1539 |
+
classifier_dropout = config.classifier_dropout
|
1540 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
1541 |
+
classifier_dropout = config.hidden_dropout
|
1542 |
+
else:
|
1543 |
+
classifier_dropout = 0.1
|
1544 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1545 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
1546 |
+
|
1547 |
+
# Initialize weights and apply final processing
|
1548 |
+
self.post_init()
|
1549 |
+
|
1550 |
+
def get_input_embeddings(self):
|
1551 |
+
return self.model.embed_tokens
|
1552 |
+
|
1553 |
+
def set_input_embeddings(self, value):
|
1554 |
+
self.model.embed_tokens = value
|
1555 |
+
|
1556 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1557 |
+
def forward(
|
1558 |
+
self,
|
1559 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1560 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1561 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1562 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1563 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1564 |
+
labels: Optional[torch.LongTensor] = None,
|
1565 |
+
use_cache: Optional[bool] = None,
|
1566 |
+
output_attentions: Optional[bool] = None,
|
1567 |
+
output_hidden_states: Optional[bool] = None,
|
1568 |
+
return_dict: Optional[bool] = None,
|
1569 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
1570 |
+
r"""
|
1571 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1572 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1573 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1574 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1575 |
+
"""
|
1576 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1577 |
+
|
1578 |
+
outputs = self.model(
|
1579 |
+
input_ids,
|
1580 |
+
attention_mask=attention_mask,
|
1581 |
+
position_ids=position_ids,
|
1582 |
+
past_key_values=past_key_values,
|
1583 |
+
inputs_embeds=inputs_embeds,
|
1584 |
+
use_cache=use_cache,
|
1585 |
+
output_attentions=output_attentions,
|
1586 |
+
output_hidden_states=output_hidden_states,
|
1587 |
+
return_dict=return_dict,
|
1588 |
+
)
|
1589 |
+
sequence_output = outputs[0]
|
1590 |
+
sequence_output = self.dropout(sequence_output)
|
1591 |
+
logits = self.score(sequence_output)
|
1592 |
+
|
1593 |
+
loss = None
|
1594 |
+
if labels is not None:
|
1595 |
+
loss_fct = CrossEntropyLoss()
|
1596 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1597 |
+
|
1598 |
+
if not return_dict:
|
1599 |
+
output = (logits,) + outputs[2:]
|
1600 |
+
return ((loss,) + output) if loss is not None else output
|
1601 |
+
|
1602 |
+
return TokenClassifierOutput(
|
1603 |
+
loss=loss,
|
1604 |
+
logits=logits,
|
1605 |
+
hidden_states=outputs.hidden_states,
|
1606 |
+
attentions=outputs.attentions,
|
1607 |
+
)
|
special_tokens_map.json
CHANGED
@@ -1,23 +1,5 @@
|
|
1 |
{
|
2 |
-
"bos_token":
|
3 |
-
|
4 |
-
|
5 |
-
"normalized": false,
|
6 |
-
"rstrip": false,
|
7 |
-
"single_word": false
|
8 |
-
},
|
9 |
-
"eos_token": {
|
10 |
-
"content": "<|eot_id|>",
|
11 |
-
"lstrip": false,
|
12 |
-
"normalized": false,
|
13 |
-
"rstrip": false,
|
14 |
-
"single_word": false
|
15 |
-
},
|
16 |
-
"pad_token": {
|
17 |
-
"content": "<|eot_id|>",
|
18 |
-
"lstrip": false,
|
19 |
-
"normalized": false,
|
20 |
-
"rstrip": false,
|
21 |
-
"single_word": false
|
22 |
-
}
|
23 |
}
|
|
|
1 |
{
|
2 |
+
"bos_token": "<|begin_of_text|>",
|
3 |
+
"eos_token": "<|eot_id|>",
|
4 |
+
"pad_token": "<|end_of_text|>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
}
|
tokenizer.json
CHANGED
@@ -2,81 +2,13 @@
|
|
2 |
"version": "1.0",
|
3 |
"truncation": null,
|
4 |
"padding": null,
|
5 |
-
"added_tokens": [
|
6 |
-
{
|
7 |
-
"id": 256,
|
8 |
-
"content": "<|begin_of_text|>",
|
9 |
-
"single_word": false,
|
10 |
-
"lstrip": false,
|
11 |
-
"rstrip": false,
|
12 |
-
"normalized": false,
|
13 |
-
"special": true
|
14 |
-
},
|
15 |
-
{
|
16 |
-
"id": 265,
|
17 |
-
"content": "<|eot_id|>",
|
18 |
-
"single_word": false,
|
19 |
-
"lstrip": false,
|
20 |
-
"rstrip": false,
|
21 |
-
"normalized": false,
|
22 |
-
"special": true
|
23 |
-
},
|
24 |
-
{
|
25 |
-
"id": 512,
|
26 |
-
"content": "ĊĊ",
|
27 |
-
"single_word": false,
|
28 |
-
"lstrip": false,
|
29 |
-
"rstrip": false,
|
30 |
-
"normalized": true,
|
31 |
-
"special": false
|
32 |
-
},
|
33 |
-
{
|
34 |
-
"id": 513,
|
35 |
-
"content": "user",
|
36 |
-
"single_word": false,
|
37 |
-
"lstrip": false,
|
38 |
-
"rstrip": false,
|
39 |
-
"normalized": true,
|
40 |
-
"special": false
|
41 |
-
},
|
42 |
-
{
|
43 |
-
"id": 514,
|
44 |
-
"content": "assistant",
|
45 |
-
"single_word": false,
|
46 |
-
"lstrip": false,
|
47 |
-
"rstrip": false,
|
48 |
-
"normalized": true,
|
49 |
-
"special": false
|
50 |
-
},
|
51 |
-
{
|
52 |
-
"id": 515,
|
53 |
-
"content": "system",
|
54 |
-
"single_word": false,
|
55 |
-
"lstrip": false,
|
56 |
-
"rstrip": false,
|
57 |
-
"normalized": true,
|
58 |
-
"special": false
|
59 |
-
}
|
60 |
-
],
|
61 |
"normalizer": null,
|
62 |
"pre_tokenizer": {
|
63 |
-
"type": "
|
64 |
-
"
|
65 |
-
|
66 |
-
|
67 |
-
"pattern": {
|
68 |
-
"Regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
|
69 |
-
},
|
70 |
-
"behavior": "Isolated",
|
71 |
-
"invert": false
|
72 |
-
},
|
73 |
-
{
|
74 |
-
"type": "ByteLevel",
|
75 |
-
"add_prefix_space": false,
|
76 |
-
"trim_offsets": true,
|
77 |
-
"use_regex": false
|
78 |
-
}
|
79 |
-
]
|
80 |
},
|
81 |
"post_processor": {
|
82 |
"type": "Sequence",
|
@@ -150,523 +82,1070 @@
|
|
150 |
"use_regex": true
|
151 |
},
|
152 |
"model": {
|
153 |
-
"type": "
|
154 |
-
"
|
155 |
-
"
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
671 |
}
|
672 |
}
|
|
|
2 |
"version": "1.0",
|
3 |
"truncation": null,
|
4 |
"padding": null,
|
5 |
+
"added_tokens": [],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
"normalizer": null,
|
7 |
"pre_tokenizer": {
|
8 |
+
"type": "ByteLevel",
|
9 |
+
"add_prefix_space": false,
|
10 |
+
"trim_offsets": true,
|
11 |
+
"use_regex": false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
},
|
13 |
"post_processor": {
|
14 |
"type": "Sequence",
|
|
|
82 |
"use_regex": true
|
83 |
},
|
84 |
"model": {
|
85 |
+
"type": "Unigram",
|
86 |
+
"unk_id": null,
|
87 |
+
"vocab": [
|
88 |
+
[
|
89 |
+
"Ā",
|
90 |
+
0.0
|
91 |
+
],
|
92 |
+
[
|
93 |
+
"ā",
|
94 |
+
0.0
|
95 |
+
],
|
96 |
+
[
|
97 |
+
"Ă",
|
98 |
+
0.0
|
99 |
+
],
|
100 |
+
[
|
101 |
+
"ă",
|
102 |
+
0.0
|
103 |
+
],
|
104 |
+
[
|
105 |
+
"Ą",
|
106 |
+
0.0
|
107 |
+
],
|
108 |
+
[
|
109 |
+
"ą",
|
110 |
+
0.0
|
111 |
+
],
|
112 |
+
[
|
113 |
+
"Ć",
|
114 |
+
0.0
|
115 |
+
],
|
116 |
+
[
|
117 |
+
"ć",
|
118 |
+
0.0
|
119 |
+
],
|
120 |
+
[
|
121 |
+
"Ĉ",
|
122 |
+
0.0
|
123 |
+
],
|
124 |
+
[
|
125 |
+
"ĉ",
|
126 |
+
0.0
|
127 |
+
],
|
128 |
+
[
|
129 |
+
"Ċ",
|
130 |
+
0.0
|
131 |
+
],
|
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 |
+
"0",
|
282 |
+
0.0
|
283 |
+
],
|
284 |
+
[
|
285 |
+
"1",
|
286 |
+
0.0
|
287 |
+
],
|
288 |
+
[
|
289 |
+
"2",
|
290 |
+
0.0
|
291 |
+
],
|
292 |
+
[
|
293 |
+
"3",
|
294 |
+
0.0
|
295 |
+
],
|
296 |
+
[
|
297 |
+
"4",
|
298 |
+
0.0
|
299 |
+
],
|
300 |
+
[
|
301 |
+
"5",
|
302 |
+
0.0
|
303 |
+
],
|
304 |
+
[
|
305 |
+
"6",
|
306 |
+
0.0
|
307 |
+
],
|
308 |
+
[
|
309 |
+
"7",
|
310 |
+
0.0
|
311 |
+
],
|
312 |
+
[
|
313 |
+
"8",
|
314 |
+
0.0
|
315 |
+
],
|
316 |
+
[
|
317 |
+
"9",
|
318 |
+
0.0
|
319 |
+
],
|
320 |
+
[
|
321 |
+
":",
|
322 |
+
0.0
|
323 |
+
],
|
324 |
+
[
|
325 |
+
";",
|
326 |
+
0.0
|
327 |
+
],
|
328 |
+
[
|
329 |
+
"<",
|
330 |
+
0.0
|
331 |
+
],
|
332 |
+
[
|
333 |
+
"=",
|
334 |
+
0.0
|
335 |
+
],
|
336 |
+
[
|
337 |
+
">",
|
338 |
+
0.0
|
339 |
+
],
|
340 |
+
[
|
341 |
+
"?",
|
342 |
+
0.0
|
343 |
+
],
|
344 |
+
[
|
345 |
+
"@",
|
346 |
+
0.0
|
347 |
+
],
|
348 |
+
[
|
349 |
+
"A",
|
350 |
+
0.0
|
351 |
+
],
|
352 |
+
[
|
353 |
+
"B",
|
354 |
+
0.0
|
355 |
+
],
|
356 |
+
[
|
357 |
+
"C",
|
358 |
+
0.0
|
359 |
+
],
|
360 |
+
[
|
361 |
+
"D",
|
362 |
+
0.0
|
363 |
+
],
|
364 |
+
[
|
365 |
+
"E",
|
366 |
+
0.0
|
367 |
+
],
|
368 |
+
[
|
369 |
+
"F",
|
370 |
+
0.0
|
371 |
+
],
|
372 |
+
[
|
373 |
+
"G",
|
374 |
+
0.0
|
375 |
+
],
|
376 |
+
[
|
377 |
+
"H",
|
378 |
+
0.0
|
379 |
+
],
|
380 |
+
[
|
381 |
+
"I",
|
382 |
+
0.0
|
383 |
+
],
|
384 |
+
[
|
385 |
+
"J",
|
386 |
+
0.0
|
387 |
+
],
|
388 |
+
[
|
389 |
+
"K",
|
390 |
+
0.0
|
391 |
+
],
|
392 |
+
[
|
393 |
+
"L",
|
394 |
+
0.0
|
395 |
+
],
|
396 |
+
[
|
397 |
+
"M",
|
398 |
+
0.0
|
399 |
+
],
|
400 |
+
[
|
401 |
+
"N",
|
402 |
+
0.0
|
403 |
+
],
|
404 |
+
[
|
405 |
+
"O",
|
406 |
+
0.0
|
407 |
+
],
|
408 |
+
[
|
409 |
+
"P",
|
410 |
+
0.0
|
411 |
+
],
|
412 |
+
[
|
413 |
+
"Q",
|
414 |
+
0.0
|
415 |
+
],
|
416 |
+
[
|
417 |
+
"R",
|
418 |
+
0.0
|
419 |
+
],
|
420 |
+
[
|
421 |
+
"S",
|
422 |
+
0.0
|
423 |
+
],
|
424 |
+
[
|
425 |
+
"T",
|
426 |
+
0.0
|
427 |
+
],
|
428 |
+
[
|
429 |
+
"U",
|
430 |
+
0.0
|
431 |
+
],
|
432 |
+
[
|
433 |
+
"V",
|
434 |
+
0.0
|
435 |
+
],
|
436 |
+
[
|
437 |
+
"W",
|
438 |
+
0.0
|
439 |
+
],
|
440 |
+
[
|
441 |
+
"X",
|
442 |
+
0.0
|
443 |
+
],
|
444 |
+
[
|
445 |
+
"Y",
|
446 |
+
0.0
|
447 |
+
],
|
448 |
+
[
|
449 |
+
"Z",
|
450 |
+
0.0
|
451 |
+
],
|
452 |
+
[
|
453 |
+
"[",
|
454 |
+
0.0
|
455 |
+
],
|
456 |
+
[
|
457 |
+
"\\",
|
458 |
+
0.0
|
459 |
+
],
|
460 |
+
[
|
461 |
+
"]",
|
462 |
+
0.0
|
463 |
+
],
|
464 |
+
[
|
465 |
+
"^",
|
466 |
+
0.0
|
467 |
+
],
|
468 |
+
[
|
469 |
+
"_",
|
470 |
+
0.0
|
471 |
+
],
|
472 |
+
[
|
473 |
+
"`",
|
474 |
+
0.0
|
475 |
+
],
|
476 |
+
[
|
477 |
+
"a",
|
478 |
+
0.0
|
479 |
+
],
|
480 |
+
[
|
481 |
+
"b",
|
482 |
+
0.0
|
483 |
+
],
|
484 |
+
[
|
485 |
+
"c",
|
486 |
+
0.0
|
487 |
+
],
|
488 |
+
[
|
489 |
+
"d",
|
490 |
+
0.0
|
491 |
+
],
|
492 |
+
[
|
493 |
+
"e",
|
494 |
+
0.0
|
495 |
+
],
|
496 |
+
[
|
497 |
+
"f",
|
498 |
+
0.0
|
499 |
+
],
|
500 |
+
[
|
501 |
+
"g",
|
502 |
+
0.0
|
503 |
+
],
|
504 |
+
[
|
505 |
+
"h",
|
506 |
+
0.0
|
507 |
+
],
|
508 |
+
[
|
509 |
+
"i",
|
510 |
+
0.0
|
511 |
+
],
|
512 |
+
[
|
513 |
+
"j",
|
514 |
+
0.0
|
515 |
+
],
|
516 |
+
[
|
517 |
+
"k",
|
518 |
+
0.0
|
519 |
+
],
|
520 |
+
[
|
521 |
+
"l",
|
522 |
+
0.0
|
523 |
+
],
|
524 |
+
[
|
525 |
+
"m",
|
526 |
+
0.0
|
527 |
+
],
|
528 |
+
[
|
529 |
+
"n",
|
530 |
+
0.0
|
531 |
+
],
|
532 |
+
[
|
533 |
+
"o",
|
534 |
+
0.0
|
535 |
+
],
|
536 |
+
[
|
537 |
+
"p",
|
538 |
+
0.0
|
539 |
+
],
|
540 |
+
[
|
541 |
+
"q",
|
542 |
+
0.0
|
543 |
+
],
|
544 |
+
[
|
545 |
+
"r",
|
546 |
+
0.0
|
547 |
+
],
|
548 |
+
[
|
549 |
+
"s",
|
550 |
+
0.0
|
551 |
+
],
|
552 |
+
[
|
553 |
+
"t",
|
554 |
+
0.0
|
555 |
+
],
|
556 |
+
[
|
557 |
+
"u",
|
558 |
+
0.0
|
559 |
+
],
|
560 |
+
[
|
561 |
+
"v",
|
562 |
+
0.0
|
563 |
+
],
|
564 |
+
[
|
565 |
+
"w",
|
566 |
+
0.0
|
567 |
+
],
|
568 |
+
[
|
569 |
+
"x",
|
570 |
+
0.0
|
571 |
+
],
|
572 |
+
[
|
573 |
+
"y",
|
574 |
+
0.0
|
575 |
+
],
|
576 |
+
[
|
577 |
+
"z",
|
578 |
+
0.0
|
579 |
+
],
|
580 |
+
[
|
581 |
+
"{",
|
582 |
+
0.0
|
583 |
+
],
|
584 |
+
[
|
585 |
+
"|",
|
586 |
+
0.0
|
587 |
+
],
|
588 |
+
[
|
589 |
+
"}",
|
590 |
+
0.0
|
591 |
+
],
|
592 |
+
[
|
593 |
+
"~",
|
594 |
+
0.0
|
595 |
+
],
|
596 |
+
[
|
597 |
+
"ġ",
|
598 |
+
0.0
|
599 |
+
],
|
600 |
+
[
|
601 |
+
"Ģ",
|
602 |
+
0.0
|
603 |
+
],
|
604 |
+
[
|
605 |
+
"ģ",
|
606 |
+
0.0
|
607 |
+
],
|
608 |
+
[
|
609 |
+
"Ĥ",
|
610 |
+
0.0
|
611 |
+
],
|
612 |
+
[
|
613 |
+
"ĥ",
|
614 |
+
0.0
|
615 |
+
],
|
616 |
+
[
|
617 |
+
"Ħ",
|
618 |
+
0.0
|
619 |
+
],
|
620 |
+
[
|
621 |
+
"ħ",
|
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 |
+
"IJ",
|
666 |
+
0.0
|
667 |
+
],
|
668 |
+
[
|
669 |
+
"ij",
|
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 |
+
"Ľ",
|
710 |
+
0.0
|
711 |
+
],
|
712 |
+
[
|
713 |
+
"ľ",
|
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 |
+
"<|begin_of_text|>",
|
1114 |
+
0.0
|
1115 |
+
],
|
1116 |
+
[
|
1117 |
+
"<|end_header_id|>",
|
1118 |
+
0.0
|
1119 |
+
],
|
1120 |
+
[
|
1121 |
+
"<|end_of_text|>",
|
1122 |
+
0.0
|
1123 |
+
],
|
1124 |
+
[
|
1125 |
+
"<|eot_id|>",
|
1126 |
+
0.0
|
1127 |
+
],
|
1128 |
+
[
|
1129 |
+
"<|start_header_id|>",
|
1130 |
+
0.0
|
1131 |
+
],
|
1132 |
+
[
|
1133 |
+
"assistant",
|
1134 |
+
0.0
|
1135 |
+
],
|
1136 |
+
[
|
1137 |
+
"system",
|
1138 |
+
0.0
|
1139 |
+
],
|
1140 |
+
[
|
1141 |
+
"user",
|
1142 |
+
0.0
|
1143 |
+
],
|
1144 |
+
[
|
1145 |
+
"ĊĊ",
|
1146 |
+
0.0
|
1147 |
+
]
|
1148 |
+
],
|
1149 |
+
"byte_fallback": false
|
1150 |
}
|
1151 |
}
|
tokenizer_config.json
CHANGED
@@ -1,54 +1,5 @@
|
|
1 |
{
|
2 |
-
"added_tokens_decoder": {
|
3 |
-
"256": {
|
4 |
-
"content": "<|begin_of_text|>",
|
5 |
-
"lstrip": false,
|
6 |
-
"normalized": false,
|
7 |
-
"rstrip": false,
|
8 |
-
"single_word": false,
|
9 |
-
"special": true
|
10 |
-
},
|
11 |
-
"265": {
|
12 |
-
"content": "<|eot_id|>",
|
13 |
-
"lstrip": false,
|
14 |
-
"normalized": false,
|
15 |
-
"rstrip": false,
|
16 |
-
"single_word": false,
|
17 |
-
"special": true
|
18 |
-
},
|
19 |
-
"512": {
|
20 |
-
"content": "ĊĊ",
|
21 |
-
"lstrip": false,
|
22 |
-
"normalized": true,
|
23 |
-
"rstrip": false,
|
24 |
-
"single_word": false,
|
25 |
-
"special": false
|
26 |
-
},
|
27 |
-
"513": {
|
28 |
-
"content": "user",
|
29 |
-
"lstrip": false,
|
30 |
-
"normalized": true,
|
31 |
-
"rstrip": false,
|
32 |
-
"single_word": false,
|
33 |
-
"special": false
|
34 |
-
},
|
35 |
-
"514": {
|
36 |
-
"content": "assistant",
|
37 |
-
"lstrip": false,
|
38 |
-
"normalized": true,
|
39 |
-
"rstrip": false,
|
40 |
-
"single_word": false,
|
41 |
-
"special": false
|
42 |
-
},
|
43 |
-
"515": {
|
44 |
-
"content": "system",
|
45 |
-
"lstrip": false,
|
46 |
-
"normalized": true,
|
47 |
-
"rstrip": false,
|
48 |
-
"single_word": false,
|
49 |
-
"special": false
|
50 |
-
}
|
51 |
-
},
|
52 |
"bos_token": "<|begin_of_text|>",
|
53 |
"chat_template": "{{- bos_token }}\n{%- if custom_tools is defined %}\n {%- set tools = custom_tools %}\n{%- endif %}\n{%- if not tools_in_user_message is defined %}\n {%- set tools_in_user_message = true %}\n{%- endif %}\n{%- if not date_string is defined %}\n {%- if strftime_now is defined %}\n {%- set date_string = strftime_now(\"%d %b %Y\") %}\n {%- else %}\n {%- set date_string = \"26 Jul 2024\" %}\n {%- endif %}\n{%- endif %}\n{%- if not tools is defined %}\n {%- set tools = none %}\n{%- endif %}\n\n{#- This block extracts the system message, so we can slot it into the right place. #}\n{%- if messages[0]['role'] == 'system' %}\n {%- set system_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n{%- else %}\n {%- set system_message = \"\" %}\n{%- endif %}\n\n{#- System message #}\n{{- \"<|start_header_id|>system<|end_header_id|>\\n\\n\" }}\n{%- if tools is not none %}\n {{- \"Environment: ipython\\n\" }}\n{%- endif %}\n{{- \"Cutting Knowledge Date: December 2023\\n\" }}\n{{- \"Today Date: \" + date_string + \"\\n\\n\" }}\n{%- if tools is not none and not tools_in_user_message %}\n {{- \"You have access to the following functions. To call a function, please respond with JSON for a function call.\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\\n\\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\\n\\n\" }}\n {%- endfor %}\n{%- endif %}\n{{- system_message }}\n{{- \"<|eot_id|>\" }}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{%- if tools_in_user_message and not tools is none %}\n {#- Extract the first user message so we can plug it in here #}\n {%- if messages | length != 0 %}\n {%- set first_user_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n {%- else %}\n {{- raise_exception(\"Cannot put tools in the first user message when there's no first user message!\") }}\n{%- endif %}\n {{- '<|start_header_id|>user<|end_header_id|>\\n\\n' -}}\n {{- \"Given the following functions, please respond with a JSON for a function call \" }}\n {{- \"with its proper arguments that best answers the given prompt.\\n\\n\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\\n\\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\\n\\n\" }}\n {%- endfor %}\n {{- first_user_message + \"<|eot_id|>\"}}\n{%- endif %}\n\n{%- for message in messages %}\n {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}\n {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\\n\\n'+ message['content'] | trim + '<|eot_id|>' }}\n {%- elif 'tool_calls' in message %}\n {%- if not message.tool_calls|length == 1 %}\n {{- raise_exception(\"This model only supports single tool-calls at once!\") }}\n {%- endif %}\n {%- set tool_call = message.tool_calls[0].function %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}}\n {{- '{\"name\": \"' + tool_call.name + '\", ' }}\n {{- '\"parameters\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- \"}\" }}\n {{- \"<|eot_id|>\" }}\n {%- elif message.role == \"tool\" or message.role == \"ipython\" %}\n {{- \"<|start_header_id|>ipython<|end_header_id|>\\n\\n\" }}\n {%- if message.content is mapping or message.content is iterable %}\n {{- message.content | tojson }}\n {%- else %}\n {{- message.content }}\n {%- endif %}\n {{- \"<|eot_id|>\" }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' }}\n{%- endif %}\n",
|
54 |
"clean_up_tokenization_spaces": true,
|
@@ -58,6 +9,6 @@
|
|
58 |
"attention_mask"
|
59 |
],
|
60 |
"model_max_length": 131072,
|
61 |
-
"pad_token": "<|
|
62 |
"tokenizer_class": "PreTrainedTokenizerFast"
|
63 |
}
|
|
|
1 |
{
|
2 |
+
"added_tokens_decoder": {},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
"bos_token": "<|begin_of_text|>",
|
4 |
"chat_template": "{{- bos_token }}\n{%- if custom_tools is defined %}\n {%- set tools = custom_tools %}\n{%- endif %}\n{%- if not tools_in_user_message is defined %}\n {%- set tools_in_user_message = true %}\n{%- endif %}\n{%- if not date_string is defined %}\n {%- if strftime_now is defined %}\n {%- set date_string = strftime_now(\"%d %b %Y\") %}\n {%- else %}\n {%- set date_string = \"26 Jul 2024\" %}\n {%- endif %}\n{%- endif %}\n{%- if not tools is defined %}\n {%- set tools = none %}\n{%- endif %}\n\n{#- This block extracts the system message, so we can slot it into the right place. #}\n{%- if messages[0]['role'] == 'system' %}\n {%- set system_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n{%- else %}\n {%- set system_message = \"\" %}\n{%- endif %}\n\n{#- System message #}\n{{- \"<|start_header_id|>system<|end_header_id|>\\n\\n\" }}\n{%- if tools is not none %}\n {{- \"Environment: ipython\\n\" }}\n{%- endif %}\n{{- \"Cutting Knowledge Date: December 2023\\n\" }}\n{{- \"Today Date: \" + date_string + \"\\n\\n\" }}\n{%- if tools is not none and not tools_in_user_message %}\n {{- \"You have access to the following functions. To call a function, please respond with JSON for a function call.\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\\n\\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\\n\\n\" }}\n {%- endfor %}\n{%- endif %}\n{{- system_message }}\n{{- \"<|eot_id|>\" }}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{%- if tools_in_user_message and not tools is none %}\n {#- Extract the first user message so we can plug it in here #}\n {%- if messages | length != 0 %}\n {%- set first_user_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n {%- else %}\n {{- raise_exception(\"Cannot put tools in the first user message when there's no first user message!\") }}\n{%- endif %}\n {{- '<|start_header_id|>user<|end_header_id|>\\n\\n' -}}\n {{- \"Given the following functions, please respond with a JSON for a function call \" }}\n {{- \"with its proper arguments that best answers the given prompt.\\n\\n\" }}\n {{- 'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\\n\\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\\n\\n\" }}\n {%- endfor %}\n {{- first_user_message + \"<|eot_id|>\"}}\n{%- endif %}\n\n{%- for message in messages %}\n {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}\n {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\\n\\n'+ message['content'] | trim + '<|eot_id|>' }}\n {%- elif 'tool_calls' in message %}\n {%- if not message.tool_calls|length == 1 %}\n {{- raise_exception(\"This model only supports single tool-calls at once!\") }}\n {%- endif %}\n {%- set tool_call = message.tool_calls[0].function %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}}\n {{- '{\"name\": \"' + tool_call.name + '\", ' }}\n {{- '\"parameters\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- \"}\" }}\n {{- \"<|eot_id|>\" }}\n {%- elif message.role == \"tool\" or message.role == \"ipython\" %}\n {{- \"<|start_header_id|>ipython<|end_header_id|>\\n\\n\" }}\n {%- if message.content is mapping or message.content is iterable %}\n {{- message.content | tojson }}\n {%- else %}\n {{- message.content }}\n {%- endif %}\n {{- \"<|eot_id|>\" }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' }}\n{%- endif %}\n",
|
5 |
"clean_up_tokenization_spaces": true,
|
|
|
9 |
"attention_mask"
|
10 |
],
|
11 |
"model_max_length": 131072,
|
12 |
+
"pad_token": "<|end_of_text|>",
|
13 |
"tokenizer_class": "PreTrainedTokenizerFast"
|
14 |
}
|