ricdomolm commited on
Commit
e21d555
·
1 Parent(s): 0f02fad

Add files from e3

Browse files
all_results.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [{"train_loss": 0.388671875, "epoch": 2, "step": 3072, "lr": 4.726356402588274e-07}, {"train_loss": 1.0546875, "epoch": 2, "step": 3200, "lr": 3.983566895352207e-07}, {"train_loss": 0.384765625, "epoch": 2, "step": 3328, "lr": 3.2895439661591673e-07}, {"train_loss": 1.375, "epoch": 2, "step": 3456, "lr": 2.6499130616403044e-07}, {"train_loss": 0.0419921875, "epoch": 2, "step": 3584, "lr": 2.069858750439768e-07}, {"train_loss": 0.484375, "epoch": 2, "step": 3712, "lr": 1.5540826993665023e-07}, {"train_loss": 0.2099609375, "epoch": 2, "step": 3840, "lr": 1.1067655637373497e-07}, {"train_loss": 0.032958984375, "epoch": 2, "step": 3968, "lr": 7.31533100811672e-08}, {"train_loss": 1.2265625, "epoch": 2, "step": 4096, "lr": 4.31426780987173e-08}, {"train_loss": 0.20703125, "epoch": 2, "step": 4224, "lr": 2.0887913496973054e-08}, {"train_loss": 0.03759765625, "epoch": 2, "step": 4352, "lr": 6.569403674232199e-09}, {"train_loss": 0.470703125, "epoch": 2, "step": 4480, "lr": 3.03208215066908e-10}]
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/fast/rolmedo/models/internlm-7b/snapshots/model/",
3
+ "architectures": [
4
+ "InternLMForCausalLM"
5
+ ],
6
+ "attn_implementation": "flash_attention_2",
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_internlm.InternLMConfig",
9
+ "AutoModel": "modeling_internlm.InternLMForCausalLM",
10
+ "AutoModelForCausalLM": "modeling_internlm.InternLMForCausalLM"
11
+ },
12
+ "bias": true,
13
+ "bos_token_id": 1,
14
+ "eos_token_id": 2,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 4096,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 11008,
19
+ "max_position_embeddings": 2048,
20
+ "model_type": "internlm",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 32,
23
+ "pad_token_id": 2,
24
+ "rms_norm_eps": 1e-06,
25
+ "rotary": {
26
+ "base": 10000,
27
+ "type": "dynamic"
28
+ },
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.40.0.dev0",
32
+ "use_cache": true,
33
+ "vocab_size": 103168
34
+ }
configuration_internlm.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ InternLM model configuration"""
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ INTERNLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
25
+
26
+
27
+ # Modified from transformers.model.llama.configuration_llama.LlamaConfig
28
+ class InternLMConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`InternLMModel`]. It is used to instantiate
31
+ an InternLM model according to the specified arguments, defining the model architecture. Instantiating a
32
+ configuration with the defaults will yield a similar configuration to that of the InternLM-7B.
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
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32000):
37
+ Vocabulary size of the InternLM model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`InternLMModel`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 11008):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
48
+ The non-linear activation function (function or string) in the decoder.
49
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
50
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
51
+ just in case (e.g., 512 or 1024 or 2048).
52
+ initializer_range (`float`, *optional*, defaults to 0.02):
53
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
54
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
55
+ The epsilon used by the rms normalization layers.
56
+ use_cache (`bool`, *optional*, defaults to `True`):
57
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
58
+ relevant if `config.is_decoder=True`.
59
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
60
+ Whether to tie weight embeddings
61
+ Example:
62
+ ```python
63
+ >>> from transformers import InternLMModel, InternLMConfig
64
+ >>> # Initializing a InternLM internlm-7b style configuration
65
+ >>> configuration = InternLMConfig()
66
+ >>> # Initializing a model from the internlm-7b style configuration
67
+ >>> model = InternLMModel(configuration)
68
+ >>> # Accessing the model configuration
69
+ >>> configuration = model.config
70
+ ```"""
71
+ model_type = "internlm"
72
+ _auto_class = "AutoConfig"
73
+
74
+ def __init__( # pylint: disable=W0102
75
+ self,
76
+ vocab_size=103168,
77
+ hidden_size=4096,
78
+ intermediate_size=11008,
79
+ num_hidden_layers=32,
80
+ num_attention_heads=32,
81
+ hidden_act="silu",
82
+ max_position_embeddings=2048,
83
+ initializer_range=0.02,
84
+ rms_norm_eps=1e-6,
85
+ use_cache=True,
86
+ pad_token_id=0,
87
+ bos_token_id=1,
88
+ eos_token_id=2,
89
+ tie_word_embeddings=False,
90
+ bias=True,
91
+ rotary={"base": 10000, "type": "dynamic"}, # pylint: disable=W0102
92
+ attn_implementation="eager",
93
+ **kwargs,
94
+ ):
95
+ self.vocab_size = vocab_size
96
+ self.max_position_embeddings = max_position_embeddings
97
+ self.hidden_size = hidden_size
98
+ self.intermediate_size = intermediate_size
99
+ self.num_hidden_layers = num_hidden_layers
100
+ self.num_attention_heads = num_attention_heads
101
+ self.hidden_act = hidden_act
102
+ self.initializer_range = initializer_range
103
+ self.rms_norm_eps = rms_norm_eps
104
+ self.use_cache = use_cache
105
+ self.bias = bias
106
+ self.rotary = rotary
107
+ self.attn_implementation = attn_implementation
108
+ if self.attn_implementation is None:
109
+ self.attn_implementation = "eager"
110
+ super().__init__(
111
+ pad_token_id=pad_token_id,
112
+ bos_token_id=bos_token_id,
113
+ eos_token_id=eos_token_id,
114
+ tie_word_embeddings=tie_word_embeddings,
115
+ **kwargs,
116
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 2,
6
+ "transformers_version": "4.40.0.dev0"
7
+ }
model-00001-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf2bb4f9bbaffaf1f06db9fde2709bebf9eff7bacd76b753cfc5990198ec420a
3
+ size 4993850648
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebba45cdb52d0d2a5074a9c2c49ce8f3ffc2e37b94866bb9d727c976275e0f84
3
+ size 4981352272
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:254dff63c97e0491db6cb096c05c1ae52ef7ffa6c87a2fe5cb547b8d3e02d6b9
3
+ size 4668741432
model.safetensors.index.json ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 14643896320
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00003-of-00003.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00003.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00003.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
13
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
14
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
15
+ "model.layers.0.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
16
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
17
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
18
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
19
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
20
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
21
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00003.safetensors",
22
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
23
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
24
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
25
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
26
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
27
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
28
+ "model.layers.1.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
29
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
30
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
31
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
32
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
33
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
34
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00003.safetensors",
35
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
36
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
37
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
38
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
39
+ "model.layers.10.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
40
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
41
+ "model.layers.10.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
42
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
43
+ "model.layers.10.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
44
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
45
+ "model.layers.10.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
46
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
47
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00003.safetensors",
48
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
49
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
50
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
51
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
52
+ "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
53
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
54
+ "model.layers.11.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
55
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
56
+ "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
57
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
58
+ "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
59
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
60
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00003.safetensors",
61
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
62
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
63
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
64
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
65
+ "model.layers.12.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
66
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
67
+ "model.layers.12.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
68
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
69
+ "model.layers.12.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
70
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
71
+ "model.layers.12.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
72
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
73
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00003.safetensors",
74
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
75
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
76
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
77
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
78
+ "model.layers.13.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
79
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
80
+ "model.layers.13.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
81
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
82
+ "model.layers.13.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
83
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
84
+ "model.layers.13.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
85
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
86
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00003.safetensors",
87
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
88
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
89
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
90
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
91
+ "model.layers.14.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
92
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
93
+ "model.layers.14.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
94
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
95
+ "model.layers.14.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
96
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
97
+ "model.layers.14.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
98
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
99
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00003.safetensors",
100
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
101
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
102
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
103
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
104
+ "model.layers.15.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
105
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
106
+ "model.layers.15.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
107
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
108
+ "model.layers.15.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
109
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
110
+ "model.layers.15.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
111
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
112
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00003.safetensors",
113
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
114
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
115
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
116
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
117
+ "model.layers.16.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
118
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
119
+ "model.layers.16.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
120
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
121
+ "model.layers.16.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
122
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
123
+ "model.layers.16.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
124
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
125
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00003.safetensors",
126
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
127
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
128
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
129
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
130
+ "model.layers.17.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
131
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
132
+ "model.layers.17.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
133
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
134
+ "model.layers.17.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
135
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
136
+ "model.layers.17.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
137
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
138
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00003.safetensors",
139
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
140
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
141
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
142
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
143
+ "model.layers.18.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
144
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
145
+ "model.layers.18.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
146
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
147
+ "model.layers.18.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
148
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
149
+ "model.layers.18.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
150
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
151
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00003.safetensors",
152
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
153
+ "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
154
+ "model.layers.19.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
155
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
156
+ "model.layers.19.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
157
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
158
+ "model.layers.19.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
159
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
160
+ "model.layers.19.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
161
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
162
+ "model.layers.19.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
163
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
164
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00003.safetensors",
165
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
166
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
167
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
168
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
169
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
170
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
171
+ "model.layers.2.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
172
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
173
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
174
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
175
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
176
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
177
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00003.safetensors",
178
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
179
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
180
+ "model.layers.20.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
181
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
182
+ "model.layers.20.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
183
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
184
+ "model.layers.20.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
185
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
186
+ "model.layers.20.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
187
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
188
+ "model.layers.20.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
189
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
190
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00003.safetensors",
191
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
192
+ "model.layers.21.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
193
+ "model.layers.21.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
194
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
195
+ "model.layers.21.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
196
+ "model.layers.21.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
197
+ "model.layers.21.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
198
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
199
+ "model.layers.21.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
200
+ "model.layers.21.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
201
+ "model.layers.21.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
202
+ "model.layers.21.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
203
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00003.safetensors",
204
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
205
+ "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
206
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
207
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
208
+ "model.layers.22.self_attn.k_proj.bias": "model-00002-of-00003.safetensors",
209
+ "model.layers.22.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
210
+ "model.layers.22.self_attn.o_proj.bias": "model-00002-of-00003.safetensors",
211
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
212
+ "model.layers.22.self_attn.q_proj.bias": "model-00002-of-00003.safetensors",
213
+ "model.layers.22.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
214
+ "model.layers.22.self_attn.v_proj.bias": "model-00002-of-00003.safetensors",
215
+ "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
216
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00003.safetensors",
217
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
218
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
219
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
220
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
221
+ "model.layers.23.self_attn.k_proj.bias": "model-00003-of-00003.safetensors",
222
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
223
+ "model.layers.23.self_attn.o_proj.bias": "model-00003-of-00003.safetensors",
224
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
225
+ "model.layers.23.self_attn.q_proj.bias": "model-00003-of-00003.safetensors",
226
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
227
+ "model.layers.23.self_attn.v_proj.bias": "model-00003-of-00003.safetensors",
228
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
229
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00003.safetensors",
230
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
231
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
232
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
233
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
234
+ "model.layers.24.self_attn.k_proj.bias": "model-00003-of-00003.safetensors",
235
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
236
+ "model.layers.24.self_attn.o_proj.bias": "model-00003-of-00003.safetensors",
237
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
238
+ "model.layers.24.self_attn.q_proj.bias": "model-00003-of-00003.safetensors",
239
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
240
+ "model.layers.24.self_attn.v_proj.bias": "model-00003-of-00003.safetensors",
241
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
242
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00003.safetensors",
243
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
244
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
245
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
246
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
247
+ "model.layers.25.self_attn.k_proj.bias": "model-00003-of-00003.safetensors",
248
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
249
+ "model.layers.25.self_attn.o_proj.bias": "model-00003-of-00003.safetensors",
250
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
251
+ "model.layers.25.self_attn.q_proj.bias": "model-00003-of-00003.safetensors",
252
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
253
+ "model.layers.25.self_attn.v_proj.bias": "model-00003-of-00003.safetensors",
254
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
255
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00003.safetensors",
256
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
257
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
258
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
259
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
260
+ "model.layers.26.self_attn.k_proj.bias": "model-00003-of-00003.safetensors",
261
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
262
+ "model.layers.26.self_attn.o_proj.bias": "model-00003-of-00003.safetensors",
263
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
264
+ "model.layers.26.self_attn.q_proj.bias": "model-00003-of-00003.safetensors",
265
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
266
+ "model.layers.26.self_attn.v_proj.bias": "model-00003-of-00003.safetensors",
267
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
268
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00003.safetensors",
269
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
270
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
271
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
272
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
273
+ "model.layers.27.self_attn.k_proj.bias": "model-00003-of-00003.safetensors",
274
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
275
+ "model.layers.27.self_attn.o_proj.bias": "model-00003-of-00003.safetensors",
276
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
277
+ "model.layers.27.self_attn.q_proj.bias": "model-00003-of-00003.safetensors",
278
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
279
+ "model.layers.27.self_attn.v_proj.bias": "model-00003-of-00003.safetensors",
280
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
281
+ "model.layers.28.input_layernorm.weight": "model-00003-of-00003.safetensors",
282
+ "model.layers.28.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
283
+ "model.layers.28.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
284
+ "model.layers.28.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
285
+ "model.layers.28.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
286
+ "model.layers.28.self_attn.k_proj.bias": "model-00003-of-00003.safetensors",
287
+ "model.layers.28.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
288
+ "model.layers.28.self_attn.o_proj.bias": "model-00003-of-00003.safetensors",
289
+ "model.layers.28.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
290
+ "model.layers.28.self_attn.q_proj.bias": "model-00003-of-00003.safetensors",
291
+ "model.layers.28.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
292
+ "model.layers.28.self_attn.v_proj.bias": "model-00003-of-00003.safetensors",
293
+ "model.layers.28.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
294
+ "model.layers.29.input_layernorm.weight": "model-00003-of-00003.safetensors",
295
+ "model.layers.29.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
296
+ "model.layers.29.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
297
+ "model.layers.29.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
298
+ "model.layers.29.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
299
+ "model.layers.29.self_attn.k_proj.bias": "model-00003-of-00003.safetensors",
300
+ "model.layers.29.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
301
+ "model.layers.29.self_attn.o_proj.bias": "model-00003-of-00003.safetensors",
302
+ "model.layers.29.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
303
+ "model.layers.29.self_attn.q_proj.bias": "model-00003-of-00003.safetensors",
304
+ "model.layers.29.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
305
+ "model.layers.29.self_attn.v_proj.bias": "model-00003-of-00003.safetensors",
306
+ "model.layers.29.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
307
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00003.safetensors",
308
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
309
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
310
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
311
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
312
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
313
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
314
+ "model.layers.3.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
315
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
316
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
317
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
318
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
319
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
320
+ "model.layers.30.input_layernorm.weight": "model-00003-of-00003.safetensors",
321
+ "model.layers.30.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
322
+ "model.layers.30.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
323
+ "model.layers.30.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
324
+ "model.layers.30.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
325
+ "model.layers.30.self_attn.k_proj.bias": "model-00003-of-00003.safetensors",
326
+ "model.layers.30.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
327
+ "model.layers.30.self_attn.o_proj.bias": "model-00003-of-00003.safetensors",
328
+ "model.layers.30.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
329
+ "model.layers.30.self_attn.q_proj.bias": "model-00003-of-00003.safetensors",
330
+ "model.layers.30.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
331
+ "model.layers.30.self_attn.v_proj.bias": "model-00003-of-00003.safetensors",
332
+ "model.layers.30.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
333
+ "model.layers.31.input_layernorm.weight": "model-00003-of-00003.safetensors",
334
+ "model.layers.31.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
335
+ "model.layers.31.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
336
+ "model.layers.31.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
337
+ "model.layers.31.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
338
+ "model.layers.31.self_attn.k_proj.bias": "model-00003-of-00003.safetensors",
339
+ "model.layers.31.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
340
+ "model.layers.31.self_attn.o_proj.bias": "model-00003-of-00003.safetensors",
341
+ "model.layers.31.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
342
+ "model.layers.31.self_attn.q_proj.bias": "model-00003-of-00003.safetensors",
343
+ "model.layers.31.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
344
+ "model.layers.31.self_attn.v_proj.bias": "model-00003-of-00003.safetensors",
345
+ "model.layers.31.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
346
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00003.safetensors",
347
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
348
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
349
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
350
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
351
+ "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
352
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
353
+ "model.layers.4.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
354
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
355
+ "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
356
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
357
+ "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
358
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
359
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00003.safetensors",
360
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
361
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
362
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
363
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
364
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
365
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
366
+ "model.layers.5.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
367
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
368
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
369
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
370
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
371
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
372
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00003.safetensors",
373
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
374
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
375
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
376
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
377
+ "model.layers.6.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
378
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
379
+ "model.layers.6.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
380
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
381
+ "model.layers.6.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
382
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
383
+ "model.layers.6.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
384
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
385
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00003.safetensors",
386
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
387
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
388
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
389
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
390
+ "model.layers.7.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
391
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
392
+ "model.layers.7.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
393
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
394
+ "model.layers.7.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
395
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
396
+ "model.layers.7.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
397
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
398
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00003.safetensors",
399
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
400
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
401
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
402
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
403
+ "model.layers.8.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
404
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
405
+ "model.layers.8.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
406
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
407
+ "model.layers.8.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
408
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
409
+ "model.layers.8.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
410
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
411
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00003.safetensors",
412
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
413
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
414
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
415
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
416
+ "model.layers.9.self_attn.k_proj.bias": "model-00001-of-00003.safetensors",
417
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
418
+ "model.layers.9.self_attn.o_proj.bias": "model-00001-of-00003.safetensors",
419
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
420
+ "model.layers.9.self_attn.q_proj.bias": "model-00001-of-00003.safetensors",
421
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
422
+ "model.layers.9.self_attn.v_proj.bias": "model-00001-of-00003.safetensors",
423
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
424
+ "model.norm.weight": "model-00003-of-00003.safetensors"
425
+ }
426
+ }
modeling_internlm.py ADDED
@@ -0,0 +1,1304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/modeling_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch InternLM model."""
17
+ import math
18
+ import queue
19
+ import threading
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+ from transformers.activations import ACT2FN
27
+ from transformers.modeling_outputs import (
28
+ BaseModelOutputWithPast,
29
+ CausalLMOutputWithPast,
30
+ SequenceClassifierOutputWithPast,
31
+ )
32
+ from transformers.modeling_utils import PreTrainedModel
33
+ from transformers.utils import (
34
+ add_start_docstrings,
35
+ add_start_docstrings_to_model_forward,
36
+ logging,
37
+ replace_return_docstrings,
38
+ )
39
+
40
+ try:
41
+ from transformers.generation.streamers import BaseStreamer
42
+ except: # noqa # pylint: disable=bare-except
43
+ BaseStreamer = None
44
+
45
+ from .configuration_internlm import InternLMConfig
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _CONFIG_FOR_DOC = "InternLMConfig"
50
+
51
+ flash_attn_func, flash_attn_varlen_func = None, None
52
+ pad_input, index_first_axis, unpad_input = None, None, None
53
+ def _import_flash_attn():
54
+ global flash_attn_func, flash_attn_varlen_func
55
+ global pad_input, index_first_axis, unpad_input
56
+ try:
57
+ from flash_attn import flash_attn_func as _flash_attn_func, flash_attn_varlen_func as _flash_attn_varlen_func
58
+ from flash_attn.bert_padding import pad_input as _pad_input, index_first_axis as _index_first_axis, unpad_input as _unpad_input
59
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
60
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
61
+ except ImportError:
62
+ raise ImportError("flash_attn is not installed.")
63
+
64
+
65
+ def _get_unpad_data(attention_mask):
66
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
67
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
68
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
69
+ cu_seqlens = nn.functional.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
70
+ return (
71
+ indices,
72
+ cu_seqlens,
73
+ max_seqlen_in_batch,
74
+ )
75
+
76
+
77
+ # Copied from transformers.models.llama.modeling_llama._make_causal_mask
78
+ def _make_causal_mask(
79
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
80
+ ):
81
+ """
82
+ Make causal mask used for bi-directional self-attention.
83
+ """
84
+ bsz, tgt_len = input_ids_shape
85
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
86
+ mask_cond = torch.arange(mask.size(-1), device=device)
87
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
88
+ mask = mask.to(dtype)
89
+
90
+ if past_key_values_length > 0:
91
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
92
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
93
+
94
+
95
+ # Copied from transformers.models.llama.modeling_llama._expand_mask
96
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
97
+ """
98
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
99
+ """
100
+ bsz, src_len = mask.size()
101
+ tgt_len = tgt_len if tgt_len is not None else src_len
102
+
103
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
104
+
105
+ inverted_mask = 1.0 - expanded_mask
106
+
107
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
108
+
109
+
110
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->InternLM
111
+ class InternLMRMSNorm(nn.Module):
112
+ """RMSNorm implemention."""
113
+
114
+ def __init__(self, hidden_size, eps=1e-6):
115
+ """
116
+ InternLMRMSNorm is equivalent to T5LayerNorm
117
+ """
118
+ super().__init__()
119
+ self.weight = nn.Parameter(torch.ones(hidden_size))
120
+ self.variance_epsilon = eps
121
+
122
+ def forward(self, hidden_states):
123
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
124
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
125
+
126
+ # convert into half-precision if necessary
127
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
128
+ hidden_states = hidden_states.to(self.weight.dtype)
129
+
130
+ return self.weight * hidden_states
131
+
132
+
133
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM
134
+ class InternLMRotaryEmbedding(torch.nn.Module):
135
+ """Implement InternLM's rotary embedding.
136
+
137
+ Args:
138
+ dim (int): Characteristic dimension of each self-attentional head.
139
+ max_position_embeddings (int, optional): Model's training length. Defaults to 2048.
140
+ base (int, optional): The rotation position encodes the rotation Angle base number. Defaults to 10000.
141
+ device (Any, optional): Running device. Defaults to None.
142
+ """
143
+
144
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
145
+ super().__init__()
146
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
147
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
148
+
149
+ # Build here to make `torch.jit.trace` work.
150
+ self.max_seq_len_cached = max_position_embeddings
151
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
152
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
153
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
154
+ emb = torch.cat((freqs, freqs), dim=-1)
155
+ self.register_buffer("cos_cached", emb.cos().to(torch.float32), persistent=False)
156
+ self.register_buffer("sin_cached", emb.sin().to(torch.float32), persistent=False)
157
+
158
+ def forward(self, x, seq_len=None):
159
+ # x: [bs, num_attention_heads, seq_len, head_size]
160
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
161
+ if seq_len > self.max_seq_len_cached:
162
+ self.max_seq_len_cached = seq_len
163
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
164
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
165
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
166
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
167
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
168
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
169
+ return (
170
+ self.cos_cached[:seq_len, ...].to(dtype=x.dtype),
171
+ self.sin_cached[:seq_len, ...].to(dtype=x.dtype),
172
+ )
173
+
174
+
175
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM
176
+ class InternLMDynamicNTKScalingRotaryEmbedding(torch.nn.Module):
177
+ """Implement InternLM's DyanmicNTK extrapolation method, thereby broadening the model support context to 16K.
178
+
179
+ Args:
180
+ dim (int): Characteristic dimension of each self-attentional head.
181
+ max_position_embeddings (int, optional): Model's training length. Defaults to 2048.
182
+ base (int, optional): The rotation position encodes the rotation Angle base number. Defaults to 10000.
183
+ device (Any, optional): Running device. Defaults to None.
184
+ scaling_factor (float, optional): NTK method extrapolation coefficient. Defaults to 1.0.
185
+ """
186
+
187
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
188
+ super().__init__()
189
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
190
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
191
+ self.dim = dim
192
+ self.base = base
193
+ self.scaling_factor = scaling_factor
194
+
195
+ # Build here to make `torch.jit.trace` work.
196
+ self.max_position_embeddings = max_position_embeddings
197
+ self.max_seq_len_cached = max_position_embeddings
198
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
199
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
200
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
201
+ emb = torch.cat((freqs, freqs), dim=-1)
202
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
203
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
204
+
205
+ def _update_cached(self, x, seq_len=None):
206
+ self.max_seq_len_cached = max(seq_len, self.max_position_embeddings)
207
+ if seq_len > self.max_position_embeddings:
208
+ base = self.base * (
209
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
210
+ ) ** (self.dim / (self.dim - 2))
211
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(x.device) / self.dim))
212
+ else:
213
+ inv_freq = self.inv_freq
214
+ t = torch.arange(self.max_seq_len_cached, device=inv_freq.device, dtype=inv_freq.dtype)
215
+ freqs = torch.einsum("i,j->ij", t, inv_freq)
216
+ emb = torch.cat((freqs, freqs), dim=-1)
217
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
218
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
219
+
220
+ def forward(self, x, seq_len=None):
221
+ # x: [bs, num_attention_heads, seq_len, head_size]
222
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
223
+ if seq_len <= self.max_position_embeddings:
224
+ # Reset the tables if the sequence length has changed,
225
+ if self.max_seq_len_cached > self.max_position_embeddings:
226
+ self._update_cached(x, seq_len)
227
+ else:
228
+ self._update_cached(x, seq_len)
229
+
230
+ return (
231
+ self.cos_cached[:seq_len, ...].to(dtype=x.dtype),
232
+ self.sin_cached[:seq_len, ...].to(dtype=x.dtype),
233
+ )
234
+
235
+
236
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
237
+ def rotate_half(x):
238
+ """Rotates half the hidden dims of the input."""
239
+ x1 = x[..., : x.shape[-1] // 2]
240
+ x2 = x[..., x.shape[-1] // 2 :]
241
+ return torch.cat((-x2, x1), dim=-1)
242
+
243
+
244
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
245
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
246
+ if position_ids.size(1) == 1:
247
+ q_cos = cos[position_ids].unsqueeze(1).expand(q.shape)
248
+ q_sin = sin[position_ids].unsqueeze(1).expand(q.shape)
249
+ q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
250
+
251
+ position_ids = position_ids.flatten() + 1
252
+ max_length = max(position_ids)
253
+ position_ids = torch.stack([torch.cat([torch.ones(max_length - w, dtype=torch.long), torch.arange(w)]) for w in position_ids])
254
+ k_cos = cos[position_ids].unsqueeze(1).expand(k.shape)
255
+ k_sin = sin[position_ids].unsqueeze(1).expand(k.shape)
256
+ k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
257
+ else:
258
+ cos = cos[position_ids].unsqueeze(1)
259
+ sin = sin[position_ids].unsqueeze(1)
260
+ q_embed = (q * cos) + (rotate_half(q) * sin)
261
+ k_embed = (k * cos) + (rotate_half(k) * sin)
262
+ return q_embed, k_embed
263
+
264
+
265
+ # Copied from transformers.models.llama.modeling_llama.LlamaMLP with Llama->InternLM
266
+ class InternLMMLP(nn.Module):
267
+ def __init__(
268
+ self,
269
+ hidden_size: int,
270
+ intermediate_size: int,
271
+ hidden_act: str,
272
+ ):
273
+ super().__init__()
274
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
275
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
276
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
277
+ self.act_fn = ACT2FN[hidden_act]
278
+
279
+ def forward(self, x):
280
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
281
+
282
+
283
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->InternLM
284
+ class InternLMAttention(nn.Module):
285
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
286
+
287
+ def __init__(self, config: InternLMConfig):
288
+ super().__init__()
289
+ self.config = config
290
+ self.hidden_size = config.hidden_size
291
+ self.num_heads = config.num_attention_heads
292
+ self.head_dim = self.hidden_size // self.num_heads
293
+ self.max_position_embeddings = config.max_position_embeddings
294
+
295
+ if (self.head_dim * self.num_heads) != self.hidden_size:
296
+ raise ValueError(
297
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
298
+ f" and `num_heads`: {self.num_heads})."
299
+ )
300
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.bias)
301
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.bias)
302
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.bias)
303
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
304
+ self.rotary_emb = self._init_rope()
305
+ self.is_causal = True
306
+
307
+ def _init_rope(self):
308
+ if self.config.rotary["type"] == "origin":
309
+ self.rotary_emb = InternLMRotaryEmbedding(
310
+ self.head_dim,
311
+ max_position_embeddings=self.max_position_embeddings,
312
+ base=self.config.rotary["base"],
313
+ )
314
+ elif self.config.rotary["type"] == "dynamic":
315
+ self.rotary_emb = InternLMDynamicNTKScalingRotaryEmbedding(
316
+ self.head_dim,
317
+ max_position_embeddings=self.max_position_embeddings,
318
+ base=self.config.rotary["base"],
319
+ scaling_factor=self.config.rotary.get("scaling_factor", 1.0),
320
+ )
321
+ else:
322
+ raise ValueError("Currently we only support rotary embedding's type being one of ('origin', 'dynamic').")
323
+ return self.rotary_emb
324
+
325
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
326
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
327
+
328
+ def forward(
329
+ self,
330
+ hidden_states: torch.Tensor,
331
+ attention_mask: Optional[torch.Tensor] = None,
332
+ position_ids: Optional[torch.LongTensor] = None,
333
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
334
+ output_attentions: bool = False,
335
+ use_cache: bool = False,
336
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
337
+ bsz, q_len, _ = hidden_states.size()
338
+
339
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
340
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
341
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
342
+
343
+ if past_key_value is not None:
344
+ # reuse k, v, self_attention
345
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
346
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
347
+
348
+ past_key_value = (key_states, value_states) if use_cache else None
349
+
350
+ kv_seq_len = key_states.shape[-2]
351
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
352
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
353
+
354
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
355
+
356
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
357
+ raise ValueError(
358
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
359
+ f" {attn_weights.size()}"
360
+ )
361
+
362
+ if attention_mask is not None:
363
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
364
+ raise ValueError(
365
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
366
+ )
367
+ attn_weights = attn_weights + attention_mask
368
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
369
+
370
+ # upcast attention to fp32
371
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
372
+ attn_output = torch.matmul(attn_weights, value_states)
373
+
374
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
375
+ raise ValueError(
376
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
377
+ f" {attn_output.size()}"
378
+ )
379
+
380
+ attn_output = attn_output.transpose(1, 2)
381
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
382
+
383
+ attn_output = self.o_proj(attn_output)
384
+
385
+ if not output_attentions:
386
+ attn_weights = None
387
+
388
+ return attn_output, attn_weights, past_key_value
389
+
390
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->InternLM
391
+ class InternLMFlashAttention2(InternLMAttention):
392
+ """
393
+ InternLM flash attention module. This module inherits from `InternLMAttention` as the weights of the module stays
394
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
395
+ flash attention and deal with padding tokens in case the input contains any of them.
396
+ """
397
+
398
+ def forward(
399
+ self,
400
+ hidden_states: torch.Tensor,
401
+ attention_mask: Optional[torch.LongTensor] = None,
402
+ position_ids: Optional[torch.LongTensor] = None,
403
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
404
+ output_attentions: bool = False,
405
+ use_cache: bool = False,
406
+ **kwargs,
407
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
408
+ # InternLMFlashAttention2 attention does not support output_attentions
409
+ bsz, q_len, _ = hidden_states.size()
410
+
411
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
412
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
413
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
414
+
415
+ if past_key_value is not None:
416
+ # reuse k, v, self_attention
417
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
418
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
419
+
420
+ past_key_value = (key_states, value_states) if use_cache else None
421
+
422
+ kv_seq_len = key_states.shape[-2]
423
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
424
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
425
+
426
+ query_states = query_states.transpose(1, 2)
427
+ key_states = key_states.transpose(1, 2)
428
+ value_states = value_states.transpose(1, 2)
429
+
430
+ attn_output = self._flash_attention_forward(
431
+ query_states, key_states, value_states, attention_mask, q_len
432
+ )
433
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
434
+ attn_output = self.o_proj(attn_output)
435
+
436
+ if not output_attentions:
437
+ attn_weights = None
438
+
439
+ return attn_output, attn_weights, past_key_value
440
+
441
+ def _flash_attention_forward(
442
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
443
+ ):
444
+ """
445
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
446
+ first unpad the input, then computes the attention scores and pad the final attention scores.
447
+
448
+ Args:
449
+ query_states (`torch.Tensor`):
450
+ Input query states to be passed to Flash Attention API
451
+ key_states (`torch.Tensor`):
452
+ Input key states to be passed to Flash Attention API
453
+ value_states (`torch.Tensor`):
454
+ Input value states to be passed to Flash Attention API
455
+ attention_mask (`torch.Tensor`):
456
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
457
+ position of padding tokens and 1 for the position of non-padding tokens.
458
+ dropout (`int`, *optional*):
459
+ Attention dropout
460
+ softmax_scale (`float`, *optional*):
461
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
462
+ """
463
+ # Contains at least one padding token in the sequence
464
+ causal = self.is_causal and query_length != 1
465
+ if attention_mask is not None:
466
+ batch_size = query_states.shape[0]
467
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
468
+ query_states, key_states, value_states, attention_mask, query_length
469
+ )
470
+
471
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
472
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
473
+
474
+ attn_output_unpad = flash_attn_varlen_func(
475
+ query_states,
476
+ key_states,
477
+ value_states,
478
+ cu_seqlens_q=cu_seqlens_q,
479
+ cu_seqlens_k=cu_seqlens_k,
480
+ max_seqlen_q=max_seqlen_in_batch_q,
481
+ max_seqlen_k=max_seqlen_in_batch_k,
482
+ dropout_p=dropout,
483
+ softmax_scale=softmax_scale,
484
+ causal=causal,
485
+ )
486
+
487
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
488
+ else:
489
+ attn_output = flash_attn_func(
490
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
491
+ )
492
+
493
+ return attn_output
494
+
495
+ def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
496
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
497
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
498
+
499
+ key_layer = index_first_axis(
500
+ key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
501
+ )
502
+ value_layer = index_first_axis(
503
+ value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
504
+ )
505
+
506
+ if query_length == kv_seq_len:
507
+ query_layer = index_first_axis(
508
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
509
+ )
510
+ cu_seqlens_q = cu_seqlens_k
511
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
512
+ indices_q = indices_k
513
+ elif query_length == 1:
514
+ max_seqlen_in_batch_q = 1
515
+ cu_seqlens_q = torch.arange(
516
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
517
+ ) # There is a memcpy here, that is very bad.
518
+ indices_q = cu_seqlens_q[:-1]
519
+ query_layer = query_layer.squeeze(1)
520
+ else:
521
+ # The -q_len: slice assumes left padding.
522
+ attention_mask = attention_mask[:, -query_length:]
523
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
524
+
525
+ return (
526
+ query_layer,
527
+ key_layer,
528
+ value_layer,
529
+ indices_q.to(torch.int64),
530
+ (cu_seqlens_q, cu_seqlens_k),
531
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
532
+ )
533
+
534
+ INTERNLM_ATTENTION_CLASSES = {
535
+ "eager": InternLMAttention,
536
+ "flash_attention_2": InternLMFlashAttention2,
537
+ }
538
+
539
+ # Copied from transformers.models.llama.modeling_llama.LlamaDecoderLayer with Llama->InternLM
540
+ class InternLMDecoderLayer(nn.Module):
541
+ def __init__(self, config: InternLMConfig):
542
+ super().__init__()
543
+ self.hidden_size = config.hidden_size
544
+
545
+ self.self_attn = INTERNLM_ATTENTION_CLASSES[config.attn_implementation](config=config)
546
+
547
+ self.mlp = InternLMMLP(
548
+ hidden_size=self.hidden_size,
549
+ intermediate_size=config.intermediate_size,
550
+ hidden_act=config.hidden_act,
551
+ )
552
+ self.input_layernorm = InternLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
553
+ self.post_attention_layernorm = InternLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
554
+
555
+ def forward(
556
+ self,
557
+ hidden_states: torch.Tensor,
558
+ attention_mask: Optional[torch.Tensor] = None,
559
+ position_ids: Optional[torch.LongTensor] = None,
560
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
561
+ output_attentions: Optional[bool] = False,
562
+ use_cache: Optional[bool] = False,
563
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
564
+ """
565
+ Args:
566
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
567
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
568
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
569
+ output_attentions (`bool`, *optional*):
570
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
571
+ returned tensors for more detail.
572
+ use_cache (`bool`, *optional*):
573
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
574
+ (see `past_key_values`).
575
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
576
+ """
577
+
578
+ residual = hidden_states
579
+
580
+ hidden_states = self.input_layernorm(hidden_states)
581
+
582
+ # Self Attention
583
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
584
+ hidden_states=hidden_states,
585
+ attention_mask=attention_mask,
586
+ position_ids=position_ids,
587
+ past_key_value=past_key_value,
588
+ output_attentions=output_attentions,
589
+ use_cache=use_cache,
590
+ )
591
+ hidden_states = residual + hidden_states
592
+
593
+ # Fully Connected
594
+ residual = hidden_states
595
+ hidden_states = self.post_attention_layernorm(hidden_states)
596
+ hidden_states = self.mlp(hidden_states)
597
+ hidden_states = residual + hidden_states
598
+
599
+ outputs = (hidden_states,)
600
+
601
+ if output_attentions:
602
+ outputs += (self_attn_weights,)
603
+
604
+ if use_cache:
605
+ outputs += (present_key_value,)
606
+
607
+ return outputs
608
+
609
+
610
+ INTERNLM_START_DOCSTRING = r"""
611
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
612
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
613
+ etc.)
614
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
615
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
616
+ and behavior.
617
+ Parameters:
618
+ config ([`InternLMConfig`]):
619
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
620
+ load the weights associated with the model, only the configuration. Check out the
621
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
622
+ """
623
+
624
+
625
+ # Copied from transformers.models.llama.modeling_llama.LlamaPretrainedModel with Llama->InternLM
626
+ @add_start_docstrings(
627
+ "The bare InternLM Model outputting raw hidden-states without any specific head on top.",
628
+ INTERNLM_START_DOCSTRING,
629
+ )
630
+ class InternLMPreTrainedModel(PreTrainedModel):
631
+ config_class = InternLMConfig
632
+ base_model_prefix = "model"
633
+ supports_gradient_checkpointing = True
634
+ _no_split_modules = ["InternLMDecoderLayer"]
635
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
636
+
637
+ def _init_weights(self, module):
638
+ std = self.config.initializer_range
639
+ if isinstance(module, nn.Linear):
640
+ module.weight.data.normal_(mean=0.0, std=std)
641
+ if module.bias is not None:
642
+ module.bias.data.zero_()
643
+ elif isinstance(module, nn.Embedding):
644
+ module.weight.data.normal_(mean=0.0, std=std)
645
+ if module.padding_idx is not None:
646
+ module.weight.data[module.padding_idx].zero_()
647
+
648
+ def _set_gradient_checkpointing(self, module, value=False):
649
+ if isinstance(module, InternLMModel):
650
+ module.gradient_checkpointing = value
651
+
652
+
653
+ INTERNLM_INPUTS_DOCSTRING = r"""
654
+ Args:
655
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
656
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
657
+ it.
658
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
659
+ [`PreTrainedTokenizer.__call__`] for details.
660
+ [What are input IDs?](../glossary#input-ids)
661
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
662
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
663
+ - 1 for tokens that are **not masked**,
664
+ - 0 for tokens that are **masked**.
665
+ [What are attention masks?](../glossary#attention-mask)
666
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
667
+ [`PreTrainedTokenizer.__call__`] for details.
668
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
669
+ `past_key_values`).
670
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
671
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
672
+ information on the default strategy.
673
+ - 1 indicates the head is **not masked**,
674
+ - 0 indicates the head is **masked**.
675
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
676
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
677
+ config.n_positions - 1]`.
678
+ [What are position IDs?](../glossary#position-ids)
679
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
680
+ when `config.use_cache=True`):
681
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
682
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
683
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
684
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
685
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
686
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
687
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
688
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
689
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
690
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
691
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
692
+ model's internal embedding lookup matrix.
693
+ use_cache (`bool`, *optional*):
694
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
695
+ `past_key_values`).
696
+ output_attentions (`bool`, *optional*):
697
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
698
+ tensors for more detail.
699
+ output_hidden_states (`bool`, *optional*):
700
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
701
+ more detail.
702
+ return_dict (`bool`, *optional*):
703
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
704
+ """
705
+
706
+
707
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel with Llama->InternLM
708
+ @add_start_docstrings(
709
+ "The bare InternLM Model outputting raw hidden-states without any specific head on top.",
710
+ INTERNLM_START_DOCSTRING,
711
+ )
712
+ class InternLMModel(InternLMPreTrainedModel):
713
+ """
714
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLMDecoderLayer`]
715
+ Args:
716
+ config: InternLMConfig
717
+ """
718
+
719
+ _auto_class = "AutoModel"
720
+
721
+ def __init__(self, config: InternLMConfig):
722
+ super().__init__(config)
723
+ self.padding_idx = config.pad_token_id
724
+ self.vocab_size = config.vocab_size
725
+ self.config = config
726
+
727
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
728
+
729
+ self.layers = nn.ModuleList([InternLMDecoderLayer(config) for _ in range(config.num_hidden_layers)])
730
+ self.norm = InternLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
731
+
732
+ self.gradient_checkpointing = False
733
+ # Initialize weights and apply final processing
734
+ self.post_init()
735
+
736
+ def get_input_embeddings(self):
737
+ return self.embed_tokens
738
+
739
+ def set_input_embeddings(self, value):
740
+ self.embed_tokens = value
741
+
742
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
743
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
744
+ # create causal mask
745
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
746
+ combined_attention_mask = None
747
+ if input_shape[-1] > 1:
748
+ combined_attention_mask = _make_causal_mask(
749
+ input_shape,
750
+ inputs_embeds.dtype,
751
+ device=inputs_embeds.device,
752
+ past_key_values_length=past_key_values_length,
753
+ )
754
+
755
+ if attention_mask is not None:
756
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
757
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
758
+ inputs_embeds.device
759
+ )
760
+ combined_attention_mask = (
761
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
762
+ )
763
+
764
+ return combined_attention_mask
765
+
766
+ @add_start_docstrings_to_model_forward(INTERNLM_INPUTS_DOCSTRING)
767
+ def forward(
768
+ self,
769
+ input_ids: torch.LongTensor = None,
770
+ attention_mask: Optional[torch.Tensor] = None,
771
+ position_ids: Optional[torch.LongTensor] = None,
772
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
773
+ inputs_embeds: Optional[torch.FloatTensor] = None,
774
+ use_cache: Optional[bool] = None,
775
+ output_attentions: Optional[bool] = None,
776
+ output_hidden_states: Optional[bool] = None,
777
+ return_dict: Optional[bool] = None,
778
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
779
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
780
+ output_hidden_states = (
781
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
782
+ )
783
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
784
+
785
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
786
+
787
+ if self.config.attn_implementation == "flash_attention_2":
788
+ _import_flash_attn()
789
+
790
+ # retrieve input_ids and inputs_embeds
791
+ if input_ids is not None and inputs_embeds is not None:
792
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
793
+ elif input_ids is not None:
794
+ batch_size, seq_length = input_ids.shape
795
+ elif inputs_embeds is not None:
796
+ batch_size, seq_length, _ = inputs_embeds.shape
797
+ else:
798
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
799
+
800
+ seq_length_with_past = seq_length
801
+ past_key_values_length = 0
802
+
803
+ if past_key_values is not None:
804
+ past_key_values_length = past_key_values[0][0].shape[2]
805
+ seq_length_with_past = seq_length_with_past + past_key_values_length
806
+
807
+ if position_ids is None:
808
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
809
+ position_ids = torch.arange(
810
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
811
+ )
812
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
813
+ else:
814
+ position_ids = position_ids.view(-1, seq_length).long()
815
+
816
+ if inputs_embeds is None:
817
+ inputs_embeds = self.embed_tokens(input_ids)
818
+ if self.config.attn_implementation == "flash_attention_2":
819
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
820
+ else:
821
+ if attention_mask is None:
822
+ attention_mask = torch.ones(
823
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
824
+ )
825
+ attention_mask = self._prepare_decoder_attention_mask(
826
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
827
+ )
828
+
829
+ hidden_states = inputs_embeds
830
+
831
+ if self.gradient_checkpointing and self.training:
832
+ if use_cache:
833
+ logger.warning_once(
834
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
835
+ )
836
+ use_cache = False
837
+
838
+ # decoder layers
839
+ all_hidden_states = () if output_hidden_states else None
840
+ all_self_attns = () if output_attentions else None
841
+ next_decoder_cache = () if use_cache else None
842
+
843
+ for idx, decoder_layer in enumerate(self.layers):
844
+ if output_hidden_states:
845
+ all_hidden_states += (hidden_states,)
846
+
847
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
848
+
849
+ if self.gradient_checkpointing and self.training:
850
+
851
+ def create_custom_forward(module):
852
+ def custom_forward(*inputs):
853
+ # None for past_key_value
854
+ return module(*inputs, output_attentions, None)
855
+
856
+ return custom_forward
857
+
858
+ layer_outputs = torch.utils.checkpoint.checkpoint(
859
+ create_custom_forward(decoder_layer),
860
+ hidden_states,
861
+ attention_mask,
862
+ position_ids,
863
+ None,
864
+ )
865
+ else:
866
+ layer_outputs = decoder_layer(
867
+ hidden_states,
868
+ attention_mask=attention_mask,
869
+ position_ids=position_ids,
870
+ past_key_value=past_key_value,
871
+ output_attentions=output_attentions,
872
+ use_cache=use_cache,
873
+ )
874
+
875
+ hidden_states = layer_outputs[0]
876
+
877
+ if use_cache:
878
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
879
+
880
+ if output_attentions:
881
+ all_self_attns += (layer_outputs[1],)
882
+
883
+ hidden_states = self.norm(hidden_states)
884
+
885
+ # add hidden states from the last decoder layer
886
+ if output_hidden_states:
887
+ all_hidden_states += (hidden_states,)
888
+
889
+ next_cache = next_decoder_cache if use_cache else None
890
+ if not return_dict:
891
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
892
+ return BaseModelOutputWithPast(
893
+ last_hidden_state=hidden_states,
894
+ past_key_values=next_cache,
895
+ hidden_states=all_hidden_states,
896
+ attentions=all_self_attns,
897
+ )
898
+
899
+
900
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM with Llama->InternLM
901
+ class InternLMForCausalLM(InternLMPreTrainedModel):
902
+ _auto_class = "AutoModelForCausalLM"
903
+
904
+ def __init__(self, config):
905
+ super().__init__(config)
906
+ self.model = InternLMModel(config)
907
+
908
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
909
+
910
+ # Initialize weights and apply final processing
911
+ self.post_init()
912
+
913
+ def get_input_embeddings(self):
914
+ return self.model.embed_tokens
915
+
916
+ def set_input_embeddings(self, value):
917
+ self.model.embed_tokens = value
918
+
919
+ def get_output_embeddings(self):
920
+ return self.lm_head
921
+
922
+ def set_output_embeddings(self, new_embeddings):
923
+ self.lm_head = new_embeddings
924
+
925
+ def set_decoder(self, decoder):
926
+ self.model = decoder
927
+
928
+ def get_decoder(self):
929
+ return self.model
930
+
931
+ @add_start_docstrings_to_model_forward(INTERNLM_INPUTS_DOCSTRING)
932
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
933
+ def forward(
934
+ self,
935
+ input_ids: torch.LongTensor = None,
936
+ attention_mask: Optional[torch.Tensor] = None,
937
+ position_ids: Optional[torch.LongTensor] = None,
938
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
939
+ inputs_embeds: Optional[torch.FloatTensor] = None,
940
+ labels: Optional[torch.LongTensor] = None,
941
+ use_cache: Optional[bool] = None,
942
+ output_attentions: Optional[bool] = None,
943
+ output_hidden_states: Optional[bool] = None,
944
+ return_dict: Optional[bool] = None,
945
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
946
+ r"""
947
+ Args:
948
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
949
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
950
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
951
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
952
+ Returns:
953
+
954
+ Example:
955
+ ```python
956
+ >>> from transformers import AutoTokenizer, InternLMForCausalLM
957
+ >>> model = InternLMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
958
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
959
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
960
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
961
+ >>> # Generate
962
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
963
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
964
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
965
+ ```
966
+
967
+ """
968
+
969
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
970
+ output_hidden_states = (
971
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
972
+ )
973
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
974
+
975
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
976
+ outputs = self.model(
977
+ input_ids=input_ids,
978
+ attention_mask=attention_mask,
979
+ position_ids=position_ids,
980
+ past_key_values=past_key_values,
981
+ inputs_embeds=inputs_embeds,
982
+ use_cache=use_cache,
983
+ output_attentions=output_attentions,
984
+ output_hidden_states=output_hidden_states,
985
+ return_dict=return_dict,
986
+ )
987
+
988
+ hidden_states = outputs[0]
989
+ logits = self.lm_head(hidden_states)
990
+
991
+ loss = None
992
+ if labels is not None:
993
+ # Shift so that tokens < n predict n
994
+ shift_logits = logits[..., :-1, :].contiguous()
995
+ shift_labels = labels[..., 1:].contiguous()
996
+ # Flatten the tokens
997
+ loss_fct = CrossEntropyLoss()
998
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
999
+ shift_labels = shift_labels.view(-1)
1000
+ # Enable model parallelism
1001
+ shift_labels = shift_labels.to(shift_logits.device)
1002
+ loss = loss_fct(shift_logits, shift_labels)
1003
+
1004
+ if not return_dict:
1005
+ output = (logits,) + outputs[1:]
1006
+ return (loss,) + output if loss is not None else output
1007
+
1008
+ return CausalLMOutputWithPast(
1009
+ loss=loss,
1010
+ logits=logits,
1011
+ past_key_values=outputs.past_key_values,
1012
+ hidden_states=outputs.hidden_states,
1013
+ attentions=outputs.attentions,
1014
+ )
1015
+
1016
+ def prepare_inputs_for_generation(
1017
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1018
+ ):
1019
+ if past_key_values:
1020
+ input_ids = input_ids[:, -1:]
1021
+
1022
+ position_ids = kwargs.get("position_ids", None)
1023
+ if attention_mask is not None and position_ids is None:
1024
+ # create position_ids on the fly for batch generation
1025
+ position_ids = attention_mask.long().cumsum(-1) - 1
1026
+ position_ids.masked_fill_(attention_mask == 0, 1)
1027
+ if past_key_values:
1028
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1029
+
1030
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1031
+ if inputs_embeds is not None and past_key_values is None:
1032
+ model_inputs = {"inputs_embeds": inputs_embeds}
1033
+ else:
1034
+ model_inputs = {"input_ids": input_ids}
1035
+
1036
+ model_inputs.update(
1037
+ {
1038
+ "position_ids": position_ids,
1039
+ "past_key_values": past_key_values,
1040
+ "use_cache": kwargs.get("use_cache"),
1041
+ "attention_mask": attention_mask,
1042
+ }
1043
+ )
1044
+ return model_inputs
1045
+
1046
+ @staticmethod
1047
+ def _reorder_cache(past_key_values, beam_idx):
1048
+ reordered_past = ()
1049
+ for layer_past in past_key_values:
1050
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1051
+ return reordered_past
1052
+
1053
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = [], meta_instruction=""):
1054
+ if tokenizer.add_bos_token:
1055
+ prompt = ""
1056
+ else:
1057
+ prompt = tokenizer.bos_token
1058
+ if meta_instruction:
1059
+ prompt += f"""<|System|>:{meta_instruction}\n"""
1060
+ for record in history:
1061
+ prompt += f"""<|User|>:{record[0]}\n<|Bot|>:{record[1]}<eoa>\n"""
1062
+ prompt += f"""<|User|>:{query}\n<|Bot|>:"""
1063
+ return tokenizer([prompt], return_tensors="pt")
1064
+
1065
+ @torch.no_grad()
1066
+ def chat(
1067
+ self,
1068
+ tokenizer,
1069
+ query: str,
1070
+ history: List[Tuple[str, str]] = [],
1071
+ streamer: Optional[BaseStreamer] = None,
1072
+ max_new_tokens: int = 1024,
1073
+ do_sample: bool = True,
1074
+ temperature: float = 0.8,
1075
+ top_p: float = 0.8,
1076
+ meta_instruction: str = "You are an AI assistant whose name is InternLM (书生·浦语).\n"
1077
+ "- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
1078
+ "- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.",
1079
+ **kwargs,
1080
+ ):
1081
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1082
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1083
+ outputs = self.generate(
1084
+ **inputs,
1085
+ streamer=streamer,
1086
+ max_new_tokens=max_new_tokens,
1087
+ do_sample=do_sample,
1088
+ temperature=temperature,
1089
+ top_p=top_p,
1090
+ **kwargs,
1091
+ )
1092
+ outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
1093
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1094
+ response = response.split("<eoa>")[0]
1095
+ history = history + [(query, response)]
1096
+ return response, history
1097
+
1098
+ @torch.no_grad()
1099
+ def stream_chat(
1100
+ self,
1101
+ tokenizer,
1102
+ query: str,
1103
+ history: List[Tuple[str, str]] = [],
1104
+ max_new_tokens: int = 1024,
1105
+ do_sample: bool = True,
1106
+ temperature: float = 0.8,
1107
+ top_p: float = 0.8,
1108
+ **kwargs,
1109
+ ):
1110
+ """
1111
+ Return a generator in format: (response, history)
1112
+ Eg.
1113
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1114
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1115
+ """
1116
+ if BaseStreamer is None:
1117
+ raise ModuleNotFoundError(
1118
+ "The version of `transformers` is too low. Please make sure "
1119
+ "that you have installed `transformers>=4.28.0`."
1120
+ )
1121
+
1122
+ response_queue = queue.Queue(maxsize=20)
1123
+
1124
+ class ChatStreamer(BaseStreamer):
1125
+ def __init__(self, tokenizer) -> None:
1126
+ super().__init__()
1127
+ self.tokenizer = tokenizer
1128
+ self.queue = response_queue
1129
+ self.query = query
1130
+ self.history = history
1131
+ self.response = ""
1132
+ self.cache = []
1133
+ self.received_inputs = False
1134
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1135
+
1136
+ def put(self, value):
1137
+ if len(value.shape) > 1 and value.shape[0] > 1:
1138
+ raise ValueError("ChatStreamer only supports batch size 1")
1139
+ elif len(value.shape) > 1:
1140
+ value = value[0]
1141
+
1142
+ if not self.received_inputs:
1143
+ # The first received value is input_ids, ignore here
1144
+ self.received_inputs = True
1145
+ return
1146
+
1147
+ self.cache.extend(value.tolist())
1148
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1149
+ if "�" in token and len(token) <= 5:
1150
+ return
1151
+ if token.strip() != "<eoa>":
1152
+ self.response = self.response + token
1153
+ history = self.history + [(self.query, self.response)]
1154
+ self.queue.put((self.response, history))
1155
+ self.cache = []
1156
+ else:
1157
+ self.end()
1158
+
1159
+ def end(self):
1160
+ self.queue.put(None)
1161
+
1162
+ def stream_producer():
1163
+ return self.chat(
1164
+ tokenizer=tokenizer,
1165
+ query=query,
1166
+ streamer=ChatStreamer(tokenizer=tokenizer),
1167
+ history=history,
1168
+ max_new_tokens=max_new_tokens,
1169
+ do_sample=do_sample,
1170
+ temperature=temperature,
1171
+ top_p=top_p,
1172
+ **kwargs,
1173
+ )
1174
+
1175
+ def consumer():
1176
+ producer = threading.Thread(target=stream_producer)
1177
+ producer.start()
1178
+ while True:
1179
+ res = response_queue.get()
1180
+ if res is None:
1181
+ return
1182
+ yield res
1183
+
1184
+ return consumer()
1185
+
1186
+
1187
+ @add_start_docstrings(
1188
+ """
1189
+ The InternLM Model transformer with a sequence classification head on top (linear layer).
1190
+ [`InternLMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1191
+ (e.g. GPT-2) do.
1192
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1193
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1194
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1195
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1196
+ each row of the batch).
1197
+ """,
1198
+ INTERNLM_START_DOCSTRING,
1199
+ )
1200
+ class InternLMForSequenceClassification(InternLMPreTrainedModel):
1201
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1202
+
1203
+ def __init__(self, config):
1204
+ super().__init__(config)
1205
+ self.num_labels = config.num_labels
1206
+ self.model = InternLMModel(config)
1207
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1208
+
1209
+ # Initialize weights and apply final processing
1210
+ self.post_init()
1211
+
1212
+ def get_input_embeddings(self):
1213
+ return self.model.embed_tokens
1214
+
1215
+ def set_input_embeddings(self, value):
1216
+ self.model.embed_tokens = value
1217
+
1218
+ @add_start_docstrings_to_model_forward(INTERNLM_INPUTS_DOCSTRING)
1219
+ def forward(
1220
+ self,
1221
+ input_ids: torch.LongTensor = None,
1222
+ attention_mask: Optional[torch.Tensor] = None,
1223
+ position_ids: Optional[torch.LongTensor] = None,
1224
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1225
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1226
+ labels: Optional[torch.LongTensor] = None,
1227
+ use_cache: Optional[bool] = None,
1228
+ output_attentions: Optional[bool] = None,
1229
+ output_hidden_states: Optional[bool] = None,
1230
+ return_dict: Optional[bool] = None,
1231
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1232
+ r"""
1233
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1234
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1235
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1236
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1237
+ """
1238
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1239
+
1240
+ transformer_outputs = self.model(
1241
+ input_ids,
1242
+ attention_mask=attention_mask,
1243
+ position_ids=position_ids,
1244
+ past_key_values=past_key_values,
1245
+ inputs_embeds=inputs_embeds,
1246
+ use_cache=use_cache,
1247
+ output_attentions=output_attentions,
1248
+ output_hidden_states=output_hidden_states,
1249
+ return_dict=return_dict,
1250
+ )
1251
+ hidden_states = transformer_outputs[0]
1252
+ logits = self.score(hidden_states)
1253
+
1254
+ if input_ids is not None:
1255
+ batch_size = input_ids.shape[0]
1256
+ else:
1257
+ batch_size = inputs_embeds.shape[0]
1258
+
1259
+ if self.config.pad_token_id is None and batch_size != 1:
1260
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1261
+ if self.config.pad_token_id is None:
1262
+ sequence_lengths = -1
1263
+ else:
1264
+ if input_ids is not None:
1265
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1266
+ else:
1267
+ sequence_lengths = -1
1268
+
1269
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1270
+
1271
+ loss = None
1272
+ if labels is not None:
1273
+ labels = labels.to(logits.device)
1274
+ if self.config.problem_type is None:
1275
+ if self.num_labels == 1:
1276
+ self.config.problem_type = "regression"
1277
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1278
+ self.config.problem_type = "single_label_classification"
1279
+ else:
1280
+ self.config.problem_type = "multi_label_classification"
1281
+
1282
+ if self.config.problem_type == "regression":
1283
+ loss_fct = MSELoss()
1284
+ if self.num_labels == 1:
1285
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1286
+ else:
1287
+ loss = loss_fct(pooled_logits, labels)
1288
+ elif self.config.problem_type == "single_label_classification":
1289
+ loss_fct = CrossEntropyLoss()
1290
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1291
+ elif self.config.problem_type == "multi_label_classification":
1292
+ loss_fct = BCEWithLogitsLoss()
1293
+ loss = loss_fct(pooled_logits, labels)
1294
+ if not return_dict:
1295
+ output = (pooled_logits,) + transformer_outputs[1:]
1296
+ return ((loss,) + output) if loss is not None else output
1297
+
1298
+ return SequenceClassifierOutputWithPast(
1299
+ loss=loss,
1300
+ logits=pooled_logits,
1301
+ past_key_values=transformer_outputs.past_key_values,
1302
+ hidden_states=transformer_outputs.hidden_states,
1303
+ attentions=transformer_outputs.attentions,
1304
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "eos_token": "</s>",
4
+ "pad_token": "</s>",
5
+ "unk_token": "<unk>"
6
+ }
tokenization_internlm.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/tokenization_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
+
18
+ """Tokenization classes for InternLM."""
19
+ import os
20
+ from shutil import copyfile
21
+ from typing import Any, Dict, List, Optional, Tuple
22
+
23
+ import sentencepiece as spm
24
+
25
+ from transformers.tokenization_utils import PreTrainedTokenizer
26
+ from transformers.utils import logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
32
+
33
+ PRETRAINED_VOCAB_FILES_MAP = {}
34
+
35
+ # Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer -> InternLM2Tokenizer
36
+ class InternLMTokenizer(PreTrainedTokenizer):
37
+ """
38
+ Construct a InternLM tokenizer. Based on byte-level Byte-Pair-Encoding.
39
+
40
+ Args:
41
+ vocab_file (`str`):
42
+ Path to the vocabulary file.
43
+ """
44
+
45
+ vocab_files_names = VOCAB_FILES_NAMES
46
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
47
+ model_input_names = ["input_ids", "attention_mask"]
48
+ _auto_class = "AutoTokenizer"
49
+
50
+ def __init__(
51
+ self,
52
+ vocab_file,
53
+ unk_token="<unk>",
54
+ bos_token="<s>",
55
+ eos_token="</s>",
56
+ pad_token="</s>",
57
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
58
+ add_bos_token=True,
59
+ add_eos_token=False,
60
+ decode_with_prefix_space=False,
61
+ clean_up_tokenization_spaces=False,
62
+ **kwargs,
63
+ ):
64
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
65
+ self.vocab_file = vocab_file
66
+ self.add_bos_token = add_bos_token
67
+ self.add_eos_token = add_eos_token
68
+ self.decode_with_prefix_space = decode_with_prefix_space
69
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
70
+ self.sp_model.Load(vocab_file)
71
+ self._no_prefix_space_tokens = None
72
+ super().__init__(
73
+ bos_token=bos_token,
74
+ eos_token=eos_token,
75
+ unk_token=unk_token,
76
+ pad_token=pad_token,
77
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
78
+ **kwargs,
79
+ )
80
+
81
+ @property
82
+ def no_prefix_space_tokens(self):
83
+ if self._no_prefix_space_tokens is None:
84
+ vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
85
+ self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith("▁")}
86
+ return self._no_prefix_space_tokens
87
+
88
+ @property
89
+ def vocab_size(self):
90
+ """Returns vocab size"""
91
+ return self.sp_model.get_piece_size()
92
+
93
+ @property
94
+ def bos_token_id(self) -> Optional[int]:
95
+ return self.sp_model.bos_id()
96
+
97
+ @property
98
+ def eos_token_id(self) -> Optional[int]:
99
+ return self.sp_model.eos_id()
100
+
101
+ def get_vocab(self):
102
+ """Returns vocab as a dict"""
103
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
104
+ vocab.update(self.added_tokens_encoder)
105
+ return vocab
106
+
107
+ def _tokenize(self, text):
108
+ """Returns a tokenized string."""
109
+ return self.sp_model.encode(text, out_type=str)
110
+
111
+ def _convert_token_to_id(self, token):
112
+ """Converts a token (str) in an id using the vocab."""
113
+ return self.sp_model.piece_to_id(token)
114
+
115
+ def _convert_id_to_token(self, index):
116
+ """Converts an index (integer) in a token (str) using the vocab."""
117
+ token = self.sp_model.IdToPiece(index)
118
+ return token
119
+
120
+ def _maybe_add_prefix_space(self, tokens, decoded):
121
+ if tokens and tokens[0] not in self.no_prefix_space_tokens:
122
+ return " " + decoded
123
+ else:
124
+ return decoded
125
+
126
+ def convert_tokens_to_string(self, tokens):
127
+ """Converts a sequence of tokens (string) in a single string."""
128
+ current_sub_tokens = []
129
+ out_string = ""
130
+ prev_is_special = False
131
+ for token in tokens:
132
+ # make sure that special tokens are not decoded using sentencepiece model
133
+ if token in self.all_special_tokens:
134
+ if not prev_is_special:
135
+ out_string += " "
136
+ out_string += self.sp_model.decode(current_sub_tokens) + token
137
+ prev_is_special = True
138
+ current_sub_tokens = []
139
+ else:
140
+ current_sub_tokens.append(token)
141
+ prev_is_special = False
142
+ out_string += self.sp_model.decode(current_sub_tokens)
143
+ out_string = self.clean_up_tokenization(out_string)
144
+ out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
145
+ return out_string[1:]
146
+
147
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
148
+ """
149
+ Save the vocabulary and special tokens file to a directory.
150
+
151
+ Args:
152
+ save_directory (`str`):
153
+ The directory in which to save the vocabulary.
154
+
155
+ Returns:
156
+ `Tuple(str)`: Paths to the files saved.
157
+ """
158
+ if not os.path.isdir(save_directory):
159
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
160
+ return
161
+ out_vocab_file = os.path.join(
162
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
163
+ )
164
+
165
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
166
+ copyfile(self.vocab_file, out_vocab_file)
167
+ elif not os.path.isfile(self.vocab_file):
168
+ with open(out_vocab_file, "wb") as fi:
169
+ content_spiece_model = self.sp_model.serialized_model_proto()
170
+ fi.write(content_spiece_model)
171
+
172
+ return (out_vocab_file,)
173
+
174
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
175
+ if self.add_bos_token:
176
+ bos_token_ids = [self.bos_token_id]
177
+ else:
178
+ bos_token_ids = []
179
+
180
+ output = bos_token_ids + token_ids_0
181
+
182
+ if token_ids_1 is not None:
183
+ output = output + token_ids_1
184
+
185
+ if self.add_eos_token:
186
+ output = output + [self.eos_token_id]
187
+
188
+ return output
189
+
190
+ def get_special_tokens_mask(
191
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
192
+ ) -> List[int]:
193
+ """
194
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
195
+ special tokens using the tokenizer `prepare_for_model` method.
196
+
197
+ Args:
198
+ token_ids_0 (`List[int]`):
199
+ List of IDs.
200
+ token_ids_1 (`List[int]`, *optional*):
201
+ Optional second list of IDs for sequence pairs.
202
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
203
+ Whether or not the token list is already formatted with special tokens for the model.
204
+
205
+ Returns:
206
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
207
+ """
208
+ if already_has_special_tokens:
209
+ return super().get_special_tokens_mask(
210
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
211
+ )
212
+
213
+ if token_ids_1 is None:
214
+ return [1] + ([0] * len(token_ids_0)) + [1]
215
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
216
+
217
+ def create_token_type_ids_from_sequences(
218
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
219
+ ) -> List[int]:
220
+ """
221
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
222
+ use of token type ids, therefore a list of zeros is returned.
223
+
224
+ Args:
225
+ token_ids_0 (`List[int]`):
226
+ List of IDs.
227
+ token_ids_1 (`List[int]`, *optional*):
228
+ Optional second list of IDs for sequence pairs.
229
+
230
+ Returns:
231
+ `List[int]`: List of zeros.
232
+ """
233
+ eos = [self.eos_token_id]
234
+
235
+ if token_ids_1 is None:
236
+ return len(token_ids_0 + eos) * [0]
237
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aab622d98c98677a1a51f969e25765154487bf3e85c7819db105db2fcacba83f
3
+ size 1658691
tokenizer_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<unk>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ }
27
+ },
28
+ "auto_map": {
29
+ "AutoTokenizer": [
30
+ "tokenization_internlm.InternLMTokenizer",
31
+ null
32
+ ]
33
+ },
34
+ "bos_token": "<s>",
35
+ "clean_up_tokenization_spaces": false,
36
+ "eos_token": "</s>",
37
+ "model_max_length": 1000000000000000019884624838656,
38
+ "pad_token": "</s>",
39
+ "tokenizer_class": "InternLMTokenizer",
40
+ "unk_token": "<unk>"
41
+ }