Upload folder using huggingface_hub
Browse files- config.json +60 -0
- configuration_llama.py +203 -0
- generation_config.json +6 -0
- model.safetensors +3 -0
- modeling_llama.py +1252 -0
- special_tokens_map.json +30 -0
- tokenizer.json +0 -0
- tokenizer.model +3 -0
- tokenizer_config.json +42 -0
config.json
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "LLaMA-MoD",
|
3 |
+
"architectures": [
|
4 |
+
"LlamaMoDForCausalLM"
|
5 |
+
],
|
6 |
+
"attention_bias": false,
|
7 |
+
"attention_dropout": 0.0,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_llama.LlamaMoDConfig",
|
10 |
+
"AutoModel": "modeling_llama.MiniCPMModelLlamaMoDModel",
|
11 |
+
"AutoModelForCausalLM": "modeling_llama.LlamaMoDForCausalLM"
|
12 |
+
},
|
13 |
+
"bos_token_id": 1,
|
14 |
+
"capacity_load": 0.5,
|
15 |
+
"eos_token_id": 2,
|
16 |
+
"hidden_act": "silu",
|
17 |
+
"hidden_size": 2048,
|
18 |
+
"initializer_range": 0.02,
|
19 |
+
"intermediate_size": 5632,
|
20 |
+
"max_position_embeddings": 2048,
|
21 |
+
"mod_method": "mod_dual",
|
22 |
+
"model_type": "llama",
|
23 |
+
"num_attention_heads": 32,
|
24 |
+
"num_hidden_layers": 22,
|
25 |
+
"num_key_value_heads": 4,
|
26 |
+
"pretraining_tp": 1,
|
27 |
+
"rms_norm_eps": 1e-05,
|
28 |
+
"rope_scaling": null,
|
29 |
+
"rope_theta": 10000.0,
|
30 |
+
"router_aux_loss_coef": 0.005,
|
31 |
+
"setup_layer_mod": [
|
32 |
+
false,
|
33 |
+
false,
|
34 |
+
false,
|
35 |
+
false,
|
36 |
+
false,
|
37 |
+
true,
|
38 |
+
false,
|
39 |
+
true,
|
40 |
+
false,
|
41 |
+
true,
|
42 |
+
false,
|
43 |
+
true,
|
44 |
+
false,
|
45 |
+
true,
|
46 |
+
false,
|
47 |
+
true,
|
48 |
+
false,
|
49 |
+
true,
|
50 |
+
false,
|
51 |
+
true,
|
52 |
+
false,
|
53 |
+
false
|
54 |
+
],
|
55 |
+
"tie_word_embeddings": false,
|
56 |
+
"torch_dtype": "bfloat16",
|
57 |
+
"transformers_version": "4.40.0.dev0",
|
58 |
+
"use_cache": true,
|
59 |
+
"vocab_size": 32000
|
60 |
+
}
|
configuration_llama.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. 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 |
+
""" LLaMA model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.utils import logging
|
24 |
+
|
25 |
+
|
26 |
+
logger = logging.get_logger(__name__)
|
27 |
+
|
28 |
+
|
29 |
+
|
30 |
+
class LlamaMoDConfig(PretrainedConfig):
|
31 |
+
r"""
|
32 |
+
This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
|
33 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
34 |
+
defaults will yield a similar configuration to that of the LLaMA-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 LLaMA model. Defines the number of different tokens that can be represented by the
|
43 |
+
`inputs_ids` passed when calling [`LlamaModel`]
|
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 decoder.
|
50 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
51 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
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. Llama 1 supports up to 2048 tokens,
|
64 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
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-06):
|
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 |
+
pad_token_id (`int`, *optional*):
|
73 |
+
Padding token id.
|
74 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
75 |
+
Beginning of stream token id.
|
76 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
77 |
+
End of stream token id.
|
78 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
79 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
80 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
|
81 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
82 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
83 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
84 |
+
Whether to tie weight embeddings
|
85 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
86 |
+
The base period of the RoPE embeddings.
|
87 |
+
rope_scaling (`Dict`, *optional*):
|
88 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
89 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
90 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
91 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
92 |
+
these scaling strategies behave:
|
93 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
94 |
+
experimental feature, subject to breaking API changes in future versions.
|
95 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
96 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
97 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
98 |
+
The dropout ratio for the attention probabilities.
|
99 |
+
|
100 |
+
```python
|
101 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
102 |
+
|
103 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
104 |
+
>>> configuration = LlamaConfig()
|
105 |
+
|
106 |
+
>>> # Initializing a model from the llama-7b style configuration
|
107 |
+
>>> model = LlamaModel(configuration)
|
108 |
+
|
109 |
+
>>> # Accessing the model configuration
|
110 |
+
>>> configuration = model.config
|
111 |
+
```"""
|
112 |
+
|
113 |
+
model_type = "llama"
|
114 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
115 |
+
|
116 |
+
def __init__(
|
117 |
+
self,
|
118 |
+
vocab_size=32000,
|
119 |
+
hidden_size=4096,
|
120 |
+
intermediate_size=11008,
|
121 |
+
num_hidden_layers=32,
|
122 |
+
num_attention_heads=32,
|
123 |
+
num_key_value_heads=None,
|
124 |
+
hidden_act="silu",
|
125 |
+
max_position_embeddings=2048,
|
126 |
+
initializer_range=0.02,
|
127 |
+
rms_norm_eps=1e-6,
|
128 |
+
use_cache=True,
|
129 |
+
pad_token_id=None,
|
130 |
+
bos_token_id=1,
|
131 |
+
eos_token_id=2,
|
132 |
+
pretraining_tp=1,
|
133 |
+
tie_word_embeddings=False,
|
134 |
+
rope_theta=10000.0,
|
135 |
+
rope_scaling=None,
|
136 |
+
attention_bias=False,
|
137 |
+
attention_dropout=0.0,
|
138 |
+
mlp_bias=False,
|
139 |
+
head_dim=None,
|
140 |
+
interleave_mod_layer=False,
|
141 |
+
router_aux_loss_coef=1e-4,
|
142 |
+
mod_method='none',
|
143 |
+
**kwargs,
|
144 |
+
):
|
145 |
+
self.setup_layer_mod = [False]*num_hidden_layers
|
146 |
+
if interleave_mod_layer:
|
147 |
+
for idx in range(num_hidden_layers):
|
148 |
+
if idx % 2:
|
149 |
+
self.setup_layer_mod[idx] = True
|
150 |
+
self.mod_method = mod_method
|
151 |
+
self.router_aux_loss_coef = router_aux_loss_coef
|
152 |
+
self.vocab_size = vocab_size
|
153 |
+
self.max_position_embeddings = max_position_embeddings
|
154 |
+
self.hidden_size = hidden_size
|
155 |
+
self.intermediate_size = intermediate_size
|
156 |
+
self.num_hidden_layers = num_hidden_layers
|
157 |
+
self.num_attention_heads = num_attention_heads
|
158 |
+
|
159 |
+
# for backward compatibility
|
160 |
+
if num_key_value_heads is None:
|
161 |
+
num_key_value_heads = num_attention_heads
|
162 |
+
|
163 |
+
self.num_key_value_heads = num_key_value_heads
|
164 |
+
self.hidden_act = hidden_act
|
165 |
+
self.initializer_range = initializer_range
|
166 |
+
self.rms_norm_eps = rms_norm_eps
|
167 |
+
self.pretraining_tp = pretraining_tp
|
168 |
+
self.use_cache = use_cache
|
169 |
+
self.rope_theta = rope_theta
|
170 |
+
self.rope_scaling = rope_scaling
|
171 |
+
self._rope_scaling_validation()
|
172 |
+
self.attention_bias = attention_bias
|
173 |
+
self.attention_dropout = attention_dropout
|
174 |
+
self.mlp_bias = mlp_bias
|
175 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
176 |
+
|
177 |
+
super().__init__(
|
178 |
+
pad_token_id=pad_token_id,
|
179 |
+
bos_token_id=bos_token_id,
|
180 |
+
eos_token_id=eos_token_id,
|
181 |
+
tie_word_embeddings=tie_word_embeddings,
|
182 |
+
**kwargs,
|
183 |
+
)
|
184 |
+
|
185 |
+
def _rope_scaling_validation(self):
|
186 |
+
"""
|
187 |
+
Validate the `rope_scaling` configuration.
|
188 |
+
"""
|
189 |
+
if self.rope_scaling is None:
|
190 |
+
return
|
191 |
+
|
192 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
193 |
+
raise ValueError(
|
194 |
+
"`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
|
195 |
+
)
|
196 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
197 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
198 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
199 |
+
raise ValueError(
|
200 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
201 |
+
)
|
202 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
203 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
generation_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"transformers_version": "4.40.0.dev0"
|
6 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4e578f3ca6f1dadbfe93f248578a20630aa5c519d750239834b08c254b003f1e
|
3 |
+
size 2233743328
|
modeling_llama.py
ADDED
@@ -0,0 +1,1252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. 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 LLaMA model."""
|
21 |
+
import json
|
22 |
+
import math
|
23 |
+
import warnings
|
24 |
+
from typing import List, Optional, Tuple, Union
|
25 |
+
|
26 |
+
import torch
|
27 |
+
import torch.nn.functional as F
|
28 |
+
import torch.utils.checkpoint
|
29 |
+
from torch import nn
|
30 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
31 |
+
|
32 |
+
from transformers.activations import ACT2FN
|
33 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
34 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
35 |
+
from transformers.modeling_outputs import (
|
36 |
+
BaseModelOutputWithPast,
|
37 |
+
CausalLMOutputWithPast,
|
38 |
+
MoeModelOutputWithPast, MoeCausalLMOutputWithPast,
|
39 |
+
QuestionAnsweringModelOutput,
|
40 |
+
SequenceClassifierOutputWithPast,
|
41 |
+
)
|
42 |
+
from transformers.modeling_utils import PreTrainedModel
|
43 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
44 |
+
from transformers.utils import (
|
45 |
+
add_start_docstrings,
|
46 |
+
add_start_docstrings_to_model_forward,
|
47 |
+
is_flash_attn_2_available,
|
48 |
+
is_flash_attn_greater_or_equal_2_10,
|
49 |
+
logging,
|
50 |
+
replace_return_docstrings,
|
51 |
+
)
|
52 |
+
# we just reuse everything we don't modified
|
53 |
+
from transformers.models.llama.modeling_llama import (
|
54 |
+
LlamaRMSNorm, LlamaRotaryEmbedding,
|
55 |
+
LlamaLinearScalingRotaryEmbedding,
|
56 |
+
LlamaDynamicNTKScalingRotaryEmbedding,
|
57 |
+
LlamaAttention,
|
58 |
+
LlamaMLP,
|
59 |
+
LlamaFlashAttention2,
|
60 |
+
LlamaSdpaAttention,
|
61 |
+
LlamaDecoderLayer
|
62 |
+
)
|
63 |
+
from .configuration_llama import LlamaMoDConfig
|
64 |
+
|
65 |
+
|
66 |
+
if is_flash_attn_2_available():
|
67 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
68 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
69 |
+
|
70 |
+
|
71 |
+
logger = logging.get_logger(__name__)
|
72 |
+
|
73 |
+
_CONFIG_FOR_DOC = "LlamaMoDConfig"
|
74 |
+
|
75 |
+
|
76 |
+
def _get_unpad_data(attention_mask):
|
77 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
78 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
79 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
80 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
81 |
+
return (
|
82 |
+
indices,
|
83 |
+
cu_seqlens,
|
84 |
+
max_seqlen_in_batch,
|
85 |
+
)
|
86 |
+
|
87 |
+
|
88 |
+
ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
|
89 |
+
|
90 |
+
LLAMA_ATTENTION_CLASSES = {
|
91 |
+
"eager": LlamaAttention,
|
92 |
+
"flash_attention_2": LlamaFlashAttention2,
|
93 |
+
"sdpa": LlamaSdpaAttention,
|
94 |
+
}
|
95 |
+
|
96 |
+
def dual_router_aux_loss(
|
97 |
+
gate_logits: torch.Tensor, num_experts: torch.Tensor = 40, capacity_load=5, attention_mask: Optional[torch.Tensor] = None
|
98 |
+
) -> float:
|
99 |
+
r"""
|
100 |
+
Computes auxiliary load balancing loss as in Layer wise mode - implemented in Pytorch.
|
101 |
+
|
102 |
+
Modified from Switch Transformer (https://arxiv.org/abs/2101.03961), I mean mixtral model.
|
103 |
+
This function implements the loss function presented in equations (4) - (6) of the paper.
|
104 |
+
It aims at penalizing cases where the routing between experts is too unbalanced.
|
105 |
+
|
106 |
+
Args:
|
107 |
+
gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
|
108 |
+
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
109 |
+
shape [batch_size X sequence_length, num_experts].
|
110 |
+
attention_mask (`torch.Tensor`, None):
|
111 |
+
The attention_mask used in forward function
|
112 |
+
shape [batch_size X sequence_length] if not None.
|
113 |
+
num_experts (`int`):
|
114 |
+
Number of layers
|
115 |
+
top_k (`int`):
|
116 |
+
Number of experts (capacility load * num_experts)
|
117 |
+
|
118 |
+
Returns:
|
119 |
+
The auxiliary loss.
|
120 |
+
"""
|
121 |
+
if gate_logits is None or not isinstance(gate_logits, tuple):
|
122 |
+
return 0
|
123 |
+
|
124 |
+
bce_loss = nn.BCEWithLogitsLoss()
|
125 |
+
if isinstance(gate_logits, tuple):
|
126 |
+
compute_device = gate_logits[0].device
|
127 |
+
concatenated_gate_logits = torch.cat([layer_gate.unsqueeze(-1).to(compute_device) for layer_gate in gate_logits], dim=-1)
|
128 |
+
seq_len = concatenated_gate_logits.shape[1]
|
129 |
+
top_k = int(capacity_load*seq_len)
|
130 |
+
bs = concatenated_gate_logits.shape[0]
|
131 |
+
# concatenated_gate_logits : bs x seq_len x [ route logits, mlp router pred ] x layers
|
132 |
+
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits[:, :, 0, :], dim=1)
|
133 |
+
# routing_weights = routing_weights
|
134 |
+
_, selected_tokens = torch.topk(routing_weights, top_k, dim=1)
|
135 |
+
pred_logits = concatenated_gate_logits[:, :, 1, :]
|
136 |
+
router_targets = torch.zeros_like(pred_logits).view(-1)
|
137 |
+
router_targets[selected_tokens.view(-1)] = 1.0
|
138 |
+
loss = bce_loss(pred_logits, router_targets.view(bs, seq_len, -1))
|
139 |
+
return loss
|
140 |
+
|
141 |
+
class LlamaMoDDuaRouter(nn.Module):
|
142 |
+
# implement the prediction inside this instead to make sure weights are transferable
|
143 |
+
# Implement method 1
|
144 |
+
|
145 |
+
def __init__(self, config: LlamaMoDConfig, layer_idx: int):
|
146 |
+
super().__init__()
|
147 |
+
self.hidden_size = config.hidden_size
|
148 |
+
self.layer_idx = layer_idx
|
149 |
+
self.capacity_factor = config.capacity_load
|
150 |
+
self.dynamic_skip = config.setup_layer_mod[layer_idx]
|
151 |
+
if self.dynamic_skip:
|
152 |
+
self.mod_router = nn.Linear(self.hidden_size, 1, bias=False)
|
153 |
+
# used in inference instead
|
154 |
+
self.mlp_router = nn.Sequential(
|
155 |
+
nn.Linear(self.hidden_size, self.hidden_size//2),
|
156 |
+
nn.SiLU(),
|
157 |
+
nn.Linear(self.hidden_size//2, 1, bias=False)
|
158 |
+
)
|
159 |
+
|
160 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
161 |
+
|
162 |
+
self.mlp = LlamaMLP(config)
|
163 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
164 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
165 |
+
|
166 |
+
def forward(
|
167 |
+
self,
|
168 |
+
hidden_states: torch.Tensor,
|
169 |
+
attention_mask: Optional[torch.Tensor] = None,
|
170 |
+
position_ids: Optional[torch.LongTensor] = None,
|
171 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
172 |
+
output_attentions: Optional[bool] = False,
|
173 |
+
use_cache: Optional[bool] = False,
|
174 |
+
cache_position: Optional[torch.LongTensor] = None,
|
175 |
+
**kwargs,
|
176 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
177 |
+
"""
|
178 |
+
Args:
|
179 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
180 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
181 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
182 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
183 |
+
output_attentions (`bool`, *optional*):
|
184 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
185 |
+
returned tensors for more detail.
|
186 |
+
use_cache (`bool`, *optional*):
|
187 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
188 |
+
(see `past_key_values`).
|
189 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
190 |
+
"""
|
191 |
+
if "padding_mask" in kwargs:
|
192 |
+
warnings.warn(
|
193 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
194 |
+
)
|
195 |
+
|
196 |
+
initial_residual = hidden_states
|
197 |
+
if self.dynamic_skip:
|
198 |
+
residual = hidden_states
|
199 |
+
seq_len = hidden_states.shape[1]
|
200 |
+
route = torch.softmax(self.mod_router(hidden_states), dim=1)
|
201 |
+
mlp_router_logits = self.mlp_router(hidden_states)
|
202 |
+
if not self.training:
|
203 |
+
# use mlp for during inference
|
204 |
+
_old_router = route
|
205 |
+
route = torch.sigmoid(mlp_router_logits)
|
206 |
+
hidden_states = self.input_layernorm(hidden_states)
|
207 |
+
|
208 |
+
if not self.training and hidden_states.shape[1] == 1 and hidden_states.shape[0] == 1:
|
209 |
+
# TODO: fix this broke when batch is > 1
|
210 |
+
if route[-1] > 0.5:
|
211 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
212 |
+
hidden_states=hidden_states,
|
213 |
+
attention_mask=attention_mask,
|
214 |
+
position_ids=position_ids,
|
215 |
+
past_key_value=past_key_value,
|
216 |
+
output_attentions=output_attentions,
|
217 |
+
use_cache=use_cache,
|
218 |
+
**kwargs,
|
219 |
+
)
|
220 |
+
hidden_states = residual + hidden_states
|
221 |
+
# Fully Connected
|
222 |
+
residual = hidden_states
|
223 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
224 |
+
hidden_states = self.mlp(hidden_states)
|
225 |
+
hidden_states = residual + hidden_states
|
226 |
+
hidden_states *= route
|
227 |
+
else:
|
228 |
+
hidden_states = initial_residual
|
229 |
+
self_attn_weights = None
|
230 |
+
present_key_value = None
|
231 |
+
else:
|
232 |
+
# There should be a sigmoid version where we sample the route based on > 0.5
|
233 |
+
# but this doesn't really work mainly in batch inference
|
234 |
+
acc_route_choice = torch.cumsum(route > 0.5, dim=-1)
|
235 |
+
min_top_k = max(int(self.capacity_factor*seq_len), 2)
|
236 |
+
top_k = max(torch.max(acc_route_choice), min_top_k)
|
237 |
+
weights, selected_tokens = torch.topk(route, top_k, dim=1, sorted=False)
|
238 |
+
# reorder back to original position?
|
239 |
+
selected_tokens, index = torch.sort(selected_tokens, dim=1)
|
240 |
+
weights = torch.gather(weights, dim=1, index=index)
|
241 |
+
indices_expanded = selected_tokens.expand(-1, -1, self.hidden_size)
|
242 |
+
sub_hidden_states = torch.gather(hidden_states, 1, indices_expanded)
|
243 |
+
sub_position_ids = position_ids[: , :top_k]
|
244 |
+
if len(attention_mask.shape) == 4:
|
245 |
+
sub_attention_mask = attention_mask[:, :, :top_k,:top_k]
|
246 |
+
else:
|
247 |
+
sub_attention_mask = attention_mask[:, :top_k]
|
248 |
+
|
249 |
+
residual = sub_hidden_states
|
250 |
+
|
251 |
+
sub_hidden_states, attn_weights, present_key_value = self.self_attn(
|
252 |
+
hidden_states=sub_hidden_states,
|
253 |
+
attention_mask=sub_attention_mask,
|
254 |
+
position_ids=sub_position_ids,
|
255 |
+
past_key_value=past_key_value,
|
256 |
+
output_attentions=output_attentions,
|
257 |
+
use_cache=use_cache,
|
258 |
+
**kwargs,
|
259 |
+
)
|
260 |
+
if not self.training:
|
261 |
+
print(int(top_k), seq_len, self.layer_idx)
|
262 |
+
print(selected_tokens.flatten())
|
263 |
+
print(_old_router.flatten())
|
264 |
+
print(route.flatten())
|
265 |
+
|
266 |
+
sub_hidden_states = residual + sub_hidden_states
|
267 |
+
sub_residual = sub_hidden_states
|
268 |
+
# MLP
|
269 |
+
sub_hidden_states = self.post_attention_layernorm(sub_hidden_states)
|
270 |
+
sub_hidden_states = self.mlp(sub_hidden_states)
|
271 |
+
sub_hidden_states = sub_residual + sub_hidden_states
|
272 |
+
|
273 |
+
hidden_states = torch.scatter(
|
274 |
+
initial_residual,
|
275 |
+
dim=1,
|
276 |
+
index=indices_expanded,
|
277 |
+
src=sub_hidden_states * weights,
|
278 |
+
)
|
279 |
+
else:
|
280 |
+
residual = initial_residual
|
281 |
+
hidden_states = self.input_layernorm(hidden_states)
|
282 |
+
|
283 |
+
# Self Attention
|
284 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
285 |
+
hidden_states=hidden_states,
|
286 |
+
attention_mask=attention_mask,
|
287 |
+
position_ids=position_ids,
|
288 |
+
past_key_value=past_key_value,
|
289 |
+
output_attentions=output_attentions,
|
290 |
+
use_cache=use_cache,
|
291 |
+
**kwargs,
|
292 |
+
)
|
293 |
+
hidden_states = residual + hidden_states
|
294 |
+
|
295 |
+
# Fully Connected
|
296 |
+
residual = hidden_states
|
297 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
298 |
+
hidden_states = self.mlp(hidden_states)
|
299 |
+
hidden_states = residual + hidden_states
|
300 |
+
|
301 |
+
# this section must be modified during inference, otherwise no speedup
|
302 |
+
outputs = (hidden_states,)
|
303 |
+
|
304 |
+
if output_attentions:
|
305 |
+
outputs += (self_attn_weights,)
|
306 |
+
|
307 |
+
if use_cache:
|
308 |
+
outputs += (present_key_value,)
|
309 |
+
|
310 |
+
if self.dynamic_skip:
|
311 |
+
outputs += (torch.concat([route, mlp_router_logits], dim=-1), )
|
312 |
+
|
313 |
+
return outputs
|
314 |
+
|
315 |
+
def load_balancing_loss_func(
|
316 |
+
gate_logits: torch.Tensor, num_experts: torch.Tensor = 40, capacity_load=0.125, attention_mask: Optional[torch.Tensor] = None
|
317 |
+
) -> float:
|
318 |
+
r"""
|
319 |
+
Computes auxiliary load balancing loss as in Layer wise mode - implemented in Pytorch.
|
320 |
+
|
321 |
+
The original paper of mixture of depth didn't specify beyond one word : use aux loss
|
322 |
+
|
323 |
+
I would assume its from this:
|
324 |
+
|
325 |
+
Modified from Switch Transformer (https://arxiv.org/abs/2101.03961), I mean mixtral model.
|
326 |
+
This function implements the loss function presented in equations (4) - (6) of the paper.
|
327 |
+
It aims at penalizing cases where the routing between experts is too unbalanced.
|
328 |
+
|
329 |
+
Args:
|
330 |
+
gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
|
331 |
+
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
332 |
+
shape [batch_size X sequence_length, num_experts].
|
333 |
+
attention_mask (`torch.Tensor`, None):
|
334 |
+
The attention_mask used in forward function
|
335 |
+
shape [batch_size X sequence_length] if not None.
|
336 |
+
num_experts (`int`):
|
337 |
+
Number of layers
|
338 |
+
top_k (`int`):
|
339 |
+
Number of experts (capacility load * num_experts)
|
340 |
+
|
341 |
+
Returns:
|
342 |
+
The auxiliary loss.
|
343 |
+
"""
|
344 |
+
if gate_logits is None or not isinstance(gate_logits, tuple):
|
345 |
+
return 0
|
346 |
+
|
347 |
+
if isinstance(gate_logits, tuple):
|
348 |
+
compute_device = gate_logits[0].device
|
349 |
+
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=-1)
|
350 |
+
batch_size, sequence_length, num_hidden_layers = concatenated_gate_logits.shape
|
351 |
+
top_k = int(capacity_load*sequence_length)
|
352 |
+
|
353 |
+
# bs x seq_length x layers
|
354 |
+
routing_weights = torch.nn.functional.sigmoid(concatenated_gate_logits)
|
355 |
+
# bs x layers x seq_length
|
356 |
+
routing_weights = routing_weights.permute(0, 2, 1)
|
357 |
+
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
|
358 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, sequence_length)
|
359 |
+
expert_mask = expert_mask.reshape(-1, top_k, sequence_length)
|
360 |
+
# bs x num_layers x top_k x sequence length
|
361 |
+
if attention_mask is None:
|
362 |
+
# Compute the percentage of tokens routed to each experts
|
363 |
+
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
|
364 |
+
|
365 |
+
# Compute the average probability of routing to these experts
|
366 |
+
router_prob_per_expert = torch.mean(routing_weights, dim=0)
|
367 |
+
else:
|
368 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
369 |
+
expert_attention_mask = (
|
370 |
+
attention_mask[:, :, None, None]
|
371 |
+
.expand((batch_size, sequence_length, top_k, num_experts))
|
372 |
+
.permute(0, 3, 2, 1)
|
373 |
+
.reshape(-1, top_k, sequence_length)
|
374 |
+
.to(compute_device)
|
375 |
+
)
|
376 |
+
|
377 |
+
# Compute the percentage of tokens routed to each position id
|
378 |
+
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
|
379 |
+
expert_attention_mask, dim=0
|
380 |
+
)
|
381 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
382 |
+
router_per_expert_attention_mask = (
|
383 |
+
attention_mask[:, :, None]
|
384 |
+
.expand((batch_size, sequence_length, num_experts))
|
385 |
+
.reshape(-1, sequence_length)
|
386 |
+
.to(compute_device)
|
387 |
+
)
|
388 |
+
# Compute the average probability of routing to these experts
|
389 |
+
router_prob_per_expert = torch.sum(routing_weights.reshape(-1, sequence_length) * router_per_expert_attention_mask, dim=0) / torch.sum(
|
390 |
+
router_per_expert_attention_mask, dim=0
|
391 |
+
)
|
392 |
+
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
|
393 |
+
return overall_loss
|
394 |
+
|
395 |
+
|
396 |
+
|
397 |
+
class LlamaMoDBalanceAux(nn.Module):
|
398 |
+
# implement the prediction inside this instead to make sure weights are transferable
|
399 |
+
# Implement method 1
|
400 |
+
|
401 |
+
def __init__(self, config: LlamaMoDConfig, layer_idx: int):
|
402 |
+
super().__init__()
|
403 |
+
self.hidden_size = config.hidden_size
|
404 |
+
self.layer_idx = layer_idx
|
405 |
+
self.capacity_factor = config.capacity_load
|
406 |
+
self.dynamic_skip = config.setup_layer_mod[layer_idx]
|
407 |
+
if self.dynamic_skip:
|
408 |
+
self.mod_router = nn.Linear(self.hidden_size, 1, bias=True)
|
409 |
+
|
410 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
411 |
+
|
412 |
+
self.mlp = LlamaMLP(config)
|
413 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
414 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
415 |
+
|
416 |
+
def forward(
|
417 |
+
self,
|
418 |
+
hidden_states: torch.Tensor,
|
419 |
+
attention_mask: Optional[torch.Tensor] = None,
|
420 |
+
position_ids: Optional[torch.LongTensor] = None,
|
421 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
422 |
+
output_attentions: Optional[bool] = False,
|
423 |
+
use_cache: Optional[bool] = False,
|
424 |
+
cache_position: Optional[torch.LongTensor] = None,
|
425 |
+
**kwargs,
|
426 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
427 |
+
"""
|
428 |
+
Args:
|
429 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
430 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
431 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
432 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
433 |
+
output_attentions (`bool`, *optional*):
|
434 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
435 |
+
returned tensors for more detail.
|
436 |
+
use_cache (`bool`, *optional*):
|
437 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
438 |
+
(see `past_key_values`).
|
439 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
440 |
+
"""
|
441 |
+
if "padding_mask" in kwargs:
|
442 |
+
warnings.warn(
|
443 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
444 |
+
)
|
445 |
+
|
446 |
+
initial_residual = hidden_states
|
447 |
+
if self.dynamic_skip:
|
448 |
+
residual = hidden_states
|
449 |
+
seq_len = hidden_states.shape[1]
|
450 |
+
route = torch.sigmoid(self.mod_router(hidden_states))
|
451 |
+
|
452 |
+
if not self.training and (hidden_states.shape[1] == 1 and hidden_states.shape[0] == 1):
|
453 |
+
# TODO: fix this broke when batch is > 1
|
454 |
+
# single inference mode
|
455 |
+
if route[-1] > 0.5:
|
456 |
+
hidden_states = self.input_layernorm(hidden_states)
|
457 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
458 |
+
hidden_states=hidden_states,
|
459 |
+
attention_mask=attention_mask,
|
460 |
+
position_ids=position_ids,
|
461 |
+
past_key_value=past_key_value,
|
462 |
+
output_attentions=output_attentions,
|
463 |
+
use_cache=use_cache,
|
464 |
+
**kwargs,
|
465 |
+
)
|
466 |
+
hidden_states = residual + hidden_states
|
467 |
+
# Fully Connected
|
468 |
+
residual = hidden_states
|
469 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
470 |
+
hidden_states = self.mlp(hidden_states)
|
471 |
+
hidden_states = residual + hidden_states
|
472 |
+
else:
|
473 |
+
hidden_states = initial_residual
|
474 |
+
self_attn_weights = None
|
475 |
+
present_key_value = None
|
476 |
+
|
477 |
+
else:
|
478 |
+
acc_route_choice = torch.cumsum(route > 0.5, dim=1)
|
479 |
+
min_top_k = max(int(self.capacity_factor*seq_len), 2)
|
480 |
+
top_k = max(torch.max(acc_route_choice), min_top_k)
|
481 |
+
# with open('experiments_bias_0.1_aux_0.001.jsonl', 'a') as fout:
|
482 |
+
# fout.write(json.dumps({'idx': self.layer_idx, 'top_k': int(top_k), 'seq_len': seq_len})+'\n')
|
483 |
+
weights, selected_tokens = torch.topk(route, top_k, dim=1, sorted=False)
|
484 |
+
# reorder back to original position?
|
485 |
+
selected_tokens, index = torch.sort(selected_tokens, dim=1)
|
486 |
+
if not self.training:
|
487 |
+
print(int(top_k), seq_len, self.layer_idx)
|
488 |
+
print(selected_tokens.flatten())
|
489 |
+
|
490 |
+
weights = torch.gather(weights, dim=1, index=index)
|
491 |
+
indices_expanded = selected_tokens.expand(-1, -1, self.hidden_size)
|
492 |
+
sub_hidden_states = torch.gather(hidden_states, 1, indices_expanded)
|
493 |
+
sub_position_ids = position_ids[: , :top_k]
|
494 |
+
if len(attention_mask.shape) == 4:
|
495 |
+
sub_attention_mask = attention_mask[:, :, :top_k,:top_k]
|
496 |
+
else:
|
497 |
+
sub_attention_mask = attention_mask[:, :top_k]
|
498 |
+
|
499 |
+
|
500 |
+
residual = sub_hidden_states
|
501 |
+
sub_hidden_states = self.input_layernorm(sub_hidden_states)
|
502 |
+
sub_hidden_states, attn_weights, present_key_value = self.self_attn(
|
503 |
+
hidden_states=sub_hidden_states,
|
504 |
+
attention_mask=sub_attention_mask,
|
505 |
+
position_ids=sub_position_ids,
|
506 |
+
past_key_value=past_key_value,
|
507 |
+
output_attentions=output_attentions,
|
508 |
+
use_cache=use_cache,
|
509 |
+
**kwargs,
|
510 |
+
)
|
511 |
+
|
512 |
+
sub_hidden_states = residual + sub_hidden_states
|
513 |
+
sub_residual = sub_hidden_states
|
514 |
+
# MLP
|
515 |
+
sub_hidden_states = self.post_attention_layernorm(sub_hidden_states)
|
516 |
+
sub_hidden_states = self.mlp(sub_hidden_states)
|
517 |
+
sub_hidden_states = sub_residual + sub_hidden_states
|
518 |
+
hidden_states = sub_hidden_states
|
519 |
+
hidden_states = torch.scatter(
|
520 |
+
initial_residual,
|
521 |
+
dim=1,
|
522 |
+
index=indices_expanded,
|
523 |
+
src=sub_hidden_states,
|
524 |
+
)
|
525 |
+
else:
|
526 |
+
residual = initial_residual
|
527 |
+
hidden_states = self.input_layernorm(hidden_states)
|
528 |
+
|
529 |
+
# Self Attention
|
530 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
531 |
+
hidden_states=hidden_states,
|
532 |
+
attention_mask=attention_mask,
|
533 |
+
position_ids=position_ids,
|
534 |
+
past_key_value=past_key_value,
|
535 |
+
output_attentions=output_attentions,
|
536 |
+
use_cache=use_cache,
|
537 |
+
**kwargs,
|
538 |
+
)
|
539 |
+
hidden_states = residual + hidden_states
|
540 |
+
|
541 |
+
# Fully Connected
|
542 |
+
residual = hidden_states
|
543 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
544 |
+
hidden_states = self.mlp(hidden_states)
|
545 |
+
hidden_states = residual + hidden_states
|
546 |
+
|
547 |
+
# this section must be modified during inference, otherwise no speedup
|
548 |
+
outputs = (hidden_states,)
|
549 |
+
|
550 |
+
if output_attentions:
|
551 |
+
outputs += (self_attn_weights,)
|
552 |
+
|
553 |
+
if use_cache:
|
554 |
+
outputs += (present_key_value,)
|
555 |
+
|
556 |
+
if self.dynamic_skip:
|
557 |
+
outputs += (route, )
|
558 |
+
|
559 |
+
return outputs
|
560 |
+
|
561 |
+
|
562 |
+
class LlamaPreTrainedModel(PreTrainedModel):
|
563 |
+
config_class = LlamaMoDConfig
|
564 |
+
base_model_prefix = "model"
|
565 |
+
supports_gradient_checkpointing = True
|
566 |
+
_no_split_modules = ["LlamaDecoderLayer"]
|
567 |
+
_skip_keys_device_placement = ["past_key_values"]
|
568 |
+
_supports_flash_attn_2 = True
|
569 |
+
_supports_sdpa = True
|
570 |
+
_supports_cache_class = True
|
571 |
+
|
572 |
+
def _init_weights(self, module):
|
573 |
+
std = self.config.initializer_range
|
574 |
+
if isinstance(module, nn.Linear):
|
575 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
576 |
+
if module.bias is not None:
|
577 |
+
module.bias.data.zero_()
|
578 |
+
elif isinstance(module, nn.Embedding):
|
579 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
580 |
+
if module.padding_idx is not None:
|
581 |
+
module.weight.data[module.padding_idx].zero_()
|
582 |
+
|
583 |
+
def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
|
584 |
+
if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
|
585 |
+
raise ValueError(
|
586 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
587 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
588 |
+
)
|
589 |
+
|
590 |
+
for layer in self.model.layers:
|
591 |
+
device = layer.input_layernorm.weight.device
|
592 |
+
if hasattr(self.config, "_pre_quantization_dtype"):
|
593 |
+
dtype = self.config._pre_quantization_dtype
|
594 |
+
else:
|
595 |
+
dtype = layer.self_attn.o_proj.weight.dtype
|
596 |
+
layer.self_attn.past_key_value = cache_cls(
|
597 |
+
self.config, max_batch_size, max_cache_len, device=device, dtype=dtype
|
598 |
+
)
|
599 |
+
|
600 |
+
def _reset_cache(self):
|
601 |
+
for layer in self.model.layers:
|
602 |
+
layer.self_attn.past_key_value = None
|
603 |
+
|
604 |
+
|
605 |
+
LLAMA_DECODER_LAYER = {
|
606 |
+
'none': LlamaDecoderLayer,
|
607 |
+
'mod_1aux': LlamaMoDBalanceAux,
|
608 |
+
'mod_dual': LlamaMoDDuaRouter
|
609 |
+
}
|
610 |
+
|
611 |
+
AUX_LOSS = {
|
612 |
+
'mod_1aux': load_balancing_loss_func,
|
613 |
+
'mod_dual': dual_router_aux_loss
|
614 |
+
}
|
615 |
+
|
616 |
+
class LlamaMoDModel(LlamaPreTrainedModel):
|
617 |
+
"""
|
618 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
|
619 |
+
|
620 |
+
Args:
|
621 |
+
config: LlamaMoDConfig
|
622 |
+
"""
|
623 |
+
|
624 |
+
def __init__(self, config: LlamaMoDConfig):
|
625 |
+
super().__init__(config)
|
626 |
+
self.padding_idx = config.pad_token_id
|
627 |
+
self.vocab_size = config.vocab_size
|
628 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
629 |
+
self.has_router = config.mod_method != 'none'
|
630 |
+
self.layers = nn.ModuleList(
|
631 |
+
[LLAMA_DECODER_LAYER[config.mod_method](config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
632 |
+
)
|
633 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
634 |
+
self.gradient_checkpointing = False
|
635 |
+
|
636 |
+
# Initialize weights and apply final processing
|
637 |
+
self.post_init()
|
638 |
+
|
639 |
+
def get_input_embeddings(self):
|
640 |
+
return self.embed_tokens
|
641 |
+
|
642 |
+
def set_input_embeddings(self, value):
|
643 |
+
self.embed_tokens = value
|
644 |
+
|
645 |
+
def forward(
|
646 |
+
self,
|
647 |
+
input_ids: torch.LongTensor = None,
|
648 |
+
attention_mask: Optional[torch.Tensor] = None,
|
649 |
+
position_ids: Optional[torch.LongTensor] = None,
|
650 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
651 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
652 |
+
use_cache: Optional[bool] = None,
|
653 |
+
output_attentions: Optional[bool] = None,
|
654 |
+
output_hidden_states: Optional[bool] = None,
|
655 |
+
return_dict: Optional[bool] = None,
|
656 |
+
cache_position: Optional[torch.LongTensor] = None,
|
657 |
+
output_router_logits: Optional[bool] = None,
|
658 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
659 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
660 |
+
output_hidden_states = (
|
661 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
662 |
+
)
|
663 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
664 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
665 |
+
|
666 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
667 |
+
raise ValueError(
|
668 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
669 |
+
)
|
670 |
+
|
671 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
672 |
+
logger.warning_once(
|
673 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
674 |
+
)
|
675 |
+
use_cache = False
|
676 |
+
|
677 |
+
if inputs_embeds is None:
|
678 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
679 |
+
|
680 |
+
past_seen_tokens = 0
|
681 |
+
if use_cache: # kept for BC (cache positions)
|
682 |
+
if not isinstance(past_key_values, StaticCache):
|
683 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
684 |
+
past_seen_tokens = past_key_values.get_seq_length()
|
685 |
+
|
686 |
+
if cache_position is None:
|
687 |
+
if isinstance(past_key_values, StaticCache):
|
688 |
+
raise ValueError("cache_position is a required argument when using StaticCache.")
|
689 |
+
cache_position = torch.arange(
|
690 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
691 |
+
)
|
692 |
+
|
693 |
+
if position_ids is None:
|
694 |
+
position_ids = cache_position.unsqueeze(0)
|
695 |
+
|
696 |
+
causal_mask = self._update_causal_mask(
|
697 |
+
attention_mask, inputs_embeds, cache_position, past_seen_tokens + inputs_embeds.shape[1]
|
698 |
+
)
|
699 |
+
|
700 |
+
# embed positions
|
701 |
+
hidden_states = inputs_embeds
|
702 |
+
|
703 |
+
# decoder layers
|
704 |
+
all_hidden_states = () if output_hidden_states else None
|
705 |
+
all_self_attns = () if output_attentions else None
|
706 |
+
all_router_logits = () if output_router_logits else None
|
707 |
+
next_decoder_cache = None
|
708 |
+
|
709 |
+
for decoder_layer in self.layers:
|
710 |
+
if output_hidden_states:
|
711 |
+
all_hidden_states += (hidden_states,)
|
712 |
+
|
713 |
+
if self.gradient_checkpointing and self.training:
|
714 |
+
layer_outputs = self._gradient_checkpointing_func(
|
715 |
+
decoder_layer.__call__,
|
716 |
+
hidden_states,
|
717 |
+
causal_mask,
|
718 |
+
position_ids,
|
719 |
+
past_key_values,
|
720 |
+
output_attentions,
|
721 |
+
use_cache,
|
722 |
+
cache_position,
|
723 |
+
)
|
724 |
+
else:
|
725 |
+
layer_outputs = decoder_layer(
|
726 |
+
hidden_states,
|
727 |
+
attention_mask=causal_mask,
|
728 |
+
position_ids=position_ids,
|
729 |
+
past_key_value=past_key_values,
|
730 |
+
output_attentions=output_attentions,
|
731 |
+
use_cache=use_cache,
|
732 |
+
cache_position=cache_position,
|
733 |
+
)
|
734 |
+
|
735 |
+
hidden_states = layer_outputs[0]
|
736 |
+
|
737 |
+
if use_cache:
|
738 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
739 |
+
|
740 |
+
if output_attentions:
|
741 |
+
all_self_attns += (layer_outputs[1],)
|
742 |
+
if self.has_router and decoder_layer.dynamic_skip and output_router_logits:
|
743 |
+
all_router_logits += (layer_outputs[-1],)
|
744 |
+
|
745 |
+
hidden_states = self.norm(hidden_states)
|
746 |
+
|
747 |
+
# add hidden states from the last decoder layer
|
748 |
+
if output_hidden_states:
|
749 |
+
all_hidden_states += (hidden_states,)
|
750 |
+
|
751 |
+
next_cache = None
|
752 |
+
if use_cache:
|
753 |
+
next_cache = (
|
754 |
+
next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
|
755 |
+
)
|
756 |
+
if not return_dict:
|
757 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
758 |
+
return MoeModelOutputWithPast(
|
759 |
+
last_hidden_state=hidden_states,
|
760 |
+
past_key_values=next_cache,
|
761 |
+
hidden_states=all_hidden_states,
|
762 |
+
attentions=all_self_attns,
|
763 |
+
router_logits=all_router_logits
|
764 |
+
)
|
765 |
+
|
766 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
|
767 |
+
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
|
768 |
+
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
|
769 |
+
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
|
770 |
+
def _update_causal_mask(self, attention_mask, input_tensor, cache_position, current_length):
|
771 |
+
if self.config._attn_implementation == "flash_attention_2":
|
772 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
773 |
+
return attention_mask
|
774 |
+
return None
|
775 |
+
|
776 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
777 |
+
min_dtype = torch.finfo(dtype).min
|
778 |
+
sequence_length = input_tensor.shape[1]
|
779 |
+
if hasattr(getattr(self.layers[0], "self_attn", {}), "past_key_value"): # static cache
|
780 |
+
target_length = self.config.max_position_embeddings
|
781 |
+
else: # dynamic cache
|
782 |
+
target_length = (
|
783 |
+
attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else current_length + 1
|
784 |
+
)
|
785 |
+
|
786 |
+
causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
|
787 |
+
if sequence_length != 1:
|
788 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
789 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
790 |
+
causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
|
791 |
+
if attention_mask is not None:
|
792 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
793 |
+
if attention_mask.dim() == 2:
|
794 |
+
mask_length = attention_mask.shape[-1]
|
795 |
+
padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
|
796 |
+
causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
|
797 |
+
elif attention_mask.dim() == 4:
|
798 |
+
# backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
|
799 |
+
# cache. In that case, the 4D attention mask attends to the newest tokens only.
|
800 |
+
if attention_mask.shape[-2] < cache_position[0] + sequence_length:
|
801 |
+
offset = cache_position[0]
|
802 |
+
else:
|
803 |
+
offset = 0
|
804 |
+
mask_shape = attention_mask.shape
|
805 |
+
mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
|
806 |
+
causal_mask[
|
807 |
+
: mask_shape[0], : mask_shape[1], offset : mask_shape[2] + offset, : mask_shape[3]
|
808 |
+
] = mask_slice
|
809 |
+
|
810 |
+
if (
|
811 |
+
self.config._attn_implementation == "sdpa"
|
812 |
+
and attention_mask is not None
|
813 |
+
and attention_mask.device.type == "cuda"
|
814 |
+
):
|
815 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
816 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
817 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
818 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
819 |
+
|
820 |
+
return causal_mask
|
821 |
+
|
822 |
+
|
823 |
+
class LlamaMoDForCausalLM(LlamaPreTrainedModel):
|
824 |
+
_tied_weights_keys = ["lm_head.weight"]
|
825 |
+
|
826 |
+
def __init__(self, config):
|
827 |
+
super().__init__(config)
|
828 |
+
self.model = LlamaMoDModel(config)
|
829 |
+
self.vocab_size = config.vocab_size
|
830 |
+
self.route_method = config.mod_method
|
831 |
+
self.router_aux_loss_coef = config.router_aux_loss_coef
|
832 |
+
if config.mod_method != 'none':
|
833 |
+
self.num_experts = sum(config.setup_layer_mod)
|
834 |
+
self.capacity_load = config.capacity_load
|
835 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
836 |
+
|
837 |
+
# Initialize weights and apply final processing
|
838 |
+
self.post_init()
|
839 |
+
|
840 |
+
def get_input_embeddings(self):
|
841 |
+
return self.model.embed_tokens
|
842 |
+
|
843 |
+
def set_input_embeddings(self, value):
|
844 |
+
self.model.embed_tokens = value
|
845 |
+
|
846 |
+
def get_output_embeddings(self):
|
847 |
+
return self.lm_head
|
848 |
+
|
849 |
+
def set_output_embeddings(self, new_embeddings):
|
850 |
+
self.lm_head = new_embeddings
|
851 |
+
|
852 |
+
def set_decoder(self, decoder):
|
853 |
+
self.model = decoder
|
854 |
+
|
855 |
+
def get_decoder(self):
|
856 |
+
return self.model
|
857 |
+
|
858 |
+
def forward(
|
859 |
+
self,
|
860 |
+
input_ids: torch.LongTensor = None,
|
861 |
+
attention_mask: Optional[torch.Tensor] = None,
|
862 |
+
position_ids: Optional[torch.LongTensor] = None,
|
863 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
864 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
865 |
+
labels: Optional[torch.LongTensor] = None,
|
866 |
+
use_cache: Optional[bool] = None,
|
867 |
+
output_attentions: Optional[bool] = None,
|
868 |
+
output_hidden_states: Optional[bool] = None,
|
869 |
+
return_dict: Optional[bool] = None,
|
870 |
+
cache_position: Optional[torch.LongTensor] = None,
|
871 |
+
output_router_logits: Optional[bool] = None,
|
872 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
873 |
+
r"""
|
874 |
+
Args:
|
875 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
876 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
877 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
878 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
879 |
+
|
880 |
+
Returns:
|
881 |
+
|
882 |
+
Example:
|
883 |
+
|
884 |
+
```python
|
885 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
886 |
+
|
887 |
+
>>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
|
888 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
|
889 |
+
|
890 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
891 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
892 |
+
|
893 |
+
>>> # Generate
|
894 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
895 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
896 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
897 |
+
```"""
|
898 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
899 |
+
output_hidden_states = (
|
900 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
901 |
+
)
|
902 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
903 |
+
|
904 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
905 |
+
outputs = self.model(
|
906 |
+
input_ids=input_ids,
|
907 |
+
attention_mask=attention_mask,
|
908 |
+
position_ids=position_ids,
|
909 |
+
past_key_values=past_key_values,
|
910 |
+
inputs_embeds=inputs_embeds,
|
911 |
+
use_cache=use_cache,
|
912 |
+
output_attentions=output_attentions,
|
913 |
+
output_hidden_states=output_hidden_states,
|
914 |
+
return_dict=return_dict,
|
915 |
+
cache_position=cache_position,
|
916 |
+
output_router_logits=output_router_logits
|
917 |
+
)
|
918 |
+
|
919 |
+
hidden_states = outputs[0]
|
920 |
+
if self.config.pretraining_tp > 1:
|
921 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
922 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
923 |
+
logits = torch.cat(logits, dim=-1)
|
924 |
+
else:
|
925 |
+
logits = self.lm_head(hidden_states)
|
926 |
+
logits = logits.float()
|
927 |
+
|
928 |
+
loss = None
|
929 |
+
if labels is not None:
|
930 |
+
# Shift so that tokens < n predict n
|
931 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
932 |
+
shift_labels = labels[..., 1:].contiguous()
|
933 |
+
# Flatten the tokens
|
934 |
+
loss_fct = CrossEntropyLoss()
|
935 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
936 |
+
shift_labels = shift_labels.view(-1)
|
937 |
+
# Enable model parallelism
|
938 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
939 |
+
loss = loss_fct(shift_logits, shift_labels)
|
940 |
+
|
941 |
+
if output_router_logits:
|
942 |
+
aux_loss = AUX_LOSS[self.route_method](
|
943 |
+
outputs.router_logits if return_dict else outputs[-1],
|
944 |
+
self.num_experts,
|
945 |
+
self.capacity_load,
|
946 |
+
attention_mask,
|
947 |
+
)
|
948 |
+
if labels is not None:
|
949 |
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device)
|
950 |
+
|
951 |
+
|
952 |
+
if not return_dict:
|
953 |
+
output = (logits,) + outputs[1:]
|
954 |
+
return (loss,) + output if loss is not None else output
|
955 |
+
|
956 |
+
return MoeCausalLMOutputWithPast(
|
957 |
+
loss=loss,
|
958 |
+
logits=logits,
|
959 |
+
past_key_values=outputs.past_key_values,
|
960 |
+
hidden_states=outputs.hidden_states,
|
961 |
+
attentions=outputs.attentions,
|
962 |
+
)
|
963 |
+
|
964 |
+
def prepare_inputs_for_generation(
|
965 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
|
966 |
+
):
|
967 |
+
# With static cache, the `past_key_values` is None
|
968 |
+
# TODO joao: standardize interface for the different Cache classes and remove of this if
|
969 |
+
has_static_cache = False
|
970 |
+
if past_key_values is None:
|
971 |
+
past_key_values = getattr(getattr(self.model.layers[0], "self_attn", {}), "past_key_value", None)
|
972 |
+
has_static_cache = past_key_values is not None
|
973 |
+
|
974 |
+
past_length = 0
|
975 |
+
if past_key_values is not None:
|
976 |
+
if isinstance(past_key_values, Cache):
|
977 |
+
past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
|
978 |
+
max_cache_length = (
|
979 |
+
torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
|
980 |
+
if past_key_values.get_max_length() is not None
|
981 |
+
else None
|
982 |
+
)
|
983 |
+
cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
|
984 |
+
# TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
|
985 |
+
else:
|
986 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
987 |
+
max_cache_length = None
|
988 |
+
|
989 |
+
# Keep only the unprocessed tokens:
|
990 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
991 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
992 |
+
# input)
|
993 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
994 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
995 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
996 |
+
# input_ids based on the past_length.
|
997 |
+
elif past_length < input_ids.shape[1]:
|
998 |
+
input_ids = input_ids[:, past_length:]
|
999 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1000 |
+
|
1001 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1002 |
+
if (
|
1003 |
+
max_cache_length is not None
|
1004 |
+
and attention_mask is not None
|
1005 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1006 |
+
):
|
1007 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1008 |
+
|
1009 |
+
position_ids = kwargs.get("position_ids", None)
|
1010 |
+
if attention_mask is not None and position_ids is None:
|
1011 |
+
# create position_ids on the fly for batch generation
|
1012 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1013 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1014 |
+
if past_key_values:
|
1015 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1016 |
+
|
1017 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1018 |
+
if inputs_embeds is not None and past_key_values is None:
|
1019 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1020 |
+
else:
|
1021 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
1022 |
+
# recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
|
1023 |
+
# TODO: use `next_tokens` directly instead.
|
1024 |
+
model_inputs = {"input_ids": input_ids.contiguous()}
|
1025 |
+
|
1026 |
+
input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
|
1027 |
+
if cache_position is None:
|
1028 |
+
cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
|
1029 |
+
else:
|
1030 |
+
cache_position = cache_position[-input_length:]
|
1031 |
+
|
1032 |
+
if has_static_cache:
|
1033 |
+
past_key_values = None
|
1034 |
+
|
1035 |
+
model_inputs.update(
|
1036 |
+
{
|
1037 |
+
"position_ids": position_ids,
|
1038 |
+
"cache_position": cache_position,
|
1039 |
+
"past_key_values": past_key_values,
|
1040 |
+
"use_cache": kwargs.get("use_cache"),
|
1041 |
+
"attention_mask": attention_mask,
|
1042 |
+
}
|
1043 |
+
)
|
1044 |
+
return model_inputs
|
1045 |
+
|
1046 |
+
@staticmethod
|
1047 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1048 |
+
reordered_past = ()
|
1049 |
+
for layer_past in past_key_values:
|
1050 |
+
reordered_past += (
|
1051 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1052 |
+
)
|
1053 |
+
return reordered_past
|
1054 |
+
|
1055 |
+
|
1056 |
+
|
1057 |
+
class LlamaForSequenceClassification(LlamaPreTrainedModel):
|
1058 |
+
def __init__(self, config):
|
1059 |
+
super().__init__(config)
|
1060 |
+
self.num_labels = config.num_labels
|
1061 |
+
self.model = LlamaModel(config)
|
1062 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1063 |
+
|
1064 |
+
# Initialize weights and apply final processing
|
1065 |
+
self.post_init()
|
1066 |
+
|
1067 |
+
def get_input_embeddings(self):
|
1068 |
+
return self.model.embed_tokens
|
1069 |
+
|
1070 |
+
def set_input_embeddings(self, value):
|
1071 |
+
self.model.embed_tokens = value
|
1072 |
+
|
1073 |
+
def forward(
|
1074 |
+
self,
|
1075 |
+
input_ids: torch.LongTensor = None,
|
1076 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1077 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1078 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1079 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1080 |
+
labels: Optional[torch.LongTensor] = None,
|
1081 |
+
use_cache: Optional[bool] = None,
|
1082 |
+
output_attentions: Optional[bool] = None,
|
1083 |
+
output_hidden_states: Optional[bool] = None,
|
1084 |
+
return_dict: Optional[bool] = None,
|
1085 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1086 |
+
r"""
|
1087 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1088 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1089 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1090 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1091 |
+
"""
|
1092 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1093 |
+
|
1094 |
+
transformer_outputs = self.model(
|
1095 |
+
input_ids,
|
1096 |
+
attention_mask=attention_mask,
|
1097 |
+
position_ids=position_ids,
|
1098 |
+
past_key_values=past_key_values,
|
1099 |
+
inputs_embeds=inputs_embeds,
|
1100 |
+
use_cache=use_cache,
|
1101 |
+
output_attentions=output_attentions,
|
1102 |
+
output_hidden_states=output_hidden_states,
|
1103 |
+
return_dict=return_dict,
|
1104 |
+
)
|
1105 |
+
hidden_states = transformer_outputs[0]
|
1106 |
+
logits = self.score(hidden_states)
|
1107 |
+
|
1108 |
+
if input_ids is not None:
|
1109 |
+
batch_size = input_ids.shape[0]
|
1110 |
+
else:
|
1111 |
+
batch_size = inputs_embeds.shape[0]
|
1112 |
+
|
1113 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1114 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1115 |
+
if self.config.pad_token_id is None:
|
1116 |
+
sequence_lengths = -1
|
1117 |
+
else:
|
1118 |
+
if input_ids is not None:
|
1119 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1120 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1121 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1122 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1123 |
+
else:
|
1124 |
+
sequence_lengths = -1
|
1125 |
+
|
1126 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1127 |
+
|
1128 |
+
loss = None
|
1129 |
+
if labels is not None:
|
1130 |
+
labels = labels.to(logits.device)
|
1131 |
+
if self.config.problem_type is None:
|
1132 |
+
if self.num_labels == 1:
|
1133 |
+
self.config.problem_type = "regression"
|
1134 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1135 |
+
self.config.problem_type = "single_label_classification"
|
1136 |
+
else:
|
1137 |
+
self.config.problem_type = "multi_label_classification"
|
1138 |
+
|
1139 |
+
if self.config.problem_type == "regression":
|
1140 |
+
loss_fct = MSELoss()
|
1141 |
+
if self.num_labels == 1:
|
1142 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1143 |
+
else:
|
1144 |
+
loss = loss_fct(pooled_logits, labels)
|
1145 |
+
elif self.config.problem_type == "single_label_classification":
|
1146 |
+
loss_fct = CrossEntropyLoss()
|
1147 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1148 |
+
elif self.config.problem_type == "multi_label_classification":
|
1149 |
+
loss_fct = BCEWithLogitsLoss()
|
1150 |
+
loss = loss_fct(pooled_logits, labels)
|
1151 |
+
if not return_dict:
|
1152 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1153 |
+
return ((loss,) + output) if loss is not None else output
|
1154 |
+
|
1155 |
+
return SequenceClassifierOutputWithPast(
|
1156 |
+
loss=loss,
|
1157 |
+
logits=pooled_logits,
|
1158 |
+
past_key_values=transformer_outputs.past_key_values,
|
1159 |
+
hidden_states=transformer_outputs.hidden_states,
|
1160 |
+
attentions=transformer_outputs.attentions,
|
1161 |
+
)
|
1162 |
+
|
1163 |
+
|
1164 |
+
class LlamaForQuestionAnswering(LlamaPreTrainedModel):
|
1165 |
+
base_model_prefix = "transformer"
|
1166 |
+
|
1167 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
|
1168 |
+
def __init__(self, config):
|
1169 |
+
super().__init__(config)
|
1170 |
+
self.transformer = LlamaModel(config)
|
1171 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1172 |
+
|
1173 |
+
# Initialize weights and apply final processing
|
1174 |
+
self.post_init()
|
1175 |
+
|
1176 |
+
def get_input_embeddings(self):
|
1177 |
+
return self.transformer.embed_tokens
|
1178 |
+
|
1179 |
+
def set_input_embeddings(self, value):
|
1180 |
+
self.transformer.embed_tokens = value
|
1181 |
+
|
1182 |
+
def forward(
|
1183 |
+
self,
|
1184 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1185 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1186 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1187 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1188 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1189 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1190 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1191 |
+
output_attentions: Optional[bool] = None,
|
1192 |
+
output_hidden_states: Optional[bool] = None,
|
1193 |
+
return_dict: Optional[bool] = None,
|
1194 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1195 |
+
r"""
|
1196 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1197 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1198 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1199 |
+
are not taken into account for computing the loss.
|
1200 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1201 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1202 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1203 |
+
are not taken into account for computing the loss.
|
1204 |
+
"""
|
1205 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1206 |
+
|
1207 |
+
outputs = self.transformer(
|
1208 |
+
input_ids,
|
1209 |
+
attention_mask=attention_mask,
|
1210 |
+
position_ids=position_ids,
|
1211 |
+
past_key_values=past_key_values,
|
1212 |
+
inputs_embeds=inputs_embeds,
|
1213 |
+
output_attentions=output_attentions,
|
1214 |
+
output_hidden_states=output_hidden_states,
|
1215 |
+
return_dict=return_dict,
|
1216 |
+
)
|
1217 |
+
|
1218 |
+
sequence_output = outputs[0]
|
1219 |
+
|
1220 |
+
logits = self.qa_outputs(sequence_output)
|
1221 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1222 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1223 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1224 |
+
|
1225 |
+
total_loss = None
|
1226 |
+
if start_positions is not None and end_positions is not None:
|
1227 |
+
# If we are on multi-GPU, split add a dimension
|
1228 |
+
if len(start_positions.size()) > 1:
|
1229 |
+
start_positions = start_positions.squeeze(-1).to(start_logits.device)
|
1230 |
+
if len(end_positions.size()) > 1:
|
1231 |
+
end_positions = end_positions.squeeze(-1).to(end_logits.device)
|
1232 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
1233 |
+
ignored_index = start_logits.size(1)
|
1234 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
1235 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
1236 |
+
|
1237 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
1238 |
+
start_loss = loss_fct(start_logits, start_positions)
|
1239 |
+
end_loss = loss_fct(end_logits, end_positions)
|
1240 |
+
total_loss = (start_loss + end_loss) / 2
|
1241 |
+
|
1242 |
+
if not return_dict:
|
1243 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1244 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1245 |
+
|
1246 |
+
return QuestionAnsweringModelOutput(
|
1247 |
+
loss=total_loss,
|
1248 |
+
start_logits=start_logits,
|
1249 |
+
end_logits=end_logits,
|
1250 |
+
hidden_states=outputs.hidden_states,
|
1251 |
+
attentions=outputs.attentions,
|
1252 |
+
)
|
special_tokens_map.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "</s>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"unk_token": {
|
24 |
+
"content": "<unk>",
|
25 |
+
"lstrip": false,
|
26 |
+
"normalized": false,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
}
|
30 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
|
3 |
+
size 499723
|
tokenizer_config.json
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": true,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"0": {
|
6 |
+
"content": "<unk>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"1": {
|
14 |
+
"content": "<s>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"2": {
|
22 |
+
"content": "</s>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
}
|
29 |
+
},
|
30 |
+
"bos_token": "<s>",
|
31 |
+
"chat_template": "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '<|user|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'system' %}\n{{ '<|system|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'assistant' %}\n{{ '<|assistant|>\n' + message['content'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}",
|
32 |
+
"clean_up_tokenization_spaces": false,
|
33 |
+
"eos_token": "</s>",
|
34 |
+
"legacy": false,
|
35 |
+
"model_max_length": 2048,
|
36 |
+
"pad_token": "</s>",
|
37 |
+
"padding_side": "right",
|
38 |
+
"sp_model_kwargs": {},
|
39 |
+
"tokenizer_class": "LlamaTokenizer",
|
40 |
+
"unk_token": "<unk>",
|
41 |
+
"use_default_system_prompt": false
|
42 |
+
}
|