unsubscribe commited on
Commit
dd5335b
·
verified ·
1 Parent(s): 5581b0e

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_attn_implementation_autoset": true,
3
+ "_name_or_path": "/mnt/141/develop_internlm3_open_source_hf_0110v1/20250109095225_hf-080_open_source_hf",
4
+ "architectures": [
5
+ "InternLM3ForCausalLM"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_internlm3.InternLM3Config",
10
+ "AutoModel": "modeling_internlm3.InternLM3Model",
11
+ "AutoModelForCausalLM": "modeling_internlm3.InternLM3ForCausalLM"
12
+ },
13
+ "bias": false,
14
+ "bos_token_id": 1,
15
+ "eos_token_id": 2,
16
+ "head_dim": 128,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 4096,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 10240,
21
+ "max_position_embeddings": 32768,
22
+ "model_type": "internlm3",
23
+ "num_attention_heads": 32,
24
+ "num_hidden_layers": 48,
25
+ "num_key_value_heads": 2,
26
+ "pad_token_id": 2,
27
+ "qkv_bias": false,
28
+ "quantization_config": {
29
+ "bits": 4,
30
+ "damp_percent": 0.01,
31
+ "desc_act": false,
32
+ "group_size": 128,
33
+ "is_marlin_format": false,
34
+ "model_file_base_name": null,
35
+ "model_name_or_path": null,
36
+ "quant_method": "gptq",
37
+ "static_groups": false,
38
+ "sym": true,
39
+ "true_sequential": true
40
+ },
41
+ "rms_norm_eps": 1e-05,
42
+ "rope_scaling": {
43
+ "factor": 6.0,
44
+ "rope_type": "dynamic"
45
+ },
46
+ "rope_theta": 50000000,
47
+ "tie_word_embeddings": false,
48
+ "torch_dtype": "bfloat16",
49
+ "transformers_version": "4.48.0.dev0",
50
+ "use_cache": true,
51
+ "vocab_size": 128512
52
+ }
configuration_internlm3.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on transformers/src/transformers/models/llama/configuration_llama.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ InternLM3 model configuration"""
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.modeling_rope_utils import rope_config_validation
21
+ from transformers.utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class InternLM3Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
30
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 151936):
39
+ Vocabulary size of the InternLM3 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`InternLM3Model`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 22016):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ num_key_value_heads (`int`, *optional*, defaults to 32):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
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 32768):
59
+ The maximum sequence length that this model might ever be used with.
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
63
+ The epsilon used by the rms normalization layers.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
66
+ relevant if `config.is_decoder=True`.
67
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
68
+ Whether the model's input and output word embeddings should be tied.
69
+ rope_theta (`float`, *optional*, defaults to 10000.0):
70
+ The base period of the RoPE embeddings.
71
+ rope_scaling (`Dict`, *optional*):
72
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
73
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
74
+ accordingly.
75
+ Expected contents:
76
+ `rope_type` (`str`):
77
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
78
+ 'llama3'], with 'default' being the original RoPE implementation.
79
+ `factor` (`float`, *optional*):
80
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
81
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
82
+ original maximum pre-trained length.
83
+ `original_max_position_embeddings` (`int`, *optional*):
84
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
85
+ pretraining.
86
+ `attention_factor` (`float`, *optional*):
87
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
88
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
89
+ `factor` field to infer the suggested value.
90
+ `beta_fast` (`float`, *optional*):
91
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
92
+ ramp function. If unspecified, it defaults to 32.
93
+ `beta_slow` (`float`, *optional*):
94
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
95
+ ramp function. If unspecified, it defaults to 1.
96
+ `short_factor` (`List[float]`, *optional*):
97
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
98
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
99
+ size divided by the number of attention heads divided by 2
100
+ `long_factor` (`List[float]`, *optional*):
101
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
102
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
103
+ size divided by the number of attention heads divided by 2
104
+ `low_freq_factor` (`float`, *optional*):
105
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
106
+ `high_freq_factor` (`float`, *optional*):
107
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
108
+ qkv_bias (`bool`, *optional*, defaults to `False`):
109
+ Whether to use a bias in the query, key and value projection layers during self-attention.
110
+ attention_dropout (`float`, *optional*, defaults to 0.0):
111
+ The dropout ratio for the attention probabilities.
112
+ bias (`bool`, *optional*, defaults to `False`):
113
+ Whether to use a bias in o_proj, up_proj, down_proj and gate_proj layers.
114
+ head_dim (`int`, *optional*):
115
+ The attention head dimension. If None, it will default to hidden_size // num_heads
116
+
117
+ ```python
118
+ >>> from transformers import InternLM3Model, InternLM3Config
119
+
120
+ >>> # Initializing a InternLM3 style configuration
121
+ >>> configuration = InternLM3Config()
122
+
123
+ >>> # Initializing a model from the InternLM3-8B style configuration
124
+ >>> model = InternLM3Model(configuration)
125
+
126
+ >>> # Accessing the model configuration
127
+ >>> configuration = model.config
128
+ ```"""
129
+
130
+ model_type = "internlm3"
131
+ keys_to_ignore_at_inference = ["past_key_values"]
132
+
133
+ # Default tensor parallel plan for base model `InternLM3`
134
+ base_model_tp_plan = {
135
+ "layers.*.self_attn.q_proj": "colwise",
136
+ "layers.*.self_attn.k_proj": "colwise",
137
+ "layers.*.self_attn.v_proj": "colwise",
138
+ "layers.*.self_attn.o_proj": "rowwise",
139
+ "layers.*.mlp.gate_proj": "colwise",
140
+ "layers.*.mlp.up_proj": "colwise",
141
+ "layers.*.mlp.down_proj": "rowwise",
142
+ }
143
+
144
+ def __init__(
145
+ self,
146
+ vocab_size=128512,
147
+ hidden_size=4096,
148
+ intermediate_size=11008,
149
+ num_hidden_layers=32,
150
+ num_attention_heads=32,
151
+ num_key_value_heads=32,
152
+ hidden_act="silu",
153
+ max_position_embeddings=32768,
154
+ initializer_range=0.02,
155
+ rms_norm_eps=1e-6,
156
+ use_cache=True,
157
+ tie_word_embeddings=False,
158
+ rope_theta=10000.0,
159
+ rope_scaling=None,
160
+ qkv_bias=False,
161
+ attention_dropout=0.0,
162
+ bias=False,
163
+ head_dim=None,
164
+ **kwargs,
165
+ ):
166
+ self.vocab_size = vocab_size
167
+ self.max_position_embeddings = max_position_embeddings
168
+ self.hidden_size = hidden_size
169
+ self.intermediate_size = intermediate_size
170
+ self.num_hidden_layers = num_hidden_layers
171
+ self.num_attention_heads = num_attention_heads
172
+
173
+ # for backward compatibility
174
+ if num_key_value_heads is None:
175
+ num_key_value_heads = num_attention_heads
176
+
177
+ self.num_key_value_heads = num_key_value_heads
178
+ self.hidden_act = hidden_act
179
+ self.initializer_range = initializer_range
180
+ self.rms_norm_eps = rms_norm_eps
181
+ self.use_cache = use_cache
182
+ self.rope_theta = rope_theta
183
+ self.rope_scaling = rope_scaling
184
+ self.qkv_bias = qkv_bias
185
+ self.attention_dropout = attention_dropout
186
+ self.bias = bias
187
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
188
+ # Validate the correctness of rotary position embeddings parameters
189
+ # BC: if there is a 'type' field, move it to 'rope_type'.
190
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
191
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
192
+ rope_config_validation(self)
193
+
194
+ super().__init__(
195
+ tie_word_embeddings=tie_word_embeddings,
196
+ **kwargs,
197
+ )
gptq_model-4bit-128g.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b7e5f460501c46bae53373710dd17037936802d3dbb9b46578657742a7d041d
3
+ size 6143339208
quantize_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bits": 4,
3
+ "group_size": 128,
4
+ "damp_percent": 0.01,
5
+ "desc_act": false,
6
+ "static_groups": false,
7
+ "sym": true,
8
+ "true_sequential": true,
9
+ "model_name_or_path": null,
10
+ "model_file_base_name": null,
11
+ "is_marlin_format": false,
12
+ "quant_method": "gptq"
13
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|action_start|>",
6
+ "<|action_end|>",
7
+ "<|interpreter|>",
8
+ "<|plugin|>",
9
+ "<restate>",
10
+ "</restate>",
11
+ "<planning>",
12
+ "</planning>",
13
+ "<recollect>",
14
+ "</recollect>",
15
+ "<execution>",
16
+ "</execution>",
17
+ "<review>",
18
+ "</review>",
19
+ "<summarize>",
20
+ "</summarize>",
21
+ "<retry>",
22
+ "</retry>",
23
+ "<conclude>",
24
+ "</conclude>"
25
+ ],
26
+ "bos_token": {
27
+ "content": "<s>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ },
33
+ "eos_token": {
34
+ "content": "</s>",
35
+ "lstrip": false,
36
+ "normalized": false,
37
+ "rstrip": false,
38
+ "single_word": false
39
+ },
40
+ "pad_token": {
41
+ "content": "</s>",
42
+ "lstrip": false,
43
+ "normalized": false,
44
+ "rstrip": false,
45
+ "single_word": false
46
+ },
47
+ "unk_token": {
48
+ "content": "<unk>",
49
+ "lstrip": false,
50
+ "normalized": false,
51
+ "rstrip": false,
52
+ "single_word": false
53
+ }
54
+ }
tokenization_internlm3.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from shutil import copyfile
3
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
4
+
5
+ import sentencepiece as spm
6
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
7
+ from transformers.utils import logging
8
+
9
+ if TYPE_CHECKING:
10
+ from transformers.tokenization_utils_base import TextInput
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
15
+
16
+ SPIECE_UNDERLINE = "▁"
17
+
18
+
19
+ class InternLM3Tokenizer(PreTrainedTokenizer):
20
+ """
21
+ Construct a InternLM3 tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
22
+ no padding token in the original model.
23
+
24
+ Args:
25
+ vocab_file (`str`):
26
+ Path to the vocabulary file.
27
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
28
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
29
+ token instead.
30
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
31
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
32
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
33
+ The end of sequence token.
34
+ pad_token (`str` or `tokenizers.AddedToken`, *optional*):
35
+ A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
36
+ attention mechanisms or loss computation.
37
+ sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
38
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
39
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
40
+ to set:
41
+
42
+ - `enable_sampling`: Enable subword regularization.
43
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
44
+
45
+ - `nbest_size = {0,1}`: No sampling is performed.
46
+ - `nbest_size > 1`: samples from the nbest_size results.
47
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
48
+ using forward-filtering-and-backward-sampling algorithm.
49
+
50
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
51
+ BPE-dropout.
52
+
53
+ add_bos_token (`bool`, *optional*, defaults to `True`):
54
+ Whether or not to add an `bos_token` at the start of sequences.
55
+ add_eos_token (`bool`, *optional*, defaults to `False`):
56
+ Whether or not to add an `eos_token` at the end of sequences.
57
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
58
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
59
+ extra spaces.
60
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
61
+ Whether or not the default system prompt for InternLM3 should be used.
62
+ spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
63
+ Whether or not to add spaces between special tokens.
64
+ spaces_for_interleaved_special_tokens (`bool`, *optional*, defaults to `False`):
65
+ Whether or not to add spaces between special tokens that are interleaved with normal tokens.
66
+ add_prefix_space (`bool`, *optional*, defaults to `True`):
67
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
68
+ other word. Again, this should be set with `from_slow=True` to make sure it's taken into account.
69
+ """
70
+
71
+ vocab_files_names = VOCAB_FILES_NAMES
72
+ model_input_names = ["input_ids", "attention_mask"]
73
+
74
+ def __init__(
75
+ self,
76
+ vocab_file,
77
+ unk_token="<unk>",
78
+ bos_token="<s>",
79
+ eos_token="</s>",
80
+ pad_token=None,
81
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
82
+ add_bos_token=True,
83
+ add_eos_token=False,
84
+ clean_up_tokenization_spaces=False,
85
+ use_default_system_prompt=False,
86
+ spaces_between_special_tokens=False,
87
+ spaces_for_interleaved_special_tokens=False,
88
+ add_prefix_space=True,
89
+ **kwargs,
90
+ ):
91
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
92
+ bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
93
+ eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
94
+ unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
95
+ pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
96
+
97
+ self.vocab_file = vocab_file
98
+ self.add_bos_token = add_bos_token
99
+ self.add_eos_token = add_eos_token
100
+ self.use_default_system_prompt = use_default_system_prompt
101
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
102
+ self.sp_model.Load(vocab_file)
103
+ self.add_prefix_space = add_prefix_space
104
+ self.spaces_for_interleaved_special_tokens = spaces_for_interleaved_special_tokens
105
+
106
+ vocab_size = self.sp_model.get_piece_size()
107
+ self.decoder = {i: self.sp_model.id_to_piece(i) for i in range(vocab_size)}
108
+
109
+ super().__init__(
110
+ bos_token=bos_token,
111
+ eos_token=eos_token,
112
+ unk_token=unk_token,
113
+ pad_token=pad_token,
114
+ add_bos_token=add_bos_token,
115
+ add_eos_token=add_eos_token,
116
+ sp_model_kwargs=sp_model_kwargs,
117
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
118
+ use_default_system_prompt=use_default_system_prompt,
119
+ spaces_between_special_tokens=spaces_between_special_tokens,
120
+ add_prefix_space=add_prefix_space,
121
+ **kwargs,
122
+ )
123
+
124
+ def __getstate__(self):
125
+ state = self.__dict__.copy()
126
+ state["sp_model"] = None
127
+ state["sp_model_proto"] = self.sp_model.serialized_model_proto()
128
+ return state
129
+
130
+ def __setstate__(self, d):
131
+ self.__dict__.update(d)
132
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
133
+ self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
134
+
135
+ @property
136
+ def vocab_size(self):
137
+ """Returns vocab size"""
138
+ return self.sp_model.get_piece_size()
139
+
140
+ def get_vocab(self):
141
+ """Returns vocab as a dict"""
142
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
143
+ vocab.update(self.added_tokens_encoder)
144
+ return vocab
145
+
146
+ def tokenize(self, text: "TextInput", **kwargs) -> List[str]:
147
+ """
148
+ Args:
149
+ text: TextInput
150
+ Simply calls PreTrainedTokenizer's method
151
+ """
152
+ return super().tokenize(text, **kwargs)
153
+
154
+ def _tokenize(self, text, **kwargs):
155
+ """
156
+ Args:
157
+ text: TextInput
158
+ Returns a tokenized string. The Gemma tokenizer never adds a prefix space.
159
+ """
160
+ return self.sp_model.encode(text, out_type=str)
161
+
162
+ def _convert_token_to_id(self, token):
163
+ """Converts a token (str) in an id using the vocab."""
164
+ return self.sp_model.piece_to_id(token)
165
+
166
+ def _convert_id_to_token(self, index):
167
+ """Converts an index (integer) in a token (str) using the vocab."""
168
+ return self.decoder.get(index, "")
169
+
170
+ def convert_tokens_to_string(self, tokens):
171
+ """Converts a sequence of tokens (string) in a single string."""
172
+ # since we manually add the prefix space, we have to remove it when decoding
173
+ if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
174
+ tokens[0] = tokens[0][1:]
175
+
176
+ current_sub_tokens = []
177
+ out_string = ""
178
+ prev_is_special = False
179
+ for i, token in enumerate(tokens):
180
+ # make sure that special tokens are not decoded using sentencepiece model
181
+ if token in self.all_special_tokens:
182
+ if not prev_is_special and i != 0 and self.spaces_for_interleaved_special_tokens:
183
+ out_string += " "
184
+ out_string += self.sp_model.decode(current_sub_tokens) + token
185
+ prev_is_special = True
186
+ current_sub_tokens = []
187
+ else:
188
+ if (
189
+ prev_is_special
190
+ and i == 1
191
+ and self.add_prefix_space
192
+ and not token.startswith(SPIECE_UNDERLINE)
193
+ and self.spaces_for_interleaved_special_tokens
194
+ ):
195
+ out_string += " "
196
+ current_sub_tokens.append(token)
197
+ prev_is_special = False
198
+ out_string += self.sp_model.decode(current_sub_tokens)
199
+ return out_string
200
+
201
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
202
+ """
203
+ Save the vocabulary and special tokens file to a directory.
204
+
205
+ Args:
206
+ save_directory (`str`):
207
+ The directory in which to save the vocabulary.
208
+
209
+ Returns:
210
+ `Tuple(str)`: Paths to the files saved.
211
+ """
212
+ if not os.path.isdir(save_directory):
213
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
214
+ return
215
+ out_vocab_file = os.path.join(save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"])
216
+
217
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
218
+ copyfile(self.vocab_file, out_vocab_file)
219
+ elif not os.path.isfile(self.vocab_file):
220
+ with open(out_vocab_file, "wb") as fi:
221
+ content_spiece_model = self.sp_model.serialized_model_proto()
222
+ fi.write(content_spiece_model)
223
+
224
+ return (out_vocab_file,)
225
+
226
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
227
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
228
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
229
+
230
+ output = bos_token_id + token_ids_0 + eos_token_id
231
+
232
+ if token_ids_1 is not None:
233
+ output = output + bos_token_id + token_ids_1 + eos_token_id
234
+
235
+ return output
236
+
237
+ def get_special_tokens_mask(
238
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
239
+ ) -> List[int]:
240
+ """
241
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
242
+ special tokens using the tokenizer `prepare_for_model` method.
243
+
244
+ Args:
245
+ token_ids_0 (`List[int]`):
246
+ List of IDs.
247
+ token_ids_1 (`List[int]`, *optional*):
248
+ Optional second list of IDs for sequence pairs.
249
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
250
+ Whether or not the token list is already formatted with special tokens for the model.
251
+
252
+ Returns:
253
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
254
+ """
255
+ if already_has_special_tokens:
256
+ return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True)
257
+
258
+ bos_token_id = [1] if self.add_bos_token else []
259
+ eos_token_id = [1] if self.add_eos_token else []
260
+
261
+ if token_ids_1 is None:
262
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
263
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id + bos_token_id + ([0] * len(token_ids_1)) + eos_token_id
264
+
265
+ def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) -> List[int]:
266
+ """
267
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
268
+ sequence pair mask has the following format:
269
+
270
+ ```
271
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
272
+ | first sequence | second sequence |
273
+ ```
274
+
275
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
276
+
277
+ Args:
278
+ token_ids_0 (`List[int]`):
279
+ List of ids.
280
+ token_ids_1 (`List[int]`, *optional*):
281
+ Optional second list of IDs for sequence pairs.
282
+
283
+ Returns:
284
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
285
+ """
286
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
287
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
288
+
289
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
290
+
291
+ if token_ids_1 is not None:
292
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
293
+
294
+ return output
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bcacff3229854f5103ee7a85473a30ca9a8b3a68f3aae9b7479574b23ac2256b
3
+ size 2475075
tokenizer_config.json ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "128111": {
31
+ "content": "<restate>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "128112": {
39
+ "content": "</restate>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "128113": {
47
+ "content": "<planning>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "128114": {
55
+ "content": "</planning>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "128115": {
63
+ "content": "<recollect>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "128116": {
71
+ "content": "</recollect>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "128117": {
79
+ "content": "<execution>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "128118": {
87
+ "content": "</execution>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "128119": {
95
+ "content": "<review>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "128120": {
103
+ "content": "</review>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "128121": {
111
+ "content": "<summarize>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "128122": {
119
+ "content": "</summarize>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": true
125
+ },
126
+ "128123": {
127
+ "content": "<retry>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": true
133
+ },
134
+ "128124": {
135
+ "content": "</retry>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": true
141
+ },
142
+ "128125": {
143
+ "content": "<conclude>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": true
149
+ },
150
+ "128126": {
151
+ "content": "</conclude>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": true
157
+ },
158
+ "128127": {
159
+ "content": "<|plugin|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": true
165
+ },
166
+ "128128": {
167
+ "content": "<|interpreter|>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": true
173
+ },
174
+ "128129": {
175
+ "content": "<|action_end|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": true
181
+ },
182
+ "128130": {
183
+ "content": "<|action_start|>",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": true
189
+ },
190
+ "128131": {
191
+ "content": "<|im_end|>",
192
+ "lstrip": false,
193
+ "normalized": false,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": true
197
+ },
198
+ "128132": {
199
+ "content": "<|im_start|>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": true
205
+ }
206
+ },
207
+ "additional_special_tokens": [
208
+ "<|im_start|>",
209
+ "<|im_end|>",
210
+ "<|action_start|>",
211
+ "<|action_end|>",
212
+ "<|interpreter|>",
213
+ "<|plugin|>",
214
+ "<restate>",
215
+ "</restate>",
216
+ "<planning>",
217
+ "</planning>",
218
+ "<recollect>",
219
+ "</recollect>",
220
+ "<execution>",
221
+ "</execution>",
222
+ "<review>",
223
+ "</review>",
224
+ "<summarize>",
225
+ "</summarize>",
226
+ "<retry>",
227
+ "</retry>",
228
+ "<conclude>",
229
+ "</conclude>"
230
+ ],
231
+ "auto_map": {
232
+ "AutoTokenizer": [
233
+ "tokenization_internlm3.InternLM3Tokenizer",
234
+ null
235
+ ]
236
+ },
237
+ "bos_token": "<s>",
238
+ "chat_template": "{{ bos_token }}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
239
+ "clean_up_tokenization_spaces": false,
240
+ "eos_token": "</s>",
241
+ "extra_special_tokens": {},
242
+ "model_max_length": 1000000000000000019884624838656,
243
+ "pad_token": "</s>",
244
+ "sp_model_kwargs": {},
245
+ "spaces_between_special_tokens": false,
246
+ "tokenizer_class": "InternLM3Tokenizer",
247
+ "unk_token": "<unk>",
248
+ "use_default_system_prompt": false
249
+ }