ZwwWayne commited on
Commit
2fb05a1
1 Parent(s): 7a4f010

update model weights

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