IlyasMoutawwakil HF Staff commited on
Commit
fd0218f
·
verified ·
1 Parent(s): c1cc0cb

Mirror from katuni4ka/tiny-random-internlm

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