zstanjj commited on
Commit
dc3de94
1 Parent(s): 19fd1e2

Upload 13 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "HTML-Pruner-Llama-3.2-1B",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_llama.LlamaConfig",
8
+ "AutoModel": "modeling_llama.LlamaForCausalLM",
9
+ "AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM",
10
+ "AutoModelForSeq2SeqLM": "modeling_llama.LlamaForHTMLTreeGeneration"
11
+ },
12
+ "attention_bias": false,
13
+ "attention_dropout": 0.0,
14
+ "bos_token_id": 128000,
15
+ "eos_token_id": [
16
+ 128001,
17
+ 128008,
18
+ 128009
19
+ ],
20
+ "head_dim": 64,
21
+ "hidden_act": "silu",
22
+ "hidden_size": 2048,
23
+ "initializer_range": 0.02,
24
+ "intermediate_size": 8192,
25
+ "max_position_embeddings": 131072,
26
+ "mlp_bias": false,
27
+ "model_type": "llama",
28
+ "num_attention_heads": 32,
29
+ "num_hidden_layers": 16,
30
+ "num_key_value_heads": 8,
31
+ "pretraining_tp": 1,
32
+ "rms_norm_eps": 1e-05,
33
+ "rope_scaling": {
34
+ "factor": 32.0,
35
+ "high_freq_factor": 4.0,
36
+ "low_freq_factor": 1.0,
37
+ "original_max_position_embeddings": 8192,
38
+ "rope_type": "llama3"
39
+ },
40
+ "rope_theta": 500000.0,
41
+ "tie_word_embeddings": true,
42
+ "torch_dtype": "bfloat16",
43
+ "transformers_version": "4.45.0.dev0",
44
+ "use_cache": true,
45
+ "vocab_size": 128256,
46
+ "attn_implementation": "flash_attention_2"
47
+ }
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
configuration_llama.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 LlamaConfig(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 [`LlamaModel`]
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 = "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=128001,
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
+ **kwargs,
170
+ ):
171
+ self.vocab_size = vocab_size
172
+ self.max_position_embeddings = max_position_embeddings
173
+ self.hidden_size = hidden_size
174
+ self.intermediate_size = intermediate_size
175
+ self.num_hidden_layers = num_hidden_layers
176
+ self.num_attention_heads = num_attention_heads
177
+
178
+ # for backward compatibility
179
+ if num_key_value_heads is None:
180
+ num_key_value_heads = num_attention_heads
181
+
182
+ self.num_key_value_heads = num_key_value_heads
183
+ self.hidden_act = hidden_act
184
+ self.initializer_range = initializer_range
185
+ self.rms_norm_eps = rms_norm_eps
186
+ self.pretraining_tp = pretraining_tp
187
+ self.use_cache = use_cache
188
+ self.rope_theta = rope_theta
189
+ self.rope_scaling = rope_scaling
190
+ self.attention_bias = attention_bias
191
+ self.attention_dropout = attention_dropout
192
+ self.mlp_bias = mlp_bias
193
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
194
+ # Validate the correctness of rotary position embeddings parameters
195
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
196
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
197
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
198
+ rope_config_validation(self)
199
+
200
+ super().__init__(
201
+ pad_token_id=pad_token_id,
202
+ bos_token_id=bos_token_id,
203
+ eos_token_id=eos_token_id,
204
+ tie_word_embeddings=tie_word_embeddings,
205
+ **kwargs,
206
+ )
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 128000,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 128001,
6
+ 128008,
7
+ 128009
8
+ ],
9
+ "temperature": 0.6,
10
+ "top_p": 0.9,
11
+ "transformers_version": "4.45.0.dev0"
12
+ }
latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step381
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef427eecfe24558d8908112b54ed9ac1d1ce6f908ca1778e481c64caa9cdada7
3
+ size 2471645608
modeling_llama.py ADDED
@@ -0,0 +1,1857 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 bs4
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
33
+ from transformers.generation import GenerationMixin
34
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
35
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
36
+ from transformers.modeling_outputs import (
37
+ BaseModelOutputWithPast,
38
+ CausalLMOutputWithPast,
39
+ QuestionAnsweringModelOutput,
40
+ SequenceClassifierOutputWithPast,
41
+ TokenClassifierOutput,
42
+ )
43
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
44
+ from transformers.modeling_utils import PreTrainedModel
45
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
46
+ from transformers.utils import (
47
+ add_start_docstrings,
48
+ add_start_docstrings_to_model_forward,
49
+ is_flash_attn_greater_or_equal_2_10,
50
+ logging,
51
+ replace_return_docstrings,
52
+ )
53
+ from .configuration_llama import LlamaConfig
54
+ from collections import defaultdict
55
+ from typing import List, Tuple
56
+
57
+ import numpy as np
58
+ from anytree import Node, RenderTree
59
+ import bs4
60
+ from anytree import PreOrderIter
61
+ from anytree.exporter import DotExporter
62
+
63
+
64
+ def nodenamefunc(node):
65
+ return f"{node.name}|{node.prob}|{node.input_ids}"
66
+
67
+
68
+ class TokenDotExporter(DotExporter):
69
+ def __init__(self, node, **kwargs):
70
+ super().__init__(node, **kwargs)
71
+
72
+ def __iter__(self):
73
+ # prepare
74
+ indent = " " * self.indent
75
+ nodenamefunc = self.nodenamefunc or self._default_nodenamefunc
76
+ nodeattrfunc = self.nodeattrfunc or self._default_nodeattrfunc
77
+ edgeattrfunc = self.edgeattrfunc or self._default_edgeattrfunc
78
+ edgetypefunc = self.edgetypefunc or self._default_edgetypefunc
79
+ filter_ = self.filter_ or self._default_filter
80
+ return self.__iter(indent, nodenamefunc, nodeattrfunc, edgeattrfunc, edgetypefunc, filter_)
81
+
82
+ def __iter_nodes(self, indent, nodenamefunc, nodeattrfunc, filter_):
83
+ for node in PreOrderIter(self.node, filter_=filter_, stop=self.stop, maxlevel=self.maxlevel):
84
+ nodename = nodenamefunc(node)
85
+ nodeattr = nodeattrfunc(node)
86
+ nodeattr = " {%s}" % nodeattr if nodeattr is not None else ""
87
+ yield '%s%s' % (DotExporter.esc(nodename), nodeattr)
88
+
89
+ def __iter(self, indent, nodenamefunc, nodeattrfunc, edgeattrfunc, edgetypefunc, filter_):
90
+ for node in self.__iter_nodes(indent, nodenamefunc, nodeattrfunc, filter_):
91
+ yield node
92
+
93
+
94
+ class TokenIdNode(Node):
95
+ def __init__(self, name, parent=None, children=None, **kwargs):
96
+ super().__init__(name, parent, children, **kwargs)
97
+ self.input_ids = kwargs.get('input_ids', [])
98
+ self.prob = kwargs.get('prob', np.float32(0.0))
99
+
100
+
101
+ def split_tree(soup: bs4.BeautifulSoup, max_node_words=0) -> List[Tuple[bs4.element.Tag, List[str], bool]]:
102
+ word_count = len(soup.get_text().split())
103
+ if word_count > max_node_words:
104
+ possible_trees = [(soup, [])]
105
+ target_trees = [] # [(tag, path, is_leaf)]
106
+ # split the entire dom tee into subtrees, until the length of the subtree is less than max_node_words words
107
+ # find all possible trees
108
+ while True:
109
+ if len(possible_trees) == 0:
110
+ break
111
+ tree = possible_trees.pop(0)
112
+ tag_children = defaultdict(int)
113
+ bare_word_count = 0
114
+ # count child tags
115
+ for child in tree[0].contents:
116
+ if isinstance(child, bs4.element.Tag):
117
+ tag_children[child.name] += 1
118
+ _tag_children = {k: 0 for k in tag_children.keys()}
119
+
120
+ # check if the tree can be split
121
+ for child in tree[0].contents:
122
+ if isinstance(child, bs4.element.Tag):
123
+ # change child tag with duplicate names
124
+ if tag_children[child.name] > 1:
125
+ new_name = f"{child.name}{_tag_children[child.name]}"
126
+ new_tree = (child, tree[1] + [new_name])
127
+ _tag_children[child.name] += 1
128
+ child.name = new_name
129
+ else:
130
+ new_tree = (child, tree[1] + [child.name])
131
+ word_count = len(child.get_text().split())
132
+ # add node with more than max_node_words words, and recursion depth is less than 64
133
+ if word_count > max_node_words and len(new_tree[1]) < 64:
134
+ possible_trees.append(new_tree)
135
+ else:
136
+ target_trees.append((new_tree[0], new_tree[1], True))
137
+ else:
138
+ bare_word_count += len(str(child).split())
139
+
140
+ # add leaf node
141
+ if len(tag_children) == 0:
142
+ target_trees.append((tree[0], tree[1], True))
143
+ # add node with more than max_node_words bare words
144
+ elif bare_word_count > max_node_words:
145
+ target_trees.append((tree[0], tree[1], False))
146
+ else:
147
+ soup_children = [c for c in soup.contents if isinstance(c, bs4.element.Tag)]
148
+ if len(soup_children) == 1:
149
+ target_trees = [(soup_children[0], [soup_children[0].name], True)]
150
+ else:
151
+ # add an html tag to wrap all children
152
+ new_soup = bs4.BeautifulSoup("", 'html.parser')
153
+ new_tag = new_soup.new_tag("html")
154
+ new_soup.append(new_tag)
155
+ for child in soup_children:
156
+ new_tag.append(child)
157
+ target_trees = [(new_tag, ["html"], True)]
158
+ return target_trees
159
+
160
+ logger = logging.get_logger(__name__)
161
+
162
+ _CONFIG_FOR_DOC = "LlamaConfig"
163
+
164
+
165
+ class LlamaRMSNorm(nn.Module):
166
+ def __init__(self, hidden_size, eps=1e-6):
167
+ """
168
+ LlamaRMSNorm is equivalent to T5LayerNorm
169
+ """
170
+ super().__init__()
171
+ self.weight = nn.Parameter(torch.ones(hidden_size))
172
+ self.variance_epsilon = eps
173
+
174
+ def forward(self, hidden_states):
175
+ input_dtype = hidden_states.dtype
176
+ hidden_states = hidden_states.to(torch.float32)
177
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
178
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
179
+ return self.weight * hidden_states.to(input_dtype)
180
+
181
+ def extra_repr(self):
182
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
183
+
184
+
185
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
186
+
187
+
188
+ class LlamaRotaryEmbedding(nn.Module):
189
+ def __init__(
190
+ self,
191
+ dim=None,
192
+ max_position_embeddings=2048,
193
+ base=10000,
194
+ device=None,
195
+ scaling_factor=1.0,
196
+ rope_type="default",
197
+ config: Optional[LlamaConfig] = None,
198
+ ):
199
+ super().__init__()
200
+ # TODO (joao): remove the `if` below, only used for BC
201
+ self.rope_kwargs = {}
202
+ if config is None:
203
+ logger.warning_once(
204
+ "`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
205
+ "`config` argument. All other arguments will be removed in v4.46"
206
+ )
207
+ self.rope_kwargs = {
208
+ "rope_type": rope_type,
209
+ "factor": scaling_factor,
210
+ "dim": dim,
211
+ "base": base,
212
+ "max_position_embeddings": max_position_embeddings,
213
+ }
214
+ self.rope_type = rope_type
215
+ self.max_seq_len_cached = max_position_embeddings
216
+ self.original_max_seq_len = max_position_embeddings
217
+ else:
218
+ # BC: "rope_type" was originally "type"
219
+ if config.rope_scaling is not None:
220
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
221
+ else:
222
+ self.rope_type = "default"
223
+ self.max_seq_len_cached = config.max_position_embeddings
224
+ self.original_max_seq_len = config.max_position_embeddings
225
+
226
+ self.config = config
227
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
228
+
229
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
230
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
231
+ self.original_inv_freq = self.inv_freq
232
+
233
+ def _dynamic_frequency_update(self, position_ids, device):
234
+ """
235
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
236
+ 1 - growing beyond the cached sequence length (allow scaling)
237
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
238
+ """
239
+ seq_len = torch.max(position_ids) + 1
240
+ if seq_len > self.max_seq_len_cached: # growth
241
+ inv_freq, self.attention_scaling = self.rope_init_fn(
242
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
243
+ )
244
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
245
+ self.max_seq_len_cached = seq_len
246
+
247
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
248
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
249
+ self.max_seq_len_cached = self.original_max_seq_len
250
+
251
+ @torch.no_grad()
252
+ def forward(self, x, position_ids):
253
+ if "dynamic" in self.rope_type:
254
+ self._dynamic_frequency_update(position_ids, device=x.device)
255
+
256
+ # Core RoPE block
257
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
258
+ position_ids_expanded = position_ids[:, None, :].float()
259
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
260
+ device_type = x.device.type
261
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
262
+ with torch.autocast(device_type=device_type, enabled=False):
263
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
264
+ emb = torch.cat((freqs, freqs), dim=-1)
265
+ cos = emb.cos()
266
+ sin = emb.sin()
267
+
268
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
269
+ cos = cos * self.attention_scaling
270
+ sin = sin * self.attention_scaling
271
+
272
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
273
+
274
+
275
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
276
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
277
+
278
+ def __init__(self, *args, **kwargs):
279
+ logger.warning_once(
280
+ "`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
281
+ "`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
282
+ )
283
+ kwargs["rope_type"] = "linear"
284
+ super().__init__(*args, **kwargs)
285
+
286
+
287
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
288
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
289
+
290
+ def __init__(self, *args, **kwargs):
291
+ logger.warning_once(
292
+ "`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
293
+ "`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
294
+ "__init__)."
295
+ )
296
+ kwargs["rope_type"] = "dynamic"
297
+ super().__init__(*args, **kwargs)
298
+
299
+
300
+ def rotate_half(x):
301
+ """Rotates half the hidden dims of the input."""
302
+ x1 = x[..., : x.shape[-1] // 2]
303
+ x2 = x[..., x.shape[-1] // 2 :]
304
+ return torch.cat((-x2, x1), dim=-1)
305
+
306
+
307
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
308
+ """Applies Rotary Position Embedding to the query and key tensors.
309
+
310
+ Args:
311
+ q (`torch.Tensor`): The query tensor.
312
+ k (`torch.Tensor`): The key tensor.
313
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
314
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
315
+ position_ids (`torch.Tensor`, *optional*):
316
+ Deprecated and unused.
317
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
318
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
319
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
320
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
321
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
322
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
323
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
324
+ Returns:
325
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
326
+ """
327
+ cos = cos.unsqueeze(unsqueeze_dim)
328
+ sin = sin.unsqueeze(unsqueeze_dim)
329
+ q_embed = (q * cos) + (rotate_half(q) * sin)
330
+ k_embed = (k * cos) + (rotate_half(k) * sin)
331
+ return q_embed, k_embed
332
+
333
+
334
+ class LlamaMLP(nn.Module):
335
+ def __init__(self, config):
336
+ super().__init__()
337
+ self.config = config
338
+ self.hidden_size = config.hidden_size
339
+ self.intermediate_size = config.intermediate_size
340
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
341
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
342
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
343
+ self.act_fn = ACT2FN[config.hidden_act]
344
+
345
+ def forward(self, x):
346
+ if self.config.pretraining_tp > 1:
347
+ slice = self.intermediate_size // self.config.pretraining_tp
348
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
349
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
350
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
351
+
352
+ gate_proj = torch.cat(
353
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
354
+ )
355
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
356
+
357
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
358
+ down_proj = [
359
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
360
+ ]
361
+ down_proj = sum(down_proj)
362
+ else:
363
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
364
+
365
+ return down_proj
366
+
367
+
368
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
369
+ """
370
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
371
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
372
+ """
373
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
374
+ if n_rep == 1:
375
+ return hidden_states
376
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
377
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
378
+
379
+
380
+ class LlamaAttention(nn.Module):
381
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
382
+
383
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
384
+ super().__init__()
385
+ self.config = config
386
+ self.layer_idx = layer_idx
387
+ if layer_idx is None:
388
+ logger.warning_once(
389
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
390
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
391
+ "when creating this class."
392
+ )
393
+
394
+ self.attention_dropout = config.attention_dropout
395
+ self.hidden_size = config.hidden_size
396
+ self.num_heads = config.num_attention_heads
397
+ self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
398
+ self.num_key_value_heads = config.num_key_value_heads
399
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
400
+ self.max_position_embeddings = config.max_position_embeddings
401
+ self.rope_theta = config.rope_theta
402
+ self.is_causal = True
403
+
404
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
405
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
406
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
407
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
408
+
409
+ # TODO (joao): remove in v4.46 (RoPE is computed in the model, not in the decoder layers)
410
+ self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
411
+
412
+ def forward(
413
+ self,
414
+ hidden_states: torch.Tensor,
415
+ attention_mask: Optional[torch.Tensor] = None,
416
+ position_ids: Optional[torch.LongTensor] = None,
417
+ past_key_value: Optional[Cache] = None,
418
+ output_attentions: bool = False,
419
+ use_cache: bool = False,
420
+ cache_position: Optional[torch.LongTensor] = None,
421
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
422
+ **kwargs,
423
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
424
+ bsz, q_len, _ = hidden_states.size()
425
+
426
+ if self.config.pretraining_tp > 1:
427
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
428
+ query_slices = self.q_proj.weight.split(
429
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
430
+ )
431
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
432
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
433
+
434
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
435
+ query_states = torch.cat(query_states, dim=-1)
436
+
437
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
438
+ key_states = torch.cat(key_states, dim=-1)
439
+
440
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
441
+ value_states = torch.cat(value_states, dim=-1)
442
+
443
+ else:
444
+ query_states = self.q_proj(hidden_states)
445
+ key_states = self.k_proj(hidden_states)
446
+ value_states = self.v_proj(hidden_states)
447
+
448
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
449
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
450
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
451
+
452
+ if position_embeddings is None:
453
+ logger.warning_once(
454
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
455
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
456
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
457
+ "removed and `position_embeddings` will be mandatory."
458
+ )
459
+ cos, sin = self.rotary_emb(value_states, position_ids)
460
+ else:
461
+ cos, sin = position_embeddings
462
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
463
+
464
+ if past_key_value is not None:
465
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
466
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
467
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
468
+
469
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
470
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
471
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
472
+
473
+ if attention_mask is not None: # no matter the length, we just slice it
474
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
475
+ attn_weights = attn_weights + causal_mask
476
+
477
+ # upcast attention to fp32
478
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
479
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
480
+ attn_output = torch.matmul(attn_weights, value_states)
481
+
482
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
483
+ raise ValueError(
484
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
485
+ f" {attn_output.size()}"
486
+ )
487
+
488
+ attn_output = attn_output.transpose(1, 2).contiguous()
489
+
490
+ attn_output = attn_output.reshape(bsz, q_len, -1)
491
+
492
+ if self.config.pretraining_tp > 1:
493
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
494
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
495
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
496
+ else:
497
+ attn_output = self.o_proj(attn_output)
498
+
499
+ if not output_attentions:
500
+ attn_weights = None
501
+
502
+ return attn_output, attn_weights, past_key_value
503
+
504
+
505
+ class LlamaFlashAttention2(LlamaAttention):
506
+ """
507
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
508
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
509
+ flash attention and deal with padding tokens in case the input contains any of them.
510
+ """
511
+
512
+ def __init__(self, *args, **kwargs):
513
+ super().__init__(*args, **kwargs)
514
+
515
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
516
+ # 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.
517
+ # 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).
518
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
519
+
520
+ def forward(
521
+ self,
522
+ hidden_states: torch.Tensor,
523
+ attention_mask: Optional[torch.LongTensor] = None,
524
+ position_ids: Optional[torch.LongTensor] = None,
525
+ past_key_value: Optional[Cache] = None,
526
+ output_attentions: bool = False,
527
+ use_cache: bool = False,
528
+ cache_position: Optional[torch.LongTensor] = None,
529
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
530
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
531
+ if isinstance(past_key_value, StaticCache):
532
+ raise ValueError(
533
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
534
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
535
+ )
536
+
537
+ output_attentions = False
538
+
539
+ bsz, q_len, _ = hidden_states.size()
540
+
541
+ query_states = self.q_proj(hidden_states)
542
+ key_states = self.k_proj(hidden_states)
543
+ value_states = self.v_proj(hidden_states)
544
+
545
+ # Flash attention requires the input to have the shape
546
+ # batch_size x seq_length x head_dim x hidden_dim
547
+ # therefore we just need to keep the original shape
548
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
549
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
550
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
551
+
552
+ if position_embeddings is None:
553
+ logger.warning_once(
554
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
555
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
556
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
557
+ "removed and `position_embeddings` will be mandatory."
558
+ )
559
+ cos, sin = self.rotary_emb(value_states, position_ids)
560
+ else:
561
+ cos, sin = position_embeddings
562
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
563
+
564
+ if past_key_value is not None:
565
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
566
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
567
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
568
+
569
+ # 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
570
+ # to be able to avoid many of these transpose/reshape/view.
571
+ query_states = query_states.transpose(1, 2)
572
+ key_states = key_states.transpose(1, 2)
573
+ value_states = value_states.transpose(1, 2)
574
+
575
+ dropout_rate = self.attention_dropout if self.training else 0.0
576
+
577
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
578
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
579
+ # cast them back in the correct dtype just to be sure everything works as expected.
580
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
581
+ # in fp32. (LlamaRMSNorm handles it correctly)
582
+
583
+ input_dtype = query_states.dtype
584
+ if input_dtype == torch.float32:
585
+ if torch.is_autocast_enabled():
586
+ target_dtype = torch.get_autocast_gpu_dtype()
587
+ # Handle the case where the model is quantized
588
+ elif hasattr(self.config, "_pre_quantization_dtype"):
589
+ target_dtype = self.config._pre_quantization_dtype
590
+ else:
591
+ target_dtype = self.q_proj.weight.dtype
592
+
593
+ logger.warning_once(
594
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
595
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
596
+ f" {target_dtype}."
597
+ )
598
+
599
+ query_states = query_states.to(target_dtype)
600
+ key_states = key_states.to(target_dtype)
601
+ value_states = value_states.to(target_dtype)
602
+
603
+ attn_output = _flash_attention_forward(
604
+ query_states,
605
+ key_states,
606
+ value_states,
607
+ attention_mask,
608
+ q_len,
609
+ position_ids=position_ids,
610
+ dropout=dropout_rate,
611
+ sliding_window=getattr(self, "sliding_window", None),
612
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
613
+ is_causal=self.is_causal,
614
+ )
615
+
616
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
617
+ attn_output = self.o_proj(attn_output)
618
+
619
+ if not output_attentions:
620
+ attn_weights = None
621
+
622
+ return attn_output, attn_weights, past_key_value
623
+
624
+
625
+ class LlamaSdpaAttention(LlamaAttention):
626
+ """
627
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
628
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
629
+ SDPA API.
630
+ """
631
+
632
+ # Adapted from LlamaAttention.forward
633
+ def forward(
634
+ self,
635
+ hidden_states: torch.Tensor,
636
+ attention_mask: Optional[torch.Tensor] = None,
637
+ position_ids: Optional[torch.LongTensor] = None,
638
+ past_key_value: Optional[Cache] = None,
639
+ output_attentions: bool = False,
640
+ use_cache: bool = False,
641
+ cache_position: Optional[torch.LongTensor] = None,
642
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
643
+ **kwargs,
644
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
645
+ if output_attentions:
646
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
647
+ logger.warning_once(
648
+ "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
649
+ '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.'
650
+ )
651
+ return super().forward(
652
+ hidden_states=hidden_states,
653
+ attention_mask=attention_mask,
654
+ position_ids=position_ids,
655
+ past_key_value=past_key_value,
656
+ output_attentions=output_attentions,
657
+ use_cache=use_cache,
658
+ cache_position=cache_position,
659
+ position_embeddings=position_embeddings,
660
+ )
661
+
662
+ bsz, q_len, _ = hidden_states.size()
663
+
664
+ query_states = self.q_proj(hidden_states)
665
+ key_states = self.k_proj(hidden_states)
666
+ value_states = self.v_proj(hidden_states)
667
+
668
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
669
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
670
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
671
+
672
+ if position_embeddings is None:
673
+ logger.warning_once(
674
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
675
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
676
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
677
+ "removed and `position_embeddings` will be mandatory."
678
+ )
679
+ cos, sin = self.rotary_emb(value_states, position_ids)
680
+ else:
681
+ cos, sin = position_embeddings
682
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
683
+
684
+ if past_key_value is not None:
685
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
686
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
687
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
688
+
689
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
690
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
691
+
692
+ causal_mask = attention_mask
693
+ if attention_mask is not None:
694
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
695
+
696
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
697
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
698
+ if query_states.device.type == "cuda" and causal_mask is not None:
699
+ query_states = query_states.contiguous()
700
+ key_states = key_states.contiguous()
701
+ value_states = value_states.contiguous()
702
+
703
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
704
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
705
+ is_causal = True if causal_mask is None and q_len > 1 else False
706
+
707
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
708
+ query_states,
709
+ key_states,
710
+ value_states,
711
+ attn_mask=causal_mask,
712
+ dropout_p=self.attention_dropout if self.training else 0.0,
713
+ is_causal=is_causal,
714
+ )
715
+
716
+ attn_output = attn_output.transpose(1, 2).contiguous()
717
+ attn_output = attn_output.view(bsz, q_len, -1)
718
+
719
+ attn_output = self.o_proj(attn_output)
720
+
721
+ return attn_output, None, past_key_value
722
+
723
+
724
+ LLAMA_ATTENTION_CLASSES = {
725
+ "eager": LlamaAttention,
726
+ "flash_attention_2": LlamaFlashAttention2,
727
+ "sdpa": LlamaSdpaAttention,
728
+ }
729
+
730
+
731
+ class LlamaDecoderLayer(nn.Module):
732
+ def __init__(self, config: LlamaConfig, layer_idx: int):
733
+ super().__init__()
734
+ self.hidden_size = config.hidden_size
735
+
736
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
737
+
738
+ self.mlp = LlamaMLP(config)
739
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
740
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
741
+
742
+ def forward(
743
+ self,
744
+ hidden_states: torch.Tensor,
745
+ attention_mask: Optional[torch.Tensor] = None,
746
+ position_ids: Optional[torch.LongTensor] = None,
747
+ past_key_value: Optional[Cache] = None,
748
+ output_attentions: Optional[bool] = False,
749
+ use_cache: Optional[bool] = False,
750
+ cache_position: Optional[torch.LongTensor] = None,
751
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
752
+ **kwargs,
753
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
754
+ """
755
+ Args:
756
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
757
+ attention_mask (`torch.FloatTensor`, *optional*):
758
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
759
+ query_sequence_length, key_sequence_length)` if default attention is used.
760
+ output_attentions (`bool`, *optional*):
761
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
762
+ returned tensors for more detail.
763
+ use_cache (`bool`, *optional*):
764
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
765
+ (see `past_key_values`).
766
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
767
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
768
+ Indices depicting the position of the input sequence tokens in the sequence
769
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
770
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
771
+ with `head_dim` being the embedding dimension of each attention head.
772
+ kwargs (`dict`, *optional*):
773
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
774
+ into the model
775
+ """
776
+ residual = hidden_states
777
+
778
+ hidden_states = self.input_layernorm(hidden_states)
779
+
780
+ # Self Attention
781
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
782
+ hidden_states=hidden_states,
783
+ attention_mask=attention_mask,
784
+ position_ids=position_ids,
785
+ past_key_value=past_key_value,
786
+ output_attentions=output_attentions,
787
+ use_cache=use_cache,
788
+ cache_position=cache_position,
789
+ position_embeddings=position_embeddings,
790
+ **kwargs,
791
+ )
792
+ hidden_states = residual + hidden_states
793
+
794
+ # Fully Connected
795
+ residual = hidden_states
796
+ hidden_states = self.post_attention_layernorm(hidden_states)
797
+ hidden_states = self.mlp(hidden_states)
798
+ hidden_states = residual + hidden_states
799
+
800
+ outputs = (hidden_states,)
801
+
802
+ if output_attentions:
803
+ outputs += (self_attn_weights,)
804
+
805
+ if use_cache:
806
+ outputs += (present_key_value,)
807
+
808
+ return outputs
809
+
810
+
811
+ LLAMA_START_DOCSTRING = r"""
812
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
813
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
814
+ etc.)
815
+
816
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
817
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
818
+ and behavior.
819
+
820
+ Parameters:
821
+ config ([`LlamaConfig`]):
822
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
823
+ load the weights associated with the model, only the configuration. Check out the
824
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
825
+ """
826
+
827
+
828
+ @add_start_docstrings(
829
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
830
+ LLAMA_START_DOCSTRING,
831
+ )
832
+ class LlamaPreTrainedModel(PreTrainedModel):
833
+ config_class = LlamaConfig
834
+ base_model_prefix = "model"
835
+ supports_gradient_checkpointing = True
836
+ _no_split_modules = ["LlamaDecoderLayer"]
837
+ _skip_keys_device_placement = ["past_key_values"]
838
+ _supports_flash_attn_2 = True
839
+ _supports_sdpa = True
840
+ _supports_cache_class = True
841
+ _supports_quantized_cache = True
842
+ _supports_static_cache = True
843
+
844
+ def _init_weights(self, module):
845
+ std = self.config.initializer_range
846
+ if isinstance(module, nn.Linear):
847
+ module.weight.data.normal_(mean=0.0, std=std)
848
+ if module.bias is not None:
849
+ module.bias.data.zero_()
850
+ elif isinstance(module, nn.Embedding):
851
+ module.weight.data.normal_(mean=0.0, std=std)
852
+ if module.padding_idx is not None:
853
+ module.weight.data[module.padding_idx].zero_()
854
+
855
+
856
+ LLAMA_INPUTS_DOCSTRING = r"""
857
+ Args:
858
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
859
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
860
+ it.
861
+
862
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
863
+ [`PreTrainedTokenizer.__call__`] for details.
864
+
865
+ [What are input IDs?](../glossary#input-ids)
866
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
867
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
868
+
869
+ - 1 for tokens that are **not masked**,
870
+ - 0 for tokens that are **masked**.
871
+
872
+ [What are attention masks?](../glossary#attention-mask)
873
+
874
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
875
+ [`PreTrainedTokenizer.__call__`] for details.
876
+
877
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
878
+ `past_key_values`).
879
+
880
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
881
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
882
+ information on the default strategy.
883
+
884
+ - 1 indicates the head is **not masked**,
885
+ - 0 indicates the head is **masked**.
886
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
887
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
888
+ config.n_positions - 1]`.
889
+
890
+ [What are position IDs?](../glossary#position-ids)
891
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
892
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
893
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
894
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
895
+
896
+ Two formats are allowed:
897
+ - a [`~cache_utils.Cache`] instance, see our
898
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
899
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
900
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
901
+ cache format.
902
+
903
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
904
+ legacy cache format will be returned.
905
+
906
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
907
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
908
+ of shape `(batch_size, sequence_length)`.
909
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
910
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
911
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
912
+ model's internal embedding lookup matrix.
913
+ use_cache (`bool`, *optional*):
914
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
915
+ `past_key_values`).
916
+ output_attentions (`bool`, *optional*):
917
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
918
+ tensors for more detail.
919
+ output_hidden_states (`bool`, *optional*):
920
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
921
+ more detail.
922
+ return_dict (`bool`, *optional*):
923
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
924
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
925
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
926
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
927
+ the complete sequence length.
928
+ """
929
+
930
+
931
+ @add_start_docstrings(
932
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
933
+ LLAMA_START_DOCSTRING,
934
+ )
935
+ class LlamaModel(LlamaPreTrainedModel):
936
+ """
937
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
938
+
939
+ Args:
940
+ config: LlamaConfig
941
+ """
942
+
943
+ def __init__(self, config: LlamaConfig):
944
+ super().__init__(config)
945
+ self.padding_idx = config.pad_token_id
946
+ self.vocab_size = config.vocab_size
947
+
948
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
949
+ self.layers = nn.ModuleList(
950
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
951
+ )
952
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
953
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
954
+ self.gradient_checkpointing = False
955
+
956
+ # Initialize weights and apply final processing
957
+ self.post_init()
958
+
959
+ def get_input_embeddings(self):
960
+ return self.embed_tokens
961
+
962
+ def set_input_embeddings(self, value):
963
+ self.embed_tokens = value
964
+
965
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
966
+ def forward(
967
+ self,
968
+ input_ids: torch.LongTensor = None,
969
+ attention_mask: Optional[torch.Tensor] = None,
970
+ position_ids: Optional[torch.LongTensor] = None,
971
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
972
+ inputs_embeds: Optional[torch.FloatTensor] = None,
973
+ use_cache: Optional[bool] = None,
974
+ output_attentions: Optional[bool] = None,
975
+ output_hidden_states: Optional[bool] = None,
976
+ return_dict: Optional[bool] = None,
977
+ cache_position: Optional[torch.LongTensor] = None,
978
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
979
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
980
+ output_hidden_states = (
981
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
982
+ )
983
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
984
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
985
+
986
+ if (input_ids is None) ^ (inputs_embeds is not None):
987
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
988
+
989
+ if self.gradient_checkpointing and self.training and use_cache:
990
+ logger.warning_once(
991
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
992
+ )
993
+ use_cache = False
994
+
995
+ if inputs_embeds is None:
996
+ inputs_embeds = self.embed_tokens(input_ids)
997
+
998
+ # kept for BC (non `Cache` `past_key_values` inputs)
999
+ return_legacy_cache = False
1000
+ if use_cache and not isinstance(past_key_values, Cache):
1001
+ return_legacy_cache = True
1002
+ if past_key_values is None:
1003
+ past_key_values = DynamicCache()
1004
+ else:
1005
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1006
+ logger.warning_once(
1007
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
1008
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
1009
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
1010
+ )
1011
+
1012
+ if cache_position is None:
1013
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1014
+ cache_position = torch.arange(
1015
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1016
+ )
1017
+ if position_ids is None:
1018
+ position_ids = cache_position.unsqueeze(0)
1019
+
1020
+ causal_mask = self._update_causal_mask(
1021
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1022
+ )
1023
+ hidden_states = inputs_embeds
1024
+
1025
+ # create position embeddings to be shared across the decoder layers
1026
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1027
+
1028
+ # decoder layers
1029
+ all_hidden_states = () if output_hidden_states else None
1030
+ all_self_attns = () if output_attentions else None
1031
+ next_decoder_cache = None
1032
+
1033
+ for decoder_layer in self.layers:
1034
+ if output_hidden_states:
1035
+ all_hidden_states += (hidden_states,)
1036
+
1037
+ if self.gradient_checkpointing and self.training:
1038
+ layer_outputs = self._gradient_checkpointing_func(
1039
+ decoder_layer.__call__,
1040
+ hidden_states,
1041
+ causal_mask,
1042
+ position_ids,
1043
+ past_key_values,
1044
+ output_attentions,
1045
+ use_cache,
1046
+ cache_position,
1047
+ position_embeddings,
1048
+ )
1049
+ else:
1050
+ layer_outputs = decoder_layer(
1051
+ hidden_states,
1052
+ attention_mask=causal_mask,
1053
+ position_ids=position_ids,
1054
+ past_key_value=past_key_values,
1055
+ output_attentions=output_attentions,
1056
+ use_cache=use_cache,
1057
+ cache_position=cache_position,
1058
+ position_embeddings=position_embeddings,
1059
+ )
1060
+
1061
+ hidden_states = layer_outputs[0]
1062
+
1063
+ if use_cache:
1064
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1065
+
1066
+ if output_attentions:
1067
+ all_self_attns += (layer_outputs[1],)
1068
+
1069
+ hidden_states = self.norm(hidden_states)
1070
+
1071
+ # add hidden states from the last decoder layer
1072
+ if output_hidden_states:
1073
+ all_hidden_states += (hidden_states,)
1074
+
1075
+ next_cache = next_decoder_cache if use_cache else None
1076
+ if return_legacy_cache:
1077
+ next_cache = next_cache.to_legacy_cache()
1078
+
1079
+ if not return_dict:
1080
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1081
+ return BaseModelOutputWithPast(
1082
+ last_hidden_state=hidden_states,
1083
+ past_key_values=next_cache,
1084
+ hidden_states=all_hidden_states,
1085
+ attentions=all_self_attns,
1086
+ )
1087
+
1088
+ def _update_causal_mask(
1089
+ self,
1090
+ attention_mask: torch.Tensor,
1091
+ input_tensor: torch.Tensor,
1092
+ cache_position: torch.Tensor,
1093
+ past_key_values: Cache,
1094
+ output_attentions: bool,
1095
+ ):
1096
+ if self.config._attn_implementation == "flash_attention_2":
1097
+ if attention_mask is not None and 0.0 in attention_mask:
1098
+ return attention_mask
1099
+ return None
1100
+
1101
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1102
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1103
+ # to infer the attention mask.
1104
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1105
+ using_static_cache = isinstance(past_key_values, StaticCache)
1106
+
1107
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1108
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1109
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1110
+ attention_mask,
1111
+ inputs_embeds=input_tensor,
1112
+ past_key_values_length=past_seen_tokens,
1113
+ is_training=self.training,
1114
+ ):
1115
+ return None
1116
+
1117
+ dtype, device = input_tensor.dtype, input_tensor.device
1118
+ sequence_length = input_tensor.shape[1]
1119
+ if using_static_cache:
1120
+ target_length = past_key_values.get_max_cache_shape()
1121
+ else:
1122
+ target_length = (
1123
+ attention_mask.shape[-1]
1124
+ if isinstance(attention_mask, torch.Tensor)
1125
+ else past_seen_tokens + sequence_length + 1
1126
+ )
1127
+
1128
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1129
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1130
+ attention_mask,
1131
+ sequence_length=sequence_length,
1132
+ target_length=target_length,
1133
+ dtype=dtype,
1134
+ device=device,
1135
+ cache_position=cache_position,
1136
+ batch_size=input_tensor.shape[0],
1137
+ )
1138
+
1139
+ if (
1140
+ self.config._attn_implementation == "sdpa"
1141
+ and attention_mask is not None
1142
+ and attention_mask.device.type == "cuda"
1143
+ and not output_attentions
1144
+ ):
1145
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1146
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1147
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1148
+ min_dtype = torch.finfo(dtype).min
1149
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1150
+
1151
+ return causal_mask
1152
+
1153
+ @staticmethod
1154
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1155
+ attention_mask: torch.Tensor,
1156
+ sequence_length: int,
1157
+ target_length: int,
1158
+ dtype: torch.dtype,
1159
+ device: torch.device,
1160
+ cache_position: torch.Tensor,
1161
+ batch_size: int,
1162
+ ):
1163
+ """
1164
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1165
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1166
+
1167
+ Args:
1168
+ attention_mask (`torch.Tensor`):
1169
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1170
+ `(batch_size, 1, query_length, key_value_length)`.
1171
+ sequence_length (`int`):
1172
+ The sequence length being processed.
1173
+ target_length (`int`):
1174
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1175
+ to account for the 0 padding, the part of the cache that is not filled yet.
1176
+ dtype (`torch.dtype`):
1177
+ The dtype to use for the 4D attention mask.
1178
+ device (`torch.device`):
1179
+ The device to plcae the 4D attention mask on.
1180
+ cache_position (`torch.Tensor`):
1181
+ Indices depicting the position of the input sequence tokens in the sequence.
1182
+ batch_size (`torch.Tensor`):
1183
+ Batch size.
1184
+ """
1185
+ if attention_mask is not None and attention_mask.dim() == 4:
1186
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1187
+ causal_mask = attention_mask
1188
+ else:
1189
+ min_dtype = torch.finfo(dtype).min
1190
+ causal_mask = torch.full(
1191
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1192
+ )
1193
+ if sequence_length != 1:
1194
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1195
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1196
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1197
+ if attention_mask is not None:
1198
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1199
+ mask_length = attention_mask.shape[-1]
1200
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1201
+ padding_mask = padding_mask == 0
1202
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1203
+ padding_mask, min_dtype
1204
+ )
1205
+
1206
+ return causal_mask
1207
+
1208
+
1209
+ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
1210
+ _tied_weights_keys = ["lm_head.weight"]
1211
+
1212
+ def __init__(self, config):
1213
+ super().__init__(config)
1214
+ self.model = LlamaModel(config)
1215
+ self.vocab_size = config.vocab_size
1216
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1217
+
1218
+ # Initialize weights and apply final processing
1219
+ self.post_init()
1220
+
1221
+ def get_input_embeddings(self):
1222
+ return self.model.embed_tokens
1223
+
1224
+ def set_input_embeddings(self, value):
1225
+ self.model.embed_tokens = value
1226
+
1227
+ def get_output_embeddings(self):
1228
+ return self.lm_head
1229
+
1230
+ def set_output_embeddings(self, new_embeddings):
1231
+ self.lm_head = new_embeddings
1232
+
1233
+ def set_decoder(self, decoder):
1234
+ self.model = decoder
1235
+
1236
+ def get_decoder(self):
1237
+ return self.model
1238
+
1239
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1240
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1241
+ def forward(
1242
+ self,
1243
+ input_ids: torch.LongTensor = None,
1244
+ attention_mask: Optional[torch.Tensor] = None,
1245
+ position_ids: Optional[torch.LongTensor] = None,
1246
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1247
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1248
+ labels: Optional[torch.LongTensor] = None,
1249
+ use_cache: Optional[bool] = None,
1250
+ output_attentions: Optional[bool] = None,
1251
+ output_hidden_states: Optional[bool] = None,
1252
+ return_dict: Optional[bool] = None,
1253
+ cache_position: Optional[torch.LongTensor] = None,
1254
+ num_logits_to_keep: int = 0,
1255
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1256
+ r"""
1257
+ Args:
1258
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1259
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1260
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1261
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1262
+
1263
+ num_logits_to_keep (`int`, *optional*):
1264
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1265
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1266
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1267
+
1268
+ Returns:
1269
+
1270
+ Example:
1271
+
1272
+ ```python
1273
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1274
+
1275
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1276
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1277
+
1278
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1279
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1280
+
1281
+ >>> # Generate
1282
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1283
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1284
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1285
+ ```"""
1286
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1287
+ output_hidden_states = (
1288
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1289
+ )
1290
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1291
+
1292
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1293
+ outputs = self.model(
1294
+ input_ids=input_ids,
1295
+ attention_mask=attention_mask,
1296
+ position_ids=position_ids,
1297
+ past_key_values=past_key_values,
1298
+ inputs_embeds=inputs_embeds,
1299
+ use_cache=use_cache,
1300
+ output_attentions=output_attentions,
1301
+ output_hidden_states=output_hidden_states,
1302
+ return_dict=return_dict,
1303
+ cache_position=cache_position,
1304
+ )
1305
+
1306
+ hidden_states = outputs[0]
1307
+ if self.config.pretraining_tp > 1:
1308
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1309
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1310
+ logits = torch.cat(logits, dim=-1)
1311
+ else:
1312
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1313
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1314
+
1315
+ loss = None
1316
+ if labels is not None:
1317
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1318
+ logits = logits.float()
1319
+ # Shift so that tokens < n predict n
1320
+ shift_logits = logits[..., :-1, :].contiguous()
1321
+ shift_labels = labels[..., 1:].contiguous()
1322
+ # Flatten the tokens
1323
+ loss_fct = CrossEntropyLoss()
1324
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1325
+ shift_labels = shift_labels.view(-1)
1326
+ # Enable model parallelism
1327
+ shift_labels = shift_labels.to(shift_logits.device)
1328
+ loss = loss_fct(shift_logits, shift_labels)
1329
+
1330
+ if not return_dict:
1331
+ output = (logits,) + outputs[1:]
1332
+ return (loss,) + output if loss is not None else output
1333
+
1334
+ return CausalLMOutputWithPast(
1335
+ loss=loss,
1336
+ logits=logits,
1337
+ past_key_values=outputs.past_key_values,
1338
+ hidden_states=outputs.hidden_states,
1339
+ attentions=outputs.attentions,
1340
+ )
1341
+
1342
+
1343
+ @add_start_docstrings(
1344
+ """
1345
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1346
+
1347
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1348
+ (e.g. GPT-2) do.
1349
+
1350
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1351
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1352
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1353
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1354
+ each row of the batch).
1355
+ """,
1356
+ LLAMA_START_DOCSTRING,
1357
+ )
1358
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1359
+ def __init__(self, config):
1360
+ super().__init__(config)
1361
+ self.num_labels = config.num_labels
1362
+ self.model = LlamaModel(config)
1363
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1364
+
1365
+ # Initialize weights and apply final processing
1366
+ self.post_init()
1367
+
1368
+ def get_input_embeddings(self):
1369
+ return self.model.embed_tokens
1370
+
1371
+ def set_input_embeddings(self, value):
1372
+ self.model.embed_tokens = value
1373
+
1374
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1375
+ def forward(
1376
+ self,
1377
+ input_ids: Optional[torch.LongTensor] = None,
1378
+ attention_mask: Optional[torch.Tensor] = None,
1379
+ position_ids: Optional[torch.LongTensor] = None,
1380
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1381
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1382
+ labels: Optional[torch.LongTensor] = None,
1383
+ use_cache: Optional[bool] = None,
1384
+ output_attentions: Optional[bool] = None,
1385
+ output_hidden_states: Optional[bool] = None,
1386
+ return_dict: Optional[bool] = None,
1387
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1388
+ r"""
1389
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1390
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1391
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1392
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1393
+ """
1394
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1395
+
1396
+ transformer_outputs = self.model(
1397
+ input_ids,
1398
+ attention_mask=attention_mask,
1399
+ position_ids=position_ids,
1400
+ past_key_values=past_key_values,
1401
+ inputs_embeds=inputs_embeds,
1402
+ use_cache=use_cache,
1403
+ output_attentions=output_attentions,
1404
+ output_hidden_states=output_hidden_states,
1405
+ return_dict=return_dict,
1406
+ )
1407
+ hidden_states = transformer_outputs[0]
1408
+ logits = self.score(hidden_states)
1409
+
1410
+ if input_ids is not None:
1411
+ batch_size = input_ids.shape[0]
1412
+ else:
1413
+ batch_size = inputs_embeds.shape[0]
1414
+
1415
+ if self.config.pad_token_id is None and batch_size != 1:
1416
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1417
+ if self.config.pad_token_id is None:
1418
+ sequence_lengths = -1
1419
+ else:
1420
+ if input_ids is not None:
1421
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1422
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1423
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1424
+ sequence_lengths = sequence_lengths.to(logits.device)
1425
+ else:
1426
+ sequence_lengths = -1
1427
+
1428
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1429
+
1430
+ loss = None
1431
+ if labels is not None:
1432
+ labels = labels.to(logits.device)
1433
+ if self.config.problem_type is None:
1434
+ if self.num_labels == 1:
1435
+ self.config.problem_type = "regression"
1436
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1437
+ self.config.problem_type = "single_label_classification"
1438
+ else:
1439
+ self.config.problem_type = "multi_label_classification"
1440
+
1441
+ if self.config.problem_type == "regression":
1442
+ loss_fct = MSELoss()
1443
+ if self.num_labels == 1:
1444
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1445
+ else:
1446
+ loss = loss_fct(pooled_logits, labels)
1447
+ elif self.config.problem_type == "single_label_classification":
1448
+ loss_fct = CrossEntropyLoss()
1449
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1450
+ elif self.config.problem_type == "multi_label_classification":
1451
+ loss_fct = BCEWithLogitsLoss()
1452
+ loss = loss_fct(pooled_logits, labels)
1453
+ if not return_dict:
1454
+ output = (pooled_logits,) + transformer_outputs[1:]
1455
+ return ((loss,) + output) if loss is not None else output
1456
+
1457
+ return SequenceClassifierOutputWithPast(
1458
+ loss=loss,
1459
+ logits=pooled_logits,
1460
+ past_key_values=transformer_outputs.past_key_values,
1461
+ hidden_states=transformer_outputs.hidden_states,
1462
+ attentions=transformer_outputs.attentions,
1463
+ )
1464
+
1465
+
1466
+ @add_start_docstrings(
1467
+ """
1468
+ The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
1469
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1470
+ """,
1471
+ LLAMA_START_DOCSTRING,
1472
+ )
1473
+ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1474
+ base_model_prefix = "transformer"
1475
+
1476
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
1477
+ def __init__(self, config):
1478
+ super().__init__(config)
1479
+ self.transformer = LlamaModel(config)
1480
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1481
+
1482
+ # Initialize weights and apply final processing
1483
+ self.post_init()
1484
+
1485
+ def get_input_embeddings(self):
1486
+ return self.transformer.embed_tokens
1487
+
1488
+ def set_input_embeddings(self, value):
1489
+ self.transformer.embed_tokens = value
1490
+
1491
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1492
+ def forward(
1493
+ self,
1494
+ input_ids: Optional[torch.LongTensor] = None,
1495
+ attention_mask: Optional[torch.FloatTensor] = None,
1496
+ position_ids: Optional[torch.LongTensor] = None,
1497
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1498
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1499
+ start_positions: Optional[torch.LongTensor] = None,
1500
+ end_positions: Optional[torch.LongTensor] = None,
1501
+ output_attentions: Optional[bool] = None,
1502
+ output_hidden_states: Optional[bool] = None,
1503
+ return_dict: Optional[bool] = None,
1504
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1505
+ r"""
1506
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1507
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1508
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1509
+ are not taken into account for computing the loss.
1510
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1511
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1512
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1513
+ are not taken into account for computing the loss.
1514
+ """
1515
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1516
+
1517
+ outputs = self.transformer(
1518
+ input_ids,
1519
+ attention_mask=attention_mask,
1520
+ position_ids=position_ids,
1521
+ past_key_values=past_key_values,
1522
+ inputs_embeds=inputs_embeds,
1523
+ output_attentions=output_attentions,
1524
+ output_hidden_states=output_hidden_states,
1525
+ return_dict=return_dict,
1526
+ )
1527
+
1528
+ sequence_output = outputs[0]
1529
+
1530
+ logits = self.qa_outputs(sequence_output)
1531
+ start_logits, end_logits = logits.split(1, dim=-1)
1532
+ start_logits = start_logits.squeeze(-1).contiguous()
1533
+ end_logits = end_logits.squeeze(-1).contiguous()
1534
+
1535
+ total_loss = None
1536
+ if start_positions is not None and end_positions is not None:
1537
+ # If we are on multi-GPU, split add a dimension
1538
+ if len(start_positions.size()) > 1:
1539
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1540
+ if len(end_positions.size()) > 1:
1541
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1542
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1543
+ ignored_index = start_logits.size(1)
1544
+ start_positions = start_positions.clamp(0, ignored_index)
1545
+ end_positions = end_positions.clamp(0, ignored_index)
1546
+
1547
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1548
+ start_loss = loss_fct(start_logits, start_positions)
1549
+ end_loss = loss_fct(end_logits, end_positions)
1550
+ total_loss = (start_loss + end_loss) / 2
1551
+
1552
+ if not return_dict:
1553
+ output = (start_logits, end_logits) + outputs[2:]
1554
+ return ((total_loss,) + output) if total_loss is not None else output
1555
+
1556
+ return QuestionAnsweringModelOutput(
1557
+ loss=total_loss,
1558
+ start_logits=start_logits,
1559
+ end_logits=end_logits,
1560
+ hidden_states=outputs.hidden_states,
1561
+ attentions=outputs.attentions,
1562
+ )
1563
+
1564
+
1565
+ @add_start_docstrings(
1566
+ """
1567
+ The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1568
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1569
+ """,
1570
+ LLAMA_START_DOCSTRING,
1571
+ )
1572
+ class LlamaForTokenClassification(LlamaPreTrainedModel):
1573
+ def __init__(self, config):
1574
+ super().__init__(config)
1575
+ self.num_labels = config.num_labels
1576
+ self.model = LlamaModel(config)
1577
+ if getattr(config, "classifier_dropout", None) is not None:
1578
+ classifier_dropout = config.classifier_dropout
1579
+ elif getattr(config, "hidden_dropout", None) is not None:
1580
+ classifier_dropout = config.hidden_dropout
1581
+ else:
1582
+ classifier_dropout = 0.1
1583
+ self.dropout = nn.Dropout(classifier_dropout)
1584
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1585
+
1586
+ # Initialize weights and apply final processing
1587
+ self.post_init()
1588
+
1589
+ def get_input_embeddings(self):
1590
+ return self.model.embed_tokens
1591
+
1592
+ def set_input_embeddings(self, value):
1593
+ self.model.embed_tokens = value
1594
+
1595
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1596
+ def forward(
1597
+ self,
1598
+ input_ids: Optional[torch.LongTensor] = None,
1599
+ attention_mask: Optional[torch.Tensor] = None,
1600
+ position_ids: Optional[torch.LongTensor] = None,
1601
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1602
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1603
+ labels: Optional[torch.LongTensor] = None,
1604
+ use_cache: Optional[bool] = None,
1605
+ output_attentions: Optional[bool] = None,
1606
+ output_hidden_states: Optional[bool] = None,
1607
+ return_dict: Optional[bool] = None,
1608
+ ) -> Union[Tuple, TokenClassifierOutput]:
1609
+ r"""
1610
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1611
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1612
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1613
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1614
+ """
1615
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1616
+
1617
+ outputs = self.model(
1618
+ input_ids,
1619
+ attention_mask=attention_mask,
1620
+ position_ids=position_ids,
1621
+ past_key_values=past_key_values,
1622
+ inputs_embeds=inputs_embeds,
1623
+ use_cache=use_cache,
1624
+ output_attentions=output_attentions,
1625
+ output_hidden_states=output_hidden_states,
1626
+ return_dict=return_dict,
1627
+ )
1628
+ sequence_output = outputs[0]
1629
+ sequence_output = self.dropout(sequence_output)
1630
+ logits = self.score(sequence_output)
1631
+
1632
+ loss = None
1633
+ if labels is not None:
1634
+ loss_fct = CrossEntropyLoss()
1635
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1636
+
1637
+ if not return_dict:
1638
+ output = (logits,) + outputs[2:]
1639
+ return ((loss,) + output) if loss is not None else output
1640
+
1641
+ return TokenClassifierOutput(
1642
+ loss=loss,
1643
+ logits=logits,
1644
+ hidden_states=outputs.hidden_states,
1645
+ attentions=outputs.attentions,
1646
+ )
1647
+
1648
+
1649
+ class LlamaForHTMLTreeGeneration(LlamaPreTrainedModel):
1650
+
1651
+ def __init__(self, config):
1652
+ super().__init__(config)
1653
+ self.model = LlamaModel(config)
1654
+ self.vocab_size = config.vocab_size
1655
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1656
+
1657
+ # Initialize weights and apply final processing
1658
+ self.post_init()
1659
+
1660
+ def get_input_embeddings(self):
1661
+ return self.model.embed_tokens
1662
+
1663
+ def set_input_embeddings(self, value):
1664
+ self.model.embed_tokens = value
1665
+
1666
+ def get_output_embeddings(self):
1667
+ return self.lm_head
1668
+
1669
+ def set_output_embeddings(self, new_embeddings):
1670
+ self.lm_head = new_embeddings
1671
+
1672
+ def set_decoder(self, decoder):
1673
+ self.model = decoder
1674
+
1675
+ def get_decoder(self):
1676
+ return self.model
1677
+
1678
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1679
+ def forward(
1680
+ self,
1681
+ input_ids: torch.LongTensor = None,
1682
+ attention_mask: Optional[torch.Tensor] = None,
1683
+ position_ids: Optional[torch.LongTensor] = None,
1684
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1685
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1686
+ labels: Optional[torch.LongTensor] = None,
1687
+ use_cache: Optional[bool] = None,
1688
+ output_attentions: Optional[bool] = None,
1689
+ output_hidden_states: Optional[bool] = None,
1690
+ return_dict: Optional[bool] = None,
1691
+ cache_position: Optional[torch.LongTensor] = None,
1692
+ num_logits_to_keep: int = 0,
1693
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1694
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1695
+ output_hidden_states = (
1696
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1697
+ )
1698
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1699
+
1700
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1701
+ outputs = self.model(
1702
+ input_ids=input_ids,
1703
+ attention_mask=attention_mask,
1704
+ position_ids=position_ids,
1705
+ past_key_values=past_key_values,
1706
+ inputs_embeds=inputs_embeds,
1707
+ use_cache=use_cache,
1708
+ output_attentions=output_attentions,
1709
+ output_hidden_states=output_hidden_states,
1710
+ return_dict=return_dict,
1711
+ cache_position=cache_position,
1712
+ )
1713
+
1714
+ hidden_states = outputs[0]
1715
+ if self.config.pretraining_tp > 1:
1716
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1717
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1718
+ logits = torch.cat(logits, dim=-1)
1719
+ else:
1720
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1721
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1722
+
1723
+ loss = None
1724
+ if labels is not None:
1725
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1726
+ logits = logits.float()
1727
+ # Shift so that tokens < n predict n
1728
+ shift_logits = logits[..., :-1, :].contiguous()
1729
+ shift_labels = labels[..., 1:].contiguous()
1730
+ # Flatten the tokens
1731
+ loss_fct = CrossEntropyLoss()
1732
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1733
+ shift_labels = shift_labels.view(-1)
1734
+ # Enable model parallelism
1735
+ shift_labels = shift_labels.to(shift_logits.device)
1736
+ loss = loss_fct(shift_logits, shift_labels)
1737
+
1738
+ if not return_dict:
1739
+ output = (logits,) + outputs[1:]
1740
+ return (loss,) + output if loss is not None else output
1741
+
1742
+ return CausalLMOutputWithPast(
1743
+ loss=loss,
1744
+ logits=logits,
1745
+ past_key_values=outputs.past_key_values,
1746
+ hidden_states=outputs.hidden_states,
1747
+ attentions=outputs.attentions,
1748
+ )
1749
+
1750
+ @torch.inference_mode()
1751
+ def generate_html_tree(self,
1752
+ tokenizer,
1753
+ query: List[str],
1754
+ htmls: List[List[str]],
1755
+ **kwargs):
1756
+ max_seq_length = kwargs.pop("max_seq_length", 131072)
1757
+ def apply_html_tree_template(query, htmls):
1758
+ template = """**HTML**: ```{input_html}```\n**Question**: **{question}**\n Your task is to identify the most relevant text piece to the given question in the HTML document. This text piece could either be a direct paraphrase to the fact, or a supporting evidence that can be used to infer the fact. The overall length of the text piece should be more than 300 words and less than 500 words. You should provide the path to the text piece in the HTML document. An example for the output is: <html 1><body><div 2><p>Some key information..."""
1759
+ return template.format(input_html="\n".join(htmls), question=query)
1760
+
1761
+ res_html_refs = []
1762
+ # get the generation probability of tree nodes
1763
+ for idx, _htmls in enumerate(htmls):
1764
+ if isinstance(_htmls, str):
1765
+ _htmls = [_htmls]
1766
+ else:
1767
+ # drop htmls that are too long
1768
+ html_token_lens = [len(tokenizer.encode(html)) for html in _htmls]
1769
+ total_html_token_len = sum(html_token_lens)
1770
+ while total_html_token_len > max_seq_length - 2048:
1771
+ if len(_htmls) == 1:
1772
+ break
1773
+ max_length_idx = html_token_lens.index(max(html_token_lens))
1774
+ html_token_lens.pop(max_length_idx)
1775
+ _htmls.pop(max_length_idx)
1776
+ total_html_token_len = sum(html_token_lens)
1777
+
1778
+ model_input = apply_html_tree_template(query, _htmls)
1779
+
1780
+ inputs = tokenizer.apply_chat_template([{"role": "user", "content": model_input}], add_special_tokens=True,
1781
+ add_generation_prompt=True, tokenize=True, return_tensors="pt",
1782
+ return_dict=True)
1783
+
1784
+ # merge htmls to a single html
1785
+ soup = bs4.BeautifulSoup("", 'html.parser')
1786
+ for html in _htmls:
1787
+ soup.append(bs4.BeautifulSoup(html, 'html.parser'))
1788
+
1789
+ token_id_paths = []
1790
+ html_chunk_paths = split_tree(soup, max_node_words=self.max_node_words)
1791
+ is_leaf = [p[2] for p in html_chunk_paths]
1792
+ html_chunk_paths = [p[1] for p in html_chunk_paths]
1793
+
1794
+ for path in html_chunk_paths:
1795
+ path_str = "<" + "><".join(path) + ">"
1796
+ token_ids = tokenizer.encode(path_str, add_special_tokens=False)
1797
+ token_id_paths.append(token_ids)
1798
+
1799
+ # construct token_id_tree
1800
+ root = TokenIdNode(-1)
1801
+ for path in token_id_paths:
1802
+ parent = root
1803
+ # iterate through path
1804
+ for i, token_id in enumerate(path):
1805
+ has_child = False
1806
+ # find existing child
1807
+ for child in parent.children:
1808
+ if child.name == token_id:
1809
+ parent = child
1810
+ has_child = True
1811
+ break
1812
+ if not has_child:
1813
+ node = TokenIdNode(token_id, parent=parent, input_ids=path[:i + 1])
1814
+ parent = node
1815
+
1816
+ node_queue = [root]
1817
+ while node_queue:
1818
+ cur_node = node_queue.pop(0)
1819
+ children = cur_node.children
1820
+ if len(children) == 1:
1821
+ cur_node.children[0].prob = str(np.float32(1.0))
1822
+ node_queue.append(children[0])
1823
+ continue
1824
+ elif len(children) == 0:
1825
+ continue
1826
+ # calculate transition probability for each child
1827
+ force_token_id = [c.name for c in children]
1828
+ child_input_ids = torch.tensor(cur_node.input_ids, dtype=torch.long).unsqueeze(0)
1829
+ # concatenate context input id with child input id
1830
+ child_input_ids = torch.cat([inputs["input_ids"][idx:idx + 1], child_input_ids], dim=1).to(self.device)
1831
+ model_inputs = {
1832
+ "input_ids": child_input_ids,
1833
+ }
1834
+ outputs = self(
1835
+ **model_inputs,
1836
+ return_dict=True,
1837
+ )
1838
+ # get the probability of force_token_id
1839
+ force_token_id = torch.tensor(force_token_id, device=self.device)
1840
+ probs = torch.gather(outputs.logits[:, 0, :], -1, force_token_id.unsqueeze(0))
1841
+ # softmax
1842
+ probs = torch.nn.functional.softmax(probs, dim=-1)
1843
+ #. linear transformation
1844
+ # probs = probs / probs.sum()
1845
+ probs = probs.squeeze(0).detach().to(torch.float32).cpu().numpy()
1846
+ for i, child in enumerate(children):
1847
+ child.prob = str(probs[i])
1848
+ node_queue.append(child)
1849
+
1850
+ res_html_refs.append({
1851
+ "html": str(soup),
1852
+ "paths": html_chunk_paths,
1853
+ "is_leaf": is_leaf,
1854
+ "path_token_ids": token_id_paths,
1855
+ "node_tree": list(TokenDotExporter(root, nodenamefunc=nodenamefunc))
1856
+ })
1857
+ return res_html_refs
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin_of_text|>",
4
+ "lstrip": false,
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": "<|finetune_right_pad_id|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenization_llama.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
21
+ """Tokenization classes for LLaMA."""
22
+
23
+ import os
24
+ from shutil import copyfile
25
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
26
+
27
+ import sentencepiece as spm
28
+
29
+ from transformers.convert_slow_tokenizer import import_protobuf
30
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
31
+ from transformers.utils import logging
32
+
33
+
34
+ if TYPE_CHECKING:
35
+ from transformers.tokenization_utils_base import TextInput
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
40
+
41
+ SPIECE_UNDERLINE = "▁"
42
+
43
+ B_INST, E_INST = "[INST]", "[/INST]"
44
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
45
+
46
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
47
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
48
+ that your responses are socially unbiased and positive in nature.
49
+
50
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
51
+ correct. If you don't know the answer to a question, please don't share false information.""" # fmt: skip
52
+
53
+
54
+ class LlamaTokenizer(PreTrainedTokenizer):
55
+ """
56
+ Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
57
+ no padding token in the original model.
58
+
59
+ Args:
60
+ vocab_file (`str`):
61
+ Path to the vocabulary file.
62
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
63
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
64
+ token instead.
65
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
66
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
67
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
68
+ The end of sequence token.
69
+ pad_token (`str` or `tokenizers.AddedToken`, *optional*):
70
+ A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
71
+ attention mechanisms or loss computation.
72
+ sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
73
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
74
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
75
+ to set:
76
+
77
+ - `enable_sampling`: Enable subword regularization.
78
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
79
+
80
+ - `nbest_size = {0,1}`: No sampling is performed.
81
+ - `nbest_size > 1`: samples from the nbest_size results.
82
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
83
+ using forward-filtering-and-backward-sampling algorithm.
84
+
85
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
86
+ BPE-dropout.
87
+
88
+ add_bos_token (`bool`, *optional*, defaults to `True`):
89
+ Whether or not to add an `bos_token` at the start of sequences.
90
+ add_eos_token (`bool`, *optional*, defaults to `False`):
91
+ Whether or not to add an `eos_token` at the end of sequences.
92
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
93
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
94
+ extra spaces.
95
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
96
+ Whether or not the default system prompt for Llama should be used.
97
+ spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
98
+ Whether or not to add spaces between special tokens.
99
+ legacy (`bool`, *optional*):
100
+ Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
101
+ and #25224 which includes fixes to properly handle tokens that appear after special tokens.
102
+ Make sure to also set `from_slow` to `True`.
103
+ A simple example:
104
+
105
+ - `legacy=True`:
106
+ ```python
107
+ >>> from transformers import LlamaTokenizerFast
108
+
109
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=True, from_slow=True)
110
+ >>> tokenizer.encode("Hello <s>.") # 869 is '▁.'
111
+ [1, 15043, 29871, 1, 869]
112
+ ```
113
+ - `legacy=False`:
114
+ ```python
115
+ >>> from transformers import LlamaTokenizerFast
116
+
117
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=False, from_slow=True)
118
+ >>> tokenizer.encode("Hello <s>.") # 29889 is '.'
119
+ [1, 15043, 29871, 1, 29889]
120
+ ```
121
+ Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
122
+ add_prefix_space (`bool`, *optional*, defaults to `True`):
123
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
124
+ other word. Again, this should be set with `from_slow=True` to make sure it's taken into account.
125
+ """
126
+
127
+ vocab_files_names = VOCAB_FILES_NAMES
128
+ model_input_names = ["input_ids", "attention_mask"]
129
+
130
+ def __init__(
131
+ self,
132
+ vocab_file,
133
+ unk_token="<unk>",
134
+ bos_token="<s>",
135
+ eos_token="</s>",
136
+ pad_token=None,
137
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
138
+ add_bos_token=True,
139
+ add_eos_token=False,
140
+ clean_up_tokenization_spaces=False,
141
+ use_default_system_prompt=False,
142
+ spaces_between_special_tokens=False,
143
+ legacy=None,
144
+ add_prefix_space=True,
145
+ **kwargs,
146
+ ):
147
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
148
+ bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
149
+ eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
150
+ unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
151
+ pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
152
+
153
+ if legacy is None:
154
+ logger.warning_once(
155
+ f"You are using the default legacy behaviour of the {self.__class__}. This is"
156
+ " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
157
+ " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
158
+ " means, and thoroughly read the reason why this was added as explained in"
159
+ " https://github.com/huggingface/transformers/pull/24565 - if you loaded a llama tokenizer from a GGUF file"
160
+ " you can ignore this message"
161
+ )
162
+ legacy = True
163
+
164
+ self.legacy = legacy
165
+ self.vocab_file = vocab_file
166
+ self.add_bos_token = add_bos_token
167
+ self.add_eos_token = add_eos_token
168
+ self.use_default_system_prompt = use_default_system_prompt
169
+ self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
170
+ self.add_prefix_space = add_prefix_space
171
+
172
+ super().__init__(
173
+ bos_token=bos_token,
174
+ eos_token=eos_token,
175
+ unk_token=unk_token,
176
+ pad_token=pad_token,
177
+ add_bos_token=add_bos_token,
178
+ add_eos_token=add_eos_token,
179
+ sp_model_kwargs=self.sp_model_kwargs,
180
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
181
+ use_default_system_prompt=use_default_system_prompt,
182
+ spaces_between_special_tokens=spaces_between_special_tokens,
183
+ legacy=legacy,
184
+ add_prefix_space=add_prefix_space,
185
+ **kwargs,
186
+ )
187
+
188
+ @property
189
+ def unk_token_length(self):
190
+ return len(self.sp_model.encode(str(self.unk_token)))
191
+
192
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
193
+ def get_spm_processor(self, from_slow=False):
194
+ tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
195
+ if self.legacy or from_slow: # no dependency on protobuf
196
+ tokenizer.Load(self.vocab_file)
197
+ return tokenizer
198
+
199
+ with open(self.vocab_file, "rb") as f:
200
+ sp_model = f.read()
201
+ model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
202
+ model = model_pb2.ModelProto.FromString(sp_model)
203
+ normalizer_spec = model_pb2.NormalizerSpec()
204
+ normalizer_spec.add_dummy_prefix = False
205
+ model.normalizer_spec.MergeFrom(normalizer_spec)
206
+ sp_model = model.SerializeToString()
207
+ tokenizer.LoadFromSerializedProto(sp_model)
208
+ return tokenizer
209
+
210
+ def __getstate__(self):
211
+ state = self.__dict__.copy()
212
+ state["sp_model"] = None
213
+ state["sp_model_proto"] = self.sp_model.serialized_model_proto()
214
+ return state
215
+
216
+ def __setstate__(self, d):
217
+ self.__dict__ = d
218
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
219
+ self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
220
+
221
+ @property
222
+ def vocab_size(self):
223
+ """Returns vocab size"""
224
+ return self.sp_model.get_piece_size()
225
+
226
+ def get_vocab(self):
227
+ """Returns vocab as a dict"""
228
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
229
+ vocab.update(self.added_tokens_encoder)
230
+ return vocab
231
+
232
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
233
+ def tokenize(self, text: "TextInput", **kwargs) -> List[str]:
234
+ """
235
+ Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
236
+ first token is special.
237
+ """
238
+ if self.legacy or len(text) == 0:
239
+ return super().tokenize(text, **kwargs)
240
+
241
+ text = text.replace(SPIECE_UNDERLINE, " ")
242
+ if self.add_prefix_space:
243
+ text = SPIECE_UNDERLINE + text
244
+
245
+ tokens = super().tokenize(text, **kwargs)
246
+
247
+ if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
248
+ tokens = tokens[1:]
249
+ return tokens
250
+
251
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
252
+ def _tokenize(self, text, **kwargs):
253
+ """
254
+ Returns a tokenized string.
255
+
256
+ We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
257
+ SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
258
+ `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
259
+ `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
260
+ `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
261
+ """
262
+ if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
263
+ return self.sp_model.encode(text, out_type=str)
264
+
265
+ # 1. Encode string + prefix ex: "<unk> Hey"
266
+ tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
267
+ # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
268
+ return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
269
+
270
+ def _convert_token_to_id(self, token):
271
+ """Converts a token (str) in an id using the vocab."""
272
+ return self.sp_model.piece_to_id(token)
273
+
274
+ def _convert_id_to_token(self, index):
275
+ """Converts an index (integer) in a token (str) using the vocab."""
276
+ token = self.sp_model.IdToPiece(index)
277
+ return token
278
+
279
+ def convert_tokens_to_string(self, tokens):
280
+ """Converts a sequence of tokens (string) in a single string."""
281
+ # since we manually add the prefix space, we have to remove it when decoding
282
+ if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
283
+ tokens[0] = tokens[0][1:]
284
+
285
+ current_sub_tokens = []
286
+ out_string = ""
287
+ prev_is_special = False
288
+ for i, token in enumerate(tokens):
289
+ # make sure that special tokens are not decoded using sentencepiece model
290
+ if token in self.all_special_tokens:
291
+ if not prev_is_special and i != 0 and self.legacy:
292
+ out_string += " "
293
+ out_string += self.sp_model.decode(current_sub_tokens) + token
294
+ prev_is_special = True
295
+ current_sub_tokens = []
296
+ else:
297
+ if prev_is_special and i == 1 and self.add_prefix_space and not token.startswith(SPIECE_UNDERLINE):
298
+ out_string += " "
299
+ current_sub_tokens.append(token)
300
+ prev_is_special = False
301
+ out_string += self.sp_model.decode(current_sub_tokens)
302
+ return out_string
303
+
304
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
305
+ """
306
+ Save the vocabulary and special tokens file to a directory.
307
+
308
+ Args:
309
+ save_directory (`str`):
310
+ The directory in which to save the vocabulary.
311
+
312
+ Returns:
313
+ `Tuple(str)`: Paths to the files saved.
314
+ """
315
+ if not os.path.isdir(save_directory):
316
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
317
+ return
318
+ out_vocab_file = os.path.join(
319
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
320
+ )
321
+
322
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
323
+ copyfile(self.vocab_file, out_vocab_file)
324
+ elif not os.path.isfile(self.vocab_file):
325
+ with open(out_vocab_file, "wb") as fi:
326
+ content_spiece_model = self.sp_model.serialized_model_proto()
327
+ fi.write(content_spiece_model)
328
+
329
+ return (out_vocab_file,)
330
+
331
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
332
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
333
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
334
+
335
+ output = bos_token_id + token_ids_0 + eos_token_id
336
+
337
+ if token_ids_1 is not None:
338
+ output = output + bos_token_id + token_ids_1 + eos_token_id
339
+
340
+ return output
341
+
342
+ def get_special_tokens_mask(
343
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
344
+ ) -> List[int]:
345
+ """
346
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
347
+ special tokens using the tokenizer `prepare_for_model` method.
348
+
349
+ Args:
350
+ token_ids_0 (`List[int]`):
351
+ List of IDs.
352
+ token_ids_1 (`List[int]`, *optional*):
353
+ Optional second list of IDs for sequence pairs.
354
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
355
+ Whether or not the token list is already formatted with special tokens for the model.
356
+
357
+ Returns:
358
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
359
+ """
360
+ if already_has_special_tokens:
361
+ return super().get_special_tokens_mask(
362
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
363
+ )
364
+
365
+ bos_token_id = [1] if self.add_bos_token else []
366
+ eos_token_id = [1] if self.add_eos_token else []
367
+
368
+ if token_ids_1 is None:
369
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
370
+ return (
371
+ bos_token_id
372
+ + ([0] * len(token_ids_0))
373
+ + eos_token_id
374
+ + bos_token_id
375
+ + ([0] * len(token_ids_1))
376
+ + eos_token_id
377
+ )
378
+
379
+ def create_token_type_ids_from_sequences(
380
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
381
+ ) -> List[int]:
382
+ """
383
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
384
+ sequence pair mask has the following format:
385
+
386
+ ```
387
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
388
+ | first sequence | second sequence |
389
+ ```
390
+
391
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
392
+
393
+ Args:
394
+ token_ids_0 (`List[int]`):
395
+ List of ids.
396
+ token_ids_1 (`List[int]`, *optional*):
397
+ Optional second list of IDs for sequence pairs.
398
+
399
+ Returns:
400
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
401
+ """
402
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
403
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
404
+
405
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
406
+
407
+ if token_ids_1 is not None:
408
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
409
+
410
+ return output
tokenization_llama_fast.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import os
16
+ from shutil import copyfile
17
+ from typing import Optional, Tuple
18
+
19
+ from tokenizers import processors
20
+
21
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
22
+ from transformers.utils import is_sentencepiece_available, logging
23
+ from transformers.utils.versions import require_version
24
+
25
+
26
+ require_version("tokenizers>=0.13.3")
27
+
28
+ if is_sentencepiece_available():
29
+ from .tokenization_llama import LlamaTokenizer
30
+ else:
31
+ LlamaTokenizer = None
32
+
33
+ logger = logging.get_logger(__name__)
34
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}
35
+
36
+ B_INST, E_INST = "[INST]", "[/INST]"
37
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
38
+
39
+ # fmt: off
40
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
41
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
42
+ that your responses are socially unbiased and positive in nature.
43
+
44
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
45
+ correct. If you don't know the answer to a question, please don't share false information."""
46
+ # fmt: on
47
+
48
+
49
+ class LlamaTokenizerFast(PreTrainedTokenizerFast):
50
+ """
51
+ Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.
52
+
53
+ This uses notably ByteFallback and no normalization.
54
+
55
+ ```python
56
+ >>> from transformers import LlamaTokenizerFast
57
+
58
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("hf-internal-testing/llama-tokenizer")
59
+ >>> tokenizer.encode("Hello this is a test")
60
+ [1, 15043, 445, 338, 263, 1243]
61
+ ```
62
+
63
+ If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
64
+ call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
65
+ values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
66
+ [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
67
+
68
+
69
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
70
+ refer to this superclass for more information regarding those methods.
71
+
72
+ Args:
73
+ vocab_file (`str`, *optional*):
74
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .model extension) that
75
+ contains the vocabulary necessary to instantiate a tokenizer.
76
+ tokenizer_file (`str`, *optional*):
77
+ [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
78
+ contains everything needed to load the tokenizer.
79
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
80
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
81
+ extra spaces.
82
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
83
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
84
+ token instead.
85
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
86
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
87
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
88
+ The end of sequence token.
89
+ add_bos_token (`bool`, *optional*, defaults to `True`):
90
+ Whether or not to add an `bos_token` at the start of sequences.
91
+ add_eos_token (`bool`, *optional*, defaults to `False`):
92
+ Whether or not to add an `eos_token` at the end of sequences.
93
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
94
+ Whether or not the default system prompt for Llama should be used
95
+ legacy (`bool`, *optional*):
96
+ Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
97
+ and #25224 which includes fixes to properly handle tokens that appear after special tokens.
98
+ Make sure to also set `from_slow` to `True`.
99
+ A simple example:
100
+
101
+ - `legacy=True`:
102
+ ```python
103
+ >>> from transformers import LlamaTokenizerFast
104
+
105
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=True, from_slow=True)
106
+ >>> tokenizer.encode("Hello <s>.") # 869 is '▁.'
107
+ [1, 15043, 29871, 1, 869]
108
+ ```
109
+ - `legacy=False`:
110
+ ```python
111
+ >>> from transformers import LlamaTokenizerFast
112
+
113
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=False, from_slow=True)
114
+ >>> tokenizer.encode("Hello <s>.") # 29889 is '.'
115
+ [1, 15043, 29871, 1, 29889]
116
+ ```
117
+ Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
118
+ add_prefix_space (`bool`, *optional*):
119
+ Whether or not the tokenizer should automatically add a prefix space
120
+ """
121
+
122
+ vocab_files_names = VOCAB_FILES_NAMES
123
+ slow_tokenizer_class = LlamaTokenizer
124
+ padding_side = "left"
125
+ model_input_names = ["input_ids", "attention_mask"]
126
+
127
+ def __init__(
128
+ self,
129
+ vocab_file=None,
130
+ tokenizer_file=None,
131
+ clean_up_tokenization_spaces=False,
132
+ unk_token="<unk>",
133
+ bos_token="<s>",
134
+ eos_token="</s>",
135
+ add_bos_token=True,
136
+ add_eos_token=False,
137
+ use_default_system_prompt=False,
138
+ legacy=None,
139
+ add_prefix_space=None,
140
+ **kwargs,
141
+ ):
142
+ if legacy is None:
143
+ logger.warning_once(
144
+ f"You are using the default legacy behaviour of the {self.__class__}. This is"
145
+ " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
146
+ " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
147
+ " means, and thoroughly read the reason why this was added as explained in"
148
+ " https://github.com/huggingface/transformers/pull/24565 - if you loaded a llama tokenizer from a GGUF file"
149
+ " you can ignore this message."
150
+ )
151
+ legacy = True
152
+ self.legacy = legacy
153
+
154
+ if add_prefix_space is not None:
155
+ kwargs["from_slow"] = True
156
+
157
+ super().__init__(
158
+ vocab_file=vocab_file,
159
+ tokenizer_file=tokenizer_file,
160
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
161
+ unk_token=unk_token,
162
+ bos_token=bos_token,
163
+ eos_token=eos_token,
164
+ add_bos_token=add_bos_token,
165
+ add_eos_token=add_eos_token,
166
+ use_default_system_prompt=use_default_system_prompt,
167
+ add_prefix_space=add_prefix_space,
168
+ legacy=legacy,
169
+ **kwargs,
170
+ )
171
+ self._add_bos_token = add_bos_token
172
+ self._add_eos_token = add_eos_token
173
+ self.update_post_processor()
174
+ self.use_default_system_prompt = use_default_system_prompt
175
+ self.vocab_file = vocab_file
176
+
177
+ @property
178
+ def can_save_slow_tokenizer(self) -> bool:
179
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
180
+
181
+ def update_post_processor(self):
182
+ """
183
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
184
+ """
185
+ bos = self.bos_token
186
+ bos_token_id = self.bos_token_id
187
+ if bos is None and self.add_bos_token:
188
+ raise ValueError("add_bos_token = True but bos_token = None")
189
+
190
+ eos = self.eos_token
191
+ eos_token_id = self.eos_token_id
192
+ if eos is None and self.add_eos_token:
193
+ raise ValueError("add_eos_token = True but eos_token = None")
194
+
195
+ single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
196
+ pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
197
+
198
+ special_tokens = []
199
+ if self.add_bos_token:
200
+ special_tokens.append((bos, bos_token_id))
201
+ if self.add_eos_token:
202
+ special_tokens.append((eos, eos_token_id))
203
+ self._tokenizer.post_processor = processors.TemplateProcessing(
204
+ single=single, pair=pair, special_tokens=special_tokens
205
+ )
206
+
207
+ @property
208
+ def add_eos_token(self):
209
+ return self._add_eos_token
210
+
211
+ @property
212
+ def add_bos_token(self):
213
+ return self._add_bos_token
214
+
215
+ @add_eos_token.setter
216
+ def add_eos_token(self, value):
217
+ self._add_eos_token = value
218
+ self.update_post_processor()
219
+
220
+ @add_bos_token.setter
221
+ def add_bos_token(self, value):
222
+ self._add_bos_token = value
223
+ self.update_post_processor()
224
+
225
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
226
+ if not self.can_save_slow_tokenizer:
227
+ raise ValueError(
228
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
229
+ "tokenizer."
230
+ )
231
+
232
+ if not os.path.isdir(save_directory):
233
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
234
+ return
235
+ out_vocab_file = os.path.join(
236
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
237
+ )
238
+
239
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
240
+ copyfile(self.vocab_file, out_vocab_file)
241
+
242
+ return (out_vocab_file,)
243
+
244
+ # TODO ArthurZ let's rely on the template processor instead, refactor all fast tokenizers
245
+ # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.build_inputs_with_special_tokens
246
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
247
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
248
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
249
+
250
+ output = bos_token_id + token_ids_0 + eos_token_id
251
+
252
+ if token_ids_1 is not None:
253
+ output = output + bos_token_id + token_ids_1 + eos_token_id
254
+
255
+ return output
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b9e4e7fb171f92fd137b777cc2714bf87d11576700a1dcd7a399e7bbe39537b
3
+ size 17209920
tokenizer_config.json ADDED
@@ -0,0 +1,2063 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "128000": {
4
+ "content": "<|begin_of_text|>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "128001": {
12
+ "content": "<|end_of_text|>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "128002": {
20
+ "content": "<|reserved_special_token_0|>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "128003": {
28
+ "content": "<|reserved_special_token_1|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "128004": {
36
+ "content": "<|finetune_right_pad_id|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "128005": {
44
+ "content": "<|reserved_special_token_2|>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "128006": {
52
+ "content": "<|start_header_id|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "128007": {
60
+ "content": "<|end_header_id|>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "128008": {
68
+ "content": "<|eom_id|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "128009": {
76
+ "content": "<|eot_id|>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "128010": {
84
+ "content": "<|python_tag|>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "128011": {
92
+ "content": "<|reserved_special_token_3|>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "128012": {
100
+ "content": "<|reserved_special_token_4|>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "128013": {
108
+ "content": "<|reserved_special_token_5|>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "128014": {
116
+ "content": "<|reserved_special_token_6|>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "128015": {
124
+ "content": "<|reserved_special_token_7|>",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "128016": {
132
+ "content": "<|reserved_special_token_8|>",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "128017": {
140
+ "content": "<|reserved_special_token_9|>",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ },
147
+ "128018": {
148
+ "content": "<|reserved_special_token_10|>",
149
+ "lstrip": false,
150
+ "normalized": false,
151
+ "rstrip": false,
152
+ "single_word": false,
153
+ "special": true
154
+ },
155
+ "128019": {
156
+ "content": "<|reserved_special_token_11|>",
157
+ "lstrip": false,
158
+ "normalized": false,
159
+ "rstrip": false,
160
+ "single_word": false,
161
+ "special": true
162
+ },
163
+ "128020": {
164
+ "content": "<|reserved_special_token_12|>",
165
+ "lstrip": false,
166
+ "normalized": false,
167
+ "rstrip": false,
168
+ "single_word": false,
169
+ "special": true
170
+ },
171
+ "128021": {
172
+ "content": "<|reserved_special_token_13|>",
173
+ "lstrip": false,
174
+ "normalized": false,
175
+ "rstrip": false,
176
+ "single_word": false,
177
+ "special": true
178
+ },
179
+ "128022": {
180
+ "content": "<|reserved_special_token_14|>",
181
+ "lstrip": false,
182
+ "normalized": false,
183
+ "rstrip": false,
184
+ "single_word": false,
185
+ "special": true
186
+ },
187
+ "128023": {
188
+ "content": "<|reserved_special_token_15|>",
189
+ "lstrip": false,
190
+ "normalized": false,
191
+ "rstrip": false,
192
+ "single_word": false,
193
+ "special": true
194
+ },
195
+ "128024": {
196
+ "content": "<|reserved_special_token_16|>",
197
+ "lstrip": false,
198
+ "normalized": false,
199
+ "rstrip": false,
200
+ "single_word": false,
201
+ "special": true
202
+ },
203
+ "128025": {
204
+ "content": "<|reserved_special_token_17|>",
205
+ "lstrip": false,
206
+ "normalized": false,
207
+ "rstrip": false,
208
+ "single_word": false,
209
+ "special": true
210
+ },
211
+ "128026": {
212
+ "content": "<|reserved_special_token_18|>",
213
+ "lstrip": false,
214
+ "normalized": false,
215
+ "rstrip": false,
216
+ "single_word": false,
217
+ "special": true
218
+ },
219
+ "128027": {
220
+ "content": "<|reserved_special_token_19|>",
221
+ "lstrip": false,
222
+ "normalized": false,
223
+ "rstrip": false,
224
+ "single_word": false,
225
+ "special": true
226
+ },
227
+ "128028": {
228
+ "content": "<|reserved_special_token_20|>",
229
+ "lstrip": false,
230
+ "normalized": false,
231
+ "rstrip": false,
232
+ "single_word": false,
233
+ "special": true
234
+ },
235
+ "128029": {
236
+ "content": "<|reserved_special_token_21|>",
237
+ "lstrip": false,
238
+ "normalized": false,
239
+ "rstrip": false,
240
+ "single_word": false,
241
+ "special": true
242
+ },
243
+ "128030": {
244
+ "content": "<|reserved_special_token_22|>",
245
+ "lstrip": false,
246
+ "normalized": false,
247
+ "rstrip": false,
248
+ "single_word": false,
249
+ "special": true
250
+ },
251
+ "128031": {
252
+ "content": "<|reserved_special_token_23|>",
253
+ "lstrip": false,
254
+ "normalized": false,
255
+ "rstrip": false,
256
+ "single_word": false,
257
+ "special": true
258
+ },
259
+ "128032": {
260
+ "content": "<|reserved_special_token_24|>",
261
+ "lstrip": false,
262
+ "normalized": false,
263
+ "rstrip": false,
264
+ "single_word": false,
265
+ "special": true
266
+ },
267
+ "128033": {
268
+ "content": "<|reserved_special_token_25|>",
269
+ "lstrip": false,
270
+ "normalized": false,
271
+ "rstrip": false,
272
+ "single_word": false,
273
+ "special": true
274
+ },
275
+ "128034": {
276
+ "content": "<|reserved_special_token_26|>",
277
+ "lstrip": false,
278
+ "normalized": false,
279
+ "rstrip": false,
280
+ "single_word": false,
281
+ "special": true
282
+ },
283
+ "128035": {
284
+ "content": "<|reserved_special_token_27|>",
285
+ "lstrip": false,
286
+ "normalized": false,
287
+ "rstrip": false,
288
+ "single_word": false,
289
+ "special": true
290
+ },
291
+ "128036": {
292
+ "content": "<|reserved_special_token_28|>",
293
+ "lstrip": false,
294
+ "normalized": false,
295
+ "rstrip": false,
296
+ "single_word": false,
297
+ "special": true
298
+ },
299
+ "128037": {
300
+ "content": "<|reserved_special_token_29|>",
301
+ "lstrip": false,
302
+ "normalized": false,
303
+ "rstrip": false,
304
+ "single_word": false,
305
+ "special": true
306
+ },
307
+ "128038": {
308
+ "content": "<|reserved_special_token_30|>",
309
+ "lstrip": false,
310
+ "normalized": false,
311
+ "rstrip": false,
312
+ "single_word": false,
313
+ "special": true
314
+ },
315
+ "128039": {
316
+ "content": "<|reserved_special_token_31|>",
317
+ "lstrip": false,
318
+ "normalized": false,
319
+ "rstrip": false,
320
+ "single_word": false,
321
+ "special": true
322
+ },
323
+ "128040": {
324
+ "content": "<|reserved_special_token_32|>",
325
+ "lstrip": false,
326
+ "normalized": false,
327
+ "rstrip": false,
328
+ "single_word": false,
329
+ "special": true
330
+ },
331
+ "128041": {
332
+ "content": "<|reserved_special_token_33|>",
333
+ "lstrip": false,
334
+ "normalized": false,
335
+ "rstrip": false,
336
+ "single_word": false,
337
+ "special": true
338
+ },
339
+ "128042": {
340
+ "content": "<|reserved_special_token_34|>",
341
+ "lstrip": false,
342
+ "normalized": false,
343
+ "rstrip": false,
344
+ "single_word": false,
345
+ "special": true
346
+ },
347
+ "128043": {
348
+ "content": "<|reserved_special_token_35|>",
349
+ "lstrip": false,
350
+ "normalized": false,
351
+ "rstrip": false,
352
+ "single_word": false,
353
+ "special": true
354
+ },
355
+ "128044": {
356
+ "content": "<|reserved_special_token_36|>",
357
+ "lstrip": false,
358
+ "normalized": false,
359
+ "rstrip": false,
360
+ "single_word": false,
361
+ "special": true
362
+ },
363
+ "128045": {
364
+ "content": "<|reserved_special_token_37|>",
365
+ "lstrip": false,
366
+ "normalized": false,
367
+ "rstrip": false,
368
+ "single_word": false,
369
+ "special": true
370
+ },
371
+ "128046": {
372
+ "content": "<|reserved_special_token_38|>",
373
+ "lstrip": false,
374
+ "normalized": false,
375
+ "rstrip": false,
376
+ "single_word": false,
377
+ "special": true
378
+ },
379
+ "128047": {
380
+ "content": "<|reserved_special_token_39|>",
381
+ "lstrip": false,
382
+ "normalized": false,
383
+ "rstrip": false,
384
+ "single_word": false,
385
+ "special": true
386
+ },
387
+ "128048": {
388
+ "content": "<|reserved_special_token_40|>",
389
+ "lstrip": false,
390
+ "normalized": false,
391
+ "rstrip": false,
392
+ "single_word": false,
393
+ "special": true
394
+ },
395
+ "128049": {
396
+ "content": "<|reserved_special_token_41|>",
397
+ "lstrip": false,
398
+ "normalized": false,
399
+ "rstrip": false,
400
+ "single_word": false,
401
+ "special": true
402
+ },
403
+ "128050": {
404
+ "content": "<|reserved_special_token_42|>",
405
+ "lstrip": false,
406
+ "normalized": false,
407
+ "rstrip": false,
408
+ "single_word": false,
409
+ "special": true
410
+ },
411
+ "128051": {
412
+ "content": "<|reserved_special_token_43|>",
413
+ "lstrip": false,
414
+ "normalized": false,
415
+ "rstrip": false,
416
+ "single_word": false,
417
+ "special": true
418
+ },
419
+ "128052": {
420
+ "content": "<|reserved_special_token_44|>",
421
+ "lstrip": false,
422
+ "normalized": false,
423
+ "rstrip": false,
424
+ "single_word": false,
425
+ "special": true
426
+ },
427
+ "128053": {
428
+ "content": "<|reserved_special_token_45|>",
429
+ "lstrip": false,
430
+ "normalized": false,
431
+ "rstrip": false,
432
+ "single_word": false,
433
+ "special": true
434
+ },
435
+ "128054": {
436
+ "content": "<|reserved_special_token_46|>",
437
+ "lstrip": false,
438
+ "normalized": false,
439
+ "rstrip": false,
440
+ "single_word": false,
441
+ "special": true
442
+ },
443
+ "128055": {
444
+ "content": "<|reserved_special_token_47|>",
445
+ "lstrip": false,
446
+ "normalized": false,
447
+ "rstrip": false,
448
+ "single_word": false,
449
+ "special": true
450
+ },
451
+ "128056": {
452
+ "content": "<|reserved_special_token_48|>",
453
+ "lstrip": false,
454
+ "normalized": false,
455
+ "rstrip": false,
456
+ "single_word": false,
457
+ "special": true
458
+ },
459
+ "128057": {
460
+ "content": "<|reserved_special_token_49|>",
461
+ "lstrip": false,
462
+ "normalized": false,
463
+ "rstrip": false,
464
+ "single_word": false,
465
+ "special": true
466
+ },
467
+ "128058": {
468
+ "content": "<|reserved_special_token_50|>",
469
+ "lstrip": false,
470
+ "normalized": false,
471
+ "rstrip": false,
472
+ "single_word": false,
473
+ "special": true
474
+ },
475
+ "128059": {
476
+ "content": "<|reserved_special_token_51|>",
477
+ "lstrip": false,
478
+ "normalized": false,
479
+ "rstrip": false,
480
+ "single_word": false,
481
+ "special": true
482
+ },
483
+ "128060": {
484
+ "content": "<|reserved_special_token_52|>",
485
+ "lstrip": false,
486
+ "normalized": false,
487
+ "rstrip": false,
488
+ "single_word": false,
489
+ "special": true
490
+ },
491
+ "128061": {
492
+ "content": "<|reserved_special_token_53|>",
493
+ "lstrip": false,
494
+ "normalized": false,
495
+ "rstrip": false,
496
+ "single_word": false,
497
+ "special": true
498
+ },
499
+ "128062": {
500
+ "content": "<|reserved_special_token_54|>",
501
+ "lstrip": false,
502
+ "normalized": false,
503
+ "rstrip": false,
504
+ "single_word": false,
505
+ "special": true
506
+ },
507
+ "128063": {
508
+ "content": "<|reserved_special_token_55|>",
509
+ "lstrip": false,
510
+ "normalized": false,
511
+ "rstrip": false,
512
+ "single_word": false,
513
+ "special": true
514
+ },
515
+ "128064": {
516
+ "content": "<|reserved_special_token_56|>",
517
+ "lstrip": false,
518
+ "normalized": false,
519
+ "rstrip": false,
520
+ "single_word": false,
521
+ "special": true
522
+ },
523
+ "128065": {
524
+ "content": "<|reserved_special_token_57|>",
525
+ "lstrip": false,
526
+ "normalized": false,
527
+ "rstrip": false,
528
+ "single_word": false,
529
+ "special": true
530
+ },
531
+ "128066": {
532
+ "content": "<|reserved_special_token_58|>",
533
+ "lstrip": false,
534
+ "normalized": false,
535
+ "rstrip": false,
536
+ "single_word": false,
537
+ "special": true
538
+ },
539
+ "128067": {
540
+ "content": "<|reserved_special_token_59|>",
541
+ "lstrip": false,
542
+ "normalized": false,
543
+ "rstrip": false,
544
+ "single_word": false,
545
+ "special": true
546
+ },
547
+ "128068": {
548
+ "content": "<|reserved_special_token_60|>",
549
+ "lstrip": false,
550
+ "normalized": false,
551
+ "rstrip": false,
552
+ "single_word": false,
553
+ "special": true
554
+ },
555
+ "128069": {
556
+ "content": "<|reserved_special_token_61|>",
557
+ "lstrip": false,
558
+ "normalized": false,
559
+ "rstrip": false,
560
+ "single_word": false,
561
+ "special": true
562
+ },
563
+ "128070": {
564
+ "content": "<|reserved_special_token_62|>",
565
+ "lstrip": false,
566
+ "normalized": false,
567
+ "rstrip": false,
568
+ "single_word": false,
569
+ "special": true
570
+ },
571
+ "128071": {
572
+ "content": "<|reserved_special_token_63|>",
573
+ "lstrip": false,
574
+ "normalized": false,
575
+ "rstrip": false,
576
+ "single_word": false,
577
+ "special": true
578
+ },
579
+ "128072": {
580
+ "content": "<|reserved_special_token_64|>",
581
+ "lstrip": false,
582
+ "normalized": false,
583
+ "rstrip": false,
584
+ "single_word": false,
585
+ "special": true
586
+ },
587
+ "128073": {
588
+ "content": "<|reserved_special_token_65|>",
589
+ "lstrip": false,
590
+ "normalized": false,
591
+ "rstrip": false,
592
+ "single_word": false,
593
+ "special": true
594
+ },
595
+ "128074": {
596
+ "content": "<|reserved_special_token_66|>",
597
+ "lstrip": false,
598
+ "normalized": false,
599
+ "rstrip": false,
600
+ "single_word": false,
601
+ "special": true
602
+ },
603
+ "128075": {
604
+ "content": "<|reserved_special_token_67|>",
605
+ "lstrip": false,
606
+ "normalized": false,
607
+ "rstrip": false,
608
+ "single_word": false,
609
+ "special": true
610
+ },
611
+ "128076": {
612
+ "content": "<|reserved_special_token_68|>",
613
+ "lstrip": false,
614
+ "normalized": false,
615
+ "rstrip": false,
616
+ "single_word": false,
617
+ "special": true
618
+ },
619
+ "128077": {
620
+ "content": "<|reserved_special_token_69|>",
621
+ "lstrip": false,
622
+ "normalized": false,
623
+ "rstrip": false,
624
+ "single_word": false,
625
+ "special": true
626
+ },
627
+ "128078": {
628
+ "content": "<|reserved_special_token_70|>",
629
+ "lstrip": false,
630
+ "normalized": false,
631
+ "rstrip": false,
632
+ "single_word": false,
633
+ "special": true
634
+ },
635
+ "128079": {
636
+ "content": "<|reserved_special_token_71|>",
637
+ "lstrip": false,
638
+ "normalized": false,
639
+ "rstrip": false,
640
+ "single_word": false,
641
+ "special": true
642
+ },
643
+ "128080": {
644
+ "content": "<|reserved_special_token_72|>",
645
+ "lstrip": false,
646
+ "normalized": false,
647
+ "rstrip": false,
648
+ "single_word": false,
649
+ "special": true
650
+ },
651
+ "128081": {
652
+ "content": "<|reserved_special_token_73|>",
653
+ "lstrip": false,
654
+ "normalized": false,
655
+ "rstrip": false,
656
+ "single_word": false,
657
+ "special": true
658
+ },
659
+ "128082": {
660
+ "content": "<|reserved_special_token_74|>",
661
+ "lstrip": false,
662
+ "normalized": false,
663
+ "rstrip": false,
664
+ "single_word": false,
665
+ "special": true
666
+ },
667
+ "128083": {
668
+ "content": "<|reserved_special_token_75|>",
669
+ "lstrip": false,
670
+ "normalized": false,
671
+ "rstrip": false,
672
+ "single_word": false,
673
+ "special": true
674
+ },
675
+ "128084": {
676
+ "content": "<|reserved_special_token_76|>",
677
+ "lstrip": false,
678
+ "normalized": false,
679
+ "rstrip": false,
680
+ "single_word": false,
681
+ "special": true
682
+ },
683
+ "128085": {
684
+ "content": "<|reserved_special_token_77|>",
685
+ "lstrip": false,
686
+ "normalized": false,
687
+ "rstrip": false,
688
+ "single_word": false,
689
+ "special": true
690
+ },
691
+ "128086": {
692
+ "content": "<|reserved_special_token_78|>",
693
+ "lstrip": false,
694
+ "normalized": false,
695
+ "rstrip": false,
696
+ "single_word": false,
697
+ "special": true
698
+ },
699
+ "128087": {
700
+ "content": "<|reserved_special_token_79|>",
701
+ "lstrip": false,
702
+ "normalized": false,
703
+ "rstrip": false,
704
+ "single_word": false,
705
+ "special": true
706
+ },
707
+ "128088": {
708
+ "content": "<|reserved_special_token_80|>",
709
+ "lstrip": false,
710
+ "normalized": false,
711
+ "rstrip": false,
712
+ "single_word": false,
713
+ "special": true
714
+ },
715
+ "128089": {
716
+ "content": "<|reserved_special_token_81|>",
717
+ "lstrip": false,
718
+ "normalized": false,
719
+ "rstrip": false,
720
+ "single_word": false,
721
+ "special": true
722
+ },
723
+ "128090": {
724
+ "content": "<|reserved_special_token_82|>",
725
+ "lstrip": false,
726
+ "normalized": false,
727
+ "rstrip": false,
728
+ "single_word": false,
729
+ "special": true
730
+ },
731
+ "128091": {
732
+ "content": "<|reserved_special_token_83|>",
733
+ "lstrip": false,
734
+ "normalized": false,
735
+ "rstrip": false,
736
+ "single_word": false,
737
+ "special": true
738
+ },
739
+ "128092": {
740
+ "content": "<|reserved_special_token_84|>",
741
+ "lstrip": false,
742
+ "normalized": false,
743
+ "rstrip": false,
744
+ "single_word": false,
745
+ "special": true
746
+ },
747
+ "128093": {
748
+ "content": "<|reserved_special_token_85|>",
749
+ "lstrip": false,
750
+ "normalized": false,
751
+ "rstrip": false,
752
+ "single_word": false,
753
+ "special": true
754
+ },
755
+ "128094": {
756
+ "content": "<|reserved_special_token_86|>",
757
+ "lstrip": false,
758
+ "normalized": false,
759
+ "rstrip": false,
760
+ "single_word": false,
761
+ "special": true
762
+ },
763
+ "128095": {
764
+ "content": "<|reserved_special_token_87|>",
765
+ "lstrip": false,
766
+ "normalized": false,
767
+ "rstrip": false,
768
+ "single_word": false,
769
+ "special": true
770
+ },
771
+ "128096": {
772
+ "content": "<|reserved_special_token_88|>",
773
+ "lstrip": false,
774
+ "normalized": false,
775
+ "rstrip": false,
776
+ "single_word": false,
777
+ "special": true
778
+ },
779
+ "128097": {
780
+ "content": "<|reserved_special_token_89|>",
781
+ "lstrip": false,
782
+ "normalized": false,
783
+ "rstrip": false,
784
+ "single_word": false,
785
+ "special": true
786
+ },
787
+ "128098": {
788
+ "content": "<|reserved_special_token_90|>",
789
+ "lstrip": false,
790
+ "normalized": false,
791
+ "rstrip": false,
792
+ "single_word": false,
793
+ "special": true
794
+ },
795
+ "128099": {
796
+ "content": "<|reserved_special_token_91|>",
797
+ "lstrip": false,
798
+ "normalized": false,
799
+ "rstrip": false,
800
+ "single_word": false,
801
+ "special": true
802
+ },
803
+ "128100": {
804
+ "content": "<|reserved_special_token_92|>",
805
+ "lstrip": false,
806
+ "normalized": false,
807
+ "rstrip": false,
808
+ "single_word": false,
809
+ "special": true
810
+ },
811
+ "128101": {
812
+ "content": "<|reserved_special_token_93|>",
813
+ "lstrip": false,
814
+ "normalized": false,
815
+ "rstrip": false,
816
+ "single_word": false,
817
+ "special": true
818
+ },
819
+ "128102": {
820
+ "content": "<|reserved_special_token_94|>",
821
+ "lstrip": false,
822
+ "normalized": false,
823
+ "rstrip": false,
824
+ "single_word": false,
825
+ "special": true
826
+ },
827
+ "128103": {
828
+ "content": "<|reserved_special_token_95|>",
829
+ "lstrip": false,
830
+ "normalized": false,
831
+ "rstrip": false,
832
+ "single_word": false,
833
+ "special": true
834
+ },
835
+ "128104": {
836
+ "content": "<|reserved_special_token_96|>",
837
+ "lstrip": false,
838
+ "normalized": false,
839
+ "rstrip": false,
840
+ "single_word": false,
841
+ "special": true
842
+ },
843
+ "128105": {
844
+ "content": "<|reserved_special_token_97|>",
845
+ "lstrip": false,
846
+ "normalized": false,
847
+ "rstrip": false,
848
+ "single_word": false,
849
+ "special": true
850
+ },
851
+ "128106": {
852
+ "content": "<|reserved_special_token_98|>",
853
+ "lstrip": false,
854
+ "normalized": false,
855
+ "rstrip": false,
856
+ "single_word": false,
857
+ "special": true
858
+ },
859
+ "128107": {
860
+ "content": "<|reserved_special_token_99|>",
861
+ "lstrip": false,
862
+ "normalized": false,
863
+ "rstrip": false,
864
+ "single_word": false,
865
+ "special": true
866
+ },
867
+ "128108": {
868
+ "content": "<|reserved_special_token_100|>",
869
+ "lstrip": false,
870
+ "normalized": false,
871
+ "rstrip": false,
872
+ "single_word": false,
873
+ "special": true
874
+ },
875
+ "128109": {
876
+ "content": "<|reserved_special_token_101|>",
877
+ "lstrip": false,
878
+ "normalized": false,
879
+ "rstrip": false,
880
+ "single_word": false,
881
+ "special": true
882
+ },
883
+ "128110": {
884
+ "content": "<|reserved_special_token_102|>",
885
+ "lstrip": false,
886
+ "normalized": false,
887
+ "rstrip": false,
888
+ "single_word": false,
889
+ "special": true
890
+ },
891
+ "128111": {
892
+ "content": "<|reserved_special_token_103|>",
893
+ "lstrip": false,
894
+ "normalized": false,
895
+ "rstrip": false,
896
+ "single_word": false,
897
+ "special": true
898
+ },
899
+ "128112": {
900
+ "content": "<|reserved_special_token_104|>",
901
+ "lstrip": false,
902
+ "normalized": false,
903
+ "rstrip": false,
904
+ "single_word": false,
905
+ "special": true
906
+ },
907
+ "128113": {
908
+ "content": "<|reserved_special_token_105|>",
909
+ "lstrip": false,
910
+ "normalized": false,
911
+ "rstrip": false,
912
+ "single_word": false,
913
+ "special": true
914
+ },
915
+ "128114": {
916
+ "content": "<|reserved_special_token_106|>",
917
+ "lstrip": false,
918
+ "normalized": false,
919
+ "rstrip": false,
920
+ "single_word": false,
921
+ "special": true
922
+ },
923
+ "128115": {
924
+ "content": "<|reserved_special_token_107|>",
925
+ "lstrip": false,
926
+ "normalized": false,
927
+ "rstrip": false,
928
+ "single_word": false,
929
+ "special": true
930
+ },
931
+ "128116": {
932
+ "content": "<|reserved_special_token_108|>",
933
+ "lstrip": false,
934
+ "normalized": false,
935
+ "rstrip": false,
936
+ "single_word": false,
937
+ "special": true
938
+ },
939
+ "128117": {
940
+ "content": "<|reserved_special_token_109|>",
941
+ "lstrip": false,
942
+ "normalized": false,
943
+ "rstrip": false,
944
+ "single_word": false,
945
+ "special": true
946
+ },
947
+ "128118": {
948
+ "content": "<|reserved_special_token_110|>",
949
+ "lstrip": false,
950
+ "normalized": false,
951
+ "rstrip": false,
952
+ "single_word": false,
953
+ "special": true
954
+ },
955
+ "128119": {
956
+ "content": "<|reserved_special_token_111|>",
957
+ "lstrip": false,
958
+ "normalized": false,
959
+ "rstrip": false,
960
+ "single_word": false,
961
+ "special": true
962
+ },
963
+ "128120": {
964
+ "content": "<|reserved_special_token_112|>",
965
+ "lstrip": false,
966
+ "normalized": false,
967
+ "rstrip": false,
968
+ "single_word": false,
969
+ "special": true
970
+ },
971
+ "128121": {
972
+ "content": "<|reserved_special_token_113|>",
973
+ "lstrip": false,
974
+ "normalized": false,
975
+ "rstrip": false,
976
+ "single_word": false,
977
+ "special": true
978
+ },
979
+ "128122": {
980
+ "content": "<|reserved_special_token_114|>",
981
+ "lstrip": false,
982
+ "normalized": false,
983
+ "rstrip": false,
984
+ "single_word": false,
985
+ "special": true
986
+ },
987
+ "128123": {
988
+ "content": "<|reserved_special_token_115|>",
989
+ "lstrip": false,
990
+ "normalized": false,
991
+ "rstrip": false,
992
+ "single_word": false,
993
+ "special": true
994
+ },
995
+ "128124": {
996
+ "content": "<|reserved_special_token_116|>",
997
+ "lstrip": false,
998
+ "normalized": false,
999
+ "rstrip": false,
1000
+ "single_word": false,
1001
+ "special": true
1002
+ },
1003
+ "128125": {
1004
+ "content": "<|reserved_special_token_117|>",
1005
+ "lstrip": false,
1006
+ "normalized": false,
1007
+ "rstrip": false,
1008
+ "single_word": false,
1009
+ "special": true
1010
+ },
1011
+ "128126": {
1012
+ "content": "<|reserved_special_token_118|>",
1013
+ "lstrip": false,
1014
+ "normalized": false,
1015
+ "rstrip": false,
1016
+ "single_word": false,
1017
+ "special": true
1018
+ },
1019
+ "128127": {
1020
+ "content": "<|reserved_special_token_119|>",
1021
+ "lstrip": false,
1022
+ "normalized": false,
1023
+ "rstrip": false,
1024
+ "single_word": false,
1025
+ "special": true
1026
+ },
1027
+ "128128": {
1028
+ "content": "<|reserved_special_token_120|>",
1029
+ "lstrip": false,
1030
+ "normalized": false,
1031
+ "rstrip": false,
1032
+ "single_word": false,
1033
+ "special": true
1034
+ },
1035
+ "128129": {
1036
+ "content": "<|reserved_special_token_121|>",
1037
+ "lstrip": false,
1038
+ "normalized": false,
1039
+ "rstrip": false,
1040
+ "single_word": false,
1041
+ "special": true
1042
+ },
1043
+ "128130": {
1044
+ "content": "<|reserved_special_token_122|>",
1045
+ "lstrip": false,
1046
+ "normalized": false,
1047
+ "rstrip": false,
1048
+ "single_word": false,
1049
+ "special": true
1050
+ },
1051
+ "128131": {
1052
+ "content": "<|reserved_special_token_123|>",
1053
+ "lstrip": false,
1054
+ "normalized": false,
1055
+ "rstrip": false,
1056
+ "single_word": false,
1057
+ "special": true
1058
+ },
1059
+ "128132": {
1060
+ "content": "<|reserved_special_token_124|>",
1061
+ "lstrip": false,
1062
+ "normalized": false,
1063
+ "rstrip": false,
1064
+ "single_word": false,
1065
+ "special": true
1066
+ },
1067
+ "128133": {
1068
+ "content": "<|reserved_special_token_125|>",
1069
+ "lstrip": false,
1070
+ "normalized": false,
1071
+ "rstrip": false,
1072
+ "single_word": false,
1073
+ "special": true
1074
+ },
1075
+ "128134": {
1076
+ "content": "<|reserved_special_token_126|>",
1077
+ "lstrip": false,
1078
+ "normalized": false,
1079
+ "rstrip": false,
1080
+ "single_word": false,
1081
+ "special": true
1082
+ },
1083
+ "128135": {
1084
+ "content": "<|reserved_special_token_127|>",
1085
+ "lstrip": false,
1086
+ "normalized": false,
1087
+ "rstrip": false,
1088
+ "single_word": false,
1089
+ "special": true
1090
+ },
1091
+ "128136": {
1092
+ "content": "<|reserved_special_token_128|>",
1093
+ "lstrip": false,
1094
+ "normalized": false,
1095
+ "rstrip": false,
1096
+ "single_word": false,
1097
+ "special": true
1098
+ },
1099
+ "128137": {
1100
+ "content": "<|reserved_special_token_129|>",
1101
+ "lstrip": false,
1102
+ "normalized": false,
1103
+ "rstrip": false,
1104
+ "single_word": false,
1105
+ "special": true
1106
+ },
1107
+ "128138": {
1108
+ "content": "<|reserved_special_token_130|>",
1109
+ "lstrip": false,
1110
+ "normalized": false,
1111
+ "rstrip": false,
1112
+ "single_word": false,
1113
+ "special": true
1114
+ },
1115
+ "128139": {
1116
+ "content": "<|reserved_special_token_131|>",
1117
+ "lstrip": false,
1118
+ "normalized": false,
1119
+ "rstrip": false,
1120
+ "single_word": false,
1121
+ "special": true
1122
+ },
1123
+ "128140": {
1124
+ "content": "<|reserved_special_token_132|>",
1125
+ "lstrip": false,
1126
+ "normalized": false,
1127
+ "rstrip": false,
1128
+ "single_word": false,
1129
+ "special": true
1130
+ },
1131
+ "128141": {
1132
+ "content": "<|reserved_special_token_133|>",
1133
+ "lstrip": false,
1134
+ "normalized": false,
1135
+ "rstrip": false,
1136
+ "single_word": false,
1137
+ "special": true
1138
+ },
1139
+ "128142": {
1140
+ "content": "<|reserved_special_token_134|>",
1141
+ "lstrip": false,
1142
+ "normalized": false,
1143
+ "rstrip": false,
1144
+ "single_word": false,
1145
+ "special": true
1146
+ },
1147
+ "128143": {
1148
+ "content": "<|reserved_special_token_135|>",
1149
+ "lstrip": false,
1150
+ "normalized": false,
1151
+ "rstrip": false,
1152
+ "single_word": false,
1153
+ "special": true
1154
+ },
1155
+ "128144": {
1156
+ "content": "<|reserved_special_token_136|>",
1157
+ "lstrip": false,
1158
+ "normalized": false,
1159
+ "rstrip": false,
1160
+ "single_word": false,
1161
+ "special": true
1162
+ },
1163
+ "128145": {
1164
+ "content": "<|reserved_special_token_137|>",
1165
+ "lstrip": false,
1166
+ "normalized": false,
1167
+ "rstrip": false,
1168
+ "single_word": false,
1169
+ "special": true
1170
+ },
1171
+ "128146": {
1172
+ "content": "<|reserved_special_token_138|>",
1173
+ "lstrip": false,
1174
+ "normalized": false,
1175
+ "rstrip": false,
1176
+ "single_word": false,
1177
+ "special": true
1178
+ },
1179
+ "128147": {
1180
+ "content": "<|reserved_special_token_139|>",
1181
+ "lstrip": false,
1182
+ "normalized": false,
1183
+ "rstrip": false,
1184
+ "single_word": false,
1185
+ "special": true
1186
+ },
1187
+ "128148": {
1188
+ "content": "<|reserved_special_token_140|>",
1189
+ "lstrip": false,
1190
+ "normalized": false,
1191
+ "rstrip": false,
1192
+ "single_word": false,
1193
+ "special": true
1194
+ },
1195
+ "128149": {
1196
+ "content": "<|reserved_special_token_141|>",
1197
+ "lstrip": false,
1198
+ "normalized": false,
1199
+ "rstrip": false,
1200
+ "single_word": false,
1201
+ "special": true
1202
+ },
1203
+ "128150": {
1204
+ "content": "<|reserved_special_token_142|>",
1205
+ "lstrip": false,
1206
+ "normalized": false,
1207
+ "rstrip": false,
1208
+ "single_word": false,
1209
+ "special": true
1210
+ },
1211
+ "128151": {
1212
+ "content": "<|reserved_special_token_143|>",
1213
+ "lstrip": false,
1214
+ "normalized": false,
1215
+ "rstrip": false,
1216
+ "single_word": false,
1217
+ "special": true
1218
+ },
1219
+ "128152": {
1220
+ "content": "<|reserved_special_token_144|>",
1221
+ "lstrip": false,
1222
+ "normalized": false,
1223
+ "rstrip": false,
1224
+ "single_word": false,
1225
+ "special": true
1226
+ },
1227
+ "128153": {
1228
+ "content": "<|reserved_special_token_145|>",
1229
+ "lstrip": false,
1230
+ "normalized": false,
1231
+ "rstrip": false,
1232
+ "single_word": false,
1233
+ "special": true
1234
+ },
1235
+ "128154": {
1236
+ "content": "<|reserved_special_token_146|>",
1237
+ "lstrip": false,
1238
+ "normalized": false,
1239
+ "rstrip": false,
1240
+ "single_word": false,
1241
+ "special": true
1242
+ },
1243
+ "128155": {
1244
+ "content": "<|reserved_special_token_147|>",
1245
+ "lstrip": false,
1246
+ "normalized": false,
1247
+ "rstrip": false,
1248
+ "single_word": false,
1249
+ "special": true
1250
+ },
1251
+ "128156": {
1252
+ "content": "<|reserved_special_token_148|>",
1253
+ "lstrip": false,
1254
+ "normalized": false,
1255
+ "rstrip": false,
1256
+ "single_word": false,
1257
+ "special": true
1258
+ },
1259
+ "128157": {
1260
+ "content": "<|reserved_special_token_149|>",
1261
+ "lstrip": false,
1262
+ "normalized": false,
1263
+ "rstrip": false,
1264
+ "single_word": false,
1265
+ "special": true
1266
+ },
1267
+ "128158": {
1268
+ "content": "<|reserved_special_token_150|>",
1269
+ "lstrip": false,
1270
+ "normalized": false,
1271
+ "rstrip": false,
1272
+ "single_word": false,
1273
+ "special": true
1274
+ },
1275
+ "128159": {
1276
+ "content": "<|reserved_special_token_151|>",
1277
+ "lstrip": false,
1278
+ "normalized": false,
1279
+ "rstrip": false,
1280
+ "single_word": false,
1281
+ "special": true
1282
+ },
1283
+ "128160": {
1284
+ "content": "<|reserved_special_token_152|>",
1285
+ "lstrip": false,
1286
+ "normalized": false,
1287
+ "rstrip": false,
1288
+ "single_word": false,
1289
+ "special": true
1290
+ },
1291
+ "128161": {
1292
+ "content": "<|reserved_special_token_153|>",
1293
+ "lstrip": false,
1294
+ "normalized": false,
1295
+ "rstrip": false,
1296
+ "single_word": false,
1297
+ "special": true
1298
+ },
1299
+ "128162": {
1300
+ "content": "<|reserved_special_token_154|>",
1301
+ "lstrip": false,
1302
+ "normalized": false,
1303
+ "rstrip": false,
1304
+ "single_word": false,
1305
+ "special": true
1306
+ },
1307
+ "128163": {
1308
+ "content": "<|reserved_special_token_155|>",
1309
+ "lstrip": false,
1310
+ "normalized": false,
1311
+ "rstrip": false,
1312
+ "single_word": false,
1313
+ "special": true
1314
+ },
1315
+ "128164": {
1316
+ "content": "<|reserved_special_token_156|>",
1317
+ "lstrip": false,
1318
+ "normalized": false,
1319
+ "rstrip": false,
1320
+ "single_word": false,
1321
+ "special": true
1322
+ },
1323
+ "128165": {
1324
+ "content": "<|reserved_special_token_157|>",
1325
+ "lstrip": false,
1326
+ "normalized": false,
1327
+ "rstrip": false,
1328
+ "single_word": false,
1329
+ "special": true
1330
+ },
1331
+ "128166": {
1332
+ "content": "<|reserved_special_token_158|>",
1333
+ "lstrip": false,
1334
+ "normalized": false,
1335
+ "rstrip": false,
1336
+ "single_word": false,
1337
+ "special": true
1338
+ },
1339
+ "128167": {
1340
+ "content": "<|reserved_special_token_159|>",
1341
+ "lstrip": false,
1342
+ "normalized": false,
1343
+ "rstrip": false,
1344
+ "single_word": false,
1345
+ "special": true
1346
+ },
1347
+ "128168": {
1348
+ "content": "<|reserved_special_token_160|>",
1349
+ "lstrip": false,
1350
+ "normalized": false,
1351
+ "rstrip": false,
1352
+ "single_word": false,
1353
+ "special": true
1354
+ },
1355
+ "128169": {
1356
+ "content": "<|reserved_special_token_161|>",
1357
+ "lstrip": false,
1358
+ "normalized": false,
1359
+ "rstrip": false,
1360
+ "single_word": false,
1361
+ "special": true
1362
+ },
1363
+ "128170": {
1364
+ "content": "<|reserved_special_token_162|>",
1365
+ "lstrip": false,
1366
+ "normalized": false,
1367
+ "rstrip": false,
1368
+ "single_word": false,
1369
+ "special": true
1370
+ },
1371
+ "128171": {
1372
+ "content": "<|reserved_special_token_163|>",
1373
+ "lstrip": false,
1374
+ "normalized": false,
1375
+ "rstrip": false,
1376
+ "single_word": false,
1377
+ "special": true
1378
+ },
1379
+ "128172": {
1380
+ "content": "<|reserved_special_token_164|>",
1381
+ "lstrip": false,
1382
+ "normalized": false,
1383
+ "rstrip": false,
1384
+ "single_word": false,
1385
+ "special": true
1386
+ },
1387
+ "128173": {
1388
+ "content": "<|reserved_special_token_165|>",
1389
+ "lstrip": false,
1390
+ "normalized": false,
1391
+ "rstrip": false,
1392
+ "single_word": false,
1393
+ "special": true
1394
+ },
1395
+ "128174": {
1396
+ "content": "<|reserved_special_token_166|>",
1397
+ "lstrip": false,
1398
+ "normalized": false,
1399
+ "rstrip": false,
1400
+ "single_word": false,
1401
+ "special": true
1402
+ },
1403
+ "128175": {
1404
+ "content": "<|reserved_special_token_167|>",
1405
+ "lstrip": false,
1406
+ "normalized": false,
1407
+ "rstrip": false,
1408
+ "single_word": false,
1409
+ "special": true
1410
+ },
1411
+ "128176": {
1412
+ "content": "<|reserved_special_token_168|>",
1413
+ "lstrip": false,
1414
+ "normalized": false,
1415
+ "rstrip": false,
1416
+ "single_word": false,
1417
+ "special": true
1418
+ },
1419
+ "128177": {
1420
+ "content": "<|reserved_special_token_169|>",
1421
+ "lstrip": false,
1422
+ "normalized": false,
1423
+ "rstrip": false,
1424
+ "single_word": false,
1425
+ "special": true
1426
+ },
1427
+ "128178": {
1428
+ "content": "<|reserved_special_token_170|>",
1429
+ "lstrip": false,
1430
+ "normalized": false,
1431
+ "rstrip": false,
1432
+ "single_word": false,
1433
+ "special": true
1434
+ },
1435
+ "128179": {
1436
+ "content": "<|reserved_special_token_171|>",
1437
+ "lstrip": false,
1438
+ "normalized": false,
1439
+ "rstrip": false,
1440
+ "single_word": false,
1441
+ "special": true
1442
+ },
1443
+ "128180": {
1444
+ "content": "<|reserved_special_token_172|>",
1445
+ "lstrip": false,
1446
+ "normalized": false,
1447
+ "rstrip": false,
1448
+ "single_word": false,
1449
+ "special": true
1450
+ },
1451
+ "128181": {
1452
+ "content": "<|reserved_special_token_173|>",
1453
+ "lstrip": false,
1454
+ "normalized": false,
1455
+ "rstrip": false,
1456
+ "single_word": false,
1457
+ "special": true
1458
+ },
1459
+ "128182": {
1460
+ "content": "<|reserved_special_token_174|>",
1461
+ "lstrip": false,
1462
+ "normalized": false,
1463
+ "rstrip": false,
1464
+ "single_word": false,
1465
+ "special": true
1466
+ },
1467
+ "128183": {
1468
+ "content": "<|reserved_special_token_175|>",
1469
+ "lstrip": false,
1470
+ "normalized": false,
1471
+ "rstrip": false,
1472
+ "single_word": false,
1473
+ "special": true
1474
+ },
1475
+ "128184": {
1476
+ "content": "<|reserved_special_token_176|>",
1477
+ "lstrip": false,
1478
+ "normalized": false,
1479
+ "rstrip": false,
1480
+ "single_word": false,
1481
+ "special": true
1482
+ },
1483
+ "128185": {
1484
+ "content": "<|reserved_special_token_177|>",
1485
+ "lstrip": false,
1486
+ "normalized": false,
1487
+ "rstrip": false,
1488
+ "single_word": false,
1489
+ "special": true
1490
+ },
1491
+ "128186": {
1492
+ "content": "<|reserved_special_token_178|>",
1493
+ "lstrip": false,
1494
+ "normalized": false,
1495
+ "rstrip": false,
1496
+ "single_word": false,
1497
+ "special": true
1498
+ },
1499
+ "128187": {
1500
+ "content": "<|reserved_special_token_179|>",
1501
+ "lstrip": false,
1502
+ "normalized": false,
1503
+ "rstrip": false,
1504
+ "single_word": false,
1505
+ "special": true
1506
+ },
1507
+ "128188": {
1508
+ "content": "<|reserved_special_token_180|>",
1509
+ "lstrip": false,
1510
+ "normalized": false,
1511
+ "rstrip": false,
1512
+ "single_word": false,
1513
+ "special": true
1514
+ },
1515
+ "128189": {
1516
+ "content": "<|reserved_special_token_181|>",
1517
+ "lstrip": false,
1518
+ "normalized": false,
1519
+ "rstrip": false,
1520
+ "single_word": false,
1521
+ "special": true
1522
+ },
1523
+ "128190": {
1524
+ "content": "<|reserved_special_token_182|>",
1525
+ "lstrip": false,
1526
+ "normalized": false,
1527
+ "rstrip": false,
1528
+ "single_word": false,
1529
+ "special": true
1530
+ },
1531
+ "128191": {
1532
+ "content": "<|reserved_special_token_183|>",
1533
+ "lstrip": false,
1534
+ "normalized": false,
1535
+ "rstrip": false,
1536
+ "single_word": false,
1537
+ "special": true
1538
+ },
1539
+ "128192": {
1540
+ "content": "<|reserved_special_token_184|>",
1541
+ "lstrip": false,
1542
+ "normalized": false,
1543
+ "rstrip": false,
1544
+ "single_word": false,
1545
+ "special": true
1546
+ },
1547
+ "128193": {
1548
+ "content": "<|reserved_special_token_185|>",
1549
+ "lstrip": false,
1550
+ "normalized": false,
1551
+ "rstrip": false,
1552
+ "single_word": false,
1553
+ "special": true
1554
+ },
1555
+ "128194": {
1556
+ "content": "<|reserved_special_token_186|>",
1557
+ "lstrip": false,
1558
+ "normalized": false,
1559
+ "rstrip": false,
1560
+ "single_word": false,
1561
+ "special": true
1562
+ },
1563
+ "128195": {
1564
+ "content": "<|reserved_special_token_187|>",
1565
+ "lstrip": false,
1566
+ "normalized": false,
1567
+ "rstrip": false,
1568
+ "single_word": false,
1569
+ "special": true
1570
+ },
1571
+ "128196": {
1572
+ "content": "<|reserved_special_token_188|>",
1573
+ "lstrip": false,
1574
+ "normalized": false,
1575
+ "rstrip": false,
1576
+ "single_word": false,
1577
+ "special": true
1578
+ },
1579
+ "128197": {
1580
+ "content": "<|reserved_special_token_189|>",
1581
+ "lstrip": false,
1582
+ "normalized": false,
1583
+ "rstrip": false,
1584
+ "single_word": false,
1585
+ "special": true
1586
+ },
1587
+ "128198": {
1588
+ "content": "<|reserved_special_token_190|>",
1589
+ "lstrip": false,
1590
+ "normalized": false,
1591
+ "rstrip": false,
1592
+ "single_word": false,
1593
+ "special": true
1594
+ },
1595
+ "128199": {
1596
+ "content": "<|reserved_special_token_191|>",
1597
+ "lstrip": false,
1598
+ "normalized": false,
1599
+ "rstrip": false,
1600
+ "single_word": false,
1601
+ "special": true
1602
+ },
1603
+ "128200": {
1604
+ "content": "<|reserved_special_token_192|>",
1605
+ "lstrip": false,
1606
+ "normalized": false,
1607
+ "rstrip": false,
1608
+ "single_word": false,
1609
+ "special": true
1610
+ },
1611
+ "128201": {
1612
+ "content": "<|reserved_special_token_193|>",
1613
+ "lstrip": false,
1614
+ "normalized": false,
1615
+ "rstrip": false,
1616
+ "single_word": false,
1617
+ "special": true
1618
+ },
1619
+ "128202": {
1620
+ "content": "<|reserved_special_token_194|>",
1621
+ "lstrip": false,
1622
+ "normalized": false,
1623
+ "rstrip": false,
1624
+ "single_word": false,
1625
+ "special": true
1626
+ },
1627
+ "128203": {
1628
+ "content": "<|reserved_special_token_195|>",
1629
+ "lstrip": false,
1630
+ "normalized": false,
1631
+ "rstrip": false,
1632
+ "single_word": false,
1633
+ "special": true
1634
+ },
1635
+ "128204": {
1636
+ "content": "<|reserved_special_token_196|>",
1637
+ "lstrip": false,
1638
+ "normalized": false,
1639
+ "rstrip": false,
1640
+ "single_word": false,
1641
+ "special": true
1642
+ },
1643
+ "128205": {
1644
+ "content": "<|reserved_special_token_197|>",
1645
+ "lstrip": false,
1646
+ "normalized": false,
1647
+ "rstrip": false,
1648
+ "single_word": false,
1649
+ "special": true
1650
+ },
1651
+ "128206": {
1652
+ "content": "<|reserved_special_token_198|>",
1653
+ "lstrip": false,
1654
+ "normalized": false,
1655
+ "rstrip": false,
1656
+ "single_word": false,
1657
+ "special": true
1658
+ },
1659
+ "128207": {
1660
+ "content": "<|reserved_special_token_199|>",
1661
+ "lstrip": false,
1662
+ "normalized": false,
1663
+ "rstrip": false,
1664
+ "single_word": false,
1665
+ "special": true
1666
+ },
1667
+ "128208": {
1668
+ "content": "<|reserved_special_token_200|>",
1669
+ "lstrip": false,
1670
+ "normalized": false,
1671
+ "rstrip": false,
1672
+ "single_word": false,
1673
+ "special": true
1674
+ },
1675
+ "128209": {
1676
+ "content": "<|reserved_special_token_201|>",
1677
+ "lstrip": false,
1678
+ "normalized": false,
1679
+ "rstrip": false,
1680
+ "single_word": false,
1681
+ "special": true
1682
+ },
1683
+ "128210": {
1684
+ "content": "<|reserved_special_token_202|>",
1685
+ "lstrip": false,
1686
+ "normalized": false,
1687
+ "rstrip": false,
1688
+ "single_word": false,
1689
+ "special": true
1690
+ },
1691
+ "128211": {
1692
+ "content": "<|reserved_special_token_203|>",
1693
+ "lstrip": false,
1694
+ "normalized": false,
1695
+ "rstrip": false,
1696
+ "single_word": false,
1697
+ "special": true
1698
+ },
1699
+ "128212": {
1700
+ "content": "<|reserved_special_token_204|>",
1701
+ "lstrip": false,
1702
+ "normalized": false,
1703
+ "rstrip": false,
1704
+ "single_word": false,
1705
+ "special": true
1706
+ },
1707
+ "128213": {
1708
+ "content": "<|reserved_special_token_205|>",
1709
+ "lstrip": false,
1710
+ "normalized": false,
1711
+ "rstrip": false,
1712
+ "single_word": false,
1713
+ "special": true
1714
+ },
1715
+ "128214": {
1716
+ "content": "<|reserved_special_token_206|>",
1717
+ "lstrip": false,
1718
+ "normalized": false,
1719
+ "rstrip": false,
1720
+ "single_word": false,
1721
+ "special": true
1722
+ },
1723
+ "128215": {
1724
+ "content": "<|reserved_special_token_207|>",
1725
+ "lstrip": false,
1726
+ "normalized": false,
1727
+ "rstrip": false,
1728
+ "single_word": false,
1729
+ "special": true
1730
+ },
1731
+ "128216": {
1732
+ "content": "<|reserved_special_token_208|>",
1733
+ "lstrip": false,
1734
+ "normalized": false,
1735
+ "rstrip": false,
1736
+ "single_word": false,
1737
+ "special": true
1738
+ },
1739
+ "128217": {
1740
+ "content": "<|reserved_special_token_209|>",
1741
+ "lstrip": false,
1742
+ "normalized": false,
1743
+ "rstrip": false,
1744
+ "single_word": false,
1745
+ "special": true
1746
+ },
1747
+ "128218": {
1748
+ "content": "<|reserved_special_token_210|>",
1749
+ "lstrip": false,
1750
+ "normalized": false,
1751
+ "rstrip": false,
1752
+ "single_word": false,
1753
+ "special": true
1754
+ },
1755
+ "128219": {
1756
+ "content": "<|reserved_special_token_211|>",
1757
+ "lstrip": false,
1758
+ "normalized": false,
1759
+ "rstrip": false,
1760
+ "single_word": false,
1761
+ "special": true
1762
+ },
1763
+ "128220": {
1764
+ "content": "<|reserved_special_token_212|>",
1765
+ "lstrip": false,
1766
+ "normalized": false,
1767
+ "rstrip": false,
1768
+ "single_word": false,
1769
+ "special": true
1770
+ },
1771
+ "128221": {
1772
+ "content": "<|reserved_special_token_213|>",
1773
+ "lstrip": false,
1774
+ "normalized": false,
1775
+ "rstrip": false,
1776
+ "single_word": false,
1777
+ "special": true
1778
+ },
1779
+ "128222": {
1780
+ "content": "<|reserved_special_token_214|>",
1781
+ "lstrip": false,
1782
+ "normalized": false,
1783
+ "rstrip": false,
1784
+ "single_word": false,
1785
+ "special": true
1786
+ },
1787
+ "128223": {
1788
+ "content": "<|reserved_special_token_215|>",
1789
+ "lstrip": false,
1790
+ "normalized": false,
1791
+ "rstrip": false,
1792
+ "single_word": false,
1793
+ "special": true
1794
+ },
1795
+ "128224": {
1796
+ "content": "<|reserved_special_token_216|>",
1797
+ "lstrip": false,
1798
+ "normalized": false,
1799
+ "rstrip": false,
1800
+ "single_word": false,
1801
+ "special": true
1802
+ },
1803
+ "128225": {
1804
+ "content": "<|reserved_special_token_217|>",
1805
+ "lstrip": false,
1806
+ "normalized": false,
1807
+ "rstrip": false,
1808
+ "single_word": false,
1809
+ "special": true
1810
+ },
1811
+ "128226": {
1812
+ "content": "<|reserved_special_token_218|>",
1813
+ "lstrip": false,
1814
+ "normalized": false,
1815
+ "rstrip": false,
1816
+ "single_word": false,
1817
+ "special": true
1818
+ },
1819
+ "128227": {
1820
+ "content": "<|reserved_special_token_219|>",
1821
+ "lstrip": false,
1822
+ "normalized": false,
1823
+ "rstrip": false,
1824
+ "single_word": false,
1825
+ "special": true
1826
+ },
1827
+ "128228": {
1828
+ "content": "<|reserved_special_token_220|>",
1829
+ "lstrip": false,
1830
+ "normalized": false,
1831
+ "rstrip": false,
1832
+ "single_word": false,
1833
+ "special": true
1834
+ },
1835
+ "128229": {
1836
+ "content": "<|reserved_special_token_221|>",
1837
+ "lstrip": false,
1838
+ "normalized": false,
1839
+ "rstrip": false,
1840
+ "single_word": false,
1841
+ "special": true
1842
+ },
1843
+ "128230": {
1844
+ "content": "<|reserved_special_token_222|>",
1845
+ "lstrip": false,
1846
+ "normalized": false,
1847
+ "rstrip": false,
1848
+ "single_word": false,
1849
+ "special": true
1850
+ },
1851
+ "128231": {
1852
+ "content": "<|reserved_special_token_223|>",
1853
+ "lstrip": false,
1854
+ "normalized": false,
1855
+ "rstrip": false,
1856
+ "single_word": false,
1857
+ "special": true
1858
+ },
1859
+ "128232": {
1860
+ "content": "<|reserved_special_token_224|>",
1861
+ "lstrip": false,
1862
+ "normalized": false,
1863
+ "rstrip": false,
1864
+ "single_word": false,
1865
+ "special": true
1866
+ },
1867
+ "128233": {
1868
+ "content": "<|reserved_special_token_225|>",
1869
+ "lstrip": false,
1870
+ "normalized": false,
1871
+ "rstrip": false,
1872
+ "single_word": false,
1873
+ "special": true
1874
+ },
1875
+ "128234": {
1876
+ "content": "<|reserved_special_token_226|>",
1877
+ "lstrip": false,
1878
+ "normalized": false,
1879
+ "rstrip": false,
1880
+ "single_word": false,
1881
+ "special": true
1882
+ },
1883
+ "128235": {
1884
+ "content": "<|reserved_special_token_227|>",
1885
+ "lstrip": false,
1886
+ "normalized": false,
1887
+ "rstrip": false,
1888
+ "single_word": false,
1889
+ "special": true
1890
+ },
1891
+ "128236": {
1892
+ "content": "<|reserved_special_token_228|>",
1893
+ "lstrip": false,
1894
+ "normalized": false,
1895
+ "rstrip": false,
1896
+ "single_word": false,
1897
+ "special": true
1898
+ },
1899
+ "128237": {
1900
+ "content": "<|reserved_special_token_229|>",
1901
+ "lstrip": false,
1902
+ "normalized": false,
1903
+ "rstrip": false,
1904
+ "single_word": false,
1905
+ "special": true
1906
+ },
1907
+ "128238": {
1908
+ "content": "<|reserved_special_token_230|>",
1909
+ "lstrip": false,
1910
+ "normalized": false,
1911
+ "rstrip": false,
1912
+ "single_word": false,
1913
+ "special": true
1914
+ },
1915
+ "128239": {
1916
+ "content": "<|reserved_special_token_231|>",
1917
+ "lstrip": false,
1918
+ "normalized": false,
1919
+ "rstrip": false,
1920
+ "single_word": false,
1921
+ "special": true
1922
+ },
1923
+ "128240": {
1924
+ "content": "<|reserved_special_token_232|>",
1925
+ "lstrip": false,
1926
+ "normalized": false,
1927
+ "rstrip": false,
1928
+ "single_word": false,
1929
+ "special": true
1930
+ },
1931
+ "128241": {
1932
+ "content": "<|reserved_special_token_233|>",
1933
+ "lstrip": false,
1934
+ "normalized": false,
1935
+ "rstrip": false,
1936
+ "single_word": false,
1937
+ "special": true
1938
+ },
1939
+ "128242": {
1940
+ "content": "<|reserved_special_token_234|>",
1941
+ "lstrip": false,
1942
+ "normalized": false,
1943
+ "rstrip": false,
1944
+ "single_word": false,
1945
+ "special": true
1946
+ },
1947
+ "128243": {
1948
+ "content": "<|reserved_special_token_235|>",
1949
+ "lstrip": false,
1950
+ "normalized": false,
1951
+ "rstrip": false,
1952
+ "single_word": false,
1953
+ "special": true
1954
+ },
1955
+ "128244": {
1956
+ "content": "<|reserved_special_token_236|>",
1957
+ "lstrip": false,
1958
+ "normalized": false,
1959
+ "rstrip": false,
1960
+ "single_word": false,
1961
+ "special": true
1962
+ },
1963
+ "128245": {
1964
+ "content": "<|reserved_special_token_237|>",
1965
+ "lstrip": false,
1966
+ "normalized": false,
1967
+ "rstrip": false,
1968
+ "single_word": false,
1969
+ "special": true
1970
+ },
1971
+ "128246": {
1972
+ "content": "<|reserved_special_token_238|>",
1973
+ "lstrip": false,
1974
+ "normalized": false,
1975
+ "rstrip": false,
1976
+ "single_word": false,
1977
+ "special": true
1978
+ },
1979
+ "128247": {
1980
+ "content": "<|reserved_special_token_239|>",
1981
+ "lstrip": false,
1982
+ "normalized": false,
1983
+ "rstrip": false,
1984
+ "single_word": false,
1985
+ "special": true
1986
+ },
1987
+ "128248": {
1988
+ "content": "<|reserved_special_token_240|>",
1989
+ "lstrip": false,
1990
+ "normalized": false,
1991
+ "rstrip": false,
1992
+ "single_word": false,
1993
+ "special": true
1994
+ },
1995
+ "128249": {
1996
+ "content": "<|reserved_special_token_241|>",
1997
+ "lstrip": false,
1998
+ "normalized": false,
1999
+ "rstrip": false,
2000
+ "single_word": false,
2001
+ "special": true
2002
+ },
2003
+ "128250": {
2004
+ "content": "<|reserved_special_token_242|>",
2005
+ "lstrip": false,
2006
+ "normalized": false,
2007
+ "rstrip": false,
2008
+ "single_word": false,
2009
+ "special": true
2010
+ },
2011
+ "128251": {
2012
+ "content": "<|reserved_special_token_243|>",
2013
+ "lstrip": false,
2014
+ "normalized": false,
2015
+ "rstrip": false,
2016
+ "single_word": false,
2017
+ "special": true
2018
+ },
2019
+ "128252": {
2020
+ "content": "<|reserved_special_token_244|>",
2021
+ "lstrip": false,
2022
+ "normalized": false,
2023
+ "rstrip": false,
2024
+ "single_word": false,
2025
+ "special": true
2026
+ },
2027
+ "128253": {
2028
+ "content": "<|reserved_special_token_245|>",
2029
+ "lstrip": false,
2030
+ "normalized": false,
2031
+ "rstrip": false,
2032
+ "single_word": false,
2033
+ "special": true
2034
+ },
2035
+ "128254": {
2036
+ "content": "<|reserved_special_token_246|>",
2037
+ "lstrip": false,
2038
+ "normalized": false,
2039
+ "rstrip": false,
2040
+ "single_word": false,
2041
+ "special": true
2042
+ },
2043
+ "128255": {
2044
+ "content": "<|reserved_special_token_247|>",
2045
+ "lstrip": false,
2046
+ "normalized": false,
2047
+ "rstrip": false,
2048
+ "single_word": false,
2049
+ "special": true
2050
+ }
2051
+ },
2052
+ "bos_token": "<|begin_of_text|>",
2053
+ "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",
2054
+ "clean_up_tokenization_spaces": true,
2055
+ "eos_token": "<|eot_id|>",
2056
+ "pad_token": "<|finetune_right_pad_id|>",
2057
+ "model_input_names": [
2058
+ "input_ids",
2059
+ "attention_mask"
2060
+ ],
2061
+ "model_max_length": 131072,
2062
+ "tokenizer_class": "PreTrainedTokenizerFast"
2063
+ }
zero_to_fp32.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
153
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
154
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
155
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
156
+
157
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
158
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
159
+ # use the max of the partition_count to get the dp world_size.
160
+
161
+ if type(world_size) is list:
162
+ world_size = max(world_size)
163
+
164
+ if world_size != total_files:
165
+ raise ValueError(
166
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
167
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
168
+ )
169
+
170
+ # the groups are named differently in each stage
171
+ if zero_stage <= 2:
172
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
173
+ elif zero_stage == 3:
174
+ fp32_groups_key = FP32_FLAT_GROUPS
175
+ else:
176
+ raise ValueError(f"unknown zero stage {zero_stage}")
177
+
178
+ if zero_stage <= 2:
179
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
180
+ elif zero_stage == 3:
181
+ # if there is more than one param group, there will be multiple flattened tensors - one
182
+ # flattened tensor per group - for simplicity merge them into a single tensor
183
+ #
184
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
185
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
186
+
187
+ fp32_flat_groups = [
188
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
189
+ ]
190
+
191
+ return zero_stage, world_size, fp32_flat_groups
192
+
193
+
194
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
195
+ """
196
+ Returns fp32 state_dict reconstructed from ds checkpoint
197
+
198
+ Args:
199
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
200
+
201
+ """
202
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
203
+
204
+ optim_files = get_optim_files(ds_checkpoint_dir)
205
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
206
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
207
+
208
+ model_files = get_model_state_files(ds_checkpoint_dir)
209
+
210
+ zero_model_states = parse_model_states(model_files)
211
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
212
+
213
+ if zero_stage <= 2:
214
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
215
+ exclude_frozen_parameters)
216
+ elif zero_stage == 3:
217
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
218
+ exclude_frozen_parameters)
219
+
220
+
221
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
222
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
223
+ return
224
+
225
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
226
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
227
+
228
+ if debug:
229
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
230
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
231
+
232
+ wanted_params = len(frozen_param_shapes)
233
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
234
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
235
+ print(f'Frozen params: Have {avail_numel} numels to process.')
236
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
237
+
238
+ total_params = 0
239
+ total_numel = 0
240
+ for name, shape in frozen_param_shapes.items():
241
+ total_params += 1
242
+ unpartitioned_numel = shape.numel()
243
+ total_numel += unpartitioned_numel
244
+
245
+ state_dict[name] = frozen_param_fragments[name]
246
+
247
+ if debug:
248
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
249
+
250
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
251
+
252
+
253
+ def _has_callable(obj, fn):
254
+ attr = getattr(obj, fn, None)
255
+ return callable(attr)
256
+
257
+
258
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
259
+ param_shapes = zero_model_states[0].param_shapes
260
+
261
+ # Reconstruction protocol:
262
+ #
263
+ # XXX: document this
264
+
265
+ if debug:
266
+ for i in range(world_size):
267
+ for j in range(len(fp32_flat_groups[0])):
268
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
269
+
270
+ # XXX: memory usage doubles here (zero2)
271
+ num_param_groups = len(fp32_flat_groups[0])
272
+ merged_single_partition_of_fp32_groups = []
273
+ for i in range(num_param_groups):
274
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
275
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
276
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
277
+ avail_numel = sum(
278
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
279
+
280
+ if debug:
281
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
282
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
283
+ # not asserting if there is a mismatch due to possible padding
284
+ print(f"Have {avail_numel} numels to process.")
285
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
286
+
287
+ # params
288
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
289
+ # out-of-core computing solution
290
+ total_numel = 0
291
+ total_params = 0
292
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
293
+ offset = 0
294
+ avail_numel = full_single_fp32_vector.numel()
295
+ for name, shape in shapes.items():
296
+
297
+ unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
298
+ total_numel += unpartitioned_numel
299
+ total_params += 1
300
+
301
+ if debug:
302
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
303
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
304
+ offset += unpartitioned_numel
305
+
306
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
307
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
308
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
309
+ # live optimizer object, so we are checking that the numbers are within the right range
310
+ align_to = 2 * world_size
311
+
312
+ def zero2_align(x):
313
+ return align_to * math.ceil(x / align_to)
314
+
315
+ if debug:
316
+ print(f"original offset={offset}, avail_numel={avail_numel}")
317
+
318
+ offset = zero2_align(offset)
319
+ avail_numel = zero2_align(avail_numel)
320
+
321
+ if debug:
322
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
323
+
324
+ # Sanity check
325
+ if offset != avail_numel:
326
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
327
+
328
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
329
+
330
+
331
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
332
+ exclude_frozen_parameters):
333
+ state_dict = OrderedDict()
334
+
335
+ # buffers
336
+ buffers = zero_model_states[0].buffers
337
+ state_dict.update(buffers)
338
+ if debug:
339
+ print(f"added {len(buffers)} buffers")
340
+
341
+ if not exclude_frozen_parameters:
342
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
343
+
344
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
345
+
346
+ # recover shared parameters
347
+ for pair in zero_model_states[0].shared_params:
348
+ if pair[1] in state_dict:
349
+ state_dict[pair[0]] = state_dict[pair[1]]
350
+
351
+ return state_dict
352
+
353
+
354
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
355
+ remainder = unpartitioned_numel % world_size
356
+ padding_numel = (world_size - remainder) if remainder else 0
357
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
358
+ return partitioned_numel, padding_numel
359
+
360
+
361
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
362
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
363
+ return
364
+
365
+ if debug:
366
+ for i in range(world_size):
367
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
368
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
369
+
370
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
371
+ wanted_params = len(frozen_param_shapes)
372
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
373
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
374
+ print(f'Frozen params: Have {avail_numel} numels to process.')
375
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
376
+
377
+ total_params = 0
378
+ total_numel = 0
379
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
380
+ total_params += 1
381
+ unpartitioned_numel = shape.numel()
382
+ total_numel += unpartitioned_numel
383
+
384
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
385
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
386
+
387
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
388
+
389
+ if debug:
390
+ print(
391
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
392
+ )
393
+
394
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
395
+
396
+
397
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
398
+ param_shapes = zero_model_states[0].param_shapes
399
+ avail_numel = fp32_flat_groups[0].numel() * world_size
400
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
401
+ # param, re-consolidating each param, while dealing with padding if any
402
+
403
+ # merge list of dicts, preserving order
404
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
405
+
406
+ if debug:
407
+ for i in range(world_size):
408
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
409
+
410
+ wanted_params = len(param_shapes)
411
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
412
+ # not asserting if there is a mismatch due to possible padding
413
+ avail_numel = fp32_flat_groups[0].numel() * world_size
414
+ print(f"Trainable params: Have {avail_numel} numels to process.")
415
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
416
+
417
+ # params
418
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
419
+ # out-of-core computing solution
420
+ offset = 0
421
+ total_numel = 0
422
+ total_params = 0
423
+ for name, shape in param_shapes.items():
424
+
425
+ unpartitioned_numel = shape.numel()
426
+ total_numel += unpartitioned_numel
427
+ total_params += 1
428
+
429
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
430
+
431
+ if debug:
432
+ print(
433
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
434
+ )
435
+
436
+ # XXX: memory usage doubles here
437
+ state_dict[name] = torch.cat(
438
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
439
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
440
+ offset += partitioned_numel
441
+
442
+ offset *= world_size
443
+
444
+ # Sanity check
445
+ if offset != avail_numel:
446
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
447
+
448
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
449
+
450
+
451
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
452
+ exclude_frozen_parameters):
453
+ state_dict = OrderedDict()
454
+
455
+ # buffers
456
+ buffers = zero_model_states[0].buffers
457
+ state_dict.update(buffers)
458
+ if debug:
459
+ print(f"added {len(buffers)} buffers")
460
+
461
+ if not exclude_frozen_parameters:
462
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
463
+
464
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
465
+
466
+ # recover shared parameters
467
+ for pair in zero_model_states[0].shared_params:
468
+ if pair[1] in state_dict:
469
+ state_dict[pair[0]] = state_dict[pair[1]]
470
+
471
+ return state_dict
472
+
473
+
474
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False):
475
+ """
476
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
477
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
478
+ via a model hub.
479
+
480
+ Args:
481
+ - ``checkpoint_dir``: path to the desired checkpoint folder
482
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
483
+ - ``exclude_frozen_parameters``: exclude frozen parameters
484
+
485
+ Returns:
486
+ - pytorch ``state_dict``
487
+
488
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
489
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
490
+ the checkpoint.
491
+
492
+ A typical usage might be ::
493
+
494
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
495
+ # do the training and checkpoint saving
496
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
497
+ model = model.cpu() # move to cpu
498
+ model.load_state_dict(state_dict)
499
+ # submit to model hub or save the model to share with others
500
+
501
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
502
+ application. i.e. you will need to re-initialize the deepspeed engine, since
503
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
504
+
505
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
506
+
507
+ """
508
+ if tag is None:
509
+ latest_path = os.path.join(checkpoint_dir, 'latest')
510
+ if os.path.isfile(latest_path):
511
+ with open(latest_path, 'r') as fd:
512
+ tag = fd.read().strip()
513
+ else:
514
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
515
+
516
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
517
+
518
+ if not os.path.isdir(ds_checkpoint_dir):
519
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
520
+
521
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
522
+
523
+
524
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False):
525
+ """
526
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
527
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
528
+
529
+ Args:
530
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
531
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
532
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
533
+ - ``exclude_frozen_parameters``: exclude frozen parameters
534
+ """
535
+
536
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters)
537
+ print(f"Saving fp32 state dict to {output_file}")
538
+ torch.save(state_dict, output_file)
539
+
540
+
541
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
542
+ """
543
+ 1. Put the provided model to cpu
544
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
545
+ 3. Load it into the provided model
546
+
547
+ Args:
548
+ - ``model``: the model object to update
549
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
550
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
551
+
552
+ Returns:
553
+ - ``model`: modified model
554
+
555
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
556
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
557
+ conveniently placed for you in the checkpoint folder.
558
+
559
+ A typical usage might be ::
560
+
561
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
562
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
563
+ # submit to model hub or save the model to share with others
564
+
565
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
566
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
567
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
568
+
569
+ """
570
+ logger.info(f"Extracting fp32 weights")
571
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
572
+
573
+ logger.info(f"Overwriting model with fp32 weights")
574
+ model = model.cpu()
575
+ model.load_state_dict(state_dict, strict=False)
576
+
577
+ return model
578
+
579
+
580
+ if __name__ == "__main__":
581
+
582
+ parser = argparse.ArgumentParser()
583
+ parser.add_argument("checkpoint_dir",
584
+ type=str,
585
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
586
+ parser.add_argument(
587
+ "output_file",
588
+ type=str,
589
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
590
+ parser.add_argument("-t",
591
+ "--tag",
592
+ type=str,
593
+ default=None,
594
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
595
+ parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
596
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
597
+ args = parser.parse_args()
598
+
599
+ debug = args.debug
600
+
601
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
602
+ args.output_file,
603
+ tag=args.tag,
604
+ exclude_frozen_parameters=args.exclude_frozen_parameters)