unakar commited on
Commit
6c0d172
·
verified ·
1 Parent(s): 243906c

Upload 8 files

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