katuni4ka commited on
Commit
62fe516
1 Parent(s): 27ba27f

Upload 9 files

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