Add files using upload-large-folder tool
Browse files- .gitattributes +5 -0
- Llama-2-13b-hf/config.json +27 -0
- Llama-2-13b-hf/model.safetensors +3 -0
- Llama-2-13b-hf_trirun/config.json +31 -0
- Llama-2-13b-hf_trirun/configuration_trilmlinear.py +220 -0
- Llama-2-13b-hf_trirun/model.safetensors +3 -0
- Llama-2-13b-hf_trirun/modeling_trilmlinear.py +1037 -0
- Llama-2-70b-hf/config.json +23 -0
- Llama-2-70b-hf/model.safetensors.aa +3 -0
- Llama-2-70b-hf/model.safetensors.ab +3 -0
- Llama-2-70b-hf/model.safetensors.ac +3 -0
- Llama-2-70b-hf_trirun/config.json +28 -0
- Llama-2-70b-hf_trirun/configuration_trilmlinear.py +220 -0
- Llama-2-70b-hf_trirun/model.safetensors +3 -0
- Llama-2-70b-hf_trirun/modeling_trilmlinear.py +1037 -0
- Llama-2-7b-hf/config.json +25 -0
- Llama-2-7b-hf/model.safetensors +3 -0
- Llama-2-7b-hf_trirun/config.json +30 -0
- Llama-2-7b-hf_trirun/configuration_trilmlinear.py +220 -0
- Llama-2-7b-hf_trirun/model.safetensors +3 -0
- Llama-2-7b-hf_trirun/modeling_trilmlinear.py +1037 -0
- Mistral-Large-Instruct-2407_trirun/config.json +32 -0
- Mistral-Large-Instruct-2407_trirun/configuration_trilmlinear.py +220 -0
- Mistral-Large-Instruct-2407_trirun/model.safetensors +3 -0
- Mistral-Large-Instruct-2407_trirun/modeling_trilmlinear.py +1037 -0
- TriLMs/TriLM_1.1B_Unpacked.safetensors +3 -0
- TriLMs/TriLM_1.1B_Unpacked_trirun.safetensors +3 -0
- TriLMs/TriLM_1.5B_Unpacked.safetensors +3 -0
- TriLMs/TriLM_1.5B_Unpacked_trirun.safetensors +3 -0
- TriLMs/TriLM_190M_Unpacked.safetensors +3 -0
- TriLMs/TriLM_190M_Unpacked_trirun.safetensors +3 -0
- TriLMs/TriLM_2.4B_Unpacked.safetensors +3 -0
- TriLMs/TriLM_2.4B_Unpacked_trirun.safetensors +3 -0
- TriLMs/TriLM_3.9B_Unpacked.safetensors +3 -0
- TriLMs/TriLM_3.9B_Unpacked_trirun.safetensors +3 -0
- TriLMs/TriLM_390M_Unpacked.safetensors +3 -0
- TriLMs/TriLM_390M_Unpacked_trirun.safetensors +3 -0
- TriLMs/TriLM_560M_Unpacked.safetensors +3 -0
- TriLMs/TriLM_560M_Unpacked_trirun.safetensors +3 -0
- TriLMs/TriLM_830M_Unpacked.safetensors +3 -0
- TriLMs/TriLM_830M_Unpacked_trirun.safetensors +3 -0
- TriLMs/TriLM_99M_Unpacked.safetensors +3 -0
- TriLMs/TriLM_99M_Unpacked_trirun.safetensors +3 -0
- Yi-34B/config.json +26 -0
- Yi-34B/model.safetensors.aa +3 -0
- Yi-34B/model.safetensors.ab +3 -0
- Yi-34B_trirun/config.json +31 -0
- Yi-34B_trirun/configuration_trilmlinear.py +220 -0
- Yi-34B_trirun/model.safetensors +3 -0
- Yi-34B_trirun/modeling_trilmlinear.py +1037 -0
.gitattributes
CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
Yi-34B/model.safetensors.aa filter=lfs diff=lfs merge=lfs -text
|
37 |
+
Yi-34B/model.safetensors.ab filter=lfs diff=lfs merge=lfs -text
|
38 |
+
Llama-2-70b-hf/model.safetensors.ab filter=lfs diff=lfs merge=lfs -text
|
39 |
+
Llama-2-70b-hf/model.safetensors.aa filter=lfs diff=lfs merge=lfs -text
|
40 |
+
Llama-2-70b-hf/model.safetensors.ac filter=lfs diff=lfs merge=lfs -text
|
Llama-2-13b-hf/config.json
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "meta-llama/Llama-2-13b-hf",
|
3 |
+
"architectures": [
|
4 |
+
"LlamaForCausalLM"
|
5 |
+
],
|
6 |
+
"bos_token_id": 1,
|
7 |
+
"eos_token_id": 2,
|
8 |
+
"hidden_act": "silu",
|
9 |
+
"hidden_size": 5120,
|
10 |
+
"initializer_range": 0.02,
|
11 |
+
"intermediate_size": 13824,
|
12 |
+
"max_position_embeddings": 4096,
|
13 |
+
"model_type": "llama",
|
14 |
+
"num_attention_heads": 40,
|
15 |
+
"num_hidden_layers": 40,
|
16 |
+
"num_key_value_heads": 40,
|
17 |
+
"pad_token_id": 0,
|
18 |
+
"pretraining_tp": 1,
|
19 |
+
"rms_norm_eps": 1e-05,
|
20 |
+
"rope_scaling": null,
|
21 |
+
"tie_word_embeddings": false,
|
22 |
+
"torch_dtype": "float16",
|
23 |
+
"transformers_version": "4.31.0.dev0",
|
24 |
+
"use_cache": true,
|
25 |
+
"vocab_size": 32000
|
26 |
+
}
|
27 |
+
|
Llama-2-13b-hf/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:43eb9b51d223f73caa66686db6b0f985661b1119fea816ae8c919a3336a43696
|
3 |
+
size 26031770968
|
Llama-2-13b-hf_trirun/config.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"TriLMLinearForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_trilmlinear.TriLMLinearConfig",
|
7 |
+
"AutoModel": "modeling_trilmlinear.TriLMLinearModel",
|
8 |
+
"AutoModelForCausalLM": "modeling_trilmlinear.TriLMLinearForCausalLM"
|
9 |
+
},
|
10 |
+
"bos_token_id": 1,
|
11 |
+
"eos_token_id": 2,
|
12 |
+
"hidden_act": "silu",
|
13 |
+
"hidden_size": 5120,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 13824,
|
16 |
+
"max_position_embeddings": 4096,
|
17 |
+
"model_type": "TriLMLinear",
|
18 |
+
"num_attention_heads": 40,
|
19 |
+
"num_hidden_layers": 40,
|
20 |
+
"num_key_value_heads": 40,
|
21 |
+
"pad_token_id": 0,
|
22 |
+
"pretraining_tp": 1,
|
23 |
+
"rms_norm_eps": 1e-05,
|
24 |
+
"rope_scaling": null,
|
25 |
+
"tie_word_embeddings": false,
|
26 |
+
"torch_dtype": "float16",
|
27 |
+
"transformers_version": "4.31.0.dev0",
|
28 |
+
"use_cache": true,
|
29 |
+
"vocab_size": 32000
|
30 |
+
}
|
31 |
+
|
Llama-2-13b-hf_trirun/configuration_trilmlinear.py
ADDED
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""TriLMLinear model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
24 |
+
|
25 |
+
|
26 |
+
class TriLMLinearConfig(PretrainedConfig):
|
27 |
+
r"""
|
28 |
+
This is the configuration class to store the configuration of a [`TriLMLinearModel`]. It is used to instantiate an LLaMA
|
29 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
30 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
31 |
+
|
32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
33 |
+
documentation from [`PretrainedConfig`] for more information.
|
34 |
+
|
35 |
+
|
36 |
+
Args:
|
37 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
38 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
39 |
+
`inputs_ids` passed when calling [`LlamaModel`]
|
40 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
41 |
+
Dimension of the hidden representations.
|
42 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
43 |
+
Dimension of the MLP representations.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
45 |
+
Number of hidden layers in the Transformer decoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
47 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
48 |
+
num_key_value_heads (`int`, *optional*):
|
49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
51 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
54 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
55 |
+
`num_attention_heads`.
|
56 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
57 |
+
The non-linear activation function (function or string) in the decoder.
|
58 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
59 |
+
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
60 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
64 |
+
The epsilon used by the rms normalization layers.
|
65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
67 |
+
relevant if `config.is_decoder=True`.
|
68 |
+
pad_token_id (`int`, *optional*):
|
69 |
+
Padding token id.
|
70 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
71 |
+
Beginning of stream token id.
|
72 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
73 |
+
End of stream token id.
|
74 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
75 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
76 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
|
77 |
+
understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
|
78 |
+
results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
|
79 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
80 |
+
Whether to tie weight embeddings
|
81 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
82 |
+
The base period of the RoPE embeddings.
|
83 |
+
rope_scaling (`Dict`, *optional*):
|
84 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
85 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
86 |
+
accordingly.
|
87 |
+
Expected contents:
|
88 |
+
`rope_type` (`str`):
|
89 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
90 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
91 |
+
`factor` (`float`, *optional*):
|
92 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
93 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
94 |
+
original maximum pre-trained length.
|
95 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
96 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
97 |
+
pretraining.
|
98 |
+
`attention_factor` (`float`, *optional*):
|
99 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
100 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
101 |
+
`factor` field to infer the suggested value.
|
102 |
+
`beta_fast` (`float`, *optional*):
|
103 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
104 |
+
ramp function. If unspecified, it defaults to 32.
|
105 |
+
`beta_slow` (`float`, *optional*):
|
106 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
107 |
+
ramp function. If unspecified, it defaults to 1.
|
108 |
+
`short_factor` (`List[float]`, *optional*):
|
109 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
110 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
111 |
+
size divided by the number of attention heads divided by 2
|
112 |
+
`long_factor` (`List[float]`, *optional*):
|
113 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
114 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
115 |
+
size divided by the number of attention heads divided by 2
|
116 |
+
`low_freq_factor` (`float`, *optional*):
|
117 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
118 |
+
`high_freq_factor` (`float`, *optional*):
|
119 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
120 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
121 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
122 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
123 |
+
The dropout ratio for the attention probabilities.
|
124 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
125 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
126 |
+
head_dim (`int`, *optional*):
|
127 |
+
The attention head dimension. If None, it will default to hidden_size // num_attention_heads
|
128 |
+
|
129 |
+
```python
|
130 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
131 |
+
|
132 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
133 |
+
>>> configuration = LlamaConfig()
|
134 |
+
|
135 |
+
>>> # Initializing a model from the llama-7b style configuration
|
136 |
+
>>> model = LlamaModel(configuration)
|
137 |
+
|
138 |
+
>>> # Accessing the model configuration
|
139 |
+
>>> configuration = model.config
|
140 |
+
```"""
|
141 |
+
|
142 |
+
model_type = "TriLMLinear"
|
143 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
144 |
+
# Default tensor parallel plan for base model `LlamaModel`
|
145 |
+
base_model_tp_plan = {
|
146 |
+
"layers.*.self_attn.q_proj": "colwise",
|
147 |
+
"layers.*.self_attn.k_proj": "colwise",
|
148 |
+
"layers.*.self_attn.v_proj": "colwise",
|
149 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
150 |
+
"layers.*.mlp.gate_proj": "colwise",
|
151 |
+
"layers.*.mlp.up_proj": "colwise",
|
152 |
+
"layers.*.mlp.down_proj": "rowwise",
|
153 |
+
}
|
154 |
+
|
155 |
+
def __init__(
|
156 |
+
self,
|
157 |
+
vocab_size=32000,
|
158 |
+
hidden_size=4096,
|
159 |
+
intermediate_size=11008,
|
160 |
+
num_hidden_layers=32,
|
161 |
+
num_attention_heads=32,
|
162 |
+
num_key_value_heads=None,
|
163 |
+
hidden_act="silu",
|
164 |
+
max_position_embeddings=2048,
|
165 |
+
initializer_range=0.02,
|
166 |
+
rms_norm_eps=1e-6,
|
167 |
+
use_cache=True,
|
168 |
+
pad_token_id=None,
|
169 |
+
bos_token_id=1,
|
170 |
+
eos_token_id=2,
|
171 |
+
pretraining_tp=1,
|
172 |
+
tie_word_embeddings=False,
|
173 |
+
rope_theta=10000.0,
|
174 |
+
rope_scaling=None,
|
175 |
+
attention_bias=False,
|
176 |
+
attention_dropout=0.0,
|
177 |
+
mlp_bias=False,
|
178 |
+
head_dim=None,
|
179 |
+
**kwargs,
|
180 |
+
):
|
181 |
+
self.vocab_size = vocab_size
|
182 |
+
self.max_position_embeddings = max_position_embeddings
|
183 |
+
self.hidden_size = hidden_size
|
184 |
+
self.intermediate_size = intermediate_size
|
185 |
+
self.num_hidden_layers = num_hidden_layers
|
186 |
+
self.num_attention_heads = num_attention_heads
|
187 |
+
|
188 |
+
# for backward compatibility
|
189 |
+
if num_key_value_heads is None:
|
190 |
+
num_key_value_heads = num_attention_heads
|
191 |
+
|
192 |
+
self.num_key_value_heads = num_key_value_heads
|
193 |
+
self.hidden_act = hidden_act
|
194 |
+
self.initializer_range = initializer_range
|
195 |
+
self.rms_norm_eps = rms_norm_eps
|
196 |
+
self.pretraining_tp = pretraining_tp
|
197 |
+
self.use_cache = use_cache
|
198 |
+
self.rope_theta = rope_theta
|
199 |
+
self.rope_scaling = rope_scaling
|
200 |
+
self.attention_bias = attention_bias
|
201 |
+
self.attention_dropout = attention_dropout
|
202 |
+
self.mlp_bias = mlp_bias
|
203 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
204 |
+
# Validate the correctness of rotary position embeddings parameters
|
205 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
206 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
207 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
208 |
+
rope_config_validation(self)
|
209 |
+
|
210 |
+
super().__init__(
|
211 |
+
pad_token_id=pad_token_id,
|
212 |
+
bos_token_id=bos_token_id,
|
213 |
+
eos_token_id=eos_token_id,
|
214 |
+
tie_word_embeddings=tie_word_embeddings,
|
215 |
+
**kwargs,
|
216 |
+
)
|
217 |
+
|
218 |
+
|
219 |
+
__all__ = ["TriLMLinearConfig"]
|
220 |
+
|
Llama-2-13b-hf_trirun/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7fc83b33d61dd62f88a9b0f98aa41403d93c4622020fab28324f735bf5a1cc5d
|
3 |
+
size 3832466504
|
Llama-2-13b-hf_trirun/modeling_trilmlinear.py
ADDED
@@ -0,0 +1,1037 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from typing import Callable, List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
|
26 |
+
from transformers.activations import ACT2FN
|
27 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
28 |
+
from transformers.generation import GenerationMixin
|
29 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
30 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
31 |
+
from transformers.modeling_outputs import (
|
32 |
+
BaseModelOutputWithPast,
|
33 |
+
CausalLMOutputWithPast,
|
34 |
+
QuestionAnsweringModelOutput,
|
35 |
+
SequenceClassifierOutputWithPast,
|
36 |
+
TokenClassifierOutput,
|
37 |
+
)
|
38 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
39 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
40 |
+
from transformers.processing_utils import Unpack
|
41 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
42 |
+
from transformers.utils import (
|
43 |
+
LossKwargs,
|
44 |
+
add_code_sample_docstrings,
|
45 |
+
add_start_docstrings,
|
46 |
+
add_start_docstrings_to_model_forward,
|
47 |
+
logging,
|
48 |
+
replace_return_docstrings,
|
49 |
+
)
|
50 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
51 |
+
from .configuration_trilmlinear import TriLMLinearConfig
|
52 |
+
import marlin
|
53 |
+
|
54 |
+
logger = logging.get_logger(__name__)
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
class TriLMLinear(torch.nn.Module):
|
59 |
+
def __init__(self, in_dims, out_dims, thread_k=128, thread_n=128, groupsize=-1, sms=-1):
|
60 |
+
super(TriLMLinear, self).__init__()
|
61 |
+
self.in_dims, self.out_dims = in_dims, out_dims
|
62 |
+
self.thread_k, self.thread_n, self.groupsize, self.sms = thread_k, thread_n, groupsize, sms
|
63 |
+
packed_weight = torch.ones((in_dims//16, out_dims), dtype=torch.int32)
|
64 |
+
scales = torch.ones((1, out_dims), dtype=torch.float16)
|
65 |
+
self.register_buffer("packed_weight", packed_weight)
|
66 |
+
self.register_buffer("scales", scales)
|
67 |
+
self.workspace = torch.zeros(self.out_dims // 128 * 16, device="cuda")
|
68 |
+
def forward(self, hidden_state):
|
69 |
+
# print(A, self.name)
|
70 |
+
batch_size, seqlen, last_dim = hidden_state.shape
|
71 |
+
output = torch.zeros((batch_size * seqlen, self.out_dims), dtype=torch.float16, device=self.packed_weight.device)
|
72 |
+
marlin.mul(hidden_state.reshape(batch_size * seqlen, last_dim).contiguous(), self.packed_weight, output, self.scales,
|
73 |
+
self.workspace, self.thread_k, self.thread_n, self.sms)
|
74 |
+
return output.reshape(batch_size, seqlen, -1)
|
75 |
+
|
76 |
+
|
77 |
+
class TriLMLinearRMSNorm(nn.Module):
|
78 |
+
def __init__(self, hidden_size, eps=1e-6):
|
79 |
+
"""
|
80 |
+
TriLMLinearRMSNorm is equivalent to T5LayerNorm
|
81 |
+
"""
|
82 |
+
super().__init__()
|
83 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
84 |
+
self.variance_epsilon = eps
|
85 |
+
|
86 |
+
def forward(self, hidden_states):
|
87 |
+
input_dtype = hidden_states.dtype
|
88 |
+
hidden_states = hidden_states.to(torch.float32)
|
89 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
90 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
91 |
+
return self.weight * hidden_states.to(input_dtype)
|
92 |
+
|
93 |
+
def extra_repr(self):
|
94 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
95 |
+
|
96 |
+
|
97 |
+
ALL_LAYERNORM_LAYERS.append(TriLMLinearRMSNorm)
|
98 |
+
|
99 |
+
|
100 |
+
class TriLMLinearRotaryEmbedding(nn.Module):
|
101 |
+
def __init__(self, config: TriLMLinearConfig, device=None):
|
102 |
+
super().__init__()
|
103 |
+
# BC: "rope_type" was originally "type"
|
104 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
105 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
106 |
+
else:
|
107 |
+
self.rope_type = "default"
|
108 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
109 |
+
self.original_max_seq_len = config.max_position_embeddings
|
110 |
+
|
111 |
+
self.config = config
|
112 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
113 |
+
|
114 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
115 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
116 |
+
self.original_inv_freq = self.inv_freq
|
117 |
+
|
118 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
119 |
+
"""
|
120 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
121 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
122 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
123 |
+
"""
|
124 |
+
seq_len = torch.max(position_ids) + 1
|
125 |
+
if seq_len > self.max_seq_len_cached: # growth
|
126 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
127 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
128 |
+
self.max_seq_len_cached = seq_len
|
129 |
+
|
130 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
131 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
132 |
+
# the buffer is automatically moved, but not the original copy)
|
133 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
134 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
135 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
136 |
+
|
137 |
+
@torch.no_grad()
|
138 |
+
def forward(self, x, position_ids):
|
139 |
+
if "dynamic" in self.rope_type:
|
140 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
141 |
+
|
142 |
+
# Core RoPE block
|
143 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
144 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
145 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
146 |
+
device_type = x.device.type
|
147 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
148 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
149 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
150 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
151 |
+
cos = emb.cos()
|
152 |
+
sin = emb.sin()
|
153 |
+
|
154 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
155 |
+
cos = cos * self.attention_scaling
|
156 |
+
sin = sin * self.attention_scaling
|
157 |
+
|
158 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
159 |
+
|
160 |
+
|
161 |
+
def rotate_half(x):
|
162 |
+
"""Rotates half the hidden dims of the input."""
|
163 |
+
x1 = x[..., : x.shape[-1] // 2]
|
164 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
165 |
+
return torch.cat((-x2, x1), dim=-1)
|
166 |
+
|
167 |
+
|
168 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
169 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
170 |
+
|
171 |
+
Args:
|
172 |
+
q (`torch.Tensor`): The query tensor.
|
173 |
+
k (`torch.Tensor`): The key tensor.
|
174 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
175 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
176 |
+
position_ids (`torch.Tensor`, *optional*):
|
177 |
+
Deprecated and unused.
|
178 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
179 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
180 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
181 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
182 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
183 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
184 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
185 |
+
Returns:
|
186 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
187 |
+
"""
|
188 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
189 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
190 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
191 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
192 |
+
return q_embed, k_embed
|
193 |
+
|
194 |
+
|
195 |
+
class TriLMLinearMLP(nn.Module):
|
196 |
+
def __init__(self, config):
|
197 |
+
super().__init__()
|
198 |
+
self.config = config
|
199 |
+
self.hidden_size = config.hidden_size
|
200 |
+
self.intermediate_size = config.intermediate_size
|
201 |
+
assert config.mlp_bias == False, config.mlp_bias
|
202 |
+
self.gate_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
203 |
+
self.up_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
204 |
+
self.down_proj = TriLMLinear(self.intermediate_size, self.hidden_size)
|
205 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
206 |
+
|
207 |
+
def forward(self, x):
|
208 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
209 |
+
return down_proj
|
210 |
+
|
211 |
+
|
212 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
213 |
+
"""
|
214 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
215 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
216 |
+
"""
|
217 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
218 |
+
if n_rep == 1:
|
219 |
+
return hidden_states
|
220 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
221 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
222 |
+
|
223 |
+
|
224 |
+
def eager_attention_forward(
|
225 |
+
module: nn.Module,
|
226 |
+
query: torch.Tensor,
|
227 |
+
key: torch.Tensor,
|
228 |
+
value: torch.Tensor,
|
229 |
+
attention_mask: Optional[torch.Tensor],
|
230 |
+
scaling: float,
|
231 |
+
dropout: float = 0.0,
|
232 |
+
**kwargs,
|
233 |
+
):
|
234 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
235 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
236 |
+
|
237 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
238 |
+
if attention_mask is not None:
|
239 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
240 |
+
attn_weights = attn_weights + causal_mask
|
241 |
+
|
242 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
243 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
244 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
245 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
246 |
+
|
247 |
+
return attn_output, attn_weights
|
248 |
+
|
249 |
+
|
250 |
+
class TriLMLinearAttention(nn.Module):
|
251 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
252 |
+
|
253 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
254 |
+
super().__init__()
|
255 |
+
self.config = config
|
256 |
+
self.layer_idx = layer_idx
|
257 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
258 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
259 |
+
self.scaling = self.head_dim**-0.5
|
260 |
+
self.attention_dropout = config.attention_dropout
|
261 |
+
self.is_causal = True
|
262 |
+
assert config.attention_bias == False
|
263 |
+
self.q_proj = TriLMLinear(
|
264 |
+
config.hidden_size, config.num_attention_heads * self.head_dim#, bias=config.attention_bias
|
265 |
+
)
|
266 |
+
self.k_proj = TriLMLinear(
|
267 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
268 |
+
)
|
269 |
+
self.v_proj = TriLMLinear(
|
270 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
271 |
+
)
|
272 |
+
self.o_proj = TriLMLinear(
|
273 |
+
config.num_attention_heads * self.head_dim, config.hidden_size#, bias=config.attention_bias
|
274 |
+
)
|
275 |
+
|
276 |
+
def forward(
|
277 |
+
self,
|
278 |
+
hidden_states: torch.Tensor,
|
279 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
280 |
+
attention_mask: Optional[torch.Tensor],
|
281 |
+
past_key_value: Optional[Cache] = None,
|
282 |
+
cache_position: Optional[torch.LongTensor] = None,
|
283 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
284 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
285 |
+
input_shape = hidden_states.shape[:-1]
|
286 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
287 |
+
|
288 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
289 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
290 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
291 |
+
|
292 |
+
cos, sin = position_embeddings
|
293 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
294 |
+
|
295 |
+
if past_key_value is not None:
|
296 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
297 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
298 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
299 |
+
|
300 |
+
attention_interface: Callable = eager_attention_forward
|
301 |
+
if self.config._attn_implementation != "eager":
|
302 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
303 |
+
logger.warning_once(
|
304 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
305 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
306 |
+
)
|
307 |
+
else:
|
308 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
309 |
+
|
310 |
+
attn_output, attn_weights = attention_interface(
|
311 |
+
self,
|
312 |
+
query_states,
|
313 |
+
key_states,
|
314 |
+
value_states,
|
315 |
+
attention_mask,
|
316 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
317 |
+
scaling=self.scaling,
|
318 |
+
**kwargs,
|
319 |
+
)
|
320 |
+
|
321 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
322 |
+
attn_output = self.o_proj(attn_output)
|
323 |
+
return attn_output, attn_weights
|
324 |
+
|
325 |
+
|
326 |
+
class TriLMLinearDecoderLayer(nn.Module):
|
327 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
328 |
+
super().__init__()
|
329 |
+
self.hidden_size = config.hidden_size
|
330 |
+
|
331 |
+
self.self_attn = TriLMLinearAttention(config=config, layer_idx=layer_idx)
|
332 |
+
|
333 |
+
self.mlp = TriLMLinearMLP(config)
|
334 |
+
self.input_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
335 |
+
self.post_attention_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
336 |
+
|
337 |
+
def forward(
|
338 |
+
self,
|
339 |
+
hidden_states: torch.Tensor,
|
340 |
+
attention_mask: Optional[torch.Tensor] = None,
|
341 |
+
position_ids: Optional[torch.LongTensor] = None,
|
342 |
+
past_key_value: Optional[Cache] = None,
|
343 |
+
output_attentions: Optional[bool] = False,
|
344 |
+
use_cache: Optional[bool] = False,
|
345 |
+
cache_position: Optional[torch.LongTensor] = None,
|
346 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
347 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
348 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
349 |
+
residual = hidden_states
|
350 |
+
|
351 |
+
hidden_states = self.input_layernorm(hidden_states)
|
352 |
+
|
353 |
+
# Self Attention
|
354 |
+
hidden_states, self_attn_weights = self.self_attn(
|
355 |
+
hidden_states=hidden_states,
|
356 |
+
attention_mask=attention_mask,
|
357 |
+
position_ids=position_ids,
|
358 |
+
past_key_value=past_key_value,
|
359 |
+
output_attentions=output_attentions,
|
360 |
+
use_cache=use_cache,
|
361 |
+
cache_position=cache_position,
|
362 |
+
position_embeddings=position_embeddings,
|
363 |
+
**kwargs,
|
364 |
+
)
|
365 |
+
hidden_states = residual + hidden_states
|
366 |
+
|
367 |
+
# Fully Connected
|
368 |
+
residual = hidden_states
|
369 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
370 |
+
hidden_states = self.mlp(hidden_states)
|
371 |
+
hidden_states = residual + hidden_states
|
372 |
+
|
373 |
+
outputs = (hidden_states,)
|
374 |
+
if output_attentions:
|
375 |
+
outputs += (self_attn_weights,)
|
376 |
+
|
377 |
+
return outputs
|
378 |
+
|
379 |
+
|
380 |
+
class TriLMLinearPreTrainedModel(PreTrainedModel):
|
381 |
+
config_class = TriLMLinearConfig
|
382 |
+
base_model_prefix = "model"
|
383 |
+
supports_gradient_checkpointing = True
|
384 |
+
_no_split_modules = ["TriLMLinearDecoderLayer"]
|
385 |
+
_skip_keys_device_placement = ["past_key_values"]
|
386 |
+
_supports_flash_attn_2 = True
|
387 |
+
_supports_sdpa = True
|
388 |
+
_supports_flex_attn = True
|
389 |
+
_supports_cache_class = True
|
390 |
+
_supports_quantized_cache = True
|
391 |
+
_supports_static_cache = True
|
392 |
+
_supports_attention_backend = True
|
393 |
+
|
394 |
+
def _init_weights(self, module):
|
395 |
+
std = self.config.initializer_range
|
396 |
+
if isinstance(module, nn.Linear):
|
397 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
398 |
+
if module.bias is not None:
|
399 |
+
module.bias.data.zero_()
|
400 |
+
elif isinstance(module, nn.Embedding):
|
401 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
402 |
+
if module.padding_idx is not None:
|
403 |
+
module.weight.data[module.padding_idx].zero_()
|
404 |
+
|
405 |
+
|
406 |
+
|
407 |
+
|
408 |
+
class TriLMLinearModel(TriLMLinearPreTrainedModel):
|
409 |
+
"""
|
410 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TriLMLinearDecoderLayer`]
|
411 |
+
|
412 |
+
Args:
|
413 |
+
config: TriLMLinearConfig
|
414 |
+
"""
|
415 |
+
|
416 |
+
def __init__(self, config: TriLMLinearConfig):
|
417 |
+
super().__init__(config)
|
418 |
+
self.padding_idx = config.pad_token_id
|
419 |
+
self.vocab_size = config.vocab_size
|
420 |
+
|
421 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
422 |
+
self.layers = nn.ModuleList(
|
423 |
+
[TriLMLinearDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
424 |
+
)
|
425 |
+
self.norm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
426 |
+
self.rotary_emb = TriLMLinearRotaryEmbedding(config=config)
|
427 |
+
self.gradient_checkpointing = False
|
428 |
+
|
429 |
+
# Initialize weights and apply final processing
|
430 |
+
self.post_init()
|
431 |
+
|
432 |
+
def get_input_embeddings(self):
|
433 |
+
return self.embed_tokens
|
434 |
+
|
435 |
+
def set_input_embeddings(self, value):
|
436 |
+
self.embed_tokens = value
|
437 |
+
|
438 |
+
def forward(
|
439 |
+
self,
|
440 |
+
input_ids: torch.LongTensor = None,
|
441 |
+
attention_mask: Optional[torch.Tensor] = None,
|
442 |
+
position_ids: Optional[torch.LongTensor] = None,
|
443 |
+
past_key_values: Optional[Cache] = None,
|
444 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
445 |
+
use_cache: Optional[bool] = None,
|
446 |
+
output_attentions: Optional[bool] = None,
|
447 |
+
output_hidden_states: Optional[bool] = None,
|
448 |
+
return_dict: Optional[bool] = None,
|
449 |
+
cache_position: Optional[torch.LongTensor] = None,
|
450 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
451 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
452 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
453 |
+
output_hidden_states = (
|
454 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
455 |
+
)
|
456 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
457 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
458 |
+
|
459 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
460 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
461 |
+
|
462 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
463 |
+
logger.warning_once(
|
464 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
465 |
+
)
|
466 |
+
use_cache = False
|
467 |
+
|
468 |
+
if inputs_embeds is None:
|
469 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
470 |
+
|
471 |
+
if use_cache and past_key_values is None:
|
472 |
+
past_key_values = DynamicCache()
|
473 |
+
|
474 |
+
if cache_position is None:
|
475 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
476 |
+
cache_position = torch.arange(
|
477 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
478 |
+
)
|
479 |
+
|
480 |
+
if position_ids is None:
|
481 |
+
position_ids = cache_position.unsqueeze(0)
|
482 |
+
|
483 |
+
causal_mask = self._update_causal_mask(
|
484 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
485 |
+
)
|
486 |
+
|
487 |
+
hidden_states = inputs_embeds
|
488 |
+
|
489 |
+
# create position embeddings to be shared across the decoder layers
|
490 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
491 |
+
|
492 |
+
# decoder layers
|
493 |
+
all_hidden_states = () if output_hidden_states else None
|
494 |
+
all_self_attns = () if output_attentions else None
|
495 |
+
|
496 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
497 |
+
if output_hidden_states:
|
498 |
+
all_hidden_states += (hidden_states,)
|
499 |
+
|
500 |
+
if self.gradient_checkpointing and self.training:
|
501 |
+
layer_outputs = self._gradient_checkpointing_func(
|
502 |
+
decoder_layer.__call__,
|
503 |
+
hidden_states,
|
504 |
+
causal_mask,
|
505 |
+
position_ids,
|
506 |
+
past_key_values,
|
507 |
+
output_attentions,
|
508 |
+
use_cache,
|
509 |
+
cache_position,
|
510 |
+
position_embeddings,
|
511 |
+
)
|
512 |
+
else:
|
513 |
+
layer_outputs = decoder_layer(
|
514 |
+
hidden_states,
|
515 |
+
attention_mask=causal_mask,
|
516 |
+
position_ids=position_ids,
|
517 |
+
past_key_value=past_key_values,
|
518 |
+
output_attentions=output_attentions,
|
519 |
+
use_cache=use_cache,
|
520 |
+
cache_position=cache_position,
|
521 |
+
position_embeddings=position_embeddings,
|
522 |
+
**flash_attn_kwargs,
|
523 |
+
)
|
524 |
+
|
525 |
+
hidden_states = layer_outputs[0]
|
526 |
+
|
527 |
+
if output_attentions:
|
528 |
+
all_self_attns += (layer_outputs[1],)
|
529 |
+
|
530 |
+
hidden_states = self.norm(hidden_states)
|
531 |
+
|
532 |
+
# add hidden states from the last decoder layer
|
533 |
+
if output_hidden_states:
|
534 |
+
all_hidden_states += (hidden_states,)
|
535 |
+
|
536 |
+
output = BaseModelOutputWithPast(
|
537 |
+
last_hidden_state=hidden_states,
|
538 |
+
past_key_values=past_key_values if use_cache else None,
|
539 |
+
hidden_states=all_hidden_states,
|
540 |
+
attentions=all_self_attns,
|
541 |
+
)
|
542 |
+
return output if return_dict else output.to_tuple()
|
543 |
+
|
544 |
+
def _update_causal_mask(
|
545 |
+
self,
|
546 |
+
attention_mask: torch.Tensor,
|
547 |
+
input_tensor: torch.Tensor,
|
548 |
+
cache_position: torch.Tensor,
|
549 |
+
past_key_values: Cache,
|
550 |
+
output_attentions: bool,
|
551 |
+
):
|
552 |
+
if self.config._attn_implementation == "flash_attention_2":
|
553 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
554 |
+
return attention_mask
|
555 |
+
return None
|
556 |
+
|
557 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
558 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
559 |
+
# to infer the attention mask.
|
560 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
561 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
562 |
+
|
563 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
564 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
565 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
566 |
+
attention_mask,
|
567 |
+
inputs_embeds=input_tensor,
|
568 |
+
past_key_values_length=past_seen_tokens,
|
569 |
+
is_training=self.training,
|
570 |
+
):
|
571 |
+
return None
|
572 |
+
|
573 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
574 |
+
sequence_length = input_tensor.shape[1]
|
575 |
+
if using_static_cache:
|
576 |
+
target_length = past_key_values.get_max_cache_shape()
|
577 |
+
else:
|
578 |
+
target_length = (
|
579 |
+
attention_mask.shape[-1]
|
580 |
+
if isinstance(attention_mask, torch.Tensor)
|
581 |
+
else past_seen_tokens + sequence_length + 1
|
582 |
+
)
|
583 |
+
|
584 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
585 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
586 |
+
attention_mask,
|
587 |
+
sequence_length=sequence_length,
|
588 |
+
target_length=target_length,
|
589 |
+
dtype=dtype,
|
590 |
+
device=device,
|
591 |
+
cache_position=cache_position,
|
592 |
+
batch_size=input_tensor.shape[0],
|
593 |
+
)
|
594 |
+
|
595 |
+
if (
|
596 |
+
self.config._attn_implementation == "sdpa"
|
597 |
+
and attention_mask is not None
|
598 |
+
and attention_mask.device.type == "cuda"
|
599 |
+
and not output_attentions
|
600 |
+
):
|
601 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
602 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
603 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
604 |
+
min_dtype = torch.finfo(dtype).min
|
605 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
606 |
+
|
607 |
+
return causal_mask
|
608 |
+
|
609 |
+
@staticmethod
|
610 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
611 |
+
attention_mask: torch.Tensor,
|
612 |
+
sequence_length: int,
|
613 |
+
target_length: int,
|
614 |
+
dtype: torch.dtype,
|
615 |
+
device: torch.device,
|
616 |
+
cache_position: torch.Tensor,
|
617 |
+
batch_size: int,
|
618 |
+
**kwargs,
|
619 |
+
):
|
620 |
+
"""
|
621 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
622 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
623 |
+
|
624 |
+
Args:
|
625 |
+
attention_mask (`torch.Tensor`):
|
626 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
627 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
628 |
+
sequence_length (`int`):
|
629 |
+
The sequence length being processed.
|
630 |
+
target_length (`int`):
|
631 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
632 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
633 |
+
dtype (`torch.dtype`):
|
634 |
+
The dtype to use for the 4D attention mask.
|
635 |
+
device (`torch.device`):
|
636 |
+
The device to plcae the 4D attention mask on.
|
637 |
+
cache_position (`torch.Tensor`):
|
638 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
639 |
+
batch_size (`torch.Tensor`):
|
640 |
+
Batch size.
|
641 |
+
"""
|
642 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
643 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
644 |
+
causal_mask = attention_mask
|
645 |
+
else:
|
646 |
+
min_dtype = torch.finfo(dtype).min
|
647 |
+
causal_mask = torch.full(
|
648 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
649 |
+
)
|
650 |
+
if sequence_length != 1:
|
651 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
652 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
653 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
654 |
+
if attention_mask is not None:
|
655 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
656 |
+
mask_length = attention_mask.shape[-1]
|
657 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
658 |
+
padding_mask = padding_mask == 0
|
659 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
660 |
+
padding_mask, min_dtype
|
661 |
+
)
|
662 |
+
|
663 |
+
return causal_mask
|
664 |
+
|
665 |
+
|
666 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
667 |
+
|
668 |
+
|
669 |
+
class TriLMLinearForCausalLM(TriLMLinearPreTrainedModel, GenerationMixin):
|
670 |
+
_tied_weights_keys = ["lm_head.weight"]
|
671 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
672 |
+
|
673 |
+
def __init__(self, config):
|
674 |
+
super().__init__(config)
|
675 |
+
self.model = TriLMLinearModel(config)
|
676 |
+
self.vocab_size = config.vocab_size
|
677 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
678 |
+
|
679 |
+
# Initialize weights and apply final processing
|
680 |
+
self.post_init()
|
681 |
+
|
682 |
+
def get_input_embeddings(self):
|
683 |
+
return self.model.embed_tokens
|
684 |
+
|
685 |
+
def set_input_embeddings(self, value):
|
686 |
+
self.model.embed_tokens = value
|
687 |
+
|
688 |
+
def get_output_embeddings(self):
|
689 |
+
return self.lm_head
|
690 |
+
|
691 |
+
def set_output_embeddings(self, new_embeddings):
|
692 |
+
self.lm_head = new_embeddings
|
693 |
+
|
694 |
+
def set_decoder(self, decoder):
|
695 |
+
self.model = decoder
|
696 |
+
|
697 |
+
def get_decoder(self):
|
698 |
+
return self.model
|
699 |
+
|
700 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
701 |
+
def forward(
|
702 |
+
self,
|
703 |
+
input_ids: torch.LongTensor = None,
|
704 |
+
attention_mask: Optional[torch.Tensor] = None,
|
705 |
+
position_ids: Optional[torch.LongTensor] = None,
|
706 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
707 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
708 |
+
labels: Optional[torch.LongTensor] = None,
|
709 |
+
use_cache: Optional[bool] = None,
|
710 |
+
output_attentions: Optional[bool] = None,
|
711 |
+
output_hidden_states: Optional[bool] = None,
|
712 |
+
return_dict: Optional[bool] = None,
|
713 |
+
cache_position: Optional[torch.LongTensor] = None,
|
714 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
715 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
716 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
717 |
+
r"""
|
718 |
+
Args:
|
719 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
720 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
721 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
722 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
723 |
+
|
724 |
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
725 |
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
726 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
727 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
728 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
729 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
730 |
+
|
731 |
+
Returns:
|
732 |
+
|
733 |
+
Example:
|
734 |
+
|
735 |
+
```python
|
736 |
+
>>> from transformers import AutoTokenizer, TriLMLinearForCausalLM
|
737 |
+
|
738 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
739 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
740 |
+
|
741 |
+
>>> # Generate
|
742 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
743 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
744 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
745 |
+
```"""
|
746 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
747 |
+
output_hidden_states = (
|
748 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
749 |
+
)
|
750 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
751 |
+
|
752 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
753 |
+
outputs = self.model(
|
754 |
+
input_ids=input_ids,
|
755 |
+
attention_mask=attention_mask,
|
756 |
+
position_ids=position_ids,
|
757 |
+
past_key_values=past_key_values,
|
758 |
+
inputs_embeds=inputs_embeds,
|
759 |
+
use_cache=use_cache,
|
760 |
+
output_attentions=output_attentions,
|
761 |
+
output_hidden_states=output_hidden_states,
|
762 |
+
return_dict=return_dict,
|
763 |
+
cache_position=cache_position,
|
764 |
+
**kwargs,
|
765 |
+
)
|
766 |
+
|
767 |
+
hidden_states = outputs[0]
|
768 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
769 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
770 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
771 |
+
|
772 |
+
loss = None
|
773 |
+
if labels is not None:
|
774 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
775 |
+
|
776 |
+
if not return_dict:
|
777 |
+
output = (logits,) + outputs[1:]
|
778 |
+
return (loss,) + output if loss is not None else output
|
779 |
+
|
780 |
+
return CausalLMOutputWithPast(
|
781 |
+
loss=loss,
|
782 |
+
logits=logits,
|
783 |
+
past_key_values=outputs.past_key_values,
|
784 |
+
hidden_states=outputs.hidden_states,
|
785 |
+
attentions=outputs.attentions,
|
786 |
+
)
|
787 |
+
|
788 |
+
|
789 |
+
class TriLMLinearForSequenceClassification(TriLMLinearPreTrainedModel):
|
790 |
+
def __init__(self, config):
|
791 |
+
super().__init__(config)
|
792 |
+
self.num_labels = config.num_labels
|
793 |
+
self.model = TriLMLinearModel(config)
|
794 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
795 |
+
|
796 |
+
# Initialize weights and apply final processing
|
797 |
+
self.post_init()
|
798 |
+
|
799 |
+
def get_input_embeddings(self):
|
800 |
+
return self.model.embed_tokens
|
801 |
+
|
802 |
+
def set_input_embeddings(self, value):
|
803 |
+
self.model.embed_tokens = value
|
804 |
+
|
805 |
+
def forward(
|
806 |
+
self,
|
807 |
+
input_ids: Optional[torch.LongTensor] = None,
|
808 |
+
attention_mask: Optional[torch.Tensor] = None,
|
809 |
+
position_ids: Optional[torch.LongTensor] = None,
|
810 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
811 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
812 |
+
labels: Optional[torch.LongTensor] = None,
|
813 |
+
use_cache: Optional[bool] = None,
|
814 |
+
output_attentions: Optional[bool] = None,
|
815 |
+
output_hidden_states: Optional[bool] = None,
|
816 |
+
return_dict: Optional[bool] = None,
|
817 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
818 |
+
r"""
|
819 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
820 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
821 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
822 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
823 |
+
"""
|
824 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
825 |
+
|
826 |
+
transformer_outputs = self.model(
|
827 |
+
input_ids,
|
828 |
+
attention_mask=attention_mask,
|
829 |
+
position_ids=position_ids,
|
830 |
+
past_key_values=past_key_values,
|
831 |
+
inputs_embeds=inputs_embeds,
|
832 |
+
use_cache=use_cache,
|
833 |
+
output_attentions=output_attentions,
|
834 |
+
output_hidden_states=output_hidden_states,
|
835 |
+
return_dict=return_dict,
|
836 |
+
)
|
837 |
+
hidden_states = transformer_outputs[0]
|
838 |
+
logits = self.score(hidden_states)
|
839 |
+
|
840 |
+
if input_ids is not None:
|
841 |
+
batch_size = input_ids.shape[0]
|
842 |
+
else:
|
843 |
+
batch_size = inputs_embeds.shape[0]
|
844 |
+
|
845 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
846 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
847 |
+
if self.config.pad_token_id is None:
|
848 |
+
sequence_lengths = -1
|
849 |
+
else:
|
850 |
+
if input_ids is not None:
|
851 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
852 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
853 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
854 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
855 |
+
else:
|
856 |
+
sequence_lengths = -1
|
857 |
+
|
858 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
859 |
+
|
860 |
+
loss = None
|
861 |
+
if labels is not None:
|
862 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
863 |
+
|
864 |
+
if not return_dict:
|
865 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
866 |
+
return ((loss,) + output) if loss is not None else output
|
867 |
+
|
868 |
+
return SequenceClassifierOutputWithPast(
|
869 |
+
loss=loss,
|
870 |
+
logits=pooled_logits,
|
871 |
+
past_key_values=transformer_outputs.past_key_values,
|
872 |
+
hidden_states=transformer_outputs.hidden_states,
|
873 |
+
attentions=transformer_outputs.attentions,
|
874 |
+
)
|
875 |
+
|
876 |
+
|
877 |
+
class TriLMLinearForQuestionAnswering(TriLMLinearPreTrainedModel):
|
878 |
+
base_model_prefix = "transformer"
|
879 |
+
|
880 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->TriLMLinear
|
881 |
+
def __init__(self, config):
|
882 |
+
super().__init__(config)
|
883 |
+
self.transformer = TriLMLinearModel(config)
|
884 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
885 |
+
|
886 |
+
# Initialize weights and apply final processing
|
887 |
+
self.post_init()
|
888 |
+
|
889 |
+
def get_input_embeddings(self):
|
890 |
+
return self.transformer.embed_tokens
|
891 |
+
|
892 |
+
def set_input_embeddings(self, value):
|
893 |
+
self.transformer.embed_tokens = value
|
894 |
+
|
895 |
+
def forward(
|
896 |
+
self,
|
897 |
+
input_ids: Optional[torch.LongTensor] = None,
|
898 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
899 |
+
position_ids: Optional[torch.LongTensor] = None,
|
900 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
901 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
902 |
+
start_positions: Optional[torch.LongTensor] = None,
|
903 |
+
end_positions: Optional[torch.LongTensor] = None,
|
904 |
+
output_attentions: Optional[bool] = None,
|
905 |
+
output_hidden_states: Optional[bool] = None,
|
906 |
+
return_dict: Optional[bool] = None,
|
907 |
+
**kwargs,
|
908 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
909 |
+
r"""
|
910 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
911 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
912 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
913 |
+
are not taken into account for computing the loss.
|
914 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
915 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
916 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
917 |
+
are not taken into account for computing the loss.
|
918 |
+
"""
|
919 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
920 |
+
|
921 |
+
outputs = self.transformer(
|
922 |
+
input_ids,
|
923 |
+
attention_mask=attention_mask,
|
924 |
+
position_ids=position_ids,
|
925 |
+
past_key_values=past_key_values,
|
926 |
+
inputs_embeds=inputs_embeds,
|
927 |
+
output_attentions=output_attentions,
|
928 |
+
output_hidden_states=output_hidden_states,
|
929 |
+
return_dict=return_dict,
|
930 |
+
)
|
931 |
+
|
932 |
+
sequence_output = outputs[0]
|
933 |
+
|
934 |
+
logits = self.qa_outputs(sequence_output)
|
935 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
936 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
937 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
938 |
+
|
939 |
+
loss = None
|
940 |
+
if start_positions is not None and end_positions is not None:
|
941 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
942 |
+
|
943 |
+
if not return_dict:
|
944 |
+
output = (start_logits, end_logits) + outputs[2:]
|
945 |
+
return ((loss,) + output) if loss is not None else output
|
946 |
+
|
947 |
+
return QuestionAnsweringModelOutput(
|
948 |
+
loss=loss,
|
949 |
+
start_logits=start_logits,
|
950 |
+
end_logits=end_logits,
|
951 |
+
hidden_states=outputs.hidden_states,
|
952 |
+
attentions=outputs.attentions,
|
953 |
+
)
|
954 |
+
|
955 |
+
class TriLMLinearForTokenClassification(TriLMLinearPreTrainedModel):
|
956 |
+
def __init__(self, config):
|
957 |
+
super().__init__(config)
|
958 |
+
self.num_labels = config.num_labels
|
959 |
+
self.model = TriLMLinearModel(config)
|
960 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
961 |
+
classifier_dropout = config.classifier_dropout
|
962 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
963 |
+
classifier_dropout = config.hidden_dropout
|
964 |
+
else:
|
965 |
+
classifier_dropout = 0.1
|
966 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
967 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
968 |
+
|
969 |
+
# Initialize weights and apply final processing
|
970 |
+
self.post_init()
|
971 |
+
|
972 |
+
def get_input_embeddings(self):
|
973 |
+
return self.model.embed_tokens
|
974 |
+
|
975 |
+
def set_input_embeddings(self, value):
|
976 |
+
self.model.embed_tokens = value
|
977 |
+
|
978 |
+
def forward(
|
979 |
+
self,
|
980 |
+
input_ids: Optional[torch.LongTensor] = None,
|
981 |
+
attention_mask: Optional[torch.Tensor] = None,
|
982 |
+
position_ids: Optional[torch.LongTensor] = None,
|
983 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
984 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
985 |
+
labels: Optional[torch.LongTensor] = None,
|
986 |
+
use_cache: Optional[bool] = None,
|
987 |
+
output_attentions: Optional[bool] = None,
|
988 |
+
output_hidden_states: Optional[bool] = None,
|
989 |
+
return_dict: Optional[bool] = None,
|
990 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
991 |
+
r"""
|
992 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
993 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
994 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
995 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
996 |
+
"""
|
997 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
998 |
+
|
999 |
+
outputs = self.model(
|
1000 |
+
input_ids,
|
1001 |
+
attention_mask=attention_mask,
|
1002 |
+
position_ids=position_ids,
|
1003 |
+
past_key_values=past_key_values,
|
1004 |
+
inputs_embeds=inputs_embeds,
|
1005 |
+
use_cache=use_cache,
|
1006 |
+
output_attentions=output_attentions,
|
1007 |
+
output_hidden_states=output_hidden_states,
|
1008 |
+
return_dict=return_dict,
|
1009 |
+
)
|
1010 |
+
sequence_output = outputs[0]
|
1011 |
+
sequence_output = self.dropout(sequence_output)
|
1012 |
+
logits = self.score(sequence_output)
|
1013 |
+
|
1014 |
+
loss = None
|
1015 |
+
if labels is not None:
|
1016 |
+
loss = self.loss_function(logits, labels, self.config)
|
1017 |
+
|
1018 |
+
if not return_dict:
|
1019 |
+
output = (logits,) + outputs[2:]
|
1020 |
+
return ((loss,) + output) if loss is not None else output
|
1021 |
+
|
1022 |
+
return TokenClassifierOutput(
|
1023 |
+
loss=loss,
|
1024 |
+
logits=logits,
|
1025 |
+
hidden_states=outputs.hidden_states,
|
1026 |
+
attentions=outputs.attentions,
|
1027 |
+
)
|
1028 |
+
|
1029 |
+
|
1030 |
+
__all__ = [
|
1031 |
+
"TriLMLinearForCausalLM",
|
1032 |
+
"TriLMLinearModel",
|
1033 |
+
"TriLMLinearPreTrainedModel",
|
1034 |
+
"TriLMLinearForSequenceClassification",
|
1035 |
+
"TriLMLinearForQuestionAnswering",
|
1036 |
+
"TriLMLinearForTokenClassification",
|
1037 |
+
]
|
Llama-2-70b-hf/config.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"LlamaForCausalLM"
|
4 |
+
],
|
5 |
+
"bos_token_id": 1,
|
6 |
+
"eos_token_id": 2,
|
7 |
+
"hidden_act": "silu",
|
8 |
+
"hidden_size": 8192,
|
9 |
+
"initializer_range": 0.02,
|
10 |
+
"intermediate_size": 28672,
|
11 |
+
"max_position_embeddings": 4096,
|
12 |
+
"model_type": "llama",
|
13 |
+
"num_attention_heads": 64,
|
14 |
+
"num_hidden_layers": 80,
|
15 |
+
"num_key_value_heads": 8,
|
16 |
+
"pad_token_id": 0,
|
17 |
+
"rms_norm_eps": 1e-05,
|
18 |
+
"tie_word_embeddings": false,
|
19 |
+
"torch_dtype": "float16",
|
20 |
+
"transformers_version": "4.31.0.dev0",
|
21 |
+
"use_cache": true,
|
22 |
+
"vocab_size": 32000
|
23 |
+
}
|
Llama-2-70b-hf/model.safetensors.aa
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:39eb601e51439d0466fda9fe5a56ebe1f269c0479e1468b3ee79eea063bc9987
|
3 |
+
size 45984460568
|
Llama-2-70b-hf/model.safetensors.ab
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:afa5be21481bc6893aec0776cd7c3048beea3ae6aa2db20cbd85040675465804
|
3 |
+
size 45984460568
|
Llama-2-70b-hf/model.safetensors.ac
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e4e84547490aaa0a68f3c932dd0dd0b4a1b5a0f3a70ab1ca94521737ab98bc7c
|
3 |
+
size 45984460568
|
Llama-2-70b-hf_trirun/config.json
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"TriLMLinearForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_trilmlinear.TriLMLinearConfig",
|
7 |
+
"AutoModel": "modeling_trilmlinear.TriLMLinearModel",
|
8 |
+
"AutoModelForCausalLM": "modeling_trilmlinear.TriLMLinearForCausalLM"
|
9 |
+
},
|
10 |
+
"bos_token_id": 1,
|
11 |
+
"eos_token_id": 2,
|
12 |
+
"hidden_act": "silu",
|
13 |
+
"hidden_size": 8192,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 28672,
|
16 |
+
"max_position_embeddings": 4096,
|
17 |
+
"model_type": "TriLMLinear",
|
18 |
+
"num_attention_heads": 64,
|
19 |
+
"num_hidden_layers": 80,
|
20 |
+
"num_key_value_heads": 8,
|
21 |
+
"pad_token_id": 0,
|
22 |
+
"rms_norm_eps": 1e-05,
|
23 |
+
"tie_word_embeddings": false,
|
24 |
+
"torch_dtype": "float16",
|
25 |
+
"transformers_version": "4.31.0.dev0",
|
26 |
+
"use_cache": true,
|
27 |
+
"vocab_size": 32000
|
28 |
+
}
|
Llama-2-70b-hf_trirun/configuration_trilmlinear.py
ADDED
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""TriLMLinear model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
24 |
+
|
25 |
+
|
26 |
+
class TriLMLinearConfig(PretrainedConfig):
|
27 |
+
r"""
|
28 |
+
This is the configuration class to store the configuration of a [`TriLMLinearModel`]. It is used to instantiate an LLaMA
|
29 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
30 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
31 |
+
|
32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
33 |
+
documentation from [`PretrainedConfig`] for more information.
|
34 |
+
|
35 |
+
|
36 |
+
Args:
|
37 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
38 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
39 |
+
`inputs_ids` passed when calling [`LlamaModel`]
|
40 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
41 |
+
Dimension of the hidden representations.
|
42 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
43 |
+
Dimension of the MLP representations.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
45 |
+
Number of hidden layers in the Transformer decoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
47 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
48 |
+
num_key_value_heads (`int`, *optional*):
|
49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
51 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
54 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
55 |
+
`num_attention_heads`.
|
56 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
57 |
+
The non-linear activation function (function or string) in the decoder.
|
58 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
59 |
+
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
60 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
64 |
+
The epsilon used by the rms normalization layers.
|
65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
67 |
+
relevant if `config.is_decoder=True`.
|
68 |
+
pad_token_id (`int`, *optional*):
|
69 |
+
Padding token id.
|
70 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
71 |
+
Beginning of stream token id.
|
72 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
73 |
+
End of stream token id.
|
74 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
75 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
76 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
|
77 |
+
understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
|
78 |
+
results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
|
79 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
80 |
+
Whether to tie weight embeddings
|
81 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
82 |
+
The base period of the RoPE embeddings.
|
83 |
+
rope_scaling (`Dict`, *optional*):
|
84 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
85 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
86 |
+
accordingly.
|
87 |
+
Expected contents:
|
88 |
+
`rope_type` (`str`):
|
89 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
90 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
91 |
+
`factor` (`float`, *optional*):
|
92 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
93 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
94 |
+
original maximum pre-trained length.
|
95 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
96 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
97 |
+
pretraining.
|
98 |
+
`attention_factor` (`float`, *optional*):
|
99 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
100 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
101 |
+
`factor` field to infer the suggested value.
|
102 |
+
`beta_fast` (`float`, *optional*):
|
103 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
104 |
+
ramp function. If unspecified, it defaults to 32.
|
105 |
+
`beta_slow` (`float`, *optional*):
|
106 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
107 |
+
ramp function. If unspecified, it defaults to 1.
|
108 |
+
`short_factor` (`List[float]`, *optional*):
|
109 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
110 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
111 |
+
size divided by the number of attention heads divided by 2
|
112 |
+
`long_factor` (`List[float]`, *optional*):
|
113 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
114 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
115 |
+
size divided by the number of attention heads divided by 2
|
116 |
+
`low_freq_factor` (`float`, *optional*):
|
117 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
118 |
+
`high_freq_factor` (`float`, *optional*):
|
119 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
120 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
121 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
122 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
123 |
+
The dropout ratio for the attention probabilities.
|
124 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
125 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
126 |
+
head_dim (`int`, *optional*):
|
127 |
+
The attention head dimension. If None, it will default to hidden_size // num_attention_heads
|
128 |
+
|
129 |
+
```python
|
130 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
131 |
+
|
132 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
133 |
+
>>> configuration = LlamaConfig()
|
134 |
+
|
135 |
+
>>> # Initializing a model from the llama-7b style configuration
|
136 |
+
>>> model = LlamaModel(configuration)
|
137 |
+
|
138 |
+
>>> # Accessing the model configuration
|
139 |
+
>>> configuration = model.config
|
140 |
+
```"""
|
141 |
+
|
142 |
+
model_type = "TriLMLinear"
|
143 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
144 |
+
# Default tensor parallel plan for base model `LlamaModel`
|
145 |
+
base_model_tp_plan = {
|
146 |
+
"layers.*.self_attn.q_proj": "colwise",
|
147 |
+
"layers.*.self_attn.k_proj": "colwise",
|
148 |
+
"layers.*.self_attn.v_proj": "colwise",
|
149 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
150 |
+
"layers.*.mlp.gate_proj": "colwise",
|
151 |
+
"layers.*.mlp.up_proj": "colwise",
|
152 |
+
"layers.*.mlp.down_proj": "rowwise",
|
153 |
+
}
|
154 |
+
|
155 |
+
def __init__(
|
156 |
+
self,
|
157 |
+
vocab_size=32000,
|
158 |
+
hidden_size=4096,
|
159 |
+
intermediate_size=11008,
|
160 |
+
num_hidden_layers=32,
|
161 |
+
num_attention_heads=32,
|
162 |
+
num_key_value_heads=None,
|
163 |
+
hidden_act="silu",
|
164 |
+
max_position_embeddings=2048,
|
165 |
+
initializer_range=0.02,
|
166 |
+
rms_norm_eps=1e-6,
|
167 |
+
use_cache=True,
|
168 |
+
pad_token_id=None,
|
169 |
+
bos_token_id=1,
|
170 |
+
eos_token_id=2,
|
171 |
+
pretraining_tp=1,
|
172 |
+
tie_word_embeddings=False,
|
173 |
+
rope_theta=10000.0,
|
174 |
+
rope_scaling=None,
|
175 |
+
attention_bias=False,
|
176 |
+
attention_dropout=0.0,
|
177 |
+
mlp_bias=False,
|
178 |
+
head_dim=None,
|
179 |
+
**kwargs,
|
180 |
+
):
|
181 |
+
self.vocab_size = vocab_size
|
182 |
+
self.max_position_embeddings = max_position_embeddings
|
183 |
+
self.hidden_size = hidden_size
|
184 |
+
self.intermediate_size = intermediate_size
|
185 |
+
self.num_hidden_layers = num_hidden_layers
|
186 |
+
self.num_attention_heads = num_attention_heads
|
187 |
+
|
188 |
+
# for backward compatibility
|
189 |
+
if num_key_value_heads is None:
|
190 |
+
num_key_value_heads = num_attention_heads
|
191 |
+
|
192 |
+
self.num_key_value_heads = num_key_value_heads
|
193 |
+
self.hidden_act = hidden_act
|
194 |
+
self.initializer_range = initializer_range
|
195 |
+
self.rms_norm_eps = rms_norm_eps
|
196 |
+
self.pretraining_tp = pretraining_tp
|
197 |
+
self.use_cache = use_cache
|
198 |
+
self.rope_theta = rope_theta
|
199 |
+
self.rope_scaling = rope_scaling
|
200 |
+
self.attention_bias = attention_bias
|
201 |
+
self.attention_dropout = attention_dropout
|
202 |
+
self.mlp_bias = mlp_bias
|
203 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
204 |
+
# Validate the correctness of rotary position embeddings parameters
|
205 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
206 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
207 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
208 |
+
rope_config_validation(self)
|
209 |
+
|
210 |
+
super().__init__(
|
211 |
+
pad_token_id=pad_token_id,
|
212 |
+
bos_token_id=bos_token_id,
|
213 |
+
eos_token_id=eos_token_id,
|
214 |
+
tie_word_embeddings=tie_word_embeddings,
|
215 |
+
**kwargs,
|
216 |
+
)
|
217 |
+
|
218 |
+
|
219 |
+
__all__ = ["TriLMLinearConfig"]
|
220 |
+
|
Llama-2-70b-hf_trirun/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fb38bfe167c571952327da9671fa4e8852b17fe02e49d0f2b0d874c66f977219
|
3 |
+
size 18177560848
|
Llama-2-70b-hf_trirun/modeling_trilmlinear.py
ADDED
@@ -0,0 +1,1037 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from typing import Callable, List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
|
26 |
+
from transformers.activations import ACT2FN
|
27 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
28 |
+
from transformers.generation import GenerationMixin
|
29 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
30 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
31 |
+
from transformers.modeling_outputs import (
|
32 |
+
BaseModelOutputWithPast,
|
33 |
+
CausalLMOutputWithPast,
|
34 |
+
QuestionAnsweringModelOutput,
|
35 |
+
SequenceClassifierOutputWithPast,
|
36 |
+
TokenClassifierOutput,
|
37 |
+
)
|
38 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
39 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
40 |
+
from transformers.processing_utils import Unpack
|
41 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
42 |
+
from transformers.utils import (
|
43 |
+
LossKwargs,
|
44 |
+
add_code_sample_docstrings,
|
45 |
+
add_start_docstrings,
|
46 |
+
add_start_docstrings_to_model_forward,
|
47 |
+
logging,
|
48 |
+
replace_return_docstrings,
|
49 |
+
)
|
50 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
51 |
+
from .configuration_trilmlinear import TriLMLinearConfig
|
52 |
+
import marlin
|
53 |
+
|
54 |
+
logger = logging.get_logger(__name__)
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
class TriLMLinear(torch.nn.Module):
|
59 |
+
def __init__(self, in_dims, out_dims, thread_k=128, thread_n=128, groupsize=-1, sms=-1):
|
60 |
+
super(TriLMLinear, self).__init__()
|
61 |
+
self.in_dims, self.out_dims = in_dims, out_dims
|
62 |
+
self.thread_k, self.thread_n, self.groupsize, self.sms = thread_k, thread_n, groupsize, sms
|
63 |
+
packed_weight = torch.ones((in_dims//16, out_dims), dtype=torch.int32)
|
64 |
+
scales = torch.ones((1, out_dims), dtype=torch.float16)
|
65 |
+
self.register_buffer("packed_weight", packed_weight)
|
66 |
+
self.register_buffer("scales", scales)
|
67 |
+
self.workspace = torch.zeros(self.out_dims // 128 * 16, device="cuda")
|
68 |
+
def forward(self, hidden_state):
|
69 |
+
# print(A, self.name)
|
70 |
+
batch_size, seqlen, last_dim = hidden_state.shape
|
71 |
+
output = torch.zeros((batch_size * seqlen, self.out_dims), dtype=torch.float16, device=self.packed_weight.device)
|
72 |
+
marlin.mul(hidden_state.reshape(batch_size * seqlen, last_dim).contiguous(), self.packed_weight, output, self.scales,
|
73 |
+
self.workspace, self.thread_k, self.thread_n, self.sms)
|
74 |
+
return output.reshape(batch_size, seqlen, -1)
|
75 |
+
|
76 |
+
|
77 |
+
class TriLMLinearRMSNorm(nn.Module):
|
78 |
+
def __init__(self, hidden_size, eps=1e-6):
|
79 |
+
"""
|
80 |
+
TriLMLinearRMSNorm is equivalent to T5LayerNorm
|
81 |
+
"""
|
82 |
+
super().__init__()
|
83 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
84 |
+
self.variance_epsilon = eps
|
85 |
+
|
86 |
+
def forward(self, hidden_states):
|
87 |
+
input_dtype = hidden_states.dtype
|
88 |
+
hidden_states = hidden_states.to(torch.float32)
|
89 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
90 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
91 |
+
return self.weight * hidden_states.to(input_dtype)
|
92 |
+
|
93 |
+
def extra_repr(self):
|
94 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
95 |
+
|
96 |
+
|
97 |
+
ALL_LAYERNORM_LAYERS.append(TriLMLinearRMSNorm)
|
98 |
+
|
99 |
+
|
100 |
+
class TriLMLinearRotaryEmbedding(nn.Module):
|
101 |
+
def __init__(self, config: TriLMLinearConfig, device=None):
|
102 |
+
super().__init__()
|
103 |
+
# BC: "rope_type" was originally "type"
|
104 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
105 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
106 |
+
else:
|
107 |
+
self.rope_type = "default"
|
108 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
109 |
+
self.original_max_seq_len = config.max_position_embeddings
|
110 |
+
|
111 |
+
self.config = config
|
112 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
113 |
+
|
114 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
115 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
116 |
+
self.original_inv_freq = self.inv_freq
|
117 |
+
|
118 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
119 |
+
"""
|
120 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
121 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
122 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
123 |
+
"""
|
124 |
+
seq_len = torch.max(position_ids) + 1
|
125 |
+
if seq_len > self.max_seq_len_cached: # growth
|
126 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
127 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
128 |
+
self.max_seq_len_cached = seq_len
|
129 |
+
|
130 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
131 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
132 |
+
# the buffer is automatically moved, but not the original copy)
|
133 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
134 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
135 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
136 |
+
|
137 |
+
@torch.no_grad()
|
138 |
+
def forward(self, x, position_ids):
|
139 |
+
if "dynamic" in self.rope_type:
|
140 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
141 |
+
|
142 |
+
# Core RoPE block
|
143 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
144 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
145 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
146 |
+
device_type = x.device.type
|
147 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
148 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
149 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
150 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
151 |
+
cos = emb.cos()
|
152 |
+
sin = emb.sin()
|
153 |
+
|
154 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
155 |
+
cos = cos * self.attention_scaling
|
156 |
+
sin = sin * self.attention_scaling
|
157 |
+
|
158 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
159 |
+
|
160 |
+
|
161 |
+
def rotate_half(x):
|
162 |
+
"""Rotates half the hidden dims of the input."""
|
163 |
+
x1 = x[..., : x.shape[-1] // 2]
|
164 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
165 |
+
return torch.cat((-x2, x1), dim=-1)
|
166 |
+
|
167 |
+
|
168 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
169 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
170 |
+
|
171 |
+
Args:
|
172 |
+
q (`torch.Tensor`): The query tensor.
|
173 |
+
k (`torch.Tensor`): The key tensor.
|
174 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
175 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
176 |
+
position_ids (`torch.Tensor`, *optional*):
|
177 |
+
Deprecated and unused.
|
178 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
179 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
180 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
181 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
182 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
183 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
184 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
185 |
+
Returns:
|
186 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
187 |
+
"""
|
188 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
189 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
190 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
191 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
192 |
+
return q_embed, k_embed
|
193 |
+
|
194 |
+
|
195 |
+
class TriLMLinearMLP(nn.Module):
|
196 |
+
def __init__(self, config):
|
197 |
+
super().__init__()
|
198 |
+
self.config = config
|
199 |
+
self.hidden_size = config.hidden_size
|
200 |
+
self.intermediate_size = config.intermediate_size
|
201 |
+
assert config.mlp_bias == False, config.mlp_bias
|
202 |
+
self.gate_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
203 |
+
self.up_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
204 |
+
self.down_proj = TriLMLinear(self.intermediate_size, self.hidden_size)
|
205 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
206 |
+
|
207 |
+
def forward(self, x):
|
208 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
209 |
+
return down_proj
|
210 |
+
|
211 |
+
|
212 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
213 |
+
"""
|
214 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
215 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
216 |
+
"""
|
217 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
218 |
+
if n_rep == 1:
|
219 |
+
return hidden_states
|
220 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
221 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
222 |
+
|
223 |
+
|
224 |
+
def eager_attention_forward(
|
225 |
+
module: nn.Module,
|
226 |
+
query: torch.Tensor,
|
227 |
+
key: torch.Tensor,
|
228 |
+
value: torch.Tensor,
|
229 |
+
attention_mask: Optional[torch.Tensor],
|
230 |
+
scaling: float,
|
231 |
+
dropout: float = 0.0,
|
232 |
+
**kwargs,
|
233 |
+
):
|
234 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
235 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
236 |
+
|
237 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
238 |
+
if attention_mask is not None:
|
239 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
240 |
+
attn_weights = attn_weights + causal_mask
|
241 |
+
|
242 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
243 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
244 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
245 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
246 |
+
|
247 |
+
return attn_output, attn_weights
|
248 |
+
|
249 |
+
|
250 |
+
class TriLMLinearAttention(nn.Module):
|
251 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
252 |
+
|
253 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
254 |
+
super().__init__()
|
255 |
+
self.config = config
|
256 |
+
self.layer_idx = layer_idx
|
257 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
258 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
259 |
+
self.scaling = self.head_dim**-0.5
|
260 |
+
self.attention_dropout = config.attention_dropout
|
261 |
+
self.is_causal = True
|
262 |
+
assert config.attention_bias == False
|
263 |
+
self.q_proj = TriLMLinear(
|
264 |
+
config.hidden_size, config.num_attention_heads * self.head_dim#, bias=config.attention_bias
|
265 |
+
)
|
266 |
+
self.k_proj = TriLMLinear(
|
267 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
268 |
+
)
|
269 |
+
self.v_proj = TriLMLinear(
|
270 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
271 |
+
)
|
272 |
+
self.o_proj = TriLMLinear(
|
273 |
+
config.num_attention_heads * self.head_dim, config.hidden_size#, bias=config.attention_bias
|
274 |
+
)
|
275 |
+
|
276 |
+
def forward(
|
277 |
+
self,
|
278 |
+
hidden_states: torch.Tensor,
|
279 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
280 |
+
attention_mask: Optional[torch.Tensor],
|
281 |
+
past_key_value: Optional[Cache] = None,
|
282 |
+
cache_position: Optional[torch.LongTensor] = None,
|
283 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
284 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
285 |
+
input_shape = hidden_states.shape[:-1]
|
286 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
287 |
+
|
288 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
289 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
290 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
291 |
+
|
292 |
+
cos, sin = position_embeddings
|
293 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
294 |
+
|
295 |
+
if past_key_value is not None:
|
296 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
297 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
298 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
299 |
+
|
300 |
+
attention_interface: Callable = eager_attention_forward
|
301 |
+
if self.config._attn_implementation != "eager":
|
302 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
303 |
+
logger.warning_once(
|
304 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
305 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
306 |
+
)
|
307 |
+
else:
|
308 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
309 |
+
|
310 |
+
attn_output, attn_weights = attention_interface(
|
311 |
+
self,
|
312 |
+
query_states,
|
313 |
+
key_states,
|
314 |
+
value_states,
|
315 |
+
attention_mask,
|
316 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
317 |
+
scaling=self.scaling,
|
318 |
+
**kwargs,
|
319 |
+
)
|
320 |
+
|
321 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
322 |
+
attn_output = self.o_proj(attn_output)
|
323 |
+
return attn_output, attn_weights
|
324 |
+
|
325 |
+
|
326 |
+
class TriLMLinearDecoderLayer(nn.Module):
|
327 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
328 |
+
super().__init__()
|
329 |
+
self.hidden_size = config.hidden_size
|
330 |
+
|
331 |
+
self.self_attn = TriLMLinearAttention(config=config, layer_idx=layer_idx)
|
332 |
+
|
333 |
+
self.mlp = TriLMLinearMLP(config)
|
334 |
+
self.input_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
335 |
+
self.post_attention_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
336 |
+
|
337 |
+
def forward(
|
338 |
+
self,
|
339 |
+
hidden_states: torch.Tensor,
|
340 |
+
attention_mask: Optional[torch.Tensor] = None,
|
341 |
+
position_ids: Optional[torch.LongTensor] = None,
|
342 |
+
past_key_value: Optional[Cache] = None,
|
343 |
+
output_attentions: Optional[bool] = False,
|
344 |
+
use_cache: Optional[bool] = False,
|
345 |
+
cache_position: Optional[torch.LongTensor] = None,
|
346 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
347 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
348 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
349 |
+
residual = hidden_states
|
350 |
+
|
351 |
+
hidden_states = self.input_layernorm(hidden_states)
|
352 |
+
|
353 |
+
# Self Attention
|
354 |
+
hidden_states, self_attn_weights = self.self_attn(
|
355 |
+
hidden_states=hidden_states,
|
356 |
+
attention_mask=attention_mask,
|
357 |
+
position_ids=position_ids,
|
358 |
+
past_key_value=past_key_value,
|
359 |
+
output_attentions=output_attentions,
|
360 |
+
use_cache=use_cache,
|
361 |
+
cache_position=cache_position,
|
362 |
+
position_embeddings=position_embeddings,
|
363 |
+
**kwargs,
|
364 |
+
)
|
365 |
+
hidden_states = residual + hidden_states
|
366 |
+
|
367 |
+
# Fully Connected
|
368 |
+
residual = hidden_states
|
369 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
370 |
+
hidden_states = self.mlp(hidden_states)
|
371 |
+
hidden_states = residual + hidden_states
|
372 |
+
|
373 |
+
outputs = (hidden_states,)
|
374 |
+
if output_attentions:
|
375 |
+
outputs += (self_attn_weights,)
|
376 |
+
|
377 |
+
return outputs
|
378 |
+
|
379 |
+
|
380 |
+
class TriLMLinearPreTrainedModel(PreTrainedModel):
|
381 |
+
config_class = TriLMLinearConfig
|
382 |
+
base_model_prefix = "model"
|
383 |
+
supports_gradient_checkpointing = True
|
384 |
+
_no_split_modules = ["TriLMLinearDecoderLayer"]
|
385 |
+
_skip_keys_device_placement = ["past_key_values"]
|
386 |
+
_supports_flash_attn_2 = True
|
387 |
+
_supports_sdpa = True
|
388 |
+
_supports_flex_attn = True
|
389 |
+
_supports_cache_class = True
|
390 |
+
_supports_quantized_cache = True
|
391 |
+
_supports_static_cache = True
|
392 |
+
_supports_attention_backend = True
|
393 |
+
|
394 |
+
def _init_weights(self, module):
|
395 |
+
std = self.config.initializer_range
|
396 |
+
if isinstance(module, nn.Linear):
|
397 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
398 |
+
if module.bias is not None:
|
399 |
+
module.bias.data.zero_()
|
400 |
+
elif isinstance(module, nn.Embedding):
|
401 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
402 |
+
if module.padding_idx is not None:
|
403 |
+
module.weight.data[module.padding_idx].zero_()
|
404 |
+
|
405 |
+
|
406 |
+
|
407 |
+
|
408 |
+
class TriLMLinearModel(TriLMLinearPreTrainedModel):
|
409 |
+
"""
|
410 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TriLMLinearDecoderLayer`]
|
411 |
+
|
412 |
+
Args:
|
413 |
+
config: TriLMLinearConfig
|
414 |
+
"""
|
415 |
+
|
416 |
+
def __init__(self, config: TriLMLinearConfig):
|
417 |
+
super().__init__(config)
|
418 |
+
self.padding_idx = config.pad_token_id
|
419 |
+
self.vocab_size = config.vocab_size
|
420 |
+
|
421 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
422 |
+
self.layers = nn.ModuleList(
|
423 |
+
[TriLMLinearDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
424 |
+
)
|
425 |
+
self.norm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
426 |
+
self.rotary_emb = TriLMLinearRotaryEmbedding(config=config)
|
427 |
+
self.gradient_checkpointing = False
|
428 |
+
|
429 |
+
# Initialize weights and apply final processing
|
430 |
+
self.post_init()
|
431 |
+
|
432 |
+
def get_input_embeddings(self):
|
433 |
+
return self.embed_tokens
|
434 |
+
|
435 |
+
def set_input_embeddings(self, value):
|
436 |
+
self.embed_tokens = value
|
437 |
+
|
438 |
+
def forward(
|
439 |
+
self,
|
440 |
+
input_ids: torch.LongTensor = None,
|
441 |
+
attention_mask: Optional[torch.Tensor] = None,
|
442 |
+
position_ids: Optional[torch.LongTensor] = None,
|
443 |
+
past_key_values: Optional[Cache] = None,
|
444 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
445 |
+
use_cache: Optional[bool] = None,
|
446 |
+
output_attentions: Optional[bool] = None,
|
447 |
+
output_hidden_states: Optional[bool] = None,
|
448 |
+
return_dict: Optional[bool] = None,
|
449 |
+
cache_position: Optional[torch.LongTensor] = None,
|
450 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
451 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
452 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
453 |
+
output_hidden_states = (
|
454 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
455 |
+
)
|
456 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
457 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
458 |
+
|
459 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
460 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
461 |
+
|
462 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
463 |
+
logger.warning_once(
|
464 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
465 |
+
)
|
466 |
+
use_cache = False
|
467 |
+
|
468 |
+
if inputs_embeds is None:
|
469 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
470 |
+
|
471 |
+
if use_cache and past_key_values is None:
|
472 |
+
past_key_values = DynamicCache()
|
473 |
+
|
474 |
+
if cache_position is None:
|
475 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
476 |
+
cache_position = torch.arange(
|
477 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
478 |
+
)
|
479 |
+
|
480 |
+
if position_ids is None:
|
481 |
+
position_ids = cache_position.unsqueeze(0)
|
482 |
+
|
483 |
+
causal_mask = self._update_causal_mask(
|
484 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
485 |
+
)
|
486 |
+
|
487 |
+
hidden_states = inputs_embeds
|
488 |
+
|
489 |
+
# create position embeddings to be shared across the decoder layers
|
490 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
491 |
+
|
492 |
+
# decoder layers
|
493 |
+
all_hidden_states = () if output_hidden_states else None
|
494 |
+
all_self_attns = () if output_attentions else None
|
495 |
+
|
496 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
497 |
+
if output_hidden_states:
|
498 |
+
all_hidden_states += (hidden_states,)
|
499 |
+
|
500 |
+
if self.gradient_checkpointing and self.training:
|
501 |
+
layer_outputs = self._gradient_checkpointing_func(
|
502 |
+
decoder_layer.__call__,
|
503 |
+
hidden_states,
|
504 |
+
causal_mask,
|
505 |
+
position_ids,
|
506 |
+
past_key_values,
|
507 |
+
output_attentions,
|
508 |
+
use_cache,
|
509 |
+
cache_position,
|
510 |
+
position_embeddings,
|
511 |
+
)
|
512 |
+
else:
|
513 |
+
layer_outputs = decoder_layer(
|
514 |
+
hidden_states,
|
515 |
+
attention_mask=causal_mask,
|
516 |
+
position_ids=position_ids,
|
517 |
+
past_key_value=past_key_values,
|
518 |
+
output_attentions=output_attentions,
|
519 |
+
use_cache=use_cache,
|
520 |
+
cache_position=cache_position,
|
521 |
+
position_embeddings=position_embeddings,
|
522 |
+
**flash_attn_kwargs,
|
523 |
+
)
|
524 |
+
|
525 |
+
hidden_states = layer_outputs[0]
|
526 |
+
|
527 |
+
if output_attentions:
|
528 |
+
all_self_attns += (layer_outputs[1],)
|
529 |
+
|
530 |
+
hidden_states = self.norm(hidden_states)
|
531 |
+
|
532 |
+
# add hidden states from the last decoder layer
|
533 |
+
if output_hidden_states:
|
534 |
+
all_hidden_states += (hidden_states,)
|
535 |
+
|
536 |
+
output = BaseModelOutputWithPast(
|
537 |
+
last_hidden_state=hidden_states,
|
538 |
+
past_key_values=past_key_values if use_cache else None,
|
539 |
+
hidden_states=all_hidden_states,
|
540 |
+
attentions=all_self_attns,
|
541 |
+
)
|
542 |
+
return output if return_dict else output.to_tuple()
|
543 |
+
|
544 |
+
def _update_causal_mask(
|
545 |
+
self,
|
546 |
+
attention_mask: torch.Tensor,
|
547 |
+
input_tensor: torch.Tensor,
|
548 |
+
cache_position: torch.Tensor,
|
549 |
+
past_key_values: Cache,
|
550 |
+
output_attentions: bool,
|
551 |
+
):
|
552 |
+
if self.config._attn_implementation == "flash_attention_2":
|
553 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
554 |
+
return attention_mask
|
555 |
+
return None
|
556 |
+
|
557 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
558 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
559 |
+
# to infer the attention mask.
|
560 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
561 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
562 |
+
|
563 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
564 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
565 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
566 |
+
attention_mask,
|
567 |
+
inputs_embeds=input_tensor,
|
568 |
+
past_key_values_length=past_seen_tokens,
|
569 |
+
is_training=self.training,
|
570 |
+
):
|
571 |
+
return None
|
572 |
+
|
573 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
574 |
+
sequence_length = input_tensor.shape[1]
|
575 |
+
if using_static_cache:
|
576 |
+
target_length = past_key_values.get_max_cache_shape()
|
577 |
+
else:
|
578 |
+
target_length = (
|
579 |
+
attention_mask.shape[-1]
|
580 |
+
if isinstance(attention_mask, torch.Tensor)
|
581 |
+
else past_seen_tokens + sequence_length + 1
|
582 |
+
)
|
583 |
+
|
584 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
585 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
586 |
+
attention_mask,
|
587 |
+
sequence_length=sequence_length,
|
588 |
+
target_length=target_length,
|
589 |
+
dtype=dtype,
|
590 |
+
device=device,
|
591 |
+
cache_position=cache_position,
|
592 |
+
batch_size=input_tensor.shape[0],
|
593 |
+
)
|
594 |
+
|
595 |
+
if (
|
596 |
+
self.config._attn_implementation == "sdpa"
|
597 |
+
and attention_mask is not None
|
598 |
+
and attention_mask.device.type == "cuda"
|
599 |
+
and not output_attentions
|
600 |
+
):
|
601 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
602 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
603 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
604 |
+
min_dtype = torch.finfo(dtype).min
|
605 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
606 |
+
|
607 |
+
return causal_mask
|
608 |
+
|
609 |
+
@staticmethod
|
610 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
611 |
+
attention_mask: torch.Tensor,
|
612 |
+
sequence_length: int,
|
613 |
+
target_length: int,
|
614 |
+
dtype: torch.dtype,
|
615 |
+
device: torch.device,
|
616 |
+
cache_position: torch.Tensor,
|
617 |
+
batch_size: int,
|
618 |
+
**kwargs,
|
619 |
+
):
|
620 |
+
"""
|
621 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
622 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
623 |
+
|
624 |
+
Args:
|
625 |
+
attention_mask (`torch.Tensor`):
|
626 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
627 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
628 |
+
sequence_length (`int`):
|
629 |
+
The sequence length being processed.
|
630 |
+
target_length (`int`):
|
631 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
632 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
633 |
+
dtype (`torch.dtype`):
|
634 |
+
The dtype to use for the 4D attention mask.
|
635 |
+
device (`torch.device`):
|
636 |
+
The device to plcae the 4D attention mask on.
|
637 |
+
cache_position (`torch.Tensor`):
|
638 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
639 |
+
batch_size (`torch.Tensor`):
|
640 |
+
Batch size.
|
641 |
+
"""
|
642 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
643 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
644 |
+
causal_mask = attention_mask
|
645 |
+
else:
|
646 |
+
min_dtype = torch.finfo(dtype).min
|
647 |
+
causal_mask = torch.full(
|
648 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
649 |
+
)
|
650 |
+
if sequence_length != 1:
|
651 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
652 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
653 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
654 |
+
if attention_mask is not None:
|
655 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
656 |
+
mask_length = attention_mask.shape[-1]
|
657 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
658 |
+
padding_mask = padding_mask == 0
|
659 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
660 |
+
padding_mask, min_dtype
|
661 |
+
)
|
662 |
+
|
663 |
+
return causal_mask
|
664 |
+
|
665 |
+
|
666 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
667 |
+
|
668 |
+
|
669 |
+
class TriLMLinearForCausalLM(TriLMLinearPreTrainedModel, GenerationMixin):
|
670 |
+
_tied_weights_keys = ["lm_head.weight"]
|
671 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
672 |
+
|
673 |
+
def __init__(self, config):
|
674 |
+
super().__init__(config)
|
675 |
+
self.model = TriLMLinearModel(config)
|
676 |
+
self.vocab_size = config.vocab_size
|
677 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
678 |
+
|
679 |
+
# Initialize weights and apply final processing
|
680 |
+
self.post_init()
|
681 |
+
|
682 |
+
def get_input_embeddings(self):
|
683 |
+
return self.model.embed_tokens
|
684 |
+
|
685 |
+
def set_input_embeddings(self, value):
|
686 |
+
self.model.embed_tokens = value
|
687 |
+
|
688 |
+
def get_output_embeddings(self):
|
689 |
+
return self.lm_head
|
690 |
+
|
691 |
+
def set_output_embeddings(self, new_embeddings):
|
692 |
+
self.lm_head = new_embeddings
|
693 |
+
|
694 |
+
def set_decoder(self, decoder):
|
695 |
+
self.model = decoder
|
696 |
+
|
697 |
+
def get_decoder(self):
|
698 |
+
return self.model
|
699 |
+
|
700 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
701 |
+
def forward(
|
702 |
+
self,
|
703 |
+
input_ids: torch.LongTensor = None,
|
704 |
+
attention_mask: Optional[torch.Tensor] = None,
|
705 |
+
position_ids: Optional[torch.LongTensor] = None,
|
706 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
707 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
708 |
+
labels: Optional[torch.LongTensor] = None,
|
709 |
+
use_cache: Optional[bool] = None,
|
710 |
+
output_attentions: Optional[bool] = None,
|
711 |
+
output_hidden_states: Optional[bool] = None,
|
712 |
+
return_dict: Optional[bool] = None,
|
713 |
+
cache_position: Optional[torch.LongTensor] = None,
|
714 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
715 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
716 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
717 |
+
r"""
|
718 |
+
Args:
|
719 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
720 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
721 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
722 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
723 |
+
|
724 |
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
725 |
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
726 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
727 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
728 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
729 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
730 |
+
|
731 |
+
Returns:
|
732 |
+
|
733 |
+
Example:
|
734 |
+
|
735 |
+
```python
|
736 |
+
>>> from transformers import AutoTokenizer, TriLMLinearForCausalLM
|
737 |
+
|
738 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
739 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
740 |
+
|
741 |
+
>>> # Generate
|
742 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
743 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
744 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
745 |
+
```"""
|
746 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
747 |
+
output_hidden_states = (
|
748 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
749 |
+
)
|
750 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
751 |
+
|
752 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
753 |
+
outputs = self.model(
|
754 |
+
input_ids=input_ids,
|
755 |
+
attention_mask=attention_mask,
|
756 |
+
position_ids=position_ids,
|
757 |
+
past_key_values=past_key_values,
|
758 |
+
inputs_embeds=inputs_embeds,
|
759 |
+
use_cache=use_cache,
|
760 |
+
output_attentions=output_attentions,
|
761 |
+
output_hidden_states=output_hidden_states,
|
762 |
+
return_dict=return_dict,
|
763 |
+
cache_position=cache_position,
|
764 |
+
**kwargs,
|
765 |
+
)
|
766 |
+
|
767 |
+
hidden_states = outputs[0]
|
768 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
769 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
770 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
771 |
+
|
772 |
+
loss = None
|
773 |
+
if labels is not None:
|
774 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
775 |
+
|
776 |
+
if not return_dict:
|
777 |
+
output = (logits,) + outputs[1:]
|
778 |
+
return (loss,) + output if loss is not None else output
|
779 |
+
|
780 |
+
return CausalLMOutputWithPast(
|
781 |
+
loss=loss,
|
782 |
+
logits=logits,
|
783 |
+
past_key_values=outputs.past_key_values,
|
784 |
+
hidden_states=outputs.hidden_states,
|
785 |
+
attentions=outputs.attentions,
|
786 |
+
)
|
787 |
+
|
788 |
+
|
789 |
+
class TriLMLinearForSequenceClassification(TriLMLinearPreTrainedModel):
|
790 |
+
def __init__(self, config):
|
791 |
+
super().__init__(config)
|
792 |
+
self.num_labels = config.num_labels
|
793 |
+
self.model = TriLMLinearModel(config)
|
794 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
795 |
+
|
796 |
+
# Initialize weights and apply final processing
|
797 |
+
self.post_init()
|
798 |
+
|
799 |
+
def get_input_embeddings(self):
|
800 |
+
return self.model.embed_tokens
|
801 |
+
|
802 |
+
def set_input_embeddings(self, value):
|
803 |
+
self.model.embed_tokens = value
|
804 |
+
|
805 |
+
def forward(
|
806 |
+
self,
|
807 |
+
input_ids: Optional[torch.LongTensor] = None,
|
808 |
+
attention_mask: Optional[torch.Tensor] = None,
|
809 |
+
position_ids: Optional[torch.LongTensor] = None,
|
810 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
811 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
812 |
+
labels: Optional[torch.LongTensor] = None,
|
813 |
+
use_cache: Optional[bool] = None,
|
814 |
+
output_attentions: Optional[bool] = None,
|
815 |
+
output_hidden_states: Optional[bool] = None,
|
816 |
+
return_dict: Optional[bool] = None,
|
817 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
818 |
+
r"""
|
819 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
820 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
821 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
822 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
823 |
+
"""
|
824 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
825 |
+
|
826 |
+
transformer_outputs = self.model(
|
827 |
+
input_ids,
|
828 |
+
attention_mask=attention_mask,
|
829 |
+
position_ids=position_ids,
|
830 |
+
past_key_values=past_key_values,
|
831 |
+
inputs_embeds=inputs_embeds,
|
832 |
+
use_cache=use_cache,
|
833 |
+
output_attentions=output_attentions,
|
834 |
+
output_hidden_states=output_hidden_states,
|
835 |
+
return_dict=return_dict,
|
836 |
+
)
|
837 |
+
hidden_states = transformer_outputs[0]
|
838 |
+
logits = self.score(hidden_states)
|
839 |
+
|
840 |
+
if input_ids is not None:
|
841 |
+
batch_size = input_ids.shape[0]
|
842 |
+
else:
|
843 |
+
batch_size = inputs_embeds.shape[0]
|
844 |
+
|
845 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
846 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
847 |
+
if self.config.pad_token_id is None:
|
848 |
+
sequence_lengths = -1
|
849 |
+
else:
|
850 |
+
if input_ids is not None:
|
851 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
852 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
853 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
854 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
855 |
+
else:
|
856 |
+
sequence_lengths = -1
|
857 |
+
|
858 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
859 |
+
|
860 |
+
loss = None
|
861 |
+
if labels is not None:
|
862 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
863 |
+
|
864 |
+
if not return_dict:
|
865 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
866 |
+
return ((loss,) + output) if loss is not None else output
|
867 |
+
|
868 |
+
return SequenceClassifierOutputWithPast(
|
869 |
+
loss=loss,
|
870 |
+
logits=pooled_logits,
|
871 |
+
past_key_values=transformer_outputs.past_key_values,
|
872 |
+
hidden_states=transformer_outputs.hidden_states,
|
873 |
+
attentions=transformer_outputs.attentions,
|
874 |
+
)
|
875 |
+
|
876 |
+
|
877 |
+
class TriLMLinearForQuestionAnswering(TriLMLinearPreTrainedModel):
|
878 |
+
base_model_prefix = "transformer"
|
879 |
+
|
880 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->TriLMLinear
|
881 |
+
def __init__(self, config):
|
882 |
+
super().__init__(config)
|
883 |
+
self.transformer = TriLMLinearModel(config)
|
884 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
885 |
+
|
886 |
+
# Initialize weights and apply final processing
|
887 |
+
self.post_init()
|
888 |
+
|
889 |
+
def get_input_embeddings(self):
|
890 |
+
return self.transformer.embed_tokens
|
891 |
+
|
892 |
+
def set_input_embeddings(self, value):
|
893 |
+
self.transformer.embed_tokens = value
|
894 |
+
|
895 |
+
def forward(
|
896 |
+
self,
|
897 |
+
input_ids: Optional[torch.LongTensor] = None,
|
898 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
899 |
+
position_ids: Optional[torch.LongTensor] = None,
|
900 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
901 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
902 |
+
start_positions: Optional[torch.LongTensor] = None,
|
903 |
+
end_positions: Optional[torch.LongTensor] = None,
|
904 |
+
output_attentions: Optional[bool] = None,
|
905 |
+
output_hidden_states: Optional[bool] = None,
|
906 |
+
return_dict: Optional[bool] = None,
|
907 |
+
**kwargs,
|
908 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
909 |
+
r"""
|
910 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
911 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
912 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
913 |
+
are not taken into account for computing the loss.
|
914 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
915 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
916 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
917 |
+
are not taken into account for computing the loss.
|
918 |
+
"""
|
919 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
920 |
+
|
921 |
+
outputs = self.transformer(
|
922 |
+
input_ids,
|
923 |
+
attention_mask=attention_mask,
|
924 |
+
position_ids=position_ids,
|
925 |
+
past_key_values=past_key_values,
|
926 |
+
inputs_embeds=inputs_embeds,
|
927 |
+
output_attentions=output_attentions,
|
928 |
+
output_hidden_states=output_hidden_states,
|
929 |
+
return_dict=return_dict,
|
930 |
+
)
|
931 |
+
|
932 |
+
sequence_output = outputs[0]
|
933 |
+
|
934 |
+
logits = self.qa_outputs(sequence_output)
|
935 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
936 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
937 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
938 |
+
|
939 |
+
loss = None
|
940 |
+
if start_positions is not None and end_positions is not None:
|
941 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
942 |
+
|
943 |
+
if not return_dict:
|
944 |
+
output = (start_logits, end_logits) + outputs[2:]
|
945 |
+
return ((loss,) + output) if loss is not None else output
|
946 |
+
|
947 |
+
return QuestionAnsweringModelOutput(
|
948 |
+
loss=loss,
|
949 |
+
start_logits=start_logits,
|
950 |
+
end_logits=end_logits,
|
951 |
+
hidden_states=outputs.hidden_states,
|
952 |
+
attentions=outputs.attentions,
|
953 |
+
)
|
954 |
+
|
955 |
+
class TriLMLinearForTokenClassification(TriLMLinearPreTrainedModel):
|
956 |
+
def __init__(self, config):
|
957 |
+
super().__init__(config)
|
958 |
+
self.num_labels = config.num_labels
|
959 |
+
self.model = TriLMLinearModel(config)
|
960 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
961 |
+
classifier_dropout = config.classifier_dropout
|
962 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
963 |
+
classifier_dropout = config.hidden_dropout
|
964 |
+
else:
|
965 |
+
classifier_dropout = 0.1
|
966 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
967 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
968 |
+
|
969 |
+
# Initialize weights and apply final processing
|
970 |
+
self.post_init()
|
971 |
+
|
972 |
+
def get_input_embeddings(self):
|
973 |
+
return self.model.embed_tokens
|
974 |
+
|
975 |
+
def set_input_embeddings(self, value):
|
976 |
+
self.model.embed_tokens = value
|
977 |
+
|
978 |
+
def forward(
|
979 |
+
self,
|
980 |
+
input_ids: Optional[torch.LongTensor] = None,
|
981 |
+
attention_mask: Optional[torch.Tensor] = None,
|
982 |
+
position_ids: Optional[torch.LongTensor] = None,
|
983 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
984 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
985 |
+
labels: Optional[torch.LongTensor] = None,
|
986 |
+
use_cache: Optional[bool] = None,
|
987 |
+
output_attentions: Optional[bool] = None,
|
988 |
+
output_hidden_states: Optional[bool] = None,
|
989 |
+
return_dict: Optional[bool] = None,
|
990 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
991 |
+
r"""
|
992 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
993 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
994 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
995 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
996 |
+
"""
|
997 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
998 |
+
|
999 |
+
outputs = self.model(
|
1000 |
+
input_ids,
|
1001 |
+
attention_mask=attention_mask,
|
1002 |
+
position_ids=position_ids,
|
1003 |
+
past_key_values=past_key_values,
|
1004 |
+
inputs_embeds=inputs_embeds,
|
1005 |
+
use_cache=use_cache,
|
1006 |
+
output_attentions=output_attentions,
|
1007 |
+
output_hidden_states=output_hidden_states,
|
1008 |
+
return_dict=return_dict,
|
1009 |
+
)
|
1010 |
+
sequence_output = outputs[0]
|
1011 |
+
sequence_output = self.dropout(sequence_output)
|
1012 |
+
logits = self.score(sequence_output)
|
1013 |
+
|
1014 |
+
loss = None
|
1015 |
+
if labels is not None:
|
1016 |
+
loss = self.loss_function(logits, labels, self.config)
|
1017 |
+
|
1018 |
+
if not return_dict:
|
1019 |
+
output = (logits,) + outputs[2:]
|
1020 |
+
return ((loss,) + output) if loss is not None else output
|
1021 |
+
|
1022 |
+
return TokenClassifierOutput(
|
1023 |
+
loss=loss,
|
1024 |
+
logits=logits,
|
1025 |
+
hidden_states=outputs.hidden_states,
|
1026 |
+
attentions=outputs.attentions,
|
1027 |
+
)
|
1028 |
+
|
1029 |
+
|
1030 |
+
__all__ = [
|
1031 |
+
"TriLMLinearForCausalLM",
|
1032 |
+
"TriLMLinearModel",
|
1033 |
+
"TriLMLinearPreTrainedModel",
|
1034 |
+
"TriLMLinearForSequenceClassification",
|
1035 |
+
"TriLMLinearForQuestionAnswering",
|
1036 |
+
"TriLMLinearForTokenClassification",
|
1037 |
+
]
|
Llama-2-7b-hf/config.json
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"LlamaForCausalLM"
|
4 |
+
],
|
5 |
+
"bos_token_id": 1,
|
6 |
+
"eos_token_id": 2,
|
7 |
+
"hidden_act": "silu",
|
8 |
+
"hidden_size": 4096,
|
9 |
+
"initializer_range": 0.02,
|
10 |
+
"intermediate_size": 11008,
|
11 |
+
"max_position_embeddings": 4096,
|
12 |
+
"model_type": "llama",
|
13 |
+
"num_attention_heads": 32,
|
14 |
+
"num_hidden_layers": 32,
|
15 |
+
"num_key_value_heads": 32,
|
16 |
+
"pad_token_id": 0,
|
17 |
+
"pretraining_tp": 1,
|
18 |
+
"rms_norm_eps": 1e-05,
|
19 |
+
"rope_scaling": null,
|
20 |
+
"tie_word_embeddings": false,
|
21 |
+
"torch_dtype": "float16",
|
22 |
+
"transformers_version": "4.31.0.dev0",
|
23 |
+
"use_cache": true,
|
24 |
+
"vocab_size": 32000
|
25 |
+
}
|
Llama-2-7b-hf/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:49c4fba6ccde3f94e2bdb9ce35209d6e01a4a6f213efc177cc10a262523f48d9
|
3 |
+
size 13476864912
|
Llama-2-7b-hf_trirun/config.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"TriLMLinearForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_trilmlinear.TriLMLinearConfig",
|
7 |
+
"AutoModel": "modeling_trilmlinear.TriLMLinearModel",
|
8 |
+
"AutoModelForCausalLM": "modeling_trilmlinear.TriLMLinearForCausalLM"
|
9 |
+
},
|
10 |
+
"bos_token_id": 1,
|
11 |
+
"eos_token_id": 2,
|
12 |
+
"hidden_act": "silu",
|
13 |
+
"hidden_size": 4096,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 11008,
|
16 |
+
"max_position_embeddings": 4096,
|
17 |
+
"model_type": "TriLMLinear",
|
18 |
+
"num_attention_heads": 32,
|
19 |
+
"num_hidden_layers": 32,
|
20 |
+
"num_key_value_heads": 32,
|
21 |
+
"pad_token_id": 0,
|
22 |
+
"pretraining_tp": 1,
|
23 |
+
"rms_norm_eps": 1e-05,
|
24 |
+
"rope_scaling": null,
|
25 |
+
"tie_word_embeddings": false,
|
26 |
+
"torch_dtype": "float16",
|
27 |
+
"transformers_version": "4.31.0.dev0",
|
28 |
+
"use_cache": true,
|
29 |
+
"vocab_size": 32000
|
30 |
+
}
|
Llama-2-7b-hf_trirun/configuration_trilmlinear.py
ADDED
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""TriLMLinear model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
24 |
+
|
25 |
+
|
26 |
+
class TriLMLinearConfig(PretrainedConfig):
|
27 |
+
r"""
|
28 |
+
This is the configuration class to store the configuration of a [`TriLMLinearModel`]. It is used to instantiate an LLaMA
|
29 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
30 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
31 |
+
|
32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
33 |
+
documentation from [`PretrainedConfig`] for more information.
|
34 |
+
|
35 |
+
|
36 |
+
Args:
|
37 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
38 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
39 |
+
`inputs_ids` passed when calling [`LlamaModel`]
|
40 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
41 |
+
Dimension of the hidden representations.
|
42 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
43 |
+
Dimension of the MLP representations.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
45 |
+
Number of hidden layers in the Transformer decoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
47 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
48 |
+
num_key_value_heads (`int`, *optional*):
|
49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
51 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
54 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
55 |
+
`num_attention_heads`.
|
56 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
57 |
+
The non-linear activation function (function or string) in the decoder.
|
58 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
59 |
+
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
60 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
64 |
+
The epsilon used by the rms normalization layers.
|
65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
67 |
+
relevant if `config.is_decoder=True`.
|
68 |
+
pad_token_id (`int`, *optional*):
|
69 |
+
Padding token id.
|
70 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
71 |
+
Beginning of stream token id.
|
72 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
73 |
+
End of stream token id.
|
74 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
75 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
76 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
|
77 |
+
understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
|
78 |
+
results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
|
79 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
80 |
+
Whether to tie weight embeddings
|
81 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
82 |
+
The base period of the RoPE embeddings.
|
83 |
+
rope_scaling (`Dict`, *optional*):
|
84 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
85 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
86 |
+
accordingly.
|
87 |
+
Expected contents:
|
88 |
+
`rope_type` (`str`):
|
89 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
90 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
91 |
+
`factor` (`float`, *optional*):
|
92 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
93 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
94 |
+
original maximum pre-trained length.
|
95 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
96 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
97 |
+
pretraining.
|
98 |
+
`attention_factor` (`float`, *optional*):
|
99 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
100 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
101 |
+
`factor` field to infer the suggested value.
|
102 |
+
`beta_fast` (`float`, *optional*):
|
103 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
104 |
+
ramp function. If unspecified, it defaults to 32.
|
105 |
+
`beta_slow` (`float`, *optional*):
|
106 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
107 |
+
ramp function. If unspecified, it defaults to 1.
|
108 |
+
`short_factor` (`List[float]`, *optional*):
|
109 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
110 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
111 |
+
size divided by the number of attention heads divided by 2
|
112 |
+
`long_factor` (`List[float]`, *optional*):
|
113 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
114 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
115 |
+
size divided by the number of attention heads divided by 2
|
116 |
+
`low_freq_factor` (`float`, *optional*):
|
117 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
118 |
+
`high_freq_factor` (`float`, *optional*):
|
119 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
120 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
121 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
122 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
123 |
+
The dropout ratio for the attention probabilities.
|
124 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
125 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
126 |
+
head_dim (`int`, *optional*):
|
127 |
+
The attention head dimension. If None, it will default to hidden_size // num_attention_heads
|
128 |
+
|
129 |
+
```python
|
130 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
131 |
+
|
132 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
133 |
+
>>> configuration = LlamaConfig()
|
134 |
+
|
135 |
+
>>> # Initializing a model from the llama-7b style configuration
|
136 |
+
>>> model = LlamaModel(configuration)
|
137 |
+
|
138 |
+
>>> # Accessing the model configuration
|
139 |
+
>>> configuration = model.config
|
140 |
+
```"""
|
141 |
+
|
142 |
+
model_type = "TriLMLinear"
|
143 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
144 |
+
# Default tensor parallel plan for base model `LlamaModel`
|
145 |
+
base_model_tp_plan = {
|
146 |
+
"layers.*.self_attn.q_proj": "colwise",
|
147 |
+
"layers.*.self_attn.k_proj": "colwise",
|
148 |
+
"layers.*.self_attn.v_proj": "colwise",
|
149 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
150 |
+
"layers.*.mlp.gate_proj": "colwise",
|
151 |
+
"layers.*.mlp.up_proj": "colwise",
|
152 |
+
"layers.*.mlp.down_proj": "rowwise",
|
153 |
+
}
|
154 |
+
|
155 |
+
def __init__(
|
156 |
+
self,
|
157 |
+
vocab_size=32000,
|
158 |
+
hidden_size=4096,
|
159 |
+
intermediate_size=11008,
|
160 |
+
num_hidden_layers=32,
|
161 |
+
num_attention_heads=32,
|
162 |
+
num_key_value_heads=None,
|
163 |
+
hidden_act="silu",
|
164 |
+
max_position_embeddings=2048,
|
165 |
+
initializer_range=0.02,
|
166 |
+
rms_norm_eps=1e-6,
|
167 |
+
use_cache=True,
|
168 |
+
pad_token_id=None,
|
169 |
+
bos_token_id=1,
|
170 |
+
eos_token_id=2,
|
171 |
+
pretraining_tp=1,
|
172 |
+
tie_word_embeddings=False,
|
173 |
+
rope_theta=10000.0,
|
174 |
+
rope_scaling=None,
|
175 |
+
attention_bias=False,
|
176 |
+
attention_dropout=0.0,
|
177 |
+
mlp_bias=False,
|
178 |
+
head_dim=None,
|
179 |
+
**kwargs,
|
180 |
+
):
|
181 |
+
self.vocab_size = vocab_size
|
182 |
+
self.max_position_embeddings = max_position_embeddings
|
183 |
+
self.hidden_size = hidden_size
|
184 |
+
self.intermediate_size = intermediate_size
|
185 |
+
self.num_hidden_layers = num_hidden_layers
|
186 |
+
self.num_attention_heads = num_attention_heads
|
187 |
+
|
188 |
+
# for backward compatibility
|
189 |
+
if num_key_value_heads is None:
|
190 |
+
num_key_value_heads = num_attention_heads
|
191 |
+
|
192 |
+
self.num_key_value_heads = num_key_value_heads
|
193 |
+
self.hidden_act = hidden_act
|
194 |
+
self.initializer_range = initializer_range
|
195 |
+
self.rms_norm_eps = rms_norm_eps
|
196 |
+
self.pretraining_tp = pretraining_tp
|
197 |
+
self.use_cache = use_cache
|
198 |
+
self.rope_theta = rope_theta
|
199 |
+
self.rope_scaling = rope_scaling
|
200 |
+
self.attention_bias = attention_bias
|
201 |
+
self.attention_dropout = attention_dropout
|
202 |
+
self.mlp_bias = mlp_bias
|
203 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
204 |
+
# Validate the correctness of rotary position embeddings parameters
|
205 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
206 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
207 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
208 |
+
rope_config_validation(self)
|
209 |
+
|
210 |
+
super().__init__(
|
211 |
+
pad_token_id=pad_token_id,
|
212 |
+
bos_token_id=bos_token_id,
|
213 |
+
eos_token_id=eos_token_id,
|
214 |
+
tie_word_embeddings=tie_word_embeddings,
|
215 |
+
**kwargs,
|
216 |
+
)
|
217 |
+
|
218 |
+
|
219 |
+
__all__ = ["TriLMLinearConfig"]
|
220 |
+
|
Llama-2-7b-hf_trirun/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a21450382a2589ca67a2b4254239113289b3c35de0e6e5d7bcdf71993f7576a0
|
3 |
+
size 2146601304
|
Llama-2-7b-hf_trirun/modeling_trilmlinear.py
ADDED
@@ -0,0 +1,1037 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from typing import Callable, List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
|
26 |
+
from transformers.activations import ACT2FN
|
27 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
28 |
+
from transformers.generation import GenerationMixin
|
29 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
30 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
31 |
+
from transformers.modeling_outputs import (
|
32 |
+
BaseModelOutputWithPast,
|
33 |
+
CausalLMOutputWithPast,
|
34 |
+
QuestionAnsweringModelOutput,
|
35 |
+
SequenceClassifierOutputWithPast,
|
36 |
+
TokenClassifierOutput,
|
37 |
+
)
|
38 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
39 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
40 |
+
from transformers.processing_utils import Unpack
|
41 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
42 |
+
from transformers.utils import (
|
43 |
+
LossKwargs,
|
44 |
+
add_code_sample_docstrings,
|
45 |
+
add_start_docstrings,
|
46 |
+
add_start_docstrings_to_model_forward,
|
47 |
+
logging,
|
48 |
+
replace_return_docstrings,
|
49 |
+
)
|
50 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
51 |
+
from .configuration_trilmlinear import TriLMLinearConfig
|
52 |
+
import marlin
|
53 |
+
|
54 |
+
logger = logging.get_logger(__name__)
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
class TriLMLinear(torch.nn.Module):
|
59 |
+
def __init__(self, in_dims, out_dims, thread_k=128, thread_n=128, groupsize=-1, sms=-1):
|
60 |
+
super(TriLMLinear, self).__init__()
|
61 |
+
self.in_dims, self.out_dims = in_dims, out_dims
|
62 |
+
self.thread_k, self.thread_n, self.groupsize, self.sms = thread_k, thread_n, groupsize, sms
|
63 |
+
packed_weight = torch.ones((in_dims//16, out_dims), dtype=torch.int32)
|
64 |
+
scales = torch.ones((1, out_dims), dtype=torch.float16)
|
65 |
+
self.register_buffer("packed_weight", packed_weight)
|
66 |
+
self.register_buffer("scales", scales)
|
67 |
+
self.workspace = torch.zeros(self.out_dims // 128 * 16, device="cuda")
|
68 |
+
def forward(self, hidden_state):
|
69 |
+
# print(A, self.name)
|
70 |
+
batch_size, seqlen, last_dim = hidden_state.shape
|
71 |
+
output = torch.zeros((batch_size * seqlen, self.out_dims), dtype=torch.float16, device=self.packed_weight.device)
|
72 |
+
marlin.mul(hidden_state.reshape(batch_size * seqlen, last_dim).contiguous(), self.packed_weight, output, self.scales,
|
73 |
+
self.workspace, self.thread_k, self.thread_n, self.sms)
|
74 |
+
return output.reshape(batch_size, seqlen, -1)
|
75 |
+
|
76 |
+
|
77 |
+
class TriLMLinearRMSNorm(nn.Module):
|
78 |
+
def __init__(self, hidden_size, eps=1e-6):
|
79 |
+
"""
|
80 |
+
TriLMLinearRMSNorm is equivalent to T5LayerNorm
|
81 |
+
"""
|
82 |
+
super().__init__()
|
83 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
84 |
+
self.variance_epsilon = eps
|
85 |
+
|
86 |
+
def forward(self, hidden_states):
|
87 |
+
input_dtype = hidden_states.dtype
|
88 |
+
hidden_states = hidden_states.to(torch.float32)
|
89 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
90 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
91 |
+
return self.weight * hidden_states.to(input_dtype)
|
92 |
+
|
93 |
+
def extra_repr(self):
|
94 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
95 |
+
|
96 |
+
|
97 |
+
ALL_LAYERNORM_LAYERS.append(TriLMLinearRMSNorm)
|
98 |
+
|
99 |
+
|
100 |
+
class TriLMLinearRotaryEmbedding(nn.Module):
|
101 |
+
def __init__(self, config: TriLMLinearConfig, device=None):
|
102 |
+
super().__init__()
|
103 |
+
# BC: "rope_type" was originally "type"
|
104 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
105 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
106 |
+
else:
|
107 |
+
self.rope_type = "default"
|
108 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
109 |
+
self.original_max_seq_len = config.max_position_embeddings
|
110 |
+
|
111 |
+
self.config = config
|
112 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
113 |
+
|
114 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
115 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
116 |
+
self.original_inv_freq = self.inv_freq
|
117 |
+
|
118 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
119 |
+
"""
|
120 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
121 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
122 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
123 |
+
"""
|
124 |
+
seq_len = torch.max(position_ids) + 1
|
125 |
+
if seq_len > self.max_seq_len_cached: # growth
|
126 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
127 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
128 |
+
self.max_seq_len_cached = seq_len
|
129 |
+
|
130 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
131 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
132 |
+
# the buffer is automatically moved, but not the original copy)
|
133 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
134 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
135 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
136 |
+
|
137 |
+
@torch.no_grad()
|
138 |
+
def forward(self, x, position_ids):
|
139 |
+
if "dynamic" in self.rope_type:
|
140 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
141 |
+
|
142 |
+
# Core RoPE block
|
143 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
144 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
145 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
146 |
+
device_type = x.device.type
|
147 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
148 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
149 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
150 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
151 |
+
cos = emb.cos()
|
152 |
+
sin = emb.sin()
|
153 |
+
|
154 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
155 |
+
cos = cos * self.attention_scaling
|
156 |
+
sin = sin * self.attention_scaling
|
157 |
+
|
158 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
159 |
+
|
160 |
+
|
161 |
+
def rotate_half(x):
|
162 |
+
"""Rotates half the hidden dims of the input."""
|
163 |
+
x1 = x[..., : x.shape[-1] // 2]
|
164 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
165 |
+
return torch.cat((-x2, x1), dim=-1)
|
166 |
+
|
167 |
+
|
168 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
169 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
170 |
+
|
171 |
+
Args:
|
172 |
+
q (`torch.Tensor`): The query tensor.
|
173 |
+
k (`torch.Tensor`): The key tensor.
|
174 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
175 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
176 |
+
position_ids (`torch.Tensor`, *optional*):
|
177 |
+
Deprecated and unused.
|
178 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
179 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
180 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
181 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
182 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
183 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
184 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
185 |
+
Returns:
|
186 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
187 |
+
"""
|
188 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
189 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
190 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
191 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
192 |
+
return q_embed, k_embed
|
193 |
+
|
194 |
+
|
195 |
+
class TriLMLinearMLP(nn.Module):
|
196 |
+
def __init__(self, config):
|
197 |
+
super().__init__()
|
198 |
+
self.config = config
|
199 |
+
self.hidden_size = config.hidden_size
|
200 |
+
self.intermediate_size = config.intermediate_size
|
201 |
+
assert config.mlp_bias == False, config.mlp_bias
|
202 |
+
self.gate_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
203 |
+
self.up_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
204 |
+
self.down_proj = TriLMLinear(self.intermediate_size, self.hidden_size)
|
205 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
206 |
+
|
207 |
+
def forward(self, x):
|
208 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
209 |
+
return down_proj
|
210 |
+
|
211 |
+
|
212 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
213 |
+
"""
|
214 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
215 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
216 |
+
"""
|
217 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
218 |
+
if n_rep == 1:
|
219 |
+
return hidden_states
|
220 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
221 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
222 |
+
|
223 |
+
|
224 |
+
def eager_attention_forward(
|
225 |
+
module: nn.Module,
|
226 |
+
query: torch.Tensor,
|
227 |
+
key: torch.Tensor,
|
228 |
+
value: torch.Tensor,
|
229 |
+
attention_mask: Optional[torch.Tensor],
|
230 |
+
scaling: float,
|
231 |
+
dropout: float = 0.0,
|
232 |
+
**kwargs,
|
233 |
+
):
|
234 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
235 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
236 |
+
|
237 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
238 |
+
if attention_mask is not None:
|
239 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
240 |
+
attn_weights = attn_weights + causal_mask
|
241 |
+
|
242 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
243 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
244 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
245 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
246 |
+
|
247 |
+
return attn_output, attn_weights
|
248 |
+
|
249 |
+
|
250 |
+
class TriLMLinearAttention(nn.Module):
|
251 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
252 |
+
|
253 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
254 |
+
super().__init__()
|
255 |
+
self.config = config
|
256 |
+
self.layer_idx = layer_idx
|
257 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
258 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
259 |
+
self.scaling = self.head_dim**-0.5
|
260 |
+
self.attention_dropout = config.attention_dropout
|
261 |
+
self.is_causal = True
|
262 |
+
assert config.attention_bias == False
|
263 |
+
self.q_proj = TriLMLinear(
|
264 |
+
config.hidden_size, config.num_attention_heads * self.head_dim#, bias=config.attention_bias
|
265 |
+
)
|
266 |
+
self.k_proj = TriLMLinear(
|
267 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
268 |
+
)
|
269 |
+
self.v_proj = TriLMLinear(
|
270 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
271 |
+
)
|
272 |
+
self.o_proj = TriLMLinear(
|
273 |
+
config.num_attention_heads * self.head_dim, config.hidden_size#, bias=config.attention_bias
|
274 |
+
)
|
275 |
+
|
276 |
+
def forward(
|
277 |
+
self,
|
278 |
+
hidden_states: torch.Tensor,
|
279 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
280 |
+
attention_mask: Optional[torch.Tensor],
|
281 |
+
past_key_value: Optional[Cache] = None,
|
282 |
+
cache_position: Optional[torch.LongTensor] = None,
|
283 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
284 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
285 |
+
input_shape = hidden_states.shape[:-1]
|
286 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
287 |
+
|
288 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
289 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
290 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
291 |
+
|
292 |
+
cos, sin = position_embeddings
|
293 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
294 |
+
|
295 |
+
if past_key_value is not None:
|
296 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
297 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
298 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
299 |
+
|
300 |
+
attention_interface: Callable = eager_attention_forward
|
301 |
+
if self.config._attn_implementation != "eager":
|
302 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
303 |
+
logger.warning_once(
|
304 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
305 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
306 |
+
)
|
307 |
+
else:
|
308 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
309 |
+
|
310 |
+
attn_output, attn_weights = attention_interface(
|
311 |
+
self,
|
312 |
+
query_states,
|
313 |
+
key_states,
|
314 |
+
value_states,
|
315 |
+
attention_mask,
|
316 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
317 |
+
scaling=self.scaling,
|
318 |
+
**kwargs,
|
319 |
+
)
|
320 |
+
|
321 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
322 |
+
attn_output = self.o_proj(attn_output)
|
323 |
+
return attn_output, attn_weights
|
324 |
+
|
325 |
+
|
326 |
+
class TriLMLinearDecoderLayer(nn.Module):
|
327 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
328 |
+
super().__init__()
|
329 |
+
self.hidden_size = config.hidden_size
|
330 |
+
|
331 |
+
self.self_attn = TriLMLinearAttention(config=config, layer_idx=layer_idx)
|
332 |
+
|
333 |
+
self.mlp = TriLMLinearMLP(config)
|
334 |
+
self.input_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
335 |
+
self.post_attention_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
336 |
+
|
337 |
+
def forward(
|
338 |
+
self,
|
339 |
+
hidden_states: torch.Tensor,
|
340 |
+
attention_mask: Optional[torch.Tensor] = None,
|
341 |
+
position_ids: Optional[torch.LongTensor] = None,
|
342 |
+
past_key_value: Optional[Cache] = None,
|
343 |
+
output_attentions: Optional[bool] = False,
|
344 |
+
use_cache: Optional[bool] = False,
|
345 |
+
cache_position: Optional[torch.LongTensor] = None,
|
346 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
347 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
348 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
349 |
+
residual = hidden_states
|
350 |
+
|
351 |
+
hidden_states = self.input_layernorm(hidden_states)
|
352 |
+
|
353 |
+
# Self Attention
|
354 |
+
hidden_states, self_attn_weights = self.self_attn(
|
355 |
+
hidden_states=hidden_states,
|
356 |
+
attention_mask=attention_mask,
|
357 |
+
position_ids=position_ids,
|
358 |
+
past_key_value=past_key_value,
|
359 |
+
output_attentions=output_attentions,
|
360 |
+
use_cache=use_cache,
|
361 |
+
cache_position=cache_position,
|
362 |
+
position_embeddings=position_embeddings,
|
363 |
+
**kwargs,
|
364 |
+
)
|
365 |
+
hidden_states = residual + hidden_states
|
366 |
+
|
367 |
+
# Fully Connected
|
368 |
+
residual = hidden_states
|
369 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
370 |
+
hidden_states = self.mlp(hidden_states)
|
371 |
+
hidden_states = residual + hidden_states
|
372 |
+
|
373 |
+
outputs = (hidden_states,)
|
374 |
+
if output_attentions:
|
375 |
+
outputs += (self_attn_weights,)
|
376 |
+
|
377 |
+
return outputs
|
378 |
+
|
379 |
+
|
380 |
+
class TriLMLinearPreTrainedModel(PreTrainedModel):
|
381 |
+
config_class = TriLMLinearConfig
|
382 |
+
base_model_prefix = "model"
|
383 |
+
supports_gradient_checkpointing = True
|
384 |
+
_no_split_modules = ["TriLMLinearDecoderLayer"]
|
385 |
+
_skip_keys_device_placement = ["past_key_values"]
|
386 |
+
_supports_flash_attn_2 = True
|
387 |
+
_supports_sdpa = True
|
388 |
+
_supports_flex_attn = True
|
389 |
+
_supports_cache_class = True
|
390 |
+
_supports_quantized_cache = True
|
391 |
+
_supports_static_cache = True
|
392 |
+
_supports_attention_backend = True
|
393 |
+
|
394 |
+
def _init_weights(self, module):
|
395 |
+
std = self.config.initializer_range
|
396 |
+
if isinstance(module, nn.Linear):
|
397 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
398 |
+
if module.bias is not None:
|
399 |
+
module.bias.data.zero_()
|
400 |
+
elif isinstance(module, nn.Embedding):
|
401 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
402 |
+
if module.padding_idx is not None:
|
403 |
+
module.weight.data[module.padding_idx].zero_()
|
404 |
+
|
405 |
+
|
406 |
+
|
407 |
+
|
408 |
+
class TriLMLinearModel(TriLMLinearPreTrainedModel):
|
409 |
+
"""
|
410 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TriLMLinearDecoderLayer`]
|
411 |
+
|
412 |
+
Args:
|
413 |
+
config: TriLMLinearConfig
|
414 |
+
"""
|
415 |
+
|
416 |
+
def __init__(self, config: TriLMLinearConfig):
|
417 |
+
super().__init__(config)
|
418 |
+
self.padding_idx = config.pad_token_id
|
419 |
+
self.vocab_size = config.vocab_size
|
420 |
+
|
421 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
422 |
+
self.layers = nn.ModuleList(
|
423 |
+
[TriLMLinearDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
424 |
+
)
|
425 |
+
self.norm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
426 |
+
self.rotary_emb = TriLMLinearRotaryEmbedding(config=config)
|
427 |
+
self.gradient_checkpointing = False
|
428 |
+
|
429 |
+
# Initialize weights and apply final processing
|
430 |
+
self.post_init()
|
431 |
+
|
432 |
+
def get_input_embeddings(self):
|
433 |
+
return self.embed_tokens
|
434 |
+
|
435 |
+
def set_input_embeddings(self, value):
|
436 |
+
self.embed_tokens = value
|
437 |
+
|
438 |
+
def forward(
|
439 |
+
self,
|
440 |
+
input_ids: torch.LongTensor = None,
|
441 |
+
attention_mask: Optional[torch.Tensor] = None,
|
442 |
+
position_ids: Optional[torch.LongTensor] = None,
|
443 |
+
past_key_values: Optional[Cache] = None,
|
444 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
445 |
+
use_cache: Optional[bool] = None,
|
446 |
+
output_attentions: Optional[bool] = None,
|
447 |
+
output_hidden_states: Optional[bool] = None,
|
448 |
+
return_dict: Optional[bool] = None,
|
449 |
+
cache_position: Optional[torch.LongTensor] = None,
|
450 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
451 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
452 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
453 |
+
output_hidden_states = (
|
454 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
455 |
+
)
|
456 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
457 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
458 |
+
|
459 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
460 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
461 |
+
|
462 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
463 |
+
logger.warning_once(
|
464 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
465 |
+
)
|
466 |
+
use_cache = False
|
467 |
+
|
468 |
+
if inputs_embeds is None:
|
469 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
470 |
+
|
471 |
+
if use_cache and past_key_values is None:
|
472 |
+
past_key_values = DynamicCache()
|
473 |
+
|
474 |
+
if cache_position is None:
|
475 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
476 |
+
cache_position = torch.arange(
|
477 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
478 |
+
)
|
479 |
+
|
480 |
+
if position_ids is None:
|
481 |
+
position_ids = cache_position.unsqueeze(0)
|
482 |
+
|
483 |
+
causal_mask = self._update_causal_mask(
|
484 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
485 |
+
)
|
486 |
+
|
487 |
+
hidden_states = inputs_embeds
|
488 |
+
|
489 |
+
# create position embeddings to be shared across the decoder layers
|
490 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
491 |
+
|
492 |
+
# decoder layers
|
493 |
+
all_hidden_states = () if output_hidden_states else None
|
494 |
+
all_self_attns = () if output_attentions else None
|
495 |
+
|
496 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
497 |
+
if output_hidden_states:
|
498 |
+
all_hidden_states += (hidden_states,)
|
499 |
+
|
500 |
+
if self.gradient_checkpointing and self.training:
|
501 |
+
layer_outputs = self._gradient_checkpointing_func(
|
502 |
+
decoder_layer.__call__,
|
503 |
+
hidden_states,
|
504 |
+
causal_mask,
|
505 |
+
position_ids,
|
506 |
+
past_key_values,
|
507 |
+
output_attentions,
|
508 |
+
use_cache,
|
509 |
+
cache_position,
|
510 |
+
position_embeddings,
|
511 |
+
)
|
512 |
+
else:
|
513 |
+
layer_outputs = decoder_layer(
|
514 |
+
hidden_states,
|
515 |
+
attention_mask=causal_mask,
|
516 |
+
position_ids=position_ids,
|
517 |
+
past_key_value=past_key_values,
|
518 |
+
output_attentions=output_attentions,
|
519 |
+
use_cache=use_cache,
|
520 |
+
cache_position=cache_position,
|
521 |
+
position_embeddings=position_embeddings,
|
522 |
+
**flash_attn_kwargs,
|
523 |
+
)
|
524 |
+
|
525 |
+
hidden_states = layer_outputs[0]
|
526 |
+
|
527 |
+
if output_attentions:
|
528 |
+
all_self_attns += (layer_outputs[1],)
|
529 |
+
|
530 |
+
hidden_states = self.norm(hidden_states)
|
531 |
+
|
532 |
+
# add hidden states from the last decoder layer
|
533 |
+
if output_hidden_states:
|
534 |
+
all_hidden_states += (hidden_states,)
|
535 |
+
|
536 |
+
output = BaseModelOutputWithPast(
|
537 |
+
last_hidden_state=hidden_states,
|
538 |
+
past_key_values=past_key_values if use_cache else None,
|
539 |
+
hidden_states=all_hidden_states,
|
540 |
+
attentions=all_self_attns,
|
541 |
+
)
|
542 |
+
return output if return_dict else output.to_tuple()
|
543 |
+
|
544 |
+
def _update_causal_mask(
|
545 |
+
self,
|
546 |
+
attention_mask: torch.Tensor,
|
547 |
+
input_tensor: torch.Tensor,
|
548 |
+
cache_position: torch.Tensor,
|
549 |
+
past_key_values: Cache,
|
550 |
+
output_attentions: bool,
|
551 |
+
):
|
552 |
+
if self.config._attn_implementation == "flash_attention_2":
|
553 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
554 |
+
return attention_mask
|
555 |
+
return None
|
556 |
+
|
557 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
558 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
559 |
+
# to infer the attention mask.
|
560 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
561 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
562 |
+
|
563 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
564 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
565 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
566 |
+
attention_mask,
|
567 |
+
inputs_embeds=input_tensor,
|
568 |
+
past_key_values_length=past_seen_tokens,
|
569 |
+
is_training=self.training,
|
570 |
+
):
|
571 |
+
return None
|
572 |
+
|
573 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
574 |
+
sequence_length = input_tensor.shape[1]
|
575 |
+
if using_static_cache:
|
576 |
+
target_length = past_key_values.get_max_cache_shape()
|
577 |
+
else:
|
578 |
+
target_length = (
|
579 |
+
attention_mask.shape[-1]
|
580 |
+
if isinstance(attention_mask, torch.Tensor)
|
581 |
+
else past_seen_tokens + sequence_length + 1
|
582 |
+
)
|
583 |
+
|
584 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
585 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
586 |
+
attention_mask,
|
587 |
+
sequence_length=sequence_length,
|
588 |
+
target_length=target_length,
|
589 |
+
dtype=dtype,
|
590 |
+
device=device,
|
591 |
+
cache_position=cache_position,
|
592 |
+
batch_size=input_tensor.shape[0],
|
593 |
+
)
|
594 |
+
|
595 |
+
if (
|
596 |
+
self.config._attn_implementation == "sdpa"
|
597 |
+
and attention_mask is not None
|
598 |
+
and attention_mask.device.type == "cuda"
|
599 |
+
and not output_attentions
|
600 |
+
):
|
601 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
602 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
603 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
604 |
+
min_dtype = torch.finfo(dtype).min
|
605 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
606 |
+
|
607 |
+
return causal_mask
|
608 |
+
|
609 |
+
@staticmethod
|
610 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
611 |
+
attention_mask: torch.Tensor,
|
612 |
+
sequence_length: int,
|
613 |
+
target_length: int,
|
614 |
+
dtype: torch.dtype,
|
615 |
+
device: torch.device,
|
616 |
+
cache_position: torch.Tensor,
|
617 |
+
batch_size: int,
|
618 |
+
**kwargs,
|
619 |
+
):
|
620 |
+
"""
|
621 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
622 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
623 |
+
|
624 |
+
Args:
|
625 |
+
attention_mask (`torch.Tensor`):
|
626 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
627 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
628 |
+
sequence_length (`int`):
|
629 |
+
The sequence length being processed.
|
630 |
+
target_length (`int`):
|
631 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
632 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
633 |
+
dtype (`torch.dtype`):
|
634 |
+
The dtype to use for the 4D attention mask.
|
635 |
+
device (`torch.device`):
|
636 |
+
The device to plcae the 4D attention mask on.
|
637 |
+
cache_position (`torch.Tensor`):
|
638 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
639 |
+
batch_size (`torch.Tensor`):
|
640 |
+
Batch size.
|
641 |
+
"""
|
642 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
643 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
644 |
+
causal_mask = attention_mask
|
645 |
+
else:
|
646 |
+
min_dtype = torch.finfo(dtype).min
|
647 |
+
causal_mask = torch.full(
|
648 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
649 |
+
)
|
650 |
+
if sequence_length != 1:
|
651 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
652 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
653 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
654 |
+
if attention_mask is not None:
|
655 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
656 |
+
mask_length = attention_mask.shape[-1]
|
657 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
658 |
+
padding_mask = padding_mask == 0
|
659 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
660 |
+
padding_mask, min_dtype
|
661 |
+
)
|
662 |
+
|
663 |
+
return causal_mask
|
664 |
+
|
665 |
+
|
666 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
667 |
+
|
668 |
+
|
669 |
+
class TriLMLinearForCausalLM(TriLMLinearPreTrainedModel, GenerationMixin):
|
670 |
+
_tied_weights_keys = ["lm_head.weight"]
|
671 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
672 |
+
|
673 |
+
def __init__(self, config):
|
674 |
+
super().__init__(config)
|
675 |
+
self.model = TriLMLinearModel(config)
|
676 |
+
self.vocab_size = config.vocab_size
|
677 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
678 |
+
|
679 |
+
# Initialize weights and apply final processing
|
680 |
+
self.post_init()
|
681 |
+
|
682 |
+
def get_input_embeddings(self):
|
683 |
+
return self.model.embed_tokens
|
684 |
+
|
685 |
+
def set_input_embeddings(self, value):
|
686 |
+
self.model.embed_tokens = value
|
687 |
+
|
688 |
+
def get_output_embeddings(self):
|
689 |
+
return self.lm_head
|
690 |
+
|
691 |
+
def set_output_embeddings(self, new_embeddings):
|
692 |
+
self.lm_head = new_embeddings
|
693 |
+
|
694 |
+
def set_decoder(self, decoder):
|
695 |
+
self.model = decoder
|
696 |
+
|
697 |
+
def get_decoder(self):
|
698 |
+
return self.model
|
699 |
+
|
700 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
701 |
+
def forward(
|
702 |
+
self,
|
703 |
+
input_ids: torch.LongTensor = None,
|
704 |
+
attention_mask: Optional[torch.Tensor] = None,
|
705 |
+
position_ids: Optional[torch.LongTensor] = None,
|
706 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
707 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
708 |
+
labels: Optional[torch.LongTensor] = None,
|
709 |
+
use_cache: Optional[bool] = None,
|
710 |
+
output_attentions: Optional[bool] = None,
|
711 |
+
output_hidden_states: Optional[bool] = None,
|
712 |
+
return_dict: Optional[bool] = None,
|
713 |
+
cache_position: Optional[torch.LongTensor] = None,
|
714 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
715 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
716 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
717 |
+
r"""
|
718 |
+
Args:
|
719 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
720 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
721 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
722 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
723 |
+
|
724 |
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
725 |
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
726 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
727 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
728 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
729 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
730 |
+
|
731 |
+
Returns:
|
732 |
+
|
733 |
+
Example:
|
734 |
+
|
735 |
+
```python
|
736 |
+
>>> from transformers import AutoTokenizer, TriLMLinearForCausalLM
|
737 |
+
|
738 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
739 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
740 |
+
|
741 |
+
>>> # Generate
|
742 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
743 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
744 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
745 |
+
```"""
|
746 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
747 |
+
output_hidden_states = (
|
748 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
749 |
+
)
|
750 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
751 |
+
|
752 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
753 |
+
outputs = self.model(
|
754 |
+
input_ids=input_ids,
|
755 |
+
attention_mask=attention_mask,
|
756 |
+
position_ids=position_ids,
|
757 |
+
past_key_values=past_key_values,
|
758 |
+
inputs_embeds=inputs_embeds,
|
759 |
+
use_cache=use_cache,
|
760 |
+
output_attentions=output_attentions,
|
761 |
+
output_hidden_states=output_hidden_states,
|
762 |
+
return_dict=return_dict,
|
763 |
+
cache_position=cache_position,
|
764 |
+
**kwargs,
|
765 |
+
)
|
766 |
+
|
767 |
+
hidden_states = outputs[0]
|
768 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
769 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
770 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
771 |
+
|
772 |
+
loss = None
|
773 |
+
if labels is not None:
|
774 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
775 |
+
|
776 |
+
if not return_dict:
|
777 |
+
output = (logits,) + outputs[1:]
|
778 |
+
return (loss,) + output if loss is not None else output
|
779 |
+
|
780 |
+
return CausalLMOutputWithPast(
|
781 |
+
loss=loss,
|
782 |
+
logits=logits,
|
783 |
+
past_key_values=outputs.past_key_values,
|
784 |
+
hidden_states=outputs.hidden_states,
|
785 |
+
attentions=outputs.attentions,
|
786 |
+
)
|
787 |
+
|
788 |
+
|
789 |
+
class TriLMLinearForSequenceClassification(TriLMLinearPreTrainedModel):
|
790 |
+
def __init__(self, config):
|
791 |
+
super().__init__(config)
|
792 |
+
self.num_labels = config.num_labels
|
793 |
+
self.model = TriLMLinearModel(config)
|
794 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
795 |
+
|
796 |
+
# Initialize weights and apply final processing
|
797 |
+
self.post_init()
|
798 |
+
|
799 |
+
def get_input_embeddings(self):
|
800 |
+
return self.model.embed_tokens
|
801 |
+
|
802 |
+
def set_input_embeddings(self, value):
|
803 |
+
self.model.embed_tokens = value
|
804 |
+
|
805 |
+
def forward(
|
806 |
+
self,
|
807 |
+
input_ids: Optional[torch.LongTensor] = None,
|
808 |
+
attention_mask: Optional[torch.Tensor] = None,
|
809 |
+
position_ids: Optional[torch.LongTensor] = None,
|
810 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
811 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
812 |
+
labels: Optional[torch.LongTensor] = None,
|
813 |
+
use_cache: Optional[bool] = None,
|
814 |
+
output_attentions: Optional[bool] = None,
|
815 |
+
output_hidden_states: Optional[bool] = None,
|
816 |
+
return_dict: Optional[bool] = None,
|
817 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
818 |
+
r"""
|
819 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
820 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
821 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
822 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
823 |
+
"""
|
824 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
825 |
+
|
826 |
+
transformer_outputs = self.model(
|
827 |
+
input_ids,
|
828 |
+
attention_mask=attention_mask,
|
829 |
+
position_ids=position_ids,
|
830 |
+
past_key_values=past_key_values,
|
831 |
+
inputs_embeds=inputs_embeds,
|
832 |
+
use_cache=use_cache,
|
833 |
+
output_attentions=output_attentions,
|
834 |
+
output_hidden_states=output_hidden_states,
|
835 |
+
return_dict=return_dict,
|
836 |
+
)
|
837 |
+
hidden_states = transformer_outputs[0]
|
838 |
+
logits = self.score(hidden_states)
|
839 |
+
|
840 |
+
if input_ids is not None:
|
841 |
+
batch_size = input_ids.shape[0]
|
842 |
+
else:
|
843 |
+
batch_size = inputs_embeds.shape[0]
|
844 |
+
|
845 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
846 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
847 |
+
if self.config.pad_token_id is None:
|
848 |
+
sequence_lengths = -1
|
849 |
+
else:
|
850 |
+
if input_ids is not None:
|
851 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
852 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
853 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
854 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
855 |
+
else:
|
856 |
+
sequence_lengths = -1
|
857 |
+
|
858 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
859 |
+
|
860 |
+
loss = None
|
861 |
+
if labels is not None:
|
862 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
863 |
+
|
864 |
+
if not return_dict:
|
865 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
866 |
+
return ((loss,) + output) if loss is not None else output
|
867 |
+
|
868 |
+
return SequenceClassifierOutputWithPast(
|
869 |
+
loss=loss,
|
870 |
+
logits=pooled_logits,
|
871 |
+
past_key_values=transformer_outputs.past_key_values,
|
872 |
+
hidden_states=transformer_outputs.hidden_states,
|
873 |
+
attentions=transformer_outputs.attentions,
|
874 |
+
)
|
875 |
+
|
876 |
+
|
877 |
+
class TriLMLinearForQuestionAnswering(TriLMLinearPreTrainedModel):
|
878 |
+
base_model_prefix = "transformer"
|
879 |
+
|
880 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->TriLMLinear
|
881 |
+
def __init__(self, config):
|
882 |
+
super().__init__(config)
|
883 |
+
self.transformer = TriLMLinearModel(config)
|
884 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
885 |
+
|
886 |
+
# Initialize weights and apply final processing
|
887 |
+
self.post_init()
|
888 |
+
|
889 |
+
def get_input_embeddings(self):
|
890 |
+
return self.transformer.embed_tokens
|
891 |
+
|
892 |
+
def set_input_embeddings(self, value):
|
893 |
+
self.transformer.embed_tokens = value
|
894 |
+
|
895 |
+
def forward(
|
896 |
+
self,
|
897 |
+
input_ids: Optional[torch.LongTensor] = None,
|
898 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
899 |
+
position_ids: Optional[torch.LongTensor] = None,
|
900 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
901 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
902 |
+
start_positions: Optional[torch.LongTensor] = None,
|
903 |
+
end_positions: Optional[torch.LongTensor] = None,
|
904 |
+
output_attentions: Optional[bool] = None,
|
905 |
+
output_hidden_states: Optional[bool] = None,
|
906 |
+
return_dict: Optional[bool] = None,
|
907 |
+
**kwargs,
|
908 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
909 |
+
r"""
|
910 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
911 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
912 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
913 |
+
are not taken into account for computing the loss.
|
914 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
915 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
916 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
917 |
+
are not taken into account for computing the loss.
|
918 |
+
"""
|
919 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
920 |
+
|
921 |
+
outputs = self.transformer(
|
922 |
+
input_ids,
|
923 |
+
attention_mask=attention_mask,
|
924 |
+
position_ids=position_ids,
|
925 |
+
past_key_values=past_key_values,
|
926 |
+
inputs_embeds=inputs_embeds,
|
927 |
+
output_attentions=output_attentions,
|
928 |
+
output_hidden_states=output_hidden_states,
|
929 |
+
return_dict=return_dict,
|
930 |
+
)
|
931 |
+
|
932 |
+
sequence_output = outputs[0]
|
933 |
+
|
934 |
+
logits = self.qa_outputs(sequence_output)
|
935 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
936 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
937 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
938 |
+
|
939 |
+
loss = None
|
940 |
+
if start_positions is not None and end_positions is not None:
|
941 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
942 |
+
|
943 |
+
if not return_dict:
|
944 |
+
output = (start_logits, end_logits) + outputs[2:]
|
945 |
+
return ((loss,) + output) if loss is not None else output
|
946 |
+
|
947 |
+
return QuestionAnsweringModelOutput(
|
948 |
+
loss=loss,
|
949 |
+
start_logits=start_logits,
|
950 |
+
end_logits=end_logits,
|
951 |
+
hidden_states=outputs.hidden_states,
|
952 |
+
attentions=outputs.attentions,
|
953 |
+
)
|
954 |
+
|
955 |
+
class TriLMLinearForTokenClassification(TriLMLinearPreTrainedModel):
|
956 |
+
def __init__(self, config):
|
957 |
+
super().__init__(config)
|
958 |
+
self.num_labels = config.num_labels
|
959 |
+
self.model = TriLMLinearModel(config)
|
960 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
961 |
+
classifier_dropout = config.classifier_dropout
|
962 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
963 |
+
classifier_dropout = config.hidden_dropout
|
964 |
+
else:
|
965 |
+
classifier_dropout = 0.1
|
966 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
967 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
968 |
+
|
969 |
+
# Initialize weights and apply final processing
|
970 |
+
self.post_init()
|
971 |
+
|
972 |
+
def get_input_embeddings(self):
|
973 |
+
return self.model.embed_tokens
|
974 |
+
|
975 |
+
def set_input_embeddings(self, value):
|
976 |
+
self.model.embed_tokens = value
|
977 |
+
|
978 |
+
def forward(
|
979 |
+
self,
|
980 |
+
input_ids: Optional[torch.LongTensor] = None,
|
981 |
+
attention_mask: Optional[torch.Tensor] = None,
|
982 |
+
position_ids: Optional[torch.LongTensor] = None,
|
983 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
984 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
985 |
+
labels: Optional[torch.LongTensor] = None,
|
986 |
+
use_cache: Optional[bool] = None,
|
987 |
+
output_attentions: Optional[bool] = None,
|
988 |
+
output_hidden_states: Optional[bool] = None,
|
989 |
+
return_dict: Optional[bool] = None,
|
990 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
991 |
+
r"""
|
992 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
993 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
994 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
995 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
996 |
+
"""
|
997 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
998 |
+
|
999 |
+
outputs = self.model(
|
1000 |
+
input_ids,
|
1001 |
+
attention_mask=attention_mask,
|
1002 |
+
position_ids=position_ids,
|
1003 |
+
past_key_values=past_key_values,
|
1004 |
+
inputs_embeds=inputs_embeds,
|
1005 |
+
use_cache=use_cache,
|
1006 |
+
output_attentions=output_attentions,
|
1007 |
+
output_hidden_states=output_hidden_states,
|
1008 |
+
return_dict=return_dict,
|
1009 |
+
)
|
1010 |
+
sequence_output = outputs[0]
|
1011 |
+
sequence_output = self.dropout(sequence_output)
|
1012 |
+
logits = self.score(sequence_output)
|
1013 |
+
|
1014 |
+
loss = None
|
1015 |
+
if labels is not None:
|
1016 |
+
loss = self.loss_function(logits, labels, self.config)
|
1017 |
+
|
1018 |
+
if not return_dict:
|
1019 |
+
output = (logits,) + outputs[2:]
|
1020 |
+
return ((loss,) + output) if loss is not None else output
|
1021 |
+
|
1022 |
+
return TokenClassifierOutput(
|
1023 |
+
loss=loss,
|
1024 |
+
logits=logits,
|
1025 |
+
hidden_states=outputs.hidden_states,
|
1026 |
+
attentions=outputs.attentions,
|
1027 |
+
)
|
1028 |
+
|
1029 |
+
|
1030 |
+
__all__ = [
|
1031 |
+
"TriLMLinearForCausalLM",
|
1032 |
+
"TriLMLinearModel",
|
1033 |
+
"TriLMLinearPreTrainedModel",
|
1034 |
+
"TriLMLinearForSequenceClassification",
|
1035 |
+
"TriLMLinearForQuestionAnswering",
|
1036 |
+
"TriLMLinearForTokenClassification",
|
1037 |
+
]
|
Mistral-Large-Instruct-2407_trirun/config.json
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"TriLMLinearForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_trilmlinear.TriLMLinearConfig",
|
7 |
+
"AutoModel": "modeling_trilmlinear.TriLMLinearModel",
|
8 |
+
"AutoModelForCausalLM": "modeling_trilmlinear.TriLMLinearForCausalLM"
|
9 |
+
},
|
10 |
+
"attention_dropout": 0.0,
|
11 |
+
"bos_token_id": 1,
|
12 |
+
"pad_token_id": 2,
|
13 |
+
"eos_token_id": 2,
|
14 |
+
"hidden_act": "silu",
|
15 |
+
"hidden_size": 12288,
|
16 |
+
"initializer_range": 0.02,
|
17 |
+
"intermediate_size": 28672,
|
18 |
+
"max_position_embeddings": 131072,
|
19 |
+
"model_type": "TriLMLinear",
|
20 |
+
"num_attention_heads": 96,
|
21 |
+
"num_hidden_layers": 88,
|
22 |
+
"num_key_value_heads": 8,
|
23 |
+
"rms_norm_eps": 1e-05,
|
24 |
+
"rope_theta": 1000000.0,
|
25 |
+
"sliding_window": null,
|
26 |
+
"tie_word_embeddings": false,
|
27 |
+
"torch_dtype": "bfloat16",
|
28 |
+
"transformers_version": "4.42.3",
|
29 |
+
"use_cache": true,
|
30 |
+
"vocab_size": 32768
|
31 |
+
}
|
32 |
+
|
Mistral-Large-Instruct-2407_trirun/configuration_trilmlinear.py
ADDED
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""TriLMLinear model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
24 |
+
|
25 |
+
|
26 |
+
class TriLMLinearConfig(PretrainedConfig):
|
27 |
+
r"""
|
28 |
+
This is the configuration class to store the configuration of a [`TriLMLinearModel`]. It is used to instantiate an LLaMA
|
29 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
30 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
31 |
+
|
32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
33 |
+
documentation from [`PretrainedConfig`] for more information.
|
34 |
+
|
35 |
+
|
36 |
+
Args:
|
37 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
38 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
39 |
+
`inputs_ids` passed when calling [`LlamaModel`]
|
40 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
41 |
+
Dimension of the hidden representations.
|
42 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
43 |
+
Dimension of the MLP representations.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
45 |
+
Number of hidden layers in the Transformer decoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
47 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
48 |
+
num_key_value_heads (`int`, *optional*):
|
49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
51 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
54 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
55 |
+
`num_attention_heads`.
|
56 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
57 |
+
The non-linear activation function (function or string) in the decoder.
|
58 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
59 |
+
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
60 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
64 |
+
The epsilon used by the rms normalization layers.
|
65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
67 |
+
relevant if `config.is_decoder=True`.
|
68 |
+
pad_token_id (`int`, *optional*):
|
69 |
+
Padding token id.
|
70 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
71 |
+
Beginning of stream token id.
|
72 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
73 |
+
End of stream token id.
|
74 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
75 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
76 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
|
77 |
+
understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
|
78 |
+
results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
|
79 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
80 |
+
Whether to tie weight embeddings
|
81 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
82 |
+
The base period of the RoPE embeddings.
|
83 |
+
rope_scaling (`Dict`, *optional*):
|
84 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
85 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
86 |
+
accordingly.
|
87 |
+
Expected contents:
|
88 |
+
`rope_type` (`str`):
|
89 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
90 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
91 |
+
`factor` (`float`, *optional*):
|
92 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
93 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
94 |
+
original maximum pre-trained length.
|
95 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
96 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
97 |
+
pretraining.
|
98 |
+
`attention_factor` (`float`, *optional*):
|
99 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
100 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
101 |
+
`factor` field to infer the suggested value.
|
102 |
+
`beta_fast` (`float`, *optional*):
|
103 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
104 |
+
ramp function. If unspecified, it defaults to 32.
|
105 |
+
`beta_slow` (`float`, *optional*):
|
106 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
107 |
+
ramp function. If unspecified, it defaults to 1.
|
108 |
+
`short_factor` (`List[float]`, *optional*):
|
109 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
110 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
111 |
+
size divided by the number of attention heads divided by 2
|
112 |
+
`long_factor` (`List[float]`, *optional*):
|
113 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
114 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
115 |
+
size divided by the number of attention heads divided by 2
|
116 |
+
`low_freq_factor` (`float`, *optional*):
|
117 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
118 |
+
`high_freq_factor` (`float`, *optional*):
|
119 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
120 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
121 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
122 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
123 |
+
The dropout ratio for the attention probabilities.
|
124 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
125 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
126 |
+
head_dim (`int`, *optional*):
|
127 |
+
The attention head dimension. If None, it will default to hidden_size // num_attention_heads
|
128 |
+
|
129 |
+
```python
|
130 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
131 |
+
|
132 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
133 |
+
>>> configuration = LlamaConfig()
|
134 |
+
|
135 |
+
>>> # Initializing a model from the llama-7b style configuration
|
136 |
+
>>> model = LlamaModel(configuration)
|
137 |
+
|
138 |
+
>>> # Accessing the model configuration
|
139 |
+
>>> configuration = model.config
|
140 |
+
```"""
|
141 |
+
|
142 |
+
model_type = "TriLMLinear"
|
143 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
144 |
+
# Default tensor parallel plan for base model `LlamaModel`
|
145 |
+
base_model_tp_plan = {
|
146 |
+
"layers.*.self_attn.q_proj": "colwise",
|
147 |
+
"layers.*.self_attn.k_proj": "colwise",
|
148 |
+
"layers.*.self_attn.v_proj": "colwise",
|
149 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
150 |
+
"layers.*.mlp.gate_proj": "colwise",
|
151 |
+
"layers.*.mlp.up_proj": "colwise",
|
152 |
+
"layers.*.mlp.down_proj": "rowwise",
|
153 |
+
}
|
154 |
+
|
155 |
+
def __init__(
|
156 |
+
self,
|
157 |
+
vocab_size=32000,
|
158 |
+
hidden_size=4096,
|
159 |
+
intermediate_size=11008,
|
160 |
+
num_hidden_layers=32,
|
161 |
+
num_attention_heads=32,
|
162 |
+
num_key_value_heads=None,
|
163 |
+
hidden_act="silu",
|
164 |
+
max_position_embeddings=2048,
|
165 |
+
initializer_range=0.02,
|
166 |
+
rms_norm_eps=1e-6,
|
167 |
+
use_cache=True,
|
168 |
+
pad_token_id=None,
|
169 |
+
bos_token_id=1,
|
170 |
+
eos_token_id=2,
|
171 |
+
pretraining_tp=1,
|
172 |
+
tie_word_embeddings=False,
|
173 |
+
rope_theta=10000.0,
|
174 |
+
rope_scaling=None,
|
175 |
+
attention_bias=False,
|
176 |
+
attention_dropout=0.0,
|
177 |
+
mlp_bias=False,
|
178 |
+
head_dim=None,
|
179 |
+
**kwargs,
|
180 |
+
):
|
181 |
+
self.vocab_size = vocab_size
|
182 |
+
self.max_position_embeddings = max_position_embeddings
|
183 |
+
self.hidden_size = hidden_size
|
184 |
+
self.intermediate_size = intermediate_size
|
185 |
+
self.num_hidden_layers = num_hidden_layers
|
186 |
+
self.num_attention_heads = num_attention_heads
|
187 |
+
|
188 |
+
# for backward compatibility
|
189 |
+
if num_key_value_heads is None:
|
190 |
+
num_key_value_heads = num_attention_heads
|
191 |
+
|
192 |
+
self.num_key_value_heads = num_key_value_heads
|
193 |
+
self.hidden_act = hidden_act
|
194 |
+
self.initializer_range = initializer_range
|
195 |
+
self.rms_norm_eps = rms_norm_eps
|
196 |
+
self.pretraining_tp = pretraining_tp
|
197 |
+
self.use_cache = use_cache
|
198 |
+
self.rope_theta = rope_theta
|
199 |
+
self.rope_scaling = rope_scaling
|
200 |
+
self.attention_bias = attention_bias
|
201 |
+
self.attention_dropout = attention_dropout
|
202 |
+
self.mlp_bias = mlp_bias
|
203 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
204 |
+
# Validate the correctness of rotary position embeddings parameters
|
205 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
206 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
207 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
208 |
+
rope_config_validation(self)
|
209 |
+
|
210 |
+
super().__init__(
|
211 |
+
pad_token_id=pad_token_id,
|
212 |
+
bos_token_id=bos_token_id,
|
213 |
+
eos_token_id=eos_token_id,
|
214 |
+
tie_word_embeddings=tie_word_embeddings,
|
215 |
+
**kwargs,
|
216 |
+
)
|
217 |
+
|
218 |
+
|
219 |
+
__all__ = ["TriLMLinearConfig"]
|
220 |
+
|
Mistral-Large-Instruct-2407_trirun/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:603475b555afc8f8bbdef658767ffad9dfdc2db744cd04a5a786f620e3234866
|
3 |
+
size 32082718824
|
Mistral-Large-Instruct-2407_trirun/modeling_trilmlinear.py
ADDED
@@ -0,0 +1,1037 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from typing import Callable, List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
|
26 |
+
from transformers.activations import ACT2FN
|
27 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
28 |
+
from transformers.generation import GenerationMixin
|
29 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
30 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
31 |
+
from transformers.modeling_outputs import (
|
32 |
+
BaseModelOutputWithPast,
|
33 |
+
CausalLMOutputWithPast,
|
34 |
+
QuestionAnsweringModelOutput,
|
35 |
+
SequenceClassifierOutputWithPast,
|
36 |
+
TokenClassifierOutput,
|
37 |
+
)
|
38 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
39 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
40 |
+
from transformers.processing_utils import Unpack
|
41 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
42 |
+
from transformers.utils import (
|
43 |
+
LossKwargs,
|
44 |
+
add_code_sample_docstrings,
|
45 |
+
add_start_docstrings,
|
46 |
+
add_start_docstrings_to_model_forward,
|
47 |
+
logging,
|
48 |
+
replace_return_docstrings,
|
49 |
+
)
|
50 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
51 |
+
from .configuration_trilmlinear import TriLMLinearConfig
|
52 |
+
import marlin
|
53 |
+
|
54 |
+
logger = logging.get_logger(__name__)
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
class TriLMLinear(torch.nn.Module):
|
59 |
+
def __init__(self, in_dims, out_dims, thread_k=128, thread_n=128, groupsize=-1, sms=-1):
|
60 |
+
super(TriLMLinear, self).__init__()
|
61 |
+
self.in_dims, self.out_dims = in_dims, out_dims
|
62 |
+
self.thread_k, self.thread_n, self.groupsize, self.sms = thread_k, thread_n, groupsize, sms
|
63 |
+
packed_weight = torch.ones((in_dims//16, out_dims), dtype=torch.int32)
|
64 |
+
scales = torch.ones((1, out_dims), dtype=torch.float16)
|
65 |
+
self.register_buffer("packed_weight", packed_weight)
|
66 |
+
self.register_buffer("scales", scales)
|
67 |
+
self.workspace = torch.zeros(self.out_dims // 128 * 16, device="cuda")
|
68 |
+
def forward(self, hidden_state):
|
69 |
+
# print(A, self.name)
|
70 |
+
batch_size, seqlen, last_dim = hidden_state.shape
|
71 |
+
output = torch.zeros((batch_size * seqlen, self.out_dims), dtype=torch.float16, device=self.packed_weight.device)
|
72 |
+
marlin.mul(hidden_state.reshape(batch_size * seqlen, last_dim).contiguous(), self.packed_weight, output, self.scales,
|
73 |
+
self.workspace, self.thread_k, self.thread_n, self.sms)
|
74 |
+
return output.reshape(batch_size, seqlen, -1)
|
75 |
+
|
76 |
+
|
77 |
+
class TriLMLinearRMSNorm(nn.Module):
|
78 |
+
def __init__(self, hidden_size, eps=1e-6):
|
79 |
+
"""
|
80 |
+
TriLMLinearRMSNorm is equivalent to T5LayerNorm
|
81 |
+
"""
|
82 |
+
super().__init__()
|
83 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
84 |
+
self.variance_epsilon = eps
|
85 |
+
|
86 |
+
def forward(self, hidden_states):
|
87 |
+
input_dtype = hidden_states.dtype
|
88 |
+
hidden_states = hidden_states.to(torch.float32)
|
89 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
90 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
91 |
+
return self.weight * hidden_states.to(input_dtype)
|
92 |
+
|
93 |
+
def extra_repr(self):
|
94 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
95 |
+
|
96 |
+
|
97 |
+
ALL_LAYERNORM_LAYERS.append(TriLMLinearRMSNorm)
|
98 |
+
|
99 |
+
|
100 |
+
class TriLMLinearRotaryEmbedding(nn.Module):
|
101 |
+
def __init__(self, config: TriLMLinearConfig, device=None):
|
102 |
+
super().__init__()
|
103 |
+
# BC: "rope_type" was originally "type"
|
104 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
105 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
106 |
+
else:
|
107 |
+
self.rope_type = "default"
|
108 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
109 |
+
self.original_max_seq_len = config.max_position_embeddings
|
110 |
+
|
111 |
+
self.config = config
|
112 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
113 |
+
|
114 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
115 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
116 |
+
self.original_inv_freq = self.inv_freq
|
117 |
+
|
118 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
119 |
+
"""
|
120 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
121 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
122 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
123 |
+
"""
|
124 |
+
seq_len = torch.max(position_ids) + 1
|
125 |
+
if seq_len > self.max_seq_len_cached: # growth
|
126 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
127 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
128 |
+
self.max_seq_len_cached = seq_len
|
129 |
+
|
130 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
131 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
132 |
+
# the buffer is automatically moved, but not the original copy)
|
133 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
134 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
135 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
136 |
+
|
137 |
+
@torch.no_grad()
|
138 |
+
def forward(self, x, position_ids):
|
139 |
+
if "dynamic" in self.rope_type:
|
140 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
141 |
+
|
142 |
+
# Core RoPE block
|
143 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
144 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
145 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
146 |
+
device_type = x.device.type
|
147 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
148 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
149 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
150 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
151 |
+
cos = emb.cos()
|
152 |
+
sin = emb.sin()
|
153 |
+
|
154 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
155 |
+
cos = cos * self.attention_scaling
|
156 |
+
sin = sin * self.attention_scaling
|
157 |
+
|
158 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
159 |
+
|
160 |
+
|
161 |
+
def rotate_half(x):
|
162 |
+
"""Rotates half the hidden dims of the input."""
|
163 |
+
x1 = x[..., : x.shape[-1] // 2]
|
164 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
165 |
+
return torch.cat((-x2, x1), dim=-1)
|
166 |
+
|
167 |
+
|
168 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
169 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
170 |
+
|
171 |
+
Args:
|
172 |
+
q (`torch.Tensor`): The query tensor.
|
173 |
+
k (`torch.Tensor`): The key tensor.
|
174 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
175 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
176 |
+
position_ids (`torch.Tensor`, *optional*):
|
177 |
+
Deprecated and unused.
|
178 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
179 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
180 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
181 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
182 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
183 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
184 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
185 |
+
Returns:
|
186 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
187 |
+
"""
|
188 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
189 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
190 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
191 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
192 |
+
return q_embed, k_embed
|
193 |
+
|
194 |
+
|
195 |
+
class TriLMLinearMLP(nn.Module):
|
196 |
+
def __init__(self, config):
|
197 |
+
super().__init__()
|
198 |
+
self.config = config
|
199 |
+
self.hidden_size = config.hidden_size
|
200 |
+
self.intermediate_size = config.intermediate_size
|
201 |
+
assert config.mlp_bias == False, config.mlp_bias
|
202 |
+
self.gate_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
203 |
+
self.up_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
204 |
+
self.down_proj = TriLMLinear(self.intermediate_size, self.hidden_size)
|
205 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
206 |
+
|
207 |
+
def forward(self, x):
|
208 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
209 |
+
return down_proj
|
210 |
+
|
211 |
+
|
212 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
213 |
+
"""
|
214 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
215 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
216 |
+
"""
|
217 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
218 |
+
if n_rep == 1:
|
219 |
+
return hidden_states
|
220 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
221 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
222 |
+
|
223 |
+
|
224 |
+
def eager_attention_forward(
|
225 |
+
module: nn.Module,
|
226 |
+
query: torch.Tensor,
|
227 |
+
key: torch.Tensor,
|
228 |
+
value: torch.Tensor,
|
229 |
+
attention_mask: Optional[torch.Tensor],
|
230 |
+
scaling: float,
|
231 |
+
dropout: float = 0.0,
|
232 |
+
**kwargs,
|
233 |
+
):
|
234 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
235 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
236 |
+
|
237 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
238 |
+
if attention_mask is not None:
|
239 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
240 |
+
attn_weights = attn_weights + causal_mask
|
241 |
+
|
242 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
243 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
244 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
245 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
246 |
+
|
247 |
+
return attn_output, attn_weights
|
248 |
+
|
249 |
+
|
250 |
+
class TriLMLinearAttention(nn.Module):
|
251 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
252 |
+
|
253 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
254 |
+
super().__init__()
|
255 |
+
self.config = config
|
256 |
+
self.layer_idx = layer_idx
|
257 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
258 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
259 |
+
self.scaling = self.head_dim**-0.5
|
260 |
+
self.attention_dropout = config.attention_dropout
|
261 |
+
self.is_causal = True
|
262 |
+
assert config.attention_bias == False
|
263 |
+
self.q_proj = TriLMLinear(
|
264 |
+
config.hidden_size, config.num_attention_heads * self.head_dim#, bias=config.attention_bias
|
265 |
+
)
|
266 |
+
self.k_proj = TriLMLinear(
|
267 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
268 |
+
)
|
269 |
+
self.v_proj = TriLMLinear(
|
270 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
271 |
+
)
|
272 |
+
self.o_proj = TriLMLinear(
|
273 |
+
config.num_attention_heads * self.head_dim, config.hidden_size#, bias=config.attention_bias
|
274 |
+
)
|
275 |
+
|
276 |
+
def forward(
|
277 |
+
self,
|
278 |
+
hidden_states: torch.Tensor,
|
279 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
280 |
+
attention_mask: Optional[torch.Tensor],
|
281 |
+
past_key_value: Optional[Cache] = None,
|
282 |
+
cache_position: Optional[torch.LongTensor] = None,
|
283 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
284 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
285 |
+
input_shape = hidden_states.shape[:-1]
|
286 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
287 |
+
|
288 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
289 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
290 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
291 |
+
|
292 |
+
cos, sin = position_embeddings
|
293 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
294 |
+
|
295 |
+
if past_key_value is not None:
|
296 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
297 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
298 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
299 |
+
|
300 |
+
attention_interface: Callable = eager_attention_forward
|
301 |
+
if self.config._attn_implementation != "eager":
|
302 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
303 |
+
logger.warning_once(
|
304 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
305 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
306 |
+
)
|
307 |
+
else:
|
308 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
309 |
+
|
310 |
+
attn_output, attn_weights = attention_interface(
|
311 |
+
self,
|
312 |
+
query_states,
|
313 |
+
key_states,
|
314 |
+
value_states,
|
315 |
+
attention_mask,
|
316 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
317 |
+
scaling=self.scaling,
|
318 |
+
**kwargs,
|
319 |
+
)
|
320 |
+
|
321 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
322 |
+
attn_output = self.o_proj(attn_output)
|
323 |
+
return attn_output, attn_weights
|
324 |
+
|
325 |
+
|
326 |
+
class TriLMLinearDecoderLayer(nn.Module):
|
327 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
328 |
+
super().__init__()
|
329 |
+
self.hidden_size = config.hidden_size
|
330 |
+
|
331 |
+
self.self_attn = TriLMLinearAttention(config=config, layer_idx=layer_idx)
|
332 |
+
|
333 |
+
self.mlp = TriLMLinearMLP(config)
|
334 |
+
self.input_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
335 |
+
self.post_attention_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
336 |
+
|
337 |
+
def forward(
|
338 |
+
self,
|
339 |
+
hidden_states: torch.Tensor,
|
340 |
+
attention_mask: Optional[torch.Tensor] = None,
|
341 |
+
position_ids: Optional[torch.LongTensor] = None,
|
342 |
+
past_key_value: Optional[Cache] = None,
|
343 |
+
output_attentions: Optional[bool] = False,
|
344 |
+
use_cache: Optional[bool] = False,
|
345 |
+
cache_position: Optional[torch.LongTensor] = None,
|
346 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
347 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
348 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
349 |
+
residual = hidden_states
|
350 |
+
|
351 |
+
hidden_states = self.input_layernorm(hidden_states)
|
352 |
+
|
353 |
+
# Self Attention
|
354 |
+
hidden_states, self_attn_weights = self.self_attn(
|
355 |
+
hidden_states=hidden_states,
|
356 |
+
attention_mask=attention_mask,
|
357 |
+
position_ids=position_ids,
|
358 |
+
past_key_value=past_key_value,
|
359 |
+
output_attentions=output_attentions,
|
360 |
+
use_cache=use_cache,
|
361 |
+
cache_position=cache_position,
|
362 |
+
position_embeddings=position_embeddings,
|
363 |
+
**kwargs,
|
364 |
+
)
|
365 |
+
hidden_states = residual + hidden_states
|
366 |
+
|
367 |
+
# Fully Connected
|
368 |
+
residual = hidden_states
|
369 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
370 |
+
hidden_states = self.mlp(hidden_states)
|
371 |
+
hidden_states = residual + hidden_states
|
372 |
+
|
373 |
+
outputs = (hidden_states,)
|
374 |
+
if output_attentions:
|
375 |
+
outputs += (self_attn_weights,)
|
376 |
+
|
377 |
+
return outputs
|
378 |
+
|
379 |
+
|
380 |
+
class TriLMLinearPreTrainedModel(PreTrainedModel):
|
381 |
+
config_class = TriLMLinearConfig
|
382 |
+
base_model_prefix = "model"
|
383 |
+
supports_gradient_checkpointing = True
|
384 |
+
_no_split_modules = ["TriLMLinearDecoderLayer"]
|
385 |
+
_skip_keys_device_placement = ["past_key_values"]
|
386 |
+
_supports_flash_attn_2 = True
|
387 |
+
_supports_sdpa = True
|
388 |
+
_supports_flex_attn = True
|
389 |
+
_supports_cache_class = True
|
390 |
+
_supports_quantized_cache = True
|
391 |
+
_supports_static_cache = True
|
392 |
+
_supports_attention_backend = True
|
393 |
+
|
394 |
+
def _init_weights(self, module):
|
395 |
+
std = self.config.initializer_range
|
396 |
+
if isinstance(module, nn.Linear):
|
397 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
398 |
+
if module.bias is not None:
|
399 |
+
module.bias.data.zero_()
|
400 |
+
elif isinstance(module, nn.Embedding):
|
401 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
402 |
+
if module.padding_idx is not None:
|
403 |
+
module.weight.data[module.padding_idx].zero_()
|
404 |
+
|
405 |
+
|
406 |
+
|
407 |
+
|
408 |
+
class TriLMLinearModel(TriLMLinearPreTrainedModel):
|
409 |
+
"""
|
410 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TriLMLinearDecoderLayer`]
|
411 |
+
|
412 |
+
Args:
|
413 |
+
config: TriLMLinearConfig
|
414 |
+
"""
|
415 |
+
|
416 |
+
def __init__(self, config: TriLMLinearConfig):
|
417 |
+
super().__init__(config)
|
418 |
+
self.padding_idx = config.pad_token_id
|
419 |
+
self.vocab_size = config.vocab_size
|
420 |
+
|
421 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
422 |
+
self.layers = nn.ModuleList(
|
423 |
+
[TriLMLinearDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
424 |
+
)
|
425 |
+
self.norm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
426 |
+
self.rotary_emb = TriLMLinearRotaryEmbedding(config=config)
|
427 |
+
self.gradient_checkpointing = False
|
428 |
+
|
429 |
+
# Initialize weights and apply final processing
|
430 |
+
self.post_init()
|
431 |
+
|
432 |
+
def get_input_embeddings(self):
|
433 |
+
return self.embed_tokens
|
434 |
+
|
435 |
+
def set_input_embeddings(self, value):
|
436 |
+
self.embed_tokens = value
|
437 |
+
|
438 |
+
def forward(
|
439 |
+
self,
|
440 |
+
input_ids: torch.LongTensor = None,
|
441 |
+
attention_mask: Optional[torch.Tensor] = None,
|
442 |
+
position_ids: Optional[torch.LongTensor] = None,
|
443 |
+
past_key_values: Optional[Cache] = None,
|
444 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
445 |
+
use_cache: Optional[bool] = None,
|
446 |
+
output_attentions: Optional[bool] = None,
|
447 |
+
output_hidden_states: Optional[bool] = None,
|
448 |
+
return_dict: Optional[bool] = None,
|
449 |
+
cache_position: Optional[torch.LongTensor] = None,
|
450 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
451 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
452 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
453 |
+
output_hidden_states = (
|
454 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
455 |
+
)
|
456 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
457 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
458 |
+
|
459 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
460 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
461 |
+
|
462 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
463 |
+
logger.warning_once(
|
464 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
465 |
+
)
|
466 |
+
use_cache = False
|
467 |
+
|
468 |
+
if inputs_embeds is None:
|
469 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
470 |
+
|
471 |
+
if use_cache and past_key_values is None:
|
472 |
+
past_key_values = DynamicCache()
|
473 |
+
|
474 |
+
if cache_position is None:
|
475 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
476 |
+
cache_position = torch.arange(
|
477 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
478 |
+
)
|
479 |
+
|
480 |
+
if position_ids is None:
|
481 |
+
position_ids = cache_position.unsqueeze(0)
|
482 |
+
|
483 |
+
causal_mask = self._update_causal_mask(
|
484 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
485 |
+
)
|
486 |
+
|
487 |
+
hidden_states = inputs_embeds
|
488 |
+
|
489 |
+
# create position embeddings to be shared across the decoder layers
|
490 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
491 |
+
|
492 |
+
# decoder layers
|
493 |
+
all_hidden_states = () if output_hidden_states else None
|
494 |
+
all_self_attns = () if output_attentions else None
|
495 |
+
|
496 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
497 |
+
if output_hidden_states:
|
498 |
+
all_hidden_states += (hidden_states,)
|
499 |
+
|
500 |
+
if self.gradient_checkpointing and self.training:
|
501 |
+
layer_outputs = self._gradient_checkpointing_func(
|
502 |
+
decoder_layer.__call__,
|
503 |
+
hidden_states,
|
504 |
+
causal_mask,
|
505 |
+
position_ids,
|
506 |
+
past_key_values,
|
507 |
+
output_attentions,
|
508 |
+
use_cache,
|
509 |
+
cache_position,
|
510 |
+
position_embeddings,
|
511 |
+
)
|
512 |
+
else:
|
513 |
+
layer_outputs = decoder_layer(
|
514 |
+
hidden_states,
|
515 |
+
attention_mask=causal_mask,
|
516 |
+
position_ids=position_ids,
|
517 |
+
past_key_value=past_key_values,
|
518 |
+
output_attentions=output_attentions,
|
519 |
+
use_cache=use_cache,
|
520 |
+
cache_position=cache_position,
|
521 |
+
position_embeddings=position_embeddings,
|
522 |
+
**flash_attn_kwargs,
|
523 |
+
)
|
524 |
+
|
525 |
+
hidden_states = layer_outputs[0]
|
526 |
+
|
527 |
+
if output_attentions:
|
528 |
+
all_self_attns += (layer_outputs[1],)
|
529 |
+
|
530 |
+
hidden_states = self.norm(hidden_states)
|
531 |
+
|
532 |
+
# add hidden states from the last decoder layer
|
533 |
+
if output_hidden_states:
|
534 |
+
all_hidden_states += (hidden_states,)
|
535 |
+
|
536 |
+
output = BaseModelOutputWithPast(
|
537 |
+
last_hidden_state=hidden_states,
|
538 |
+
past_key_values=past_key_values if use_cache else None,
|
539 |
+
hidden_states=all_hidden_states,
|
540 |
+
attentions=all_self_attns,
|
541 |
+
)
|
542 |
+
return output if return_dict else output.to_tuple()
|
543 |
+
|
544 |
+
def _update_causal_mask(
|
545 |
+
self,
|
546 |
+
attention_mask: torch.Tensor,
|
547 |
+
input_tensor: torch.Tensor,
|
548 |
+
cache_position: torch.Tensor,
|
549 |
+
past_key_values: Cache,
|
550 |
+
output_attentions: bool,
|
551 |
+
):
|
552 |
+
if self.config._attn_implementation == "flash_attention_2":
|
553 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
554 |
+
return attention_mask
|
555 |
+
return None
|
556 |
+
|
557 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
558 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
559 |
+
# to infer the attention mask.
|
560 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
561 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
562 |
+
|
563 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
564 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
565 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
566 |
+
attention_mask,
|
567 |
+
inputs_embeds=input_tensor,
|
568 |
+
past_key_values_length=past_seen_tokens,
|
569 |
+
is_training=self.training,
|
570 |
+
):
|
571 |
+
return None
|
572 |
+
|
573 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
574 |
+
sequence_length = input_tensor.shape[1]
|
575 |
+
if using_static_cache:
|
576 |
+
target_length = past_key_values.get_max_cache_shape()
|
577 |
+
else:
|
578 |
+
target_length = (
|
579 |
+
attention_mask.shape[-1]
|
580 |
+
if isinstance(attention_mask, torch.Tensor)
|
581 |
+
else past_seen_tokens + sequence_length + 1
|
582 |
+
)
|
583 |
+
|
584 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
585 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
586 |
+
attention_mask,
|
587 |
+
sequence_length=sequence_length,
|
588 |
+
target_length=target_length,
|
589 |
+
dtype=dtype,
|
590 |
+
device=device,
|
591 |
+
cache_position=cache_position,
|
592 |
+
batch_size=input_tensor.shape[0],
|
593 |
+
)
|
594 |
+
|
595 |
+
if (
|
596 |
+
self.config._attn_implementation == "sdpa"
|
597 |
+
and attention_mask is not None
|
598 |
+
and attention_mask.device.type == "cuda"
|
599 |
+
and not output_attentions
|
600 |
+
):
|
601 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
602 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
603 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
604 |
+
min_dtype = torch.finfo(dtype).min
|
605 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
606 |
+
|
607 |
+
return causal_mask
|
608 |
+
|
609 |
+
@staticmethod
|
610 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
611 |
+
attention_mask: torch.Tensor,
|
612 |
+
sequence_length: int,
|
613 |
+
target_length: int,
|
614 |
+
dtype: torch.dtype,
|
615 |
+
device: torch.device,
|
616 |
+
cache_position: torch.Tensor,
|
617 |
+
batch_size: int,
|
618 |
+
**kwargs,
|
619 |
+
):
|
620 |
+
"""
|
621 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
622 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
623 |
+
|
624 |
+
Args:
|
625 |
+
attention_mask (`torch.Tensor`):
|
626 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
627 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
628 |
+
sequence_length (`int`):
|
629 |
+
The sequence length being processed.
|
630 |
+
target_length (`int`):
|
631 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
632 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
633 |
+
dtype (`torch.dtype`):
|
634 |
+
The dtype to use for the 4D attention mask.
|
635 |
+
device (`torch.device`):
|
636 |
+
The device to plcae the 4D attention mask on.
|
637 |
+
cache_position (`torch.Tensor`):
|
638 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
639 |
+
batch_size (`torch.Tensor`):
|
640 |
+
Batch size.
|
641 |
+
"""
|
642 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
643 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
644 |
+
causal_mask = attention_mask
|
645 |
+
else:
|
646 |
+
min_dtype = torch.finfo(dtype).min
|
647 |
+
causal_mask = torch.full(
|
648 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
649 |
+
)
|
650 |
+
if sequence_length != 1:
|
651 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
652 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
653 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
654 |
+
if attention_mask is not None:
|
655 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
656 |
+
mask_length = attention_mask.shape[-1]
|
657 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
658 |
+
padding_mask = padding_mask == 0
|
659 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
660 |
+
padding_mask, min_dtype
|
661 |
+
)
|
662 |
+
|
663 |
+
return causal_mask
|
664 |
+
|
665 |
+
|
666 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
667 |
+
|
668 |
+
|
669 |
+
class TriLMLinearForCausalLM(TriLMLinearPreTrainedModel, GenerationMixin):
|
670 |
+
_tied_weights_keys = ["lm_head.weight"]
|
671 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
672 |
+
|
673 |
+
def __init__(self, config):
|
674 |
+
super().__init__(config)
|
675 |
+
self.model = TriLMLinearModel(config)
|
676 |
+
self.vocab_size = config.vocab_size
|
677 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
678 |
+
|
679 |
+
# Initialize weights and apply final processing
|
680 |
+
self.post_init()
|
681 |
+
|
682 |
+
def get_input_embeddings(self):
|
683 |
+
return self.model.embed_tokens
|
684 |
+
|
685 |
+
def set_input_embeddings(self, value):
|
686 |
+
self.model.embed_tokens = value
|
687 |
+
|
688 |
+
def get_output_embeddings(self):
|
689 |
+
return self.lm_head
|
690 |
+
|
691 |
+
def set_output_embeddings(self, new_embeddings):
|
692 |
+
self.lm_head = new_embeddings
|
693 |
+
|
694 |
+
def set_decoder(self, decoder):
|
695 |
+
self.model = decoder
|
696 |
+
|
697 |
+
def get_decoder(self):
|
698 |
+
return self.model
|
699 |
+
|
700 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
701 |
+
def forward(
|
702 |
+
self,
|
703 |
+
input_ids: torch.LongTensor = None,
|
704 |
+
attention_mask: Optional[torch.Tensor] = None,
|
705 |
+
position_ids: Optional[torch.LongTensor] = None,
|
706 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
707 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
708 |
+
labels: Optional[torch.LongTensor] = None,
|
709 |
+
use_cache: Optional[bool] = None,
|
710 |
+
output_attentions: Optional[bool] = None,
|
711 |
+
output_hidden_states: Optional[bool] = None,
|
712 |
+
return_dict: Optional[bool] = None,
|
713 |
+
cache_position: Optional[torch.LongTensor] = None,
|
714 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
715 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
716 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
717 |
+
r"""
|
718 |
+
Args:
|
719 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
720 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
721 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
722 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
723 |
+
|
724 |
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
725 |
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
726 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
727 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
728 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
729 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
730 |
+
|
731 |
+
Returns:
|
732 |
+
|
733 |
+
Example:
|
734 |
+
|
735 |
+
```python
|
736 |
+
>>> from transformers import AutoTokenizer, TriLMLinearForCausalLM
|
737 |
+
|
738 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
739 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
740 |
+
|
741 |
+
>>> # Generate
|
742 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
743 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
744 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
745 |
+
```"""
|
746 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
747 |
+
output_hidden_states = (
|
748 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
749 |
+
)
|
750 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
751 |
+
|
752 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
753 |
+
outputs = self.model(
|
754 |
+
input_ids=input_ids,
|
755 |
+
attention_mask=attention_mask,
|
756 |
+
position_ids=position_ids,
|
757 |
+
past_key_values=past_key_values,
|
758 |
+
inputs_embeds=inputs_embeds,
|
759 |
+
use_cache=use_cache,
|
760 |
+
output_attentions=output_attentions,
|
761 |
+
output_hidden_states=output_hidden_states,
|
762 |
+
return_dict=return_dict,
|
763 |
+
cache_position=cache_position,
|
764 |
+
**kwargs,
|
765 |
+
)
|
766 |
+
|
767 |
+
hidden_states = outputs[0]
|
768 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
769 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
770 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
771 |
+
|
772 |
+
loss = None
|
773 |
+
if labels is not None:
|
774 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
775 |
+
|
776 |
+
if not return_dict:
|
777 |
+
output = (logits,) + outputs[1:]
|
778 |
+
return (loss,) + output if loss is not None else output
|
779 |
+
|
780 |
+
return CausalLMOutputWithPast(
|
781 |
+
loss=loss,
|
782 |
+
logits=logits,
|
783 |
+
past_key_values=outputs.past_key_values,
|
784 |
+
hidden_states=outputs.hidden_states,
|
785 |
+
attentions=outputs.attentions,
|
786 |
+
)
|
787 |
+
|
788 |
+
|
789 |
+
class TriLMLinearForSequenceClassification(TriLMLinearPreTrainedModel):
|
790 |
+
def __init__(self, config):
|
791 |
+
super().__init__(config)
|
792 |
+
self.num_labels = config.num_labels
|
793 |
+
self.model = TriLMLinearModel(config)
|
794 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
795 |
+
|
796 |
+
# Initialize weights and apply final processing
|
797 |
+
self.post_init()
|
798 |
+
|
799 |
+
def get_input_embeddings(self):
|
800 |
+
return self.model.embed_tokens
|
801 |
+
|
802 |
+
def set_input_embeddings(self, value):
|
803 |
+
self.model.embed_tokens = value
|
804 |
+
|
805 |
+
def forward(
|
806 |
+
self,
|
807 |
+
input_ids: Optional[torch.LongTensor] = None,
|
808 |
+
attention_mask: Optional[torch.Tensor] = None,
|
809 |
+
position_ids: Optional[torch.LongTensor] = None,
|
810 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
811 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
812 |
+
labels: Optional[torch.LongTensor] = None,
|
813 |
+
use_cache: Optional[bool] = None,
|
814 |
+
output_attentions: Optional[bool] = None,
|
815 |
+
output_hidden_states: Optional[bool] = None,
|
816 |
+
return_dict: Optional[bool] = None,
|
817 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
818 |
+
r"""
|
819 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
820 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
821 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
822 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
823 |
+
"""
|
824 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
825 |
+
|
826 |
+
transformer_outputs = self.model(
|
827 |
+
input_ids,
|
828 |
+
attention_mask=attention_mask,
|
829 |
+
position_ids=position_ids,
|
830 |
+
past_key_values=past_key_values,
|
831 |
+
inputs_embeds=inputs_embeds,
|
832 |
+
use_cache=use_cache,
|
833 |
+
output_attentions=output_attentions,
|
834 |
+
output_hidden_states=output_hidden_states,
|
835 |
+
return_dict=return_dict,
|
836 |
+
)
|
837 |
+
hidden_states = transformer_outputs[0]
|
838 |
+
logits = self.score(hidden_states)
|
839 |
+
|
840 |
+
if input_ids is not None:
|
841 |
+
batch_size = input_ids.shape[0]
|
842 |
+
else:
|
843 |
+
batch_size = inputs_embeds.shape[0]
|
844 |
+
|
845 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
846 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
847 |
+
if self.config.pad_token_id is None:
|
848 |
+
sequence_lengths = -1
|
849 |
+
else:
|
850 |
+
if input_ids is not None:
|
851 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
852 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
853 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
854 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
855 |
+
else:
|
856 |
+
sequence_lengths = -1
|
857 |
+
|
858 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
859 |
+
|
860 |
+
loss = None
|
861 |
+
if labels is not None:
|
862 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
863 |
+
|
864 |
+
if not return_dict:
|
865 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
866 |
+
return ((loss,) + output) if loss is not None else output
|
867 |
+
|
868 |
+
return SequenceClassifierOutputWithPast(
|
869 |
+
loss=loss,
|
870 |
+
logits=pooled_logits,
|
871 |
+
past_key_values=transformer_outputs.past_key_values,
|
872 |
+
hidden_states=transformer_outputs.hidden_states,
|
873 |
+
attentions=transformer_outputs.attentions,
|
874 |
+
)
|
875 |
+
|
876 |
+
|
877 |
+
class TriLMLinearForQuestionAnswering(TriLMLinearPreTrainedModel):
|
878 |
+
base_model_prefix = "transformer"
|
879 |
+
|
880 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->TriLMLinear
|
881 |
+
def __init__(self, config):
|
882 |
+
super().__init__(config)
|
883 |
+
self.transformer = TriLMLinearModel(config)
|
884 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
885 |
+
|
886 |
+
# Initialize weights and apply final processing
|
887 |
+
self.post_init()
|
888 |
+
|
889 |
+
def get_input_embeddings(self):
|
890 |
+
return self.transformer.embed_tokens
|
891 |
+
|
892 |
+
def set_input_embeddings(self, value):
|
893 |
+
self.transformer.embed_tokens = value
|
894 |
+
|
895 |
+
def forward(
|
896 |
+
self,
|
897 |
+
input_ids: Optional[torch.LongTensor] = None,
|
898 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
899 |
+
position_ids: Optional[torch.LongTensor] = None,
|
900 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
901 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
902 |
+
start_positions: Optional[torch.LongTensor] = None,
|
903 |
+
end_positions: Optional[torch.LongTensor] = None,
|
904 |
+
output_attentions: Optional[bool] = None,
|
905 |
+
output_hidden_states: Optional[bool] = None,
|
906 |
+
return_dict: Optional[bool] = None,
|
907 |
+
**kwargs,
|
908 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
909 |
+
r"""
|
910 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
911 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
912 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
913 |
+
are not taken into account for computing the loss.
|
914 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
915 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
916 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
917 |
+
are not taken into account for computing the loss.
|
918 |
+
"""
|
919 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
920 |
+
|
921 |
+
outputs = self.transformer(
|
922 |
+
input_ids,
|
923 |
+
attention_mask=attention_mask,
|
924 |
+
position_ids=position_ids,
|
925 |
+
past_key_values=past_key_values,
|
926 |
+
inputs_embeds=inputs_embeds,
|
927 |
+
output_attentions=output_attentions,
|
928 |
+
output_hidden_states=output_hidden_states,
|
929 |
+
return_dict=return_dict,
|
930 |
+
)
|
931 |
+
|
932 |
+
sequence_output = outputs[0]
|
933 |
+
|
934 |
+
logits = self.qa_outputs(sequence_output)
|
935 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
936 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
937 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
938 |
+
|
939 |
+
loss = None
|
940 |
+
if start_positions is not None and end_positions is not None:
|
941 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
942 |
+
|
943 |
+
if not return_dict:
|
944 |
+
output = (start_logits, end_logits) + outputs[2:]
|
945 |
+
return ((loss,) + output) if loss is not None else output
|
946 |
+
|
947 |
+
return QuestionAnsweringModelOutput(
|
948 |
+
loss=loss,
|
949 |
+
start_logits=start_logits,
|
950 |
+
end_logits=end_logits,
|
951 |
+
hidden_states=outputs.hidden_states,
|
952 |
+
attentions=outputs.attentions,
|
953 |
+
)
|
954 |
+
|
955 |
+
class TriLMLinearForTokenClassification(TriLMLinearPreTrainedModel):
|
956 |
+
def __init__(self, config):
|
957 |
+
super().__init__(config)
|
958 |
+
self.num_labels = config.num_labels
|
959 |
+
self.model = TriLMLinearModel(config)
|
960 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
961 |
+
classifier_dropout = config.classifier_dropout
|
962 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
963 |
+
classifier_dropout = config.hidden_dropout
|
964 |
+
else:
|
965 |
+
classifier_dropout = 0.1
|
966 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
967 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
968 |
+
|
969 |
+
# Initialize weights and apply final processing
|
970 |
+
self.post_init()
|
971 |
+
|
972 |
+
def get_input_embeddings(self):
|
973 |
+
return self.model.embed_tokens
|
974 |
+
|
975 |
+
def set_input_embeddings(self, value):
|
976 |
+
self.model.embed_tokens = value
|
977 |
+
|
978 |
+
def forward(
|
979 |
+
self,
|
980 |
+
input_ids: Optional[torch.LongTensor] = None,
|
981 |
+
attention_mask: Optional[torch.Tensor] = None,
|
982 |
+
position_ids: Optional[torch.LongTensor] = None,
|
983 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
984 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
985 |
+
labels: Optional[torch.LongTensor] = None,
|
986 |
+
use_cache: Optional[bool] = None,
|
987 |
+
output_attentions: Optional[bool] = None,
|
988 |
+
output_hidden_states: Optional[bool] = None,
|
989 |
+
return_dict: Optional[bool] = None,
|
990 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
991 |
+
r"""
|
992 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
993 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
994 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
995 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
996 |
+
"""
|
997 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
998 |
+
|
999 |
+
outputs = self.model(
|
1000 |
+
input_ids,
|
1001 |
+
attention_mask=attention_mask,
|
1002 |
+
position_ids=position_ids,
|
1003 |
+
past_key_values=past_key_values,
|
1004 |
+
inputs_embeds=inputs_embeds,
|
1005 |
+
use_cache=use_cache,
|
1006 |
+
output_attentions=output_attentions,
|
1007 |
+
output_hidden_states=output_hidden_states,
|
1008 |
+
return_dict=return_dict,
|
1009 |
+
)
|
1010 |
+
sequence_output = outputs[0]
|
1011 |
+
sequence_output = self.dropout(sequence_output)
|
1012 |
+
logits = self.score(sequence_output)
|
1013 |
+
|
1014 |
+
loss = None
|
1015 |
+
if labels is not None:
|
1016 |
+
loss = self.loss_function(logits, labels, self.config)
|
1017 |
+
|
1018 |
+
if not return_dict:
|
1019 |
+
output = (logits,) + outputs[2:]
|
1020 |
+
return ((loss,) + output) if loss is not None else output
|
1021 |
+
|
1022 |
+
return TokenClassifierOutput(
|
1023 |
+
loss=loss,
|
1024 |
+
logits=logits,
|
1025 |
+
hidden_states=outputs.hidden_states,
|
1026 |
+
attentions=outputs.attentions,
|
1027 |
+
)
|
1028 |
+
|
1029 |
+
|
1030 |
+
__all__ = [
|
1031 |
+
"TriLMLinearForCausalLM",
|
1032 |
+
"TriLMLinearModel",
|
1033 |
+
"TriLMLinearPreTrainedModel",
|
1034 |
+
"TriLMLinearForSequenceClassification",
|
1035 |
+
"TriLMLinearForQuestionAnswering",
|
1036 |
+
"TriLMLinearForTokenClassification",
|
1037 |
+
]
|
TriLMs/TriLM_1.1B_Unpacked.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1e86557f21a033cc7b237989d3a70453099cde11f17c3d4bc679d348c7e30ac1
|
3 |
+
size 2299465632
|
TriLMs/TriLM_1.1B_Unpacked_trirun.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bb839d7ca1acfe0154e10d345f054925b1e617afba565335b9c1997fa8a0c951
|
3 |
+
size 604858888
|
TriLMs/TriLM_1.5B_Unpacked.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c89dd3e035e76692400dc44be0e52e9ea6c50a83dcb582d71e80bfbb1d9e7472
|
3 |
+
size 3030610384
|
TriLMs/TriLM_1.5B_Unpacked_trirun.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6e901b35a5471be1b1ba78105761eac87abf609fc84c7b5e68373cab7ef99f99
|
3 |
+
size 741620784
|
TriLMs/TriLM_190M_Unpacked.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c2bb76df6f7dc4daae53c87008ef6720fb1f817861b0f0e85f258508e389f621
|
3 |
+
size 381093312
|
TriLMs/TriLM_190M_Unpacked_trirun.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ed7dce396f76c149ee83e274e27767e035b4b36d08bbd4ff1767fa6c47ba0cf1
|
3 |
+
size 183178992
|
TriLMs/TriLM_2.4B_Unpacked.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:133f7b25a28148f1a39ef07b420ab4100bc0cbdd791b76358d23a035ed6a96e7
|
3 |
+
size 4922983496
|
TriLMs/TriLM_2.4B_Unpacked_trirun.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1f9b77be25abb0fb606428c2a033b098ea89bc5ce40137c0e14092d53a6d4c11
|
3 |
+
size 1022934904
|
TriLMs/TriLM_3.9B_Unpacked.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:96d2991e7880d1734fb28103ade8b6b9c2e821204b1102d658883c09a136b461
|
3 |
+
size 7984263792
|
TriLMs/TriLM_3.9B_Unpacked_trirun.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5d2c108a7ac3848d89865f47778d48e9c81158d76b1670f7f9e57c097323940a
|
3 |
+
size 1545437592
|
TriLMs/TriLM_390M_Unpacked.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9aee97f50ef163d1126f59d923435ac16930e660abc16275ec199434282b5213
|
3 |
+
size 784984184
|
TriLMs/TriLM_390M_Unpacked_trirun.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:48b46988f6bb513fb72f13a479a42888b7b0b04c030bd4442dbbf0c8f96cdeb1
|
3 |
+
size 279032464
|
TriLMs/TriLM_560M_Unpacked.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4ae4f86d95b0f3c4e2506ed1a6b9cc19178f30ac23e05adf40e18e6935c00d3f
|
3 |
+
size 1138510528
|
TriLMs/TriLM_560M_Unpacked_trirun.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6b76f468faaf8c5282360050c6eb742bd2aeaada6eaa5c9c3ad9a36d864ec7fe
|
3 |
+
size 368428224
|
TriLMs/TriLM_830M_Unpacked.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2a2109c1f319371dc387ab0b15d08354669e8aa73727c4abaaf1f3f83cf738c3
|
3 |
+
size 1668197712
|
TriLMs/TriLM_830M_Unpacked_trirun.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ab58c093de49f63f139945f9720f38d07f7e0fc88cb15b98a60d0a73537fde51
|
3 |
+
size 479893304
|
TriLMs/TriLM_99M_Unpacked.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:34b4de19e9bc4da74ff12ac00997485a434c8e0c7846efcbd9cc44707b2dff56
|
3 |
+
size 199541696
|
TriLMs/TriLM_99M_Unpacked_trirun.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3cb3736cefebbe565cd6fd2741461e38b0df232d1009d20f0b4bed4cfea2be34
|
3 |
+
size 115307616
|
Yi-34B/config.json
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"LlamaForCausalLM"
|
4 |
+
],
|
5 |
+
"bos_token_id": 1,
|
6 |
+
"eos_token_id": 2,
|
7 |
+
"hidden_act": "silu",
|
8 |
+
"hidden_size": 7168,
|
9 |
+
"initializer_range": 0.02,
|
10 |
+
"intermediate_size": 20480,
|
11 |
+
"max_position_embeddings": 4096,
|
12 |
+
"model_type": "llama",
|
13 |
+
"num_attention_heads": 56,
|
14 |
+
"num_hidden_layers": 60,
|
15 |
+
"num_key_value_heads": 8,
|
16 |
+
"pad_token_id": 0,
|
17 |
+
"pretraining_tp": 1,
|
18 |
+
"rms_norm_eps": 1e-05,
|
19 |
+
"rope_scaling": null,
|
20 |
+
"rope_theta": 5000000.0,
|
21 |
+
"tie_word_embeddings": false,
|
22 |
+
"torch_dtype": "bfloat16",
|
23 |
+
"transformers_version": "4.34.0",
|
24 |
+
"use_cache": true,
|
25 |
+
"vocab_size": 64000
|
26 |
+
}
|
Yi-34B/model.safetensors.aa
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5c75955447a8fd4a636f629b616951d57d0e2127f48f940b4894fe8c9acedce2
|
3 |
+
size 34388949084
|
Yi-34B/model.safetensors.ab
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bd5e9de9497882619969ef48eed15810d168a66d70b56b42f5b025c03cb10ea7
|
3 |
+
size 34388949084
|
Yi-34B_trirun/config.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"TriLMLinearForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_trilmlinear.TriLMLinearConfig",
|
7 |
+
"AutoModel": "modeling_trilmlinear.TriLMLinearModel",
|
8 |
+
"AutoModelForCausalLM": "modeling_trilmlinear.TriLMLinearForCausalLM"
|
9 |
+
},
|
10 |
+
"bos_token_id": 1,
|
11 |
+
"eos_token_id": 2,
|
12 |
+
"hidden_act": "silu",
|
13 |
+
"hidden_size": 7168,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 20480,
|
16 |
+
"max_position_embeddings": 4096,
|
17 |
+
"model_type": "TriLMLinear",
|
18 |
+
"num_attention_heads": 56,
|
19 |
+
"num_hidden_layers": 60,
|
20 |
+
"num_key_value_heads": 8,
|
21 |
+
"pad_token_id": 0,
|
22 |
+
"pretraining_tp": 1,
|
23 |
+
"rms_norm_eps": 1e-05,
|
24 |
+
"rope_scaling": null,
|
25 |
+
"rope_theta": 5000000.0,
|
26 |
+
"tie_word_embeddings": false,
|
27 |
+
"torch_dtype": "bfloat16",
|
28 |
+
"transformers_version": "4.34.0",
|
29 |
+
"use_cache": true,
|
30 |
+
"vocab_size": 64000
|
31 |
+
}
|
Yi-34B_trirun/configuration_trilmlinear.py
ADDED
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""TriLMLinear model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
24 |
+
|
25 |
+
|
26 |
+
class TriLMLinearConfig(PretrainedConfig):
|
27 |
+
r"""
|
28 |
+
This is the configuration class to store the configuration of a [`TriLMLinearModel`]. It is used to instantiate an LLaMA
|
29 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
30 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
31 |
+
|
32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
33 |
+
documentation from [`PretrainedConfig`] for more information.
|
34 |
+
|
35 |
+
|
36 |
+
Args:
|
37 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
38 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
39 |
+
`inputs_ids` passed when calling [`LlamaModel`]
|
40 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
41 |
+
Dimension of the hidden representations.
|
42 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
43 |
+
Dimension of the MLP representations.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
45 |
+
Number of hidden layers in the Transformer decoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
47 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
48 |
+
num_key_value_heads (`int`, *optional*):
|
49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
51 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
54 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
55 |
+
`num_attention_heads`.
|
56 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
57 |
+
The non-linear activation function (function or string) in the decoder.
|
58 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
59 |
+
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
60 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
64 |
+
The epsilon used by the rms normalization layers.
|
65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
67 |
+
relevant if `config.is_decoder=True`.
|
68 |
+
pad_token_id (`int`, *optional*):
|
69 |
+
Padding token id.
|
70 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
71 |
+
Beginning of stream token id.
|
72 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
73 |
+
End of stream token id.
|
74 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
75 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
76 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
|
77 |
+
understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
|
78 |
+
results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
|
79 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
80 |
+
Whether to tie weight embeddings
|
81 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
82 |
+
The base period of the RoPE embeddings.
|
83 |
+
rope_scaling (`Dict`, *optional*):
|
84 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
85 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
86 |
+
accordingly.
|
87 |
+
Expected contents:
|
88 |
+
`rope_type` (`str`):
|
89 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
90 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
91 |
+
`factor` (`float`, *optional*):
|
92 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
93 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
94 |
+
original maximum pre-trained length.
|
95 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
96 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
97 |
+
pretraining.
|
98 |
+
`attention_factor` (`float`, *optional*):
|
99 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
100 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
101 |
+
`factor` field to infer the suggested value.
|
102 |
+
`beta_fast` (`float`, *optional*):
|
103 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
104 |
+
ramp function. If unspecified, it defaults to 32.
|
105 |
+
`beta_slow` (`float`, *optional*):
|
106 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
107 |
+
ramp function. If unspecified, it defaults to 1.
|
108 |
+
`short_factor` (`List[float]`, *optional*):
|
109 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
110 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
111 |
+
size divided by the number of attention heads divided by 2
|
112 |
+
`long_factor` (`List[float]`, *optional*):
|
113 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
114 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
115 |
+
size divided by the number of attention heads divided by 2
|
116 |
+
`low_freq_factor` (`float`, *optional*):
|
117 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
118 |
+
`high_freq_factor` (`float`, *optional*):
|
119 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
120 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
121 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
122 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
123 |
+
The dropout ratio for the attention probabilities.
|
124 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
125 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
126 |
+
head_dim (`int`, *optional*):
|
127 |
+
The attention head dimension. If None, it will default to hidden_size // num_attention_heads
|
128 |
+
|
129 |
+
```python
|
130 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
131 |
+
|
132 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
133 |
+
>>> configuration = LlamaConfig()
|
134 |
+
|
135 |
+
>>> # Initializing a model from the llama-7b style configuration
|
136 |
+
>>> model = LlamaModel(configuration)
|
137 |
+
|
138 |
+
>>> # Accessing the model configuration
|
139 |
+
>>> configuration = model.config
|
140 |
+
```"""
|
141 |
+
|
142 |
+
model_type = "TriLMLinear"
|
143 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
144 |
+
# Default tensor parallel plan for base model `LlamaModel`
|
145 |
+
base_model_tp_plan = {
|
146 |
+
"layers.*.self_attn.q_proj": "colwise",
|
147 |
+
"layers.*.self_attn.k_proj": "colwise",
|
148 |
+
"layers.*.self_attn.v_proj": "colwise",
|
149 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
150 |
+
"layers.*.mlp.gate_proj": "colwise",
|
151 |
+
"layers.*.mlp.up_proj": "colwise",
|
152 |
+
"layers.*.mlp.down_proj": "rowwise",
|
153 |
+
}
|
154 |
+
|
155 |
+
def __init__(
|
156 |
+
self,
|
157 |
+
vocab_size=32000,
|
158 |
+
hidden_size=4096,
|
159 |
+
intermediate_size=11008,
|
160 |
+
num_hidden_layers=32,
|
161 |
+
num_attention_heads=32,
|
162 |
+
num_key_value_heads=None,
|
163 |
+
hidden_act="silu",
|
164 |
+
max_position_embeddings=2048,
|
165 |
+
initializer_range=0.02,
|
166 |
+
rms_norm_eps=1e-6,
|
167 |
+
use_cache=True,
|
168 |
+
pad_token_id=None,
|
169 |
+
bos_token_id=1,
|
170 |
+
eos_token_id=2,
|
171 |
+
pretraining_tp=1,
|
172 |
+
tie_word_embeddings=False,
|
173 |
+
rope_theta=10000.0,
|
174 |
+
rope_scaling=None,
|
175 |
+
attention_bias=False,
|
176 |
+
attention_dropout=0.0,
|
177 |
+
mlp_bias=False,
|
178 |
+
head_dim=None,
|
179 |
+
**kwargs,
|
180 |
+
):
|
181 |
+
self.vocab_size = vocab_size
|
182 |
+
self.max_position_embeddings = max_position_embeddings
|
183 |
+
self.hidden_size = hidden_size
|
184 |
+
self.intermediate_size = intermediate_size
|
185 |
+
self.num_hidden_layers = num_hidden_layers
|
186 |
+
self.num_attention_heads = num_attention_heads
|
187 |
+
|
188 |
+
# for backward compatibility
|
189 |
+
if num_key_value_heads is None:
|
190 |
+
num_key_value_heads = num_attention_heads
|
191 |
+
|
192 |
+
self.num_key_value_heads = num_key_value_heads
|
193 |
+
self.hidden_act = hidden_act
|
194 |
+
self.initializer_range = initializer_range
|
195 |
+
self.rms_norm_eps = rms_norm_eps
|
196 |
+
self.pretraining_tp = pretraining_tp
|
197 |
+
self.use_cache = use_cache
|
198 |
+
self.rope_theta = rope_theta
|
199 |
+
self.rope_scaling = rope_scaling
|
200 |
+
self.attention_bias = attention_bias
|
201 |
+
self.attention_dropout = attention_dropout
|
202 |
+
self.mlp_bias = mlp_bias
|
203 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
204 |
+
# Validate the correctness of rotary position embeddings parameters
|
205 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
206 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
207 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
208 |
+
rope_config_validation(self)
|
209 |
+
|
210 |
+
super().__init__(
|
211 |
+
pad_token_id=pad_token_id,
|
212 |
+
bos_token_id=bos_token_id,
|
213 |
+
eos_token_id=eos_token_id,
|
214 |
+
tie_word_embeddings=tie_word_embeddings,
|
215 |
+
**kwargs,
|
216 |
+
)
|
217 |
+
|
218 |
+
|
219 |
+
__all__ = ["TriLMLinearConfig"]
|
220 |
+
|
Yi-34B_trirun/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7ca008dee2dd0a9279fb0f07c95652c077e7b963be7e589d73f8bff9d53c7811
|
3 |
+
size 10212234064
|
Yi-34B_trirun/modeling_trilmlinear.py
ADDED
@@ -0,0 +1,1037 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from typing import Callable, List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
|
26 |
+
from transformers.activations import ACT2FN
|
27 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
28 |
+
from transformers.generation import GenerationMixin
|
29 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
30 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
31 |
+
from transformers.modeling_outputs import (
|
32 |
+
BaseModelOutputWithPast,
|
33 |
+
CausalLMOutputWithPast,
|
34 |
+
QuestionAnsweringModelOutput,
|
35 |
+
SequenceClassifierOutputWithPast,
|
36 |
+
TokenClassifierOutput,
|
37 |
+
)
|
38 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
39 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
40 |
+
from transformers.processing_utils import Unpack
|
41 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
42 |
+
from transformers.utils import (
|
43 |
+
LossKwargs,
|
44 |
+
add_code_sample_docstrings,
|
45 |
+
add_start_docstrings,
|
46 |
+
add_start_docstrings_to_model_forward,
|
47 |
+
logging,
|
48 |
+
replace_return_docstrings,
|
49 |
+
)
|
50 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
51 |
+
from .configuration_trilmlinear import TriLMLinearConfig
|
52 |
+
import marlin
|
53 |
+
|
54 |
+
logger = logging.get_logger(__name__)
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
class TriLMLinear(torch.nn.Module):
|
59 |
+
def __init__(self, in_dims, out_dims, thread_k=128, thread_n=128, groupsize=-1, sms=-1):
|
60 |
+
super(TriLMLinear, self).__init__()
|
61 |
+
self.in_dims, self.out_dims = in_dims, out_dims
|
62 |
+
self.thread_k, self.thread_n, self.groupsize, self.sms = thread_k, thread_n, groupsize, sms
|
63 |
+
packed_weight = torch.ones((in_dims//16, out_dims), dtype=torch.int32)
|
64 |
+
scales = torch.ones((1, out_dims), dtype=torch.float16)
|
65 |
+
self.register_buffer("packed_weight", packed_weight)
|
66 |
+
self.register_buffer("scales", scales)
|
67 |
+
self.workspace = torch.zeros(self.out_dims // 128 * 16, device="cuda")
|
68 |
+
def forward(self, hidden_state):
|
69 |
+
# print(A, self.name)
|
70 |
+
batch_size, seqlen, last_dim = hidden_state.shape
|
71 |
+
output = torch.zeros((batch_size * seqlen, self.out_dims), dtype=torch.float16, device=self.packed_weight.device)
|
72 |
+
marlin.mul(hidden_state.reshape(batch_size * seqlen, last_dim).contiguous(), self.packed_weight, output, self.scales,
|
73 |
+
self.workspace, self.thread_k, self.thread_n, self.sms)
|
74 |
+
return output.reshape(batch_size, seqlen, -1)
|
75 |
+
|
76 |
+
|
77 |
+
class TriLMLinearRMSNorm(nn.Module):
|
78 |
+
def __init__(self, hidden_size, eps=1e-6):
|
79 |
+
"""
|
80 |
+
TriLMLinearRMSNorm is equivalent to T5LayerNorm
|
81 |
+
"""
|
82 |
+
super().__init__()
|
83 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
84 |
+
self.variance_epsilon = eps
|
85 |
+
|
86 |
+
def forward(self, hidden_states):
|
87 |
+
input_dtype = hidden_states.dtype
|
88 |
+
hidden_states = hidden_states.to(torch.float32)
|
89 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
90 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
91 |
+
return self.weight * hidden_states.to(input_dtype)
|
92 |
+
|
93 |
+
def extra_repr(self):
|
94 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
95 |
+
|
96 |
+
|
97 |
+
ALL_LAYERNORM_LAYERS.append(TriLMLinearRMSNorm)
|
98 |
+
|
99 |
+
|
100 |
+
class TriLMLinearRotaryEmbedding(nn.Module):
|
101 |
+
def __init__(self, config: TriLMLinearConfig, device=None):
|
102 |
+
super().__init__()
|
103 |
+
# BC: "rope_type" was originally "type"
|
104 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
105 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
106 |
+
else:
|
107 |
+
self.rope_type = "default"
|
108 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
109 |
+
self.original_max_seq_len = config.max_position_embeddings
|
110 |
+
|
111 |
+
self.config = config
|
112 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
113 |
+
|
114 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
115 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
116 |
+
self.original_inv_freq = self.inv_freq
|
117 |
+
|
118 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
119 |
+
"""
|
120 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
121 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
122 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
123 |
+
"""
|
124 |
+
seq_len = torch.max(position_ids) + 1
|
125 |
+
if seq_len > self.max_seq_len_cached: # growth
|
126 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
127 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
128 |
+
self.max_seq_len_cached = seq_len
|
129 |
+
|
130 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
131 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
132 |
+
# the buffer is automatically moved, but not the original copy)
|
133 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
134 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
135 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
136 |
+
|
137 |
+
@torch.no_grad()
|
138 |
+
def forward(self, x, position_ids):
|
139 |
+
if "dynamic" in self.rope_type:
|
140 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
141 |
+
|
142 |
+
# Core RoPE block
|
143 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
144 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
145 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
146 |
+
device_type = x.device.type
|
147 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
148 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
149 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
150 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
151 |
+
cos = emb.cos()
|
152 |
+
sin = emb.sin()
|
153 |
+
|
154 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
155 |
+
cos = cos * self.attention_scaling
|
156 |
+
sin = sin * self.attention_scaling
|
157 |
+
|
158 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
159 |
+
|
160 |
+
|
161 |
+
def rotate_half(x):
|
162 |
+
"""Rotates half the hidden dims of the input."""
|
163 |
+
x1 = x[..., : x.shape[-1] // 2]
|
164 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
165 |
+
return torch.cat((-x2, x1), dim=-1)
|
166 |
+
|
167 |
+
|
168 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
169 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
170 |
+
|
171 |
+
Args:
|
172 |
+
q (`torch.Tensor`): The query tensor.
|
173 |
+
k (`torch.Tensor`): The key tensor.
|
174 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
175 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
176 |
+
position_ids (`torch.Tensor`, *optional*):
|
177 |
+
Deprecated and unused.
|
178 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
179 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
180 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
181 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
182 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
183 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
184 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
185 |
+
Returns:
|
186 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
187 |
+
"""
|
188 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
189 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
190 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
191 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
192 |
+
return q_embed, k_embed
|
193 |
+
|
194 |
+
|
195 |
+
class TriLMLinearMLP(nn.Module):
|
196 |
+
def __init__(self, config):
|
197 |
+
super().__init__()
|
198 |
+
self.config = config
|
199 |
+
self.hidden_size = config.hidden_size
|
200 |
+
self.intermediate_size = config.intermediate_size
|
201 |
+
assert config.mlp_bias == False, config.mlp_bias
|
202 |
+
self.gate_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
203 |
+
self.up_proj = TriLMLinear(self.hidden_size, self.intermediate_size)
|
204 |
+
self.down_proj = TriLMLinear(self.intermediate_size, self.hidden_size)
|
205 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
206 |
+
|
207 |
+
def forward(self, x):
|
208 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
209 |
+
return down_proj
|
210 |
+
|
211 |
+
|
212 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
213 |
+
"""
|
214 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
215 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
216 |
+
"""
|
217 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
218 |
+
if n_rep == 1:
|
219 |
+
return hidden_states
|
220 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
221 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
222 |
+
|
223 |
+
|
224 |
+
def eager_attention_forward(
|
225 |
+
module: nn.Module,
|
226 |
+
query: torch.Tensor,
|
227 |
+
key: torch.Tensor,
|
228 |
+
value: torch.Tensor,
|
229 |
+
attention_mask: Optional[torch.Tensor],
|
230 |
+
scaling: float,
|
231 |
+
dropout: float = 0.0,
|
232 |
+
**kwargs,
|
233 |
+
):
|
234 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
235 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
236 |
+
|
237 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
238 |
+
if attention_mask is not None:
|
239 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
240 |
+
attn_weights = attn_weights + causal_mask
|
241 |
+
|
242 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
243 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
244 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
245 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
246 |
+
|
247 |
+
return attn_output, attn_weights
|
248 |
+
|
249 |
+
|
250 |
+
class TriLMLinearAttention(nn.Module):
|
251 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
252 |
+
|
253 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
254 |
+
super().__init__()
|
255 |
+
self.config = config
|
256 |
+
self.layer_idx = layer_idx
|
257 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
258 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
259 |
+
self.scaling = self.head_dim**-0.5
|
260 |
+
self.attention_dropout = config.attention_dropout
|
261 |
+
self.is_causal = True
|
262 |
+
assert config.attention_bias == False
|
263 |
+
self.q_proj = TriLMLinear(
|
264 |
+
config.hidden_size, config.num_attention_heads * self.head_dim#, bias=config.attention_bias
|
265 |
+
)
|
266 |
+
self.k_proj = TriLMLinear(
|
267 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
268 |
+
)
|
269 |
+
self.v_proj = TriLMLinear(
|
270 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim#, bias=config.attention_bias
|
271 |
+
)
|
272 |
+
self.o_proj = TriLMLinear(
|
273 |
+
config.num_attention_heads * self.head_dim, config.hidden_size#, bias=config.attention_bias
|
274 |
+
)
|
275 |
+
|
276 |
+
def forward(
|
277 |
+
self,
|
278 |
+
hidden_states: torch.Tensor,
|
279 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
280 |
+
attention_mask: Optional[torch.Tensor],
|
281 |
+
past_key_value: Optional[Cache] = None,
|
282 |
+
cache_position: Optional[torch.LongTensor] = None,
|
283 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
284 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
285 |
+
input_shape = hidden_states.shape[:-1]
|
286 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
287 |
+
|
288 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
289 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
290 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
291 |
+
|
292 |
+
cos, sin = position_embeddings
|
293 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
294 |
+
|
295 |
+
if past_key_value is not None:
|
296 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
297 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
298 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
299 |
+
|
300 |
+
attention_interface: Callable = eager_attention_forward
|
301 |
+
if self.config._attn_implementation != "eager":
|
302 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
303 |
+
logger.warning_once(
|
304 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
305 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
306 |
+
)
|
307 |
+
else:
|
308 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
309 |
+
|
310 |
+
attn_output, attn_weights = attention_interface(
|
311 |
+
self,
|
312 |
+
query_states,
|
313 |
+
key_states,
|
314 |
+
value_states,
|
315 |
+
attention_mask,
|
316 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
317 |
+
scaling=self.scaling,
|
318 |
+
**kwargs,
|
319 |
+
)
|
320 |
+
|
321 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
322 |
+
attn_output = self.o_proj(attn_output)
|
323 |
+
return attn_output, attn_weights
|
324 |
+
|
325 |
+
|
326 |
+
class TriLMLinearDecoderLayer(nn.Module):
|
327 |
+
def __init__(self, config: TriLMLinearConfig, layer_idx: int):
|
328 |
+
super().__init__()
|
329 |
+
self.hidden_size = config.hidden_size
|
330 |
+
|
331 |
+
self.self_attn = TriLMLinearAttention(config=config, layer_idx=layer_idx)
|
332 |
+
|
333 |
+
self.mlp = TriLMLinearMLP(config)
|
334 |
+
self.input_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
335 |
+
self.post_attention_layernorm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
336 |
+
|
337 |
+
def forward(
|
338 |
+
self,
|
339 |
+
hidden_states: torch.Tensor,
|
340 |
+
attention_mask: Optional[torch.Tensor] = None,
|
341 |
+
position_ids: Optional[torch.LongTensor] = None,
|
342 |
+
past_key_value: Optional[Cache] = None,
|
343 |
+
output_attentions: Optional[bool] = False,
|
344 |
+
use_cache: Optional[bool] = False,
|
345 |
+
cache_position: Optional[torch.LongTensor] = None,
|
346 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
347 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
348 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
349 |
+
residual = hidden_states
|
350 |
+
|
351 |
+
hidden_states = self.input_layernorm(hidden_states)
|
352 |
+
|
353 |
+
# Self Attention
|
354 |
+
hidden_states, self_attn_weights = self.self_attn(
|
355 |
+
hidden_states=hidden_states,
|
356 |
+
attention_mask=attention_mask,
|
357 |
+
position_ids=position_ids,
|
358 |
+
past_key_value=past_key_value,
|
359 |
+
output_attentions=output_attentions,
|
360 |
+
use_cache=use_cache,
|
361 |
+
cache_position=cache_position,
|
362 |
+
position_embeddings=position_embeddings,
|
363 |
+
**kwargs,
|
364 |
+
)
|
365 |
+
hidden_states = residual + hidden_states
|
366 |
+
|
367 |
+
# Fully Connected
|
368 |
+
residual = hidden_states
|
369 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
370 |
+
hidden_states = self.mlp(hidden_states)
|
371 |
+
hidden_states = residual + hidden_states
|
372 |
+
|
373 |
+
outputs = (hidden_states,)
|
374 |
+
if output_attentions:
|
375 |
+
outputs += (self_attn_weights,)
|
376 |
+
|
377 |
+
return outputs
|
378 |
+
|
379 |
+
|
380 |
+
class TriLMLinearPreTrainedModel(PreTrainedModel):
|
381 |
+
config_class = TriLMLinearConfig
|
382 |
+
base_model_prefix = "model"
|
383 |
+
supports_gradient_checkpointing = True
|
384 |
+
_no_split_modules = ["TriLMLinearDecoderLayer"]
|
385 |
+
_skip_keys_device_placement = ["past_key_values"]
|
386 |
+
_supports_flash_attn_2 = True
|
387 |
+
_supports_sdpa = True
|
388 |
+
_supports_flex_attn = True
|
389 |
+
_supports_cache_class = True
|
390 |
+
_supports_quantized_cache = True
|
391 |
+
_supports_static_cache = True
|
392 |
+
_supports_attention_backend = True
|
393 |
+
|
394 |
+
def _init_weights(self, module):
|
395 |
+
std = self.config.initializer_range
|
396 |
+
if isinstance(module, nn.Linear):
|
397 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
398 |
+
if module.bias is not None:
|
399 |
+
module.bias.data.zero_()
|
400 |
+
elif isinstance(module, nn.Embedding):
|
401 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
402 |
+
if module.padding_idx is not None:
|
403 |
+
module.weight.data[module.padding_idx].zero_()
|
404 |
+
|
405 |
+
|
406 |
+
|
407 |
+
|
408 |
+
class TriLMLinearModel(TriLMLinearPreTrainedModel):
|
409 |
+
"""
|
410 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TriLMLinearDecoderLayer`]
|
411 |
+
|
412 |
+
Args:
|
413 |
+
config: TriLMLinearConfig
|
414 |
+
"""
|
415 |
+
|
416 |
+
def __init__(self, config: TriLMLinearConfig):
|
417 |
+
super().__init__(config)
|
418 |
+
self.padding_idx = config.pad_token_id
|
419 |
+
self.vocab_size = config.vocab_size
|
420 |
+
|
421 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
422 |
+
self.layers = nn.ModuleList(
|
423 |
+
[TriLMLinearDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
424 |
+
)
|
425 |
+
self.norm = TriLMLinearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
426 |
+
self.rotary_emb = TriLMLinearRotaryEmbedding(config=config)
|
427 |
+
self.gradient_checkpointing = False
|
428 |
+
|
429 |
+
# Initialize weights and apply final processing
|
430 |
+
self.post_init()
|
431 |
+
|
432 |
+
def get_input_embeddings(self):
|
433 |
+
return self.embed_tokens
|
434 |
+
|
435 |
+
def set_input_embeddings(self, value):
|
436 |
+
self.embed_tokens = value
|
437 |
+
|
438 |
+
def forward(
|
439 |
+
self,
|
440 |
+
input_ids: torch.LongTensor = None,
|
441 |
+
attention_mask: Optional[torch.Tensor] = None,
|
442 |
+
position_ids: Optional[torch.LongTensor] = None,
|
443 |
+
past_key_values: Optional[Cache] = None,
|
444 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
445 |
+
use_cache: Optional[bool] = None,
|
446 |
+
output_attentions: Optional[bool] = None,
|
447 |
+
output_hidden_states: Optional[bool] = None,
|
448 |
+
return_dict: Optional[bool] = None,
|
449 |
+
cache_position: Optional[torch.LongTensor] = None,
|
450 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
451 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
452 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
453 |
+
output_hidden_states = (
|
454 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
455 |
+
)
|
456 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
457 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
458 |
+
|
459 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
460 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
461 |
+
|
462 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
463 |
+
logger.warning_once(
|
464 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
465 |
+
)
|
466 |
+
use_cache = False
|
467 |
+
|
468 |
+
if inputs_embeds is None:
|
469 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
470 |
+
|
471 |
+
if use_cache and past_key_values is None:
|
472 |
+
past_key_values = DynamicCache()
|
473 |
+
|
474 |
+
if cache_position is None:
|
475 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
476 |
+
cache_position = torch.arange(
|
477 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
478 |
+
)
|
479 |
+
|
480 |
+
if position_ids is None:
|
481 |
+
position_ids = cache_position.unsqueeze(0)
|
482 |
+
|
483 |
+
causal_mask = self._update_causal_mask(
|
484 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
485 |
+
)
|
486 |
+
|
487 |
+
hidden_states = inputs_embeds
|
488 |
+
|
489 |
+
# create position embeddings to be shared across the decoder layers
|
490 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
491 |
+
|
492 |
+
# decoder layers
|
493 |
+
all_hidden_states = () if output_hidden_states else None
|
494 |
+
all_self_attns = () if output_attentions else None
|
495 |
+
|
496 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
497 |
+
if output_hidden_states:
|
498 |
+
all_hidden_states += (hidden_states,)
|
499 |
+
|
500 |
+
if self.gradient_checkpointing and self.training:
|
501 |
+
layer_outputs = self._gradient_checkpointing_func(
|
502 |
+
decoder_layer.__call__,
|
503 |
+
hidden_states,
|
504 |
+
causal_mask,
|
505 |
+
position_ids,
|
506 |
+
past_key_values,
|
507 |
+
output_attentions,
|
508 |
+
use_cache,
|
509 |
+
cache_position,
|
510 |
+
position_embeddings,
|
511 |
+
)
|
512 |
+
else:
|
513 |
+
layer_outputs = decoder_layer(
|
514 |
+
hidden_states,
|
515 |
+
attention_mask=causal_mask,
|
516 |
+
position_ids=position_ids,
|
517 |
+
past_key_value=past_key_values,
|
518 |
+
output_attentions=output_attentions,
|
519 |
+
use_cache=use_cache,
|
520 |
+
cache_position=cache_position,
|
521 |
+
position_embeddings=position_embeddings,
|
522 |
+
**flash_attn_kwargs,
|
523 |
+
)
|
524 |
+
|
525 |
+
hidden_states = layer_outputs[0]
|
526 |
+
|
527 |
+
if output_attentions:
|
528 |
+
all_self_attns += (layer_outputs[1],)
|
529 |
+
|
530 |
+
hidden_states = self.norm(hidden_states)
|
531 |
+
|
532 |
+
# add hidden states from the last decoder layer
|
533 |
+
if output_hidden_states:
|
534 |
+
all_hidden_states += (hidden_states,)
|
535 |
+
|
536 |
+
output = BaseModelOutputWithPast(
|
537 |
+
last_hidden_state=hidden_states,
|
538 |
+
past_key_values=past_key_values if use_cache else None,
|
539 |
+
hidden_states=all_hidden_states,
|
540 |
+
attentions=all_self_attns,
|
541 |
+
)
|
542 |
+
return output if return_dict else output.to_tuple()
|
543 |
+
|
544 |
+
def _update_causal_mask(
|
545 |
+
self,
|
546 |
+
attention_mask: torch.Tensor,
|
547 |
+
input_tensor: torch.Tensor,
|
548 |
+
cache_position: torch.Tensor,
|
549 |
+
past_key_values: Cache,
|
550 |
+
output_attentions: bool,
|
551 |
+
):
|
552 |
+
if self.config._attn_implementation == "flash_attention_2":
|
553 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
554 |
+
return attention_mask
|
555 |
+
return None
|
556 |
+
|
557 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
558 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
559 |
+
# to infer the attention mask.
|
560 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
561 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
562 |
+
|
563 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
564 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
565 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
566 |
+
attention_mask,
|
567 |
+
inputs_embeds=input_tensor,
|
568 |
+
past_key_values_length=past_seen_tokens,
|
569 |
+
is_training=self.training,
|
570 |
+
):
|
571 |
+
return None
|
572 |
+
|
573 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
574 |
+
sequence_length = input_tensor.shape[1]
|
575 |
+
if using_static_cache:
|
576 |
+
target_length = past_key_values.get_max_cache_shape()
|
577 |
+
else:
|
578 |
+
target_length = (
|
579 |
+
attention_mask.shape[-1]
|
580 |
+
if isinstance(attention_mask, torch.Tensor)
|
581 |
+
else past_seen_tokens + sequence_length + 1
|
582 |
+
)
|
583 |
+
|
584 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
585 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
586 |
+
attention_mask,
|
587 |
+
sequence_length=sequence_length,
|
588 |
+
target_length=target_length,
|
589 |
+
dtype=dtype,
|
590 |
+
device=device,
|
591 |
+
cache_position=cache_position,
|
592 |
+
batch_size=input_tensor.shape[0],
|
593 |
+
)
|
594 |
+
|
595 |
+
if (
|
596 |
+
self.config._attn_implementation == "sdpa"
|
597 |
+
and attention_mask is not None
|
598 |
+
and attention_mask.device.type == "cuda"
|
599 |
+
and not output_attentions
|
600 |
+
):
|
601 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
602 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
603 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
604 |
+
min_dtype = torch.finfo(dtype).min
|
605 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
606 |
+
|
607 |
+
return causal_mask
|
608 |
+
|
609 |
+
@staticmethod
|
610 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
611 |
+
attention_mask: torch.Tensor,
|
612 |
+
sequence_length: int,
|
613 |
+
target_length: int,
|
614 |
+
dtype: torch.dtype,
|
615 |
+
device: torch.device,
|
616 |
+
cache_position: torch.Tensor,
|
617 |
+
batch_size: int,
|
618 |
+
**kwargs,
|
619 |
+
):
|
620 |
+
"""
|
621 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
622 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
623 |
+
|
624 |
+
Args:
|
625 |
+
attention_mask (`torch.Tensor`):
|
626 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
627 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
628 |
+
sequence_length (`int`):
|
629 |
+
The sequence length being processed.
|
630 |
+
target_length (`int`):
|
631 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
632 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
633 |
+
dtype (`torch.dtype`):
|
634 |
+
The dtype to use for the 4D attention mask.
|
635 |
+
device (`torch.device`):
|
636 |
+
The device to plcae the 4D attention mask on.
|
637 |
+
cache_position (`torch.Tensor`):
|
638 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
639 |
+
batch_size (`torch.Tensor`):
|
640 |
+
Batch size.
|
641 |
+
"""
|
642 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
643 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
644 |
+
causal_mask = attention_mask
|
645 |
+
else:
|
646 |
+
min_dtype = torch.finfo(dtype).min
|
647 |
+
causal_mask = torch.full(
|
648 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
649 |
+
)
|
650 |
+
if sequence_length != 1:
|
651 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
652 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
653 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
654 |
+
if attention_mask is not None:
|
655 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
656 |
+
mask_length = attention_mask.shape[-1]
|
657 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
658 |
+
padding_mask = padding_mask == 0
|
659 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
660 |
+
padding_mask, min_dtype
|
661 |
+
)
|
662 |
+
|
663 |
+
return causal_mask
|
664 |
+
|
665 |
+
|
666 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
667 |
+
|
668 |
+
|
669 |
+
class TriLMLinearForCausalLM(TriLMLinearPreTrainedModel, GenerationMixin):
|
670 |
+
_tied_weights_keys = ["lm_head.weight"]
|
671 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
672 |
+
|
673 |
+
def __init__(self, config):
|
674 |
+
super().__init__(config)
|
675 |
+
self.model = TriLMLinearModel(config)
|
676 |
+
self.vocab_size = config.vocab_size
|
677 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
678 |
+
|
679 |
+
# Initialize weights and apply final processing
|
680 |
+
self.post_init()
|
681 |
+
|
682 |
+
def get_input_embeddings(self):
|
683 |
+
return self.model.embed_tokens
|
684 |
+
|
685 |
+
def set_input_embeddings(self, value):
|
686 |
+
self.model.embed_tokens = value
|
687 |
+
|
688 |
+
def get_output_embeddings(self):
|
689 |
+
return self.lm_head
|
690 |
+
|
691 |
+
def set_output_embeddings(self, new_embeddings):
|
692 |
+
self.lm_head = new_embeddings
|
693 |
+
|
694 |
+
def set_decoder(self, decoder):
|
695 |
+
self.model = decoder
|
696 |
+
|
697 |
+
def get_decoder(self):
|
698 |
+
return self.model
|
699 |
+
|
700 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
701 |
+
def forward(
|
702 |
+
self,
|
703 |
+
input_ids: torch.LongTensor = None,
|
704 |
+
attention_mask: Optional[torch.Tensor] = None,
|
705 |
+
position_ids: Optional[torch.LongTensor] = None,
|
706 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
707 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
708 |
+
labels: Optional[torch.LongTensor] = None,
|
709 |
+
use_cache: Optional[bool] = None,
|
710 |
+
output_attentions: Optional[bool] = None,
|
711 |
+
output_hidden_states: Optional[bool] = None,
|
712 |
+
return_dict: Optional[bool] = None,
|
713 |
+
cache_position: Optional[torch.LongTensor] = None,
|
714 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
715 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
716 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
717 |
+
r"""
|
718 |
+
Args:
|
719 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
720 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
721 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
722 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
723 |
+
|
724 |
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
725 |
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
726 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
727 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
728 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
729 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
730 |
+
|
731 |
+
Returns:
|
732 |
+
|
733 |
+
Example:
|
734 |
+
|
735 |
+
```python
|
736 |
+
>>> from transformers import AutoTokenizer, TriLMLinearForCausalLM
|
737 |
+
|
738 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
739 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
740 |
+
|
741 |
+
>>> # Generate
|
742 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
743 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
744 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
745 |
+
```"""
|
746 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
747 |
+
output_hidden_states = (
|
748 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
749 |
+
)
|
750 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
751 |
+
|
752 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
753 |
+
outputs = self.model(
|
754 |
+
input_ids=input_ids,
|
755 |
+
attention_mask=attention_mask,
|
756 |
+
position_ids=position_ids,
|
757 |
+
past_key_values=past_key_values,
|
758 |
+
inputs_embeds=inputs_embeds,
|
759 |
+
use_cache=use_cache,
|
760 |
+
output_attentions=output_attentions,
|
761 |
+
output_hidden_states=output_hidden_states,
|
762 |
+
return_dict=return_dict,
|
763 |
+
cache_position=cache_position,
|
764 |
+
**kwargs,
|
765 |
+
)
|
766 |
+
|
767 |
+
hidden_states = outputs[0]
|
768 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
769 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
770 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
771 |
+
|
772 |
+
loss = None
|
773 |
+
if labels is not None:
|
774 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
775 |
+
|
776 |
+
if not return_dict:
|
777 |
+
output = (logits,) + outputs[1:]
|
778 |
+
return (loss,) + output if loss is not None else output
|
779 |
+
|
780 |
+
return CausalLMOutputWithPast(
|
781 |
+
loss=loss,
|
782 |
+
logits=logits,
|
783 |
+
past_key_values=outputs.past_key_values,
|
784 |
+
hidden_states=outputs.hidden_states,
|
785 |
+
attentions=outputs.attentions,
|
786 |
+
)
|
787 |
+
|
788 |
+
|
789 |
+
class TriLMLinearForSequenceClassification(TriLMLinearPreTrainedModel):
|
790 |
+
def __init__(self, config):
|
791 |
+
super().__init__(config)
|
792 |
+
self.num_labels = config.num_labels
|
793 |
+
self.model = TriLMLinearModel(config)
|
794 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
795 |
+
|
796 |
+
# Initialize weights and apply final processing
|
797 |
+
self.post_init()
|
798 |
+
|
799 |
+
def get_input_embeddings(self):
|
800 |
+
return self.model.embed_tokens
|
801 |
+
|
802 |
+
def set_input_embeddings(self, value):
|
803 |
+
self.model.embed_tokens = value
|
804 |
+
|
805 |
+
def forward(
|
806 |
+
self,
|
807 |
+
input_ids: Optional[torch.LongTensor] = None,
|
808 |
+
attention_mask: Optional[torch.Tensor] = None,
|
809 |
+
position_ids: Optional[torch.LongTensor] = None,
|
810 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
811 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
812 |
+
labels: Optional[torch.LongTensor] = None,
|
813 |
+
use_cache: Optional[bool] = None,
|
814 |
+
output_attentions: Optional[bool] = None,
|
815 |
+
output_hidden_states: Optional[bool] = None,
|
816 |
+
return_dict: Optional[bool] = None,
|
817 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
818 |
+
r"""
|
819 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
820 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
821 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
822 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
823 |
+
"""
|
824 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
825 |
+
|
826 |
+
transformer_outputs = self.model(
|
827 |
+
input_ids,
|
828 |
+
attention_mask=attention_mask,
|
829 |
+
position_ids=position_ids,
|
830 |
+
past_key_values=past_key_values,
|
831 |
+
inputs_embeds=inputs_embeds,
|
832 |
+
use_cache=use_cache,
|
833 |
+
output_attentions=output_attentions,
|
834 |
+
output_hidden_states=output_hidden_states,
|
835 |
+
return_dict=return_dict,
|
836 |
+
)
|
837 |
+
hidden_states = transformer_outputs[0]
|
838 |
+
logits = self.score(hidden_states)
|
839 |
+
|
840 |
+
if input_ids is not None:
|
841 |
+
batch_size = input_ids.shape[0]
|
842 |
+
else:
|
843 |
+
batch_size = inputs_embeds.shape[0]
|
844 |
+
|
845 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
846 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
847 |
+
if self.config.pad_token_id is None:
|
848 |
+
sequence_lengths = -1
|
849 |
+
else:
|
850 |
+
if input_ids is not None:
|
851 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
852 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
853 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
854 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
855 |
+
else:
|
856 |
+
sequence_lengths = -1
|
857 |
+
|
858 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
859 |
+
|
860 |
+
loss = None
|
861 |
+
if labels is not None:
|
862 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
863 |
+
|
864 |
+
if not return_dict:
|
865 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
866 |
+
return ((loss,) + output) if loss is not None else output
|
867 |
+
|
868 |
+
return SequenceClassifierOutputWithPast(
|
869 |
+
loss=loss,
|
870 |
+
logits=pooled_logits,
|
871 |
+
past_key_values=transformer_outputs.past_key_values,
|
872 |
+
hidden_states=transformer_outputs.hidden_states,
|
873 |
+
attentions=transformer_outputs.attentions,
|
874 |
+
)
|
875 |
+
|
876 |
+
|
877 |
+
class TriLMLinearForQuestionAnswering(TriLMLinearPreTrainedModel):
|
878 |
+
base_model_prefix = "transformer"
|
879 |
+
|
880 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->TriLMLinear
|
881 |
+
def __init__(self, config):
|
882 |
+
super().__init__(config)
|
883 |
+
self.transformer = TriLMLinearModel(config)
|
884 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
885 |
+
|
886 |
+
# Initialize weights and apply final processing
|
887 |
+
self.post_init()
|
888 |
+
|
889 |
+
def get_input_embeddings(self):
|
890 |
+
return self.transformer.embed_tokens
|
891 |
+
|
892 |
+
def set_input_embeddings(self, value):
|
893 |
+
self.transformer.embed_tokens = value
|
894 |
+
|
895 |
+
def forward(
|
896 |
+
self,
|
897 |
+
input_ids: Optional[torch.LongTensor] = None,
|
898 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
899 |
+
position_ids: Optional[torch.LongTensor] = None,
|
900 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
901 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
902 |
+
start_positions: Optional[torch.LongTensor] = None,
|
903 |
+
end_positions: Optional[torch.LongTensor] = None,
|
904 |
+
output_attentions: Optional[bool] = None,
|
905 |
+
output_hidden_states: Optional[bool] = None,
|
906 |
+
return_dict: Optional[bool] = None,
|
907 |
+
**kwargs,
|
908 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
909 |
+
r"""
|
910 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
911 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
912 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
913 |
+
are not taken into account for computing the loss.
|
914 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
915 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
916 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
917 |
+
are not taken into account for computing the loss.
|
918 |
+
"""
|
919 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
920 |
+
|
921 |
+
outputs = self.transformer(
|
922 |
+
input_ids,
|
923 |
+
attention_mask=attention_mask,
|
924 |
+
position_ids=position_ids,
|
925 |
+
past_key_values=past_key_values,
|
926 |
+
inputs_embeds=inputs_embeds,
|
927 |
+
output_attentions=output_attentions,
|
928 |
+
output_hidden_states=output_hidden_states,
|
929 |
+
return_dict=return_dict,
|
930 |
+
)
|
931 |
+
|
932 |
+
sequence_output = outputs[0]
|
933 |
+
|
934 |
+
logits = self.qa_outputs(sequence_output)
|
935 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
936 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
937 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
938 |
+
|
939 |
+
loss = None
|
940 |
+
if start_positions is not None and end_positions is not None:
|
941 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
942 |
+
|
943 |
+
if not return_dict:
|
944 |
+
output = (start_logits, end_logits) + outputs[2:]
|
945 |
+
return ((loss,) + output) if loss is not None else output
|
946 |
+
|
947 |
+
return QuestionAnsweringModelOutput(
|
948 |
+
loss=loss,
|
949 |
+
start_logits=start_logits,
|
950 |
+
end_logits=end_logits,
|
951 |
+
hidden_states=outputs.hidden_states,
|
952 |
+
attentions=outputs.attentions,
|
953 |
+
)
|
954 |
+
|
955 |
+
class TriLMLinearForTokenClassification(TriLMLinearPreTrainedModel):
|
956 |
+
def __init__(self, config):
|
957 |
+
super().__init__(config)
|
958 |
+
self.num_labels = config.num_labels
|
959 |
+
self.model = TriLMLinearModel(config)
|
960 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
961 |
+
classifier_dropout = config.classifier_dropout
|
962 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
963 |
+
classifier_dropout = config.hidden_dropout
|
964 |
+
else:
|
965 |
+
classifier_dropout = 0.1
|
966 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
967 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
968 |
+
|
969 |
+
# Initialize weights and apply final processing
|
970 |
+
self.post_init()
|
971 |
+
|
972 |
+
def get_input_embeddings(self):
|
973 |
+
return self.model.embed_tokens
|
974 |
+
|
975 |
+
def set_input_embeddings(self, value):
|
976 |
+
self.model.embed_tokens = value
|
977 |
+
|
978 |
+
def forward(
|
979 |
+
self,
|
980 |
+
input_ids: Optional[torch.LongTensor] = None,
|
981 |
+
attention_mask: Optional[torch.Tensor] = None,
|
982 |
+
position_ids: Optional[torch.LongTensor] = None,
|
983 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
984 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
985 |
+
labels: Optional[torch.LongTensor] = None,
|
986 |
+
use_cache: Optional[bool] = None,
|
987 |
+
output_attentions: Optional[bool] = None,
|
988 |
+
output_hidden_states: Optional[bool] = None,
|
989 |
+
return_dict: Optional[bool] = None,
|
990 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
991 |
+
r"""
|
992 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
993 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
994 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
995 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
996 |
+
"""
|
997 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
998 |
+
|
999 |
+
outputs = self.model(
|
1000 |
+
input_ids,
|
1001 |
+
attention_mask=attention_mask,
|
1002 |
+
position_ids=position_ids,
|
1003 |
+
past_key_values=past_key_values,
|
1004 |
+
inputs_embeds=inputs_embeds,
|
1005 |
+
use_cache=use_cache,
|
1006 |
+
output_attentions=output_attentions,
|
1007 |
+
output_hidden_states=output_hidden_states,
|
1008 |
+
return_dict=return_dict,
|
1009 |
+
)
|
1010 |
+
sequence_output = outputs[0]
|
1011 |
+
sequence_output = self.dropout(sequence_output)
|
1012 |
+
logits = self.score(sequence_output)
|
1013 |
+
|
1014 |
+
loss = None
|
1015 |
+
if labels is not None:
|
1016 |
+
loss = self.loss_function(logits, labels, self.config)
|
1017 |
+
|
1018 |
+
if not return_dict:
|
1019 |
+
output = (logits,) + outputs[2:]
|
1020 |
+
return ((loss,) + output) if loss is not None else output
|
1021 |
+
|
1022 |
+
return TokenClassifierOutput(
|
1023 |
+
loss=loss,
|
1024 |
+
logits=logits,
|
1025 |
+
hidden_states=outputs.hidden_states,
|
1026 |
+
attentions=outputs.attentions,
|
1027 |
+
)
|
1028 |
+
|
1029 |
+
|
1030 |
+
__all__ = [
|
1031 |
+
"TriLMLinearForCausalLM",
|
1032 |
+
"TriLMLinearModel",
|
1033 |
+
"TriLMLinearPreTrainedModel",
|
1034 |
+
"TriLMLinearForSequenceClassification",
|
1035 |
+
"TriLMLinearForQuestionAnswering",
|
1036 |
+
"TriLMLinearForTokenClassification",
|
1037 |
+
]
|