initial push
Browse files- config.json +34 -0
- configuration_boomer.py +194 -0
- generation_config.json +6 -0
- model.safetensors +3 -0
- modelling_boomer.py +1429 -0
- special_tokens_map.json +24 -0
- tokenizer.json +0 -0
- tokenizer.model +3 -0
- tokenizer_config.json +43 -0
config.json
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "budecosystem/boomer-bitnet-634m",
|
3 |
+
"architectures": [
|
4 |
+
"BoomerForCausalLM"
|
5 |
+
],
|
6 |
+
"attention_bias": false,
|
7 |
+
"attention_dropout": 0.0,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_boomer.BoomerConfig",
|
10 |
+
"AutoModelForCausalLM": "modelling_boomer.BoomerForCausalLM"
|
11 |
+
},
|
12 |
+
"bos_token_id": 1,
|
13 |
+
"eos_token_id": 2,
|
14 |
+
"hidden_act": "silu",
|
15 |
+
"hidden_size": 1024,
|
16 |
+
"initializer_range": 0.02,
|
17 |
+
"input_bits": 8,
|
18 |
+
"intermediate_size": 2560,
|
19 |
+
"max_position_embeddings": 4096,
|
20 |
+
"model_type": "boomer",
|
21 |
+
"num_attention_heads": 16,
|
22 |
+
"num_hidden_layers": 48,
|
23 |
+
"num_key_value_heads": 4,
|
24 |
+
"pretraining_tp": 1,
|
25 |
+
"rms_norm_eps": 1e-06,
|
26 |
+
"rope_scaling": null,
|
27 |
+
"rope_theta": 1000000.0,
|
28 |
+
"tie_word_embeddings": false,
|
29 |
+
"torch_dtype": "float16",
|
30 |
+
"transformers_version": "4.39.2",
|
31 |
+
"use_cache": false,
|
32 |
+
"vocab_size": 64000,
|
33 |
+
"weight_bits": 1
|
34 |
+
}
|
configuration_boomer.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" LLaMA model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.utils import logging
|
24 |
+
|
25 |
+
|
26 |
+
logger = logging.get_logger(__name__)
|
27 |
+
|
28 |
+
LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
29 |
+
|
30 |
+
|
31 |
+
class BoomerConfig(PretrainedConfig):
|
32 |
+
r"""
|
33 |
+
This is the configuration class to store the configuration of a [`BoomerModel`]. It is used to instantiate an LLaMA
|
34 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
35 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
36 |
+
|
37 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
38 |
+
documentation from [`PretrainedConfig`] for more information.
|
39 |
+
|
40 |
+
|
41 |
+
Args:
|
42 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
43 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
44 |
+
`inputs_ids` passed when calling [`BoomerModel`]
|
45 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
46 |
+
Dimension of the hidden representations.
|
47 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
48 |
+
Dimension of the MLP representations.
|
49 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
50 |
+
Number of hidden layers in the Transformer decoder.
|
51 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
52 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
53 |
+
num_key_value_heads (`int`, *optional*):
|
54 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
55 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
56 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
57 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
58 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
59 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
60 |
+
`num_attention_heads`.
|
61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
62 |
+
The non-linear activation function (function or string) in the decoder.
|
63 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
64 |
+
The maximum sequence length that this model might ever be used with.
|
65 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
66 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
67 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
68 |
+
The epsilon used by the rms normalization layers.
|
69 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
70 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
71 |
+
relevant if `config.is_decoder=True`.
|
72 |
+
pad_token_id (`int`, *optional*):
|
73 |
+
Padding token id.
|
74 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
75 |
+
Beginning of stream token id.
|
76 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
77 |
+
End of stream token id.
|
78 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
79 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
80 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
|
81 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
82 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
83 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
84 |
+
Whether to tie weight embeddings
|
85 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
86 |
+
The base period of the RoPE embeddings.
|
87 |
+
rope_scaling (`Dict`, *optional*):
|
88 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
89 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
90 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
91 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
92 |
+
these scaling strategies behave:
|
93 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
94 |
+
experimental feature, subject to breaking API changes in future versions.
|
95 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
96 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
97 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
98 |
+
The dropout ratio for the attention probabilities.
|
99 |
+
|
100 |
+
```python
|
101 |
+
>>> from transformers import BoomerModel, BoomerConfig
|
102 |
+
|
103 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
104 |
+
>>> configuration = BoomerConfig()
|
105 |
+
|
106 |
+
>>> # Initializing a model from the llama-7b style configuration
|
107 |
+
>>> model = BoomerModel(configuration)
|
108 |
+
|
109 |
+
>>> # Accessing the model configuration
|
110 |
+
>>> configuration = model.config
|
111 |
+
```"""
|
112 |
+
|
113 |
+
model_type = "llama"
|
114 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
115 |
+
|
116 |
+
def __init__(
|
117 |
+
self,
|
118 |
+
vocab_size=32000,
|
119 |
+
hidden_size=4096,
|
120 |
+
intermediate_size=11008,
|
121 |
+
num_hidden_layers=32,
|
122 |
+
num_attention_heads=32,
|
123 |
+
num_key_value_heads=None,
|
124 |
+
hidden_act="silu",
|
125 |
+
max_position_embeddings=2048,
|
126 |
+
initializer_range=0.02,
|
127 |
+
rms_norm_eps=1e-6,
|
128 |
+
use_cache=True,
|
129 |
+
pad_token_id=None,
|
130 |
+
bos_token_id=1,
|
131 |
+
eos_token_id=2,
|
132 |
+
pretraining_tp=1,
|
133 |
+
tie_word_embeddings=False,
|
134 |
+
rope_theta=10000.0,
|
135 |
+
rope_scaling=None,
|
136 |
+
attention_bias=False,
|
137 |
+
attention_dropout=0.0,
|
138 |
+
weight_bits=1,
|
139 |
+
input_bits=8,
|
140 |
+
**kwargs,
|
141 |
+
):
|
142 |
+
self.vocab_size = vocab_size
|
143 |
+
self.max_position_embeddings = max_position_embeddings
|
144 |
+
self.hidden_size = hidden_size
|
145 |
+
self.intermediate_size = intermediate_size
|
146 |
+
self.num_hidden_layers = num_hidden_layers
|
147 |
+
self.num_attention_heads = num_attention_heads
|
148 |
+
|
149 |
+
# for backward compatibility
|
150 |
+
if num_key_value_heads is None:
|
151 |
+
num_key_value_heads = num_attention_heads
|
152 |
+
|
153 |
+
self.num_key_value_heads = num_key_value_heads
|
154 |
+
self.hidden_act = hidden_act
|
155 |
+
self.initializer_range = initializer_range
|
156 |
+
self.rms_norm_eps = rms_norm_eps
|
157 |
+
self.pretraining_tp = pretraining_tp
|
158 |
+
self.use_cache = use_cache
|
159 |
+
self.rope_theta = rope_theta
|
160 |
+
self.rope_scaling = rope_scaling
|
161 |
+
self._rope_scaling_validation()
|
162 |
+
self.attention_bias = attention_bias
|
163 |
+
self.attention_dropout = attention_dropout
|
164 |
+
self.weight_bits = weight_bits
|
165 |
+
self.input_bits = input_bits
|
166 |
+
|
167 |
+
super().__init__(
|
168 |
+
pad_token_id=pad_token_id,
|
169 |
+
bos_token_id=bos_token_id,
|
170 |
+
eos_token_id=eos_token_id,
|
171 |
+
tie_word_embeddings=tie_word_embeddings,
|
172 |
+
**kwargs,
|
173 |
+
)
|
174 |
+
|
175 |
+
def _rope_scaling_validation(self):
|
176 |
+
"""
|
177 |
+
Validate the `rope_scaling` configuration.
|
178 |
+
"""
|
179 |
+
if self.rope_scaling is None:
|
180 |
+
return
|
181 |
+
|
182 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
183 |
+
raise ValueError(
|
184 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
185 |
+
f"got {self.rope_scaling}"
|
186 |
+
)
|
187 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
188 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
189 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
190 |
+
raise ValueError(
|
191 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
192 |
+
)
|
193 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
194 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
generation_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"transformers_version": "4.39.2"
|
6 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ef4774e0a5faade38cfbbb577f612139cfae17b1bcdd809883176e1d1d165286
|
3 |
+
size 1269388584
|
modelling_boomer.py
ADDED
@@ -0,0 +1,1429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
"""PyTorch LLaMA model."""
|
21 |
+
|
22 |
+
import math
|
23 |
+
import warnings
|
24 |
+
from typing import List, Optional, Tuple, Union
|
25 |
+
|
26 |
+
import torch
|
27 |
+
import torch.nn.functional as F
|
28 |
+
import torch.utils.checkpoint
|
29 |
+
from torch import nn
|
30 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
31 |
+
|
32 |
+
from transformers.activations import ACT2FN
|
33 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
34 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
35 |
+
from transformers.modeling_outputs import (
|
36 |
+
BaseModelOutputWithPast,
|
37 |
+
CausalLMOutputWithPast,
|
38 |
+
QuestionAnsweringModelOutput,
|
39 |
+
SequenceClassifierOutputWithPast,
|
40 |
+
)
|
41 |
+
from transformers.modeling_utils import PreTrainedModel
|
42 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
43 |
+
from transformers.utils import (
|
44 |
+
add_start_docstrings,
|
45 |
+
add_start_docstrings_to_model_forward,
|
46 |
+
is_flash_attn_2_available,
|
47 |
+
is_flash_attn_greater_or_equal_2_10,
|
48 |
+
logging,
|
49 |
+
replace_return_docstrings,
|
50 |
+
)
|
51 |
+
from .configuration_boomer import BoomerConfig
|
52 |
+
|
53 |
+
if is_flash_attn_2_available():
|
54 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
55 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
56 |
+
|
57 |
+
|
58 |
+
logger = logging.get_logger(__name__)
|
59 |
+
|
60 |
+
_CONFIG_FOR_DOC = "BoomerConfig"
|
61 |
+
|
62 |
+
|
63 |
+
def _get_unpad_data(attention_mask):
|
64 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
65 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
66 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
67 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
68 |
+
return (
|
69 |
+
indices,
|
70 |
+
cu_seqlens,
|
71 |
+
max_seqlen_in_batch,
|
72 |
+
)
|
73 |
+
|
74 |
+
def weight_quant(weight, num_bits=1):
|
75 |
+
dtype = weight.dtype
|
76 |
+
weight = weight.float()
|
77 |
+
s = 1 / weight.abs().mean().clamp(min=1e-5)
|
78 |
+
result = (weight * s).round().clamp(-1, 1) / s
|
79 |
+
return result.type(dtype)
|
80 |
+
|
81 |
+
|
82 |
+
def activation_quant(x, num_bits=8):
|
83 |
+
dtype = x.dtype
|
84 |
+
x = x.float()
|
85 |
+
Qn = -2 ** (num_bits - 1)
|
86 |
+
Qp = 2 ** (num_bits - 1) - 1
|
87 |
+
s = Qp / x.abs().max(dim=-1, keepdim=True).values.clamp(min=1e-5)
|
88 |
+
result = (x * s).round().clamp(Qn, Qp) / s
|
89 |
+
return result.type(dtype)
|
90 |
+
|
91 |
+
|
92 |
+
class BitLinear(nn.Linear):
|
93 |
+
|
94 |
+
def __init__(self,
|
95 |
+
*kargs,
|
96 |
+
weight_bits=1,
|
97 |
+
input_bits=8,
|
98 |
+
**kwargs
|
99 |
+
):
|
100 |
+
super(BitLinear, self).__init__(*kargs, **kwargs)
|
101 |
+
"""
|
102 |
+
RMSNorm is placed outside BitLinear
|
103 |
+
"""
|
104 |
+
self.weight_bits = weight_bits
|
105 |
+
self.input_bits = input_bits
|
106 |
+
|
107 |
+
def forward(self, input):
|
108 |
+
|
109 |
+
quant_input = input + (activation_quant(input, self.input_bits) - input).detach()
|
110 |
+
quant_weight = self.weight + (weight_quant(self.weight, self.weight_bits) - self.weight).detach()
|
111 |
+
|
112 |
+
out = nn.functional.linear(quant_input, quant_weight)
|
113 |
+
if not self.bias is None:
|
114 |
+
out += self.bias.view(1, -1).expand_as(out)
|
115 |
+
|
116 |
+
return out
|
117 |
+
|
118 |
+
|
119 |
+
class BoomerRMSNorm(nn.Module):
|
120 |
+
def __init__(self, hidden_size, eps=1e-6):
|
121 |
+
"""
|
122 |
+
BoomerRMSNorm is equivalent to T5LayerNorm
|
123 |
+
"""
|
124 |
+
super().__init__()
|
125 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
126 |
+
self.variance_epsilon = eps
|
127 |
+
|
128 |
+
def forward(self, hidden_states):
|
129 |
+
input_dtype = hidden_states.dtype
|
130 |
+
hidden_states = hidden_states.to(torch.float32)
|
131 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
132 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
133 |
+
return self.weight * hidden_states.to(input_dtype)
|
134 |
+
|
135 |
+
|
136 |
+
ALL_LAYERNORM_LAYERS.append(BoomerRMSNorm)
|
137 |
+
|
138 |
+
|
139 |
+
class BoomerRotaryEmbedding(nn.Module):
|
140 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
141 |
+
super().__init__()
|
142 |
+
self.scaling_factor = scaling_factor
|
143 |
+
self.dim = dim
|
144 |
+
self.max_position_embeddings = max_position_embeddings
|
145 |
+
self.base = base
|
146 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
147 |
+
self.register_buffer("inv_freq", inv_freq)
|
148 |
+
# For BC we register cos and sin cached
|
149 |
+
self.max_seq_len_cached = max_position_embeddings
|
150 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
151 |
+
t = t / self.scaling_factor
|
152 |
+
freqs = torch.outer(t, self.inv_freq)
|
153 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
154 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
155 |
+
self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False)
|
156 |
+
self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False)
|
157 |
+
|
158 |
+
@property
|
159 |
+
def sin_cached(self):
|
160 |
+
logger.warning_once(
|
161 |
+
"The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
|
162 |
+
"the forward method of RoPE from now on instead. It is not used in the `BoomerAttention` class"
|
163 |
+
)
|
164 |
+
return self._sin_cached
|
165 |
+
|
166 |
+
@property
|
167 |
+
def cos_cached(self):
|
168 |
+
logger.warning_once(
|
169 |
+
"The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
|
170 |
+
"the forward method of RoPE from now on instead. It is not used in the `BoomerAttention` class"
|
171 |
+
)
|
172 |
+
return self._cos_cached
|
173 |
+
|
174 |
+
@torch.no_grad()
|
175 |
+
def forward(self, x, position_ids):
|
176 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
177 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
178 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
179 |
+
# Force float32 since bfloat16 loses precision on long contexts
|
180 |
+
# See https://github.com/huggingface/transformers/pull/29285
|
181 |
+
device_type = x.device.type
|
182 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
183 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
184 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
185 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
186 |
+
cos = emb.cos()
|
187 |
+
sin = emb.sin()
|
188 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
189 |
+
|
190 |
+
|
191 |
+
def rotate_half(x):
|
192 |
+
"""Rotates half the hidden dims of the input."""
|
193 |
+
x1 = x[..., : x.shape[-1] // 2]
|
194 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
195 |
+
return torch.cat((-x2, x1), dim=-1)
|
196 |
+
|
197 |
+
|
198 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
199 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
200 |
+
|
201 |
+
Args:
|
202 |
+
q (`torch.Tensor`): The query tensor.
|
203 |
+
k (`torch.Tensor`): The key tensor.
|
204 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
205 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
206 |
+
position_ids (`torch.Tensor`, *optional*):
|
207 |
+
Deprecated and unused.
|
208 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
209 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
210 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
211 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
212 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
213 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
214 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
215 |
+
Returns:
|
216 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
217 |
+
"""
|
218 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
219 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
220 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
221 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
222 |
+
return q_embed, k_embed
|
223 |
+
|
224 |
+
|
225 |
+
class BoomerMLP(nn.Module):
|
226 |
+
def __init__(self, config):
|
227 |
+
super().__init__()
|
228 |
+
self.config = config
|
229 |
+
self.hidden_size = config.hidden_size
|
230 |
+
self.intermediate_size = config.intermediate_size
|
231 |
+
self.gate_proj = BitLinear(
|
232 |
+
self.hidden_size, self.intermediate_size, bias=False,
|
233 |
+
weight_bits=config.weight_bits, input_bits=config.input_bits,
|
234 |
+
)
|
235 |
+
self.up_proj = BitLinear(
|
236 |
+
self.hidden_size, self.intermediate_size, bias=False,
|
237 |
+
weight_bits=config.weight_bits, input_bits=config.input_bits,
|
238 |
+
)
|
239 |
+
self.down_proj = BitLinear(
|
240 |
+
self.intermediate_size, self.hidden_size, bias=False,
|
241 |
+
weight_bits=config.weight_bits, input_bits=config.input_bits,
|
242 |
+
)
|
243 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
244 |
+
self.ffn_layernorm = BoomerRMSNorm(self.intermediate_size, eps=config.rms_norm_eps)
|
245 |
+
|
246 |
+
def forward(self, x):
|
247 |
+
x = self.act_fn(self.gate_proj(x)) * self.up_proj(x)
|
248 |
+
x = self.ffn_layernorm(x)
|
249 |
+
x = self.down_proj(x)
|
250 |
+
return x
|
251 |
+
|
252 |
+
|
253 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
254 |
+
"""
|
255 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
256 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
257 |
+
"""
|
258 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
259 |
+
if n_rep == 1:
|
260 |
+
return hidden_states
|
261 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
262 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
263 |
+
|
264 |
+
|
265 |
+
class BoomerAttention(nn.Module):
|
266 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
267 |
+
|
268 |
+
def __init__(self, config: BoomerConfig, layer_idx: Optional[int] = None):
|
269 |
+
super().__init__()
|
270 |
+
self.config = config
|
271 |
+
self.layer_idx = layer_idx
|
272 |
+
if layer_idx is None:
|
273 |
+
logger.warning_once(
|
274 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
275 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
276 |
+
"when creating this class."
|
277 |
+
)
|
278 |
+
|
279 |
+
self.attention_dropout = config.attention_dropout
|
280 |
+
self.hidden_size = config.hidden_size
|
281 |
+
self.num_heads = config.num_attention_heads
|
282 |
+
self.head_dim = self.hidden_size // self.num_heads
|
283 |
+
self.num_key_value_heads = config.num_key_value_heads
|
284 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
285 |
+
self.max_position_embeddings = config.max_position_embeddings
|
286 |
+
self.rope_theta = config.rope_theta
|
287 |
+
self.is_causal = True
|
288 |
+
|
289 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
290 |
+
raise ValueError(
|
291 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
292 |
+
f" and `num_heads`: {self.num_heads})."
|
293 |
+
)
|
294 |
+
|
295 |
+
self.q_proj = BitLinear(
|
296 |
+
self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias,
|
297 |
+
weight_bits=config.weight_bits, input_bits=config.input_bits,
|
298 |
+
)
|
299 |
+
self.k_proj = BitLinear(
|
300 |
+
self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias,
|
301 |
+
weight_bits=config.weight_bits, input_bits=config.input_bits,
|
302 |
+
)
|
303 |
+
self.v_proj = BitLinear(
|
304 |
+
self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias,
|
305 |
+
weight_bits=config.weight_bits, input_bits=config.input_bits,
|
306 |
+
)
|
307 |
+
self.o_proj = BitLinear(
|
308 |
+
self.hidden_size, self.hidden_size, bias=config.attention_bias,
|
309 |
+
weight_bits=config.weight_bits, input_bits=config.input_bits,
|
310 |
+
)
|
311 |
+
self._init_rope()
|
312 |
+
self.inner_attn_ln = BoomerRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
|
313 |
+
|
314 |
+
def _init_rope(self):
|
315 |
+
if self.config.rope_scaling is None:
|
316 |
+
self.rotary_emb = BoomerRotaryEmbedding(
|
317 |
+
self.head_dim,
|
318 |
+
max_position_embeddings=self.max_position_embeddings,
|
319 |
+
base=self.rope_theta,
|
320 |
+
)
|
321 |
+
else:
|
322 |
+
raise NotImplementedError
|
323 |
+
|
324 |
+
def forward(
|
325 |
+
self,
|
326 |
+
hidden_states: torch.Tensor,
|
327 |
+
attention_mask: Optional[torch.Tensor] = None,
|
328 |
+
position_ids: Optional[torch.LongTensor] = None,
|
329 |
+
past_key_value: Optional[Cache] = None,
|
330 |
+
output_attentions: bool = False,
|
331 |
+
use_cache: bool = False,
|
332 |
+
cache_position: Optional[torch.LongTensor] = None,
|
333 |
+
**kwargs,
|
334 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
335 |
+
bsz, q_len, _ = hidden_states.size()
|
336 |
+
|
337 |
+
query_states = self.q_proj(hidden_states)
|
338 |
+
key_states = self.k_proj(hidden_states)
|
339 |
+
value_states = self.v_proj(hidden_states)
|
340 |
+
|
341 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
342 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
343 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
344 |
+
|
345 |
+
past_key_value = getattr(self, "past_key_value", past_key_value)
|
346 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
347 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
348 |
+
|
349 |
+
if past_key_value is not None:
|
350 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
351 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
352 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
353 |
+
|
354 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
355 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
356 |
+
|
357 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
358 |
+
|
359 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
360 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
361 |
+
attn_weights = attn_weights + causal_mask
|
362 |
+
|
363 |
+
# upcast attention to fp32
|
364 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
365 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
366 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
367 |
+
|
368 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
369 |
+
raise ValueError(
|
370 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
371 |
+
f" {attn_output.size()}"
|
372 |
+
)
|
373 |
+
|
374 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
375 |
+
|
376 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
377 |
+
|
378 |
+
attn_output = self.inner_attn_ln(attn_output)
|
379 |
+
attn_output = self.o_proj(attn_output)
|
380 |
+
|
381 |
+
if not output_attentions:
|
382 |
+
attn_weights = None
|
383 |
+
|
384 |
+
return attn_output, attn_weights, past_key_value
|
385 |
+
|
386 |
+
|
387 |
+
class BoomerFlashAttention2(BoomerAttention):
|
388 |
+
"""
|
389 |
+
Boomer flash attention module. This module inherits from `BoomerAttention` as the weights of the module stays
|
390 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
391 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
392 |
+
"""
|
393 |
+
|
394 |
+
def __init__(self, *args, **kwargs):
|
395 |
+
super().__init__(*args, **kwargs)
|
396 |
+
|
397 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
398 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
399 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
400 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
401 |
+
|
402 |
+
def forward(
|
403 |
+
self,
|
404 |
+
hidden_states: torch.Tensor,
|
405 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
406 |
+
position_ids: Optional[torch.LongTensor] = None,
|
407 |
+
past_key_value: Optional[Cache] = None,
|
408 |
+
output_attentions: bool = False,
|
409 |
+
use_cache: bool = False,
|
410 |
+
cache_position: Optional[torch.LongTensor] = None,
|
411 |
+
**kwargs,
|
412 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
413 |
+
output_attentions = False
|
414 |
+
|
415 |
+
bsz, q_len, _ = hidden_states.size()
|
416 |
+
|
417 |
+
query_states = self.q_proj(hidden_states)
|
418 |
+
key_states = self.k_proj(hidden_states)
|
419 |
+
value_states = self.v_proj(hidden_states)
|
420 |
+
|
421 |
+
# Flash attention requires the input to have the shape
|
422 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
423 |
+
# therefore we just need to keep the original shape
|
424 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
425 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
426 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
427 |
+
|
428 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
429 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
430 |
+
|
431 |
+
past_key_value = getattr(self, "past_key_value", past_key_value)
|
432 |
+
|
433 |
+
if past_key_value is not None:
|
434 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
435 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
436 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
437 |
+
|
438 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
439 |
+
# to be able to avoid many of these transpose/reshape/view.
|
440 |
+
query_states = query_states.transpose(1, 2)
|
441 |
+
key_states = key_states.transpose(1, 2)
|
442 |
+
value_states = value_states.transpose(1, 2)
|
443 |
+
|
444 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
445 |
+
|
446 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
447 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
448 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
449 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
450 |
+
# in fp32. (BoomerRMSNorm handles it correctly)
|
451 |
+
|
452 |
+
input_dtype = query_states.dtype
|
453 |
+
if input_dtype == torch.float32:
|
454 |
+
if torch.is_autocast_enabled():
|
455 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
456 |
+
# Handle the case where the model is quantized
|
457 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
458 |
+
target_dtype = self.config._pre_quantization_dtype
|
459 |
+
else:
|
460 |
+
target_dtype = self.q_proj.weight.dtype
|
461 |
+
|
462 |
+
logger.warning_once(
|
463 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
464 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
465 |
+
f" {target_dtype}."
|
466 |
+
)
|
467 |
+
|
468 |
+
query_states = query_states.to(target_dtype)
|
469 |
+
key_states = key_states.to(target_dtype)
|
470 |
+
value_states = value_states.to(target_dtype)
|
471 |
+
|
472 |
+
attn_output = self._flash_attention_forward(
|
473 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
474 |
+
)
|
475 |
+
|
476 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
477 |
+
attn_output = self.inner_attn_ln(attn_output)
|
478 |
+
attn_output = self.o_proj(attn_output)
|
479 |
+
|
480 |
+
if not output_attentions:
|
481 |
+
attn_weights = None
|
482 |
+
|
483 |
+
return attn_output, attn_weights, past_key_value
|
484 |
+
|
485 |
+
def _flash_attention_forward(
|
486 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
487 |
+
):
|
488 |
+
"""
|
489 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
490 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
491 |
+
|
492 |
+
Args:
|
493 |
+
query_states (`torch.Tensor`):
|
494 |
+
Input query states to be passed to Flash Attention API
|
495 |
+
key_states (`torch.Tensor`):
|
496 |
+
Input key states to be passed to Flash Attention API
|
497 |
+
value_states (`torch.Tensor`):
|
498 |
+
Input value states to be passed to Flash Attention API
|
499 |
+
attention_mask (`torch.Tensor`):
|
500 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
501 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
502 |
+
dropout (`float`):
|
503 |
+
Attention dropout
|
504 |
+
softmax_scale (`float`, *optional*):
|
505 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
506 |
+
"""
|
507 |
+
if not self._flash_attn_uses_top_left_mask:
|
508 |
+
causal = self.is_causal
|
509 |
+
else:
|
510 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in BoomerFlashAttention2 __init__.
|
511 |
+
causal = self.is_causal and query_length != 1
|
512 |
+
|
513 |
+
# Contains at least one padding token in the sequence
|
514 |
+
if attention_mask is not None:
|
515 |
+
batch_size = query_states.shape[0]
|
516 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
517 |
+
query_states, key_states, value_states, attention_mask, query_length
|
518 |
+
)
|
519 |
+
|
520 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
521 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
522 |
+
|
523 |
+
attn_output_unpad = flash_attn_varlen_func(
|
524 |
+
query_states,
|
525 |
+
key_states,
|
526 |
+
value_states,
|
527 |
+
cu_seqlens_q=cu_seqlens_q,
|
528 |
+
cu_seqlens_k=cu_seqlens_k,
|
529 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
530 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
531 |
+
dropout_p=dropout,
|
532 |
+
softmax_scale=softmax_scale,
|
533 |
+
causal=causal,
|
534 |
+
)
|
535 |
+
|
536 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
537 |
+
else:
|
538 |
+
attn_output = flash_attn_func(
|
539 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
540 |
+
)
|
541 |
+
|
542 |
+
return attn_output
|
543 |
+
|
544 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
545 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
546 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
547 |
+
|
548 |
+
key_layer = index_first_axis(
|
549 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
550 |
+
)
|
551 |
+
value_layer = index_first_axis(
|
552 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
553 |
+
)
|
554 |
+
if query_length == kv_seq_len:
|
555 |
+
query_layer = index_first_axis(
|
556 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
557 |
+
)
|
558 |
+
cu_seqlens_q = cu_seqlens_k
|
559 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
560 |
+
indices_q = indices_k
|
561 |
+
elif query_length == 1:
|
562 |
+
max_seqlen_in_batch_q = 1
|
563 |
+
cu_seqlens_q = torch.arange(
|
564 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
565 |
+
) # There is a memcpy here, that is very bad.
|
566 |
+
indices_q = cu_seqlens_q[:-1]
|
567 |
+
query_layer = query_layer.squeeze(1)
|
568 |
+
else:
|
569 |
+
# The -q_len: slice assumes left padding.
|
570 |
+
attention_mask = attention_mask[:, -query_length:]
|
571 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
572 |
+
|
573 |
+
return (
|
574 |
+
query_layer,
|
575 |
+
key_layer,
|
576 |
+
value_layer,
|
577 |
+
indices_q,
|
578 |
+
(cu_seqlens_q, cu_seqlens_k),
|
579 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
580 |
+
)
|
581 |
+
|
582 |
+
|
583 |
+
|
584 |
+
LLAMA_ATTENTION_CLASSES = {
|
585 |
+
"eager": BoomerAttention,
|
586 |
+
"flash_attention_2": BoomerFlashAttention2,
|
587 |
+
}
|
588 |
+
|
589 |
+
|
590 |
+
class BoomerDecoderLayer(nn.Module):
|
591 |
+
def __init__(self, config: BoomerConfig, layer_idx: int):
|
592 |
+
super().__init__()
|
593 |
+
self.hidden_size = config.hidden_size
|
594 |
+
|
595 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
596 |
+
|
597 |
+
self.mlp = BoomerMLP(config)
|
598 |
+
self.input_layernorm = BoomerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
599 |
+
self.post_attention_layernorm = BoomerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
600 |
+
|
601 |
+
def forward(
|
602 |
+
self,
|
603 |
+
hidden_states: torch.Tensor,
|
604 |
+
attention_mask: Optional[torch.Tensor] = None,
|
605 |
+
position_ids: Optional[torch.LongTensor] = None,
|
606 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
607 |
+
output_attentions: Optional[bool] = False,
|
608 |
+
use_cache: Optional[bool] = False,
|
609 |
+
cache_position: Optional[torch.LongTensor] = None,
|
610 |
+
**kwargs,
|
611 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
612 |
+
"""
|
613 |
+
Args:
|
614 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
615 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
616 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
617 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
618 |
+
output_attentions (`bool`, *optional*):
|
619 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
620 |
+
returned tensors for more detail.
|
621 |
+
use_cache (`bool`, *optional*):
|
622 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
623 |
+
(see `past_key_values`).
|
624 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
625 |
+
"""
|
626 |
+
if "padding_mask" in kwargs:
|
627 |
+
warnings.warn(
|
628 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
629 |
+
)
|
630 |
+
|
631 |
+
residual = hidden_states
|
632 |
+
|
633 |
+
hidden_states = self.input_layernorm(hidden_states)
|
634 |
+
|
635 |
+
# Self Attention
|
636 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
637 |
+
hidden_states=hidden_states,
|
638 |
+
attention_mask=attention_mask,
|
639 |
+
position_ids=position_ids,
|
640 |
+
past_key_value=past_key_value,
|
641 |
+
output_attentions=output_attentions,
|
642 |
+
use_cache=use_cache,
|
643 |
+
cache_position=cache_position,
|
644 |
+
**kwargs,
|
645 |
+
)
|
646 |
+
hidden_states = residual + hidden_states
|
647 |
+
|
648 |
+
# Fully Connected
|
649 |
+
residual = hidden_states
|
650 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
651 |
+
hidden_states = self.mlp(hidden_states)
|
652 |
+
hidden_states = residual + hidden_states
|
653 |
+
|
654 |
+
outputs = (hidden_states,)
|
655 |
+
|
656 |
+
if output_attentions:
|
657 |
+
outputs += (self_attn_weights,)
|
658 |
+
|
659 |
+
if use_cache:
|
660 |
+
outputs += (present_key_value,)
|
661 |
+
|
662 |
+
return outputs
|
663 |
+
|
664 |
+
|
665 |
+
LLAMA_START_DOCSTRING = r"""
|
666 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
667 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
668 |
+
etc.)
|
669 |
+
|
670 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
671 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
672 |
+
and behavior.
|
673 |
+
|
674 |
+
Parameters:
|
675 |
+
config ([`BoomerConfig`]):
|
676 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
677 |
+
load the weights associated with the model, only the configuration. Check out the
|
678 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
679 |
+
"""
|
680 |
+
|
681 |
+
|
682 |
+
@add_start_docstrings(
|
683 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
684 |
+
LLAMA_START_DOCSTRING,
|
685 |
+
)
|
686 |
+
class BoomerPreTrainedModel(PreTrainedModel):
|
687 |
+
config_class = BoomerConfig
|
688 |
+
base_model_prefix = "model"
|
689 |
+
supports_gradient_checkpointing = True
|
690 |
+
_no_split_modules = ["BoomerDecoderLayer"]
|
691 |
+
_skip_keys_device_placement = ["past_key_values"]
|
692 |
+
_supports_flash_attn_2 = True
|
693 |
+
_supports_sdpa = False
|
694 |
+
_supports_cache_class = True
|
695 |
+
|
696 |
+
def _init_weights(self, module):
|
697 |
+
std = self.config.initializer_range
|
698 |
+
if isinstance(module, nn.Linear):
|
699 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
700 |
+
if module.bias is not None:
|
701 |
+
module.bias.data.zero_()
|
702 |
+
elif isinstance(module, nn.Embedding):
|
703 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
704 |
+
if module.padding_idx is not None:
|
705 |
+
module.weight.data[module.padding_idx].zero_()
|
706 |
+
|
707 |
+
def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
|
708 |
+
if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
|
709 |
+
raise ValueError(
|
710 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
711 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
712 |
+
)
|
713 |
+
|
714 |
+
for layer in self.model.layers:
|
715 |
+
device = layer.input_layernorm.weight.device
|
716 |
+
if hasattr(self.config, "_pre_quantization_dtype"):
|
717 |
+
dtype = self.config._pre_quantization_dtype
|
718 |
+
else:
|
719 |
+
dtype = layer.self_attn.o_proj.weight.dtype
|
720 |
+
layer.self_attn.past_key_value = cache_cls(
|
721 |
+
self.config, max_batch_size, max_cache_len, device=device, dtype=dtype
|
722 |
+
)
|
723 |
+
|
724 |
+
def _reset_cache(self):
|
725 |
+
for layer in self.model.layers:
|
726 |
+
layer.self_attn.past_key_value = None
|
727 |
+
|
728 |
+
|
729 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
730 |
+
Args:
|
731 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
732 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
733 |
+
it.
|
734 |
+
|
735 |
+
Indices can be obtained using [`BoomerTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
736 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
737 |
+
|
738 |
+
[What are input IDs?](../glossary#input-ids)
|
739 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
740 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
741 |
+
|
742 |
+
- 1 for tokens that are **not masked**,
|
743 |
+
- 0 for tokens that are **masked**.
|
744 |
+
|
745 |
+
[What are attention masks?](../glossary#attention-mask)
|
746 |
+
|
747 |
+
Indices can be obtained using [`BoomerTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
748 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
749 |
+
|
750 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
751 |
+
`past_key_values`).
|
752 |
+
|
753 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
754 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
755 |
+
information on the default strategy.
|
756 |
+
|
757 |
+
- 1 indicates the head is **not masked**,
|
758 |
+
- 0 indicates the head is **masked**.
|
759 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
760 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
761 |
+
config.n_positions - 1]`.
|
762 |
+
|
763 |
+
[What are position IDs?](../glossary#position-ids)
|
764 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
765 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
766 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
767 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
768 |
+
|
769 |
+
Two formats are allowed:
|
770 |
+
- a [`~cache_utils.Cache`] instance;
|
771 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
772 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
773 |
+
cache format.
|
774 |
+
|
775 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
776 |
+
legacy cache format will be returned.
|
777 |
+
|
778 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
779 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
780 |
+
of shape `(batch_size, sequence_length)`.
|
781 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
782 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
783 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
784 |
+
model's internal embedding lookup matrix.
|
785 |
+
use_cache (`bool`, *optional*):
|
786 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
787 |
+
`past_key_values`).
|
788 |
+
output_attentions (`bool`, *optional*):
|
789 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
790 |
+
tensors for more detail.
|
791 |
+
output_hidden_states (`bool`, *optional*):
|
792 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
793 |
+
more detail.
|
794 |
+
return_dict (`bool`, *optional*):
|
795 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
796 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
797 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
798 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
799 |
+
the complete sequence length.
|
800 |
+
"""
|
801 |
+
|
802 |
+
|
803 |
+
@add_start_docstrings(
|
804 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
805 |
+
LLAMA_START_DOCSTRING,
|
806 |
+
)
|
807 |
+
class BoomerModel(BoomerPreTrainedModel):
|
808 |
+
"""
|
809 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BoomerDecoderLayer`]
|
810 |
+
|
811 |
+
Args:
|
812 |
+
config: BoomerConfig
|
813 |
+
"""
|
814 |
+
|
815 |
+
def __init__(self, config: BoomerConfig):
|
816 |
+
super().__init__(config)
|
817 |
+
self.padding_idx = config.pad_token_id
|
818 |
+
self.vocab_size = config.vocab_size
|
819 |
+
|
820 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
821 |
+
self.layers = nn.ModuleList(
|
822 |
+
[BoomerDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
823 |
+
)
|
824 |
+
self.norm = BoomerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
825 |
+
self.gradient_checkpointing = False
|
826 |
+
|
827 |
+
# Initialize weights and apply final processing
|
828 |
+
self.post_init()
|
829 |
+
|
830 |
+
def get_input_embeddings(self):
|
831 |
+
return self.embed_tokens
|
832 |
+
|
833 |
+
def set_input_embeddings(self, value):
|
834 |
+
self.embed_tokens = value
|
835 |
+
|
836 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
837 |
+
def forward(
|
838 |
+
self,
|
839 |
+
input_ids: torch.LongTensor = None,
|
840 |
+
attention_mask: Optional[torch.Tensor] = None,
|
841 |
+
position_ids: Optional[torch.LongTensor] = None,
|
842 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
843 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
844 |
+
use_cache: Optional[bool] = None,
|
845 |
+
output_attentions: Optional[bool] = None,
|
846 |
+
output_hidden_states: Optional[bool] = None,
|
847 |
+
return_dict: Optional[bool] = None,
|
848 |
+
cache_position: Optional[torch.LongTensor] = None,
|
849 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
850 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
851 |
+
output_hidden_states = (
|
852 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
853 |
+
)
|
854 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
855 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
856 |
+
|
857 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
858 |
+
raise ValueError(
|
859 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
860 |
+
)
|
861 |
+
|
862 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
863 |
+
logger.warning_once(
|
864 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
865 |
+
)
|
866 |
+
use_cache = False
|
867 |
+
|
868 |
+
if inputs_embeds is None:
|
869 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
870 |
+
|
871 |
+
past_seen_tokens = 0
|
872 |
+
if use_cache: # kept for BC (cache positions)
|
873 |
+
if not isinstance(past_key_values, StaticCache):
|
874 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
875 |
+
past_seen_tokens = past_key_values.get_seq_length()
|
876 |
+
|
877 |
+
if cache_position is None:
|
878 |
+
if isinstance(past_key_values, StaticCache):
|
879 |
+
raise ValueError("cache_position is a required argument when using StaticCache.")
|
880 |
+
cache_position = torch.arange(
|
881 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
882 |
+
)
|
883 |
+
|
884 |
+
if position_ids is None:
|
885 |
+
position_ids = cache_position.unsqueeze(0)
|
886 |
+
|
887 |
+
causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
|
888 |
+
|
889 |
+
# embed positions
|
890 |
+
hidden_states = inputs_embeds
|
891 |
+
|
892 |
+
# decoder layers
|
893 |
+
all_hidden_states = () if output_hidden_states else None
|
894 |
+
all_self_attns = () if output_attentions else None
|
895 |
+
next_decoder_cache = None
|
896 |
+
|
897 |
+
for decoder_layer in self.layers:
|
898 |
+
if output_hidden_states:
|
899 |
+
all_hidden_states += (hidden_states,)
|
900 |
+
|
901 |
+
if self.gradient_checkpointing and self.training:
|
902 |
+
layer_outputs = self._gradient_checkpointing_func(
|
903 |
+
decoder_layer.__call__,
|
904 |
+
hidden_states,
|
905 |
+
causal_mask,
|
906 |
+
position_ids,
|
907 |
+
past_key_values,
|
908 |
+
output_attentions,
|
909 |
+
use_cache,
|
910 |
+
cache_position,
|
911 |
+
)
|
912 |
+
else:
|
913 |
+
layer_outputs = decoder_layer(
|
914 |
+
hidden_states,
|
915 |
+
attention_mask=causal_mask,
|
916 |
+
position_ids=position_ids,
|
917 |
+
past_key_value=past_key_values,
|
918 |
+
output_attentions=output_attentions,
|
919 |
+
use_cache=use_cache,
|
920 |
+
cache_position=cache_position,
|
921 |
+
)
|
922 |
+
|
923 |
+
hidden_states = layer_outputs[0]
|
924 |
+
|
925 |
+
if use_cache:
|
926 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
927 |
+
|
928 |
+
if output_attentions:
|
929 |
+
all_self_attns += (layer_outputs[1],)
|
930 |
+
|
931 |
+
hidden_states = self.norm(hidden_states)
|
932 |
+
|
933 |
+
# add hidden states from the last decoder layer
|
934 |
+
if output_hidden_states:
|
935 |
+
all_hidden_states += (hidden_states,)
|
936 |
+
|
937 |
+
next_cache = None
|
938 |
+
if use_cache:
|
939 |
+
next_cache = (
|
940 |
+
next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
|
941 |
+
)
|
942 |
+
if not return_dict:
|
943 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
944 |
+
return BaseModelOutputWithPast(
|
945 |
+
last_hidden_state=hidden_states,
|
946 |
+
past_key_values=next_cache,
|
947 |
+
hidden_states=all_hidden_states,
|
948 |
+
attentions=all_self_attns,
|
949 |
+
)
|
950 |
+
|
951 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
|
952 |
+
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
|
953 |
+
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
|
954 |
+
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
|
955 |
+
def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
|
956 |
+
if self.config._attn_implementation == "flash_attention_2":
|
957 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
958 |
+
return attention_mask
|
959 |
+
return None
|
960 |
+
|
961 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
962 |
+
min_dtype = torch.finfo(dtype).min
|
963 |
+
sequence_length = input_tensor.shape[1]
|
964 |
+
if hasattr(self.layers[0].self_attn, "past_key_value"): # static cache
|
965 |
+
target_length = self.config.max_position_embeddings
|
966 |
+
else: # dynamic cache
|
967 |
+
target_length = (
|
968 |
+
attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else cache_position[-1] + 1
|
969 |
+
)
|
970 |
+
|
971 |
+
causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
|
972 |
+
if sequence_length != 1:
|
973 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
974 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
975 |
+
causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
|
976 |
+
if attention_mask is not None:
|
977 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
978 |
+
if attention_mask.dim() == 2:
|
979 |
+
mask_length = attention_mask.shape[-1]
|
980 |
+
padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
|
981 |
+
causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
|
982 |
+
elif attention_mask.dim() == 4:
|
983 |
+
# backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
|
984 |
+
# cache. In that case, the 4D attention mask attends to the newest tokens only.
|
985 |
+
if attention_mask.shape[-2] < cache_position[0] + sequence_length:
|
986 |
+
offset = cache_position[0]
|
987 |
+
else:
|
988 |
+
offset = 0
|
989 |
+
mask_shape = attention_mask.shape
|
990 |
+
mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
|
991 |
+
causal_mask[
|
992 |
+
: mask_shape[0], : mask_shape[1], offset : mask_shape[2] + offset, : mask_shape[3]
|
993 |
+
] = mask_slice
|
994 |
+
|
995 |
+
return causal_mask
|
996 |
+
|
997 |
+
|
998 |
+
class BoomerForCausalLM(BoomerPreTrainedModel):
|
999 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1000 |
+
|
1001 |
+
def __init__(self, config):
|
1002 |
+
super().__init__(config)
|
1003 |
+
self.model = BoomerModel(config)
|
1004 |
+
self.vocab_size = config.vocab_size
|
1005 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1006 |
+
|
1007 |
+
# Initialize weights and apply final processing
|
1008 |
+
self.post_init()
|
1009 |
+
|
1010 |
+
def get_input_embeddings(self):
|
1011 |
+
return self.model.embed_tokens
|
1012 |
+
|
1013 |
+
def set_input_embeddings(self, value):
|
1014 |
+
self.model.embed_tokens = value
|
1015 |
+
|
1016 |
+
def get_output_embeddings(self):
|
1017 |
+
return self.lm_head
|
1018 |
+
|
1019 |
+
def set_output_embeddings(self, new_embeddings):
|
1020 |
+
self.lm_head = new_embeddings
|
1021 |
+
|
1022 |
+
def set_decoder(self, decoder):
|
1023 |
+
self.model = decoder
|
1024 |
+
|
1025 |
+
def get_decoder(self):
|
1026 |
+
return self.model
|
1027 |
+
|
1028 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1029 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1030 |
+
def forward(
|
1031 |
+
self,
|
1032 |
+
input_ids: torch.LongTensor = None,
|
1033 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1034 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1035 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1036 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1037 |
+
labels: Optional[torch.LongTensor] = None,
|
1038 |
+
use_cache: Optional[bool] = None,
|
1039 |
+
output_attentions: Optional[bool] = None,
|
1040 |
+
output_hidden_states: Optional[bool] = None,
|
1041 |
+
return_dict: Optional[bool] = None,
|
1042 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1043 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1044 |
+
r"""
|
1045 |
+
Args:
|
1046 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1047 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1048 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1049 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1050 |
+
|
1051 |
+
Returns:
|
1052 |
+
|
1053 |
+
Example:
|
1054 |
+
|
1055 |
+
```python
|
1056 |
+
>>> from transformers import LlamaTokenizer, LlamaForCausalLM
|
1057 |
+
|
1058 |
+
>>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
|
1059 |
+
>>> tokenizer = LlamaTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
|
1060 |
+
|
1061 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1062 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1063 |
+
|
1064 |
+
>>> # Generate
|
1065 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1066 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1067 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1068 |
+
```"""
|
1069 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1070 |
+
output_hidden_states = (
|
1071 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1072 |
+
)
|
1073 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1074 |
+
|
1075 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1076 |
+
outputs = self.model(
|
1077 |
+
input_ids=input_ids,
|
1078 |
+
attention_mask=attention_mask,
|
1079 |
+
position_ids=position_ids,
|
1080 |
+
past_key_values=past_key_values,
|
1081 |
+
inputs_embeds=inputs_embeds,
|
1082 |
+
use_cache=use_cache,
|
1083 |
+
output_attentions=output_attentions,
|
1084 |
+
output_hidden_states=output_hidden_states,
|
1085 |
+
return_dict=return_dict,
|
1086 |
+
cache_position=cache_position,
|
1087 |
+
)
|
1088 |
+
|
1089 |
+
hidden_states = outputs[0]
|
1090 |
+
logits = self.lm_head(hidden_states)
|
1091 |
+
logits = logits.float()
|
1092 |
+
|
1093 |
+
loss = None
|
1094 |
+
if labels is not None:
|
1095 |
+
# Shift so that tokens < n predict n
|
1096 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1097 |
+
shift_labels = labels[..., 1:].contiguous()
|
1098 |
+
# Flatten the tokens
|
1099 |
+
loss_fct = CrossEntropyLoss()
|
1100 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1101 |
+
shift_labels = shift_labels.view(-1)
|
1102 |
+
# Enable model parallelism
|
1103 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1104 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1105 |
+
|
1106 |
+
if not return_dict:
|
1107 |
+
output = (logits,) + outputs[1:]
|
1108 |
+
return (loss,) + output if loss is not None else output
|
1109 |
+
|
1110 |
+
return CausalLMOutputWithPast(
|
1111 |
+
loss=loss,
|
1112 |
+
logits=logits,
|
1113 |
+
past_key_values=outputs.past_key_values,
|
1114 |
+
hidden_states=outputs.hidden_states,
|
1115 |
+
attentions=outputs.attentions,
|
1116 |
+
)
|
1117 |
+
|
1118 |
+
def prepare_inputs_for_generation(
|
1119 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
|
1120 |
+
):
|
1121 |
+
# With static cache, the `past_key_values` is None
|
1122 |
+
# TODO joao: standardize interface for the different Cache classes and remove of this if
|
1123 |
+
has_static_cache = False
|
1124 |
+
if past_key_values is None:
|
1125 |
+
past_key_values = getattr(self.model.layers[0].self_attn, "past_key_value", None)
|
1126 |
+
has_static_cache = past_key_values is not None
|
1127 |
+
|
1128 |
+
past_length = 0
|
1129 |
+
if past_key_values is not None:
|
1130 |
+
if isinstance(past_key_values, Cache):
|
1131 |
+
past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
|
1132 |
+
max_cache_length = (
|
1133 |
+
torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
|
1134 |
+
if past_key_values.get_max_length() is not None
|
1135 |
+
else None
|
1136 |
+
)
|
1137 |
+
cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
|
1138 |
+
# TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
|
1139 |
+
else:
|
1140 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1141 |
+
max_cache_length = None
|
1142 |
+
|
1143 |
+
# Keep only the unprocessed tokens:
|
1144 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1145 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1146 |
+
# input)
|
1147 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1148 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1149 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1150 |
+
# input_ids based on the past_length.
|
1151 |
+
elif past_length < input_ids.shape[1]:
|
1152 |
+
input_ids = input_ids[:, past_length:]
|
1153 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1154 |
+
|
1155 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1156 |
+
if (
|
1157 |
+
max_cache_length is not None
|
1158 |
+
and attention_mask is not None
|
1159 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1160 |
+
):
|
1161 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1162 |
+
|
1163 |
+
position_ids = kwargs.get("position_ids", None)
|
1164 |
+
if attention_mask is not None and position_ids is None:
|
1165 |
+
# create position_ids on the fly for batch generation
|
1166 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1167 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1168 |
+
if past_key_values:
|
1169 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1170 |
+
|
1171 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1172 |
+
if inputs_embeds is not None and past_key_values is None:
|
1173 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1174 |
+
else:
|
1175 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
1176 |
+
# recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
|
1177 |
+
# TODO: use `next_tokens` directly instead.
|
1178 |
+
model_inputs = {"input_ids": input_ids.contiguous()}
|
1179 |
+
|
1180 |
+
input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
|
1181 |
+
if cache_position is None:
|
1182 |
+
cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
|
1183 |
+
else:
|
1184 |
+
cache_position = cache_position[-input_length:]
|
1185 |
+
|
1186 |
+
if has_static_cache:
|
1187 |
+
past_key_values = None
|
1188 |
+
|
1189 |
+
model_inputs.update(
|
1190 |
+
{
|
1191 |
+
"position_ids": position_ids,
|
1192 |
+
"cache_position": cache_position,
|
1193 |
+
"past_key_values": past_key_values,
|
1194 |
+
"use_cache": kwargs.get("use_cache"),
|
1195 |
+
"attention_mask": attention_mask,
|
1196 |
+
}
|
1197 |
+
)
|
1198 |
+
return model_inputs
|
1199 |
+
|
1200 |
+
@staticmethod
|
1201 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1202 |
+
reordered_past = ()
|
1203 |
+
for layer_past in past_key_values:
|
1204 |
+
reordered_past += (
|
1205 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1206 |
+
)
|
1207 |
+
return reordered_past
|
1208 |
+
|
1209 |
+
|
1210 |
+
@add_start_docstrings(
|
1211 |
+
"""
|
1212 |
+
The LLaMa Model transformer with a sequence classification head on top (linear layer).
|
1213 |
+
|
1214 |
+
[`BoomerForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1215 |
+
(e.g. GPT-2) do.
|
1216 |
+
|
1217 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1218 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1219 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1220 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1221 |
+
each row of the batch).
|
1222 |
+
""",
|
1223 |
+
LLAMA_START_DOCSTRING,
|
1224 |
+
)
|
1225 |
+
class BoomerForSequenceClassification(BoomerPreTrainedModel):
|
1226 |
+
def __init__(self, config):
|
1227 |
+
super().__init__(config)
|
1228 |
+
self.num_labels = config.num_labels
|
1229 |
+
self.model = BoomerModel(config)
|
1230 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1231 |
+
|
1232 |
+
# Initialize weights and apply final processing
|
1233 |
+
self.post_init()
|
1234 |
+
|
1235 |
+
def get_input_embeddings(self):
|
1236 |
+
return self.model.embed_tokens
|
1237 |
+
|
1238 |
+
def set_input_embeddings(self, value):
|
1239 |
+
self.model.embed_tokens = value
|
1240 |
+
|
1241 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1242 |
+
def forward(
|
1243 |
+
self,
|
1244 |
+
input_ids: torch.LongTensor = None,
|
1245 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1246 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1247 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1248 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1249 |
+
labels: Optional[torch.LongTensor] = None,
|
1250 |
+
use_cache: Optional[bool] = None,
|
1251 |
+
output_attentions: Optional[bool] = None,
|
1252 |
+
output_hidden_states: Optional[bool] = None,
|
1253 |
+
return_dict: Optional[bool] = None,
|
1254 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1255 |
+
r"""
|
1256 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1257 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1258 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1259 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1260 |
+
"""
|
1261 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1262 |
+
|
1263 |
+
transformer_outputs = self.model(
|
1264 |
+
input_ids,
|
1265 |
+
attention_mask=attention_mask,
|
1266 |
+
position_ids=position_ids,
|
1267 |
+
past_key_values=past_key_values,
|
1268 |
+
inputs_embeds=inputs_embeds,
|
1269 |
+
use_cache=use_cache,
|
1270 |
+
output_attentions=output_attentions,
|
1271 |
+
output_hidden_states=output_hidden_states,
|
1272 |
+
return_dict=return_dict,
|
1273 |
+
)
|
1274 |
+
hidden_states = transformer_outputs[0]
|
1275 |
+
logits = self.score(hidden_states)
|
1276 |
+
|
1277 |
+
if input_ids is not None:
|
1278 |
+
batch_size = input_ids.shape[0]
|
1279 |
+
else:
|
1280 |
+
batch_size = inputs_embeds.shape[0]
|
1281 |
+
|
1282 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1283 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1284 |
+
if self.config.pad_token_id is None:
|
1285 |
+
sequence_lengths = -1
|
1286 |
+
else:
|
1287 |
+
if input_ids is not None:
|
1288 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1289 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1290 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1291 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1292 |
+
else:
|
1293 |
+
sequence_lengths = -1
|
1294 |
+
|
1295 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1296 |
+
|
1297 |
+
loss = None
|
1298 |
+
if labels is not None:
|
1299 |
+
labels = labels.to(logits.device)
|
1300 |
+
if self.config.problem_type is None:
|
1301 |
+
if self.num_labels == 1:
|
1302 |
+
self.config.problem_type = "regression"
|
1303 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1304 |
+
self.config.problem_type = "single_label_classification"
|
1305 |
+
else:
|
1306 |
+
self.config.problem_type = "multi_label_classification"
|
1307 |
+
|
1308 |
+
if self.config.problem_type == "regression":
|
1309 |
+
loss_fct = MSELoss()
|
1310 |
+
if self.num_labels == 1:
|
1311 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1312 |
+
else:
|
1313 |
+
loss = loss_fct(pooled_logits, labels)
|
1314 |
+
elif self.config.problem_type == "single_label_classification":
|
1315 |
+
loss_fct = CrossEntropyLoss()
|
1316 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1317 |
+
elif self.config.problem_type == "multi_label_classification":
|
1318 |
+
loss_fct = BCEWithLogitsLoss()
|
1319 |
+
loss = loss_fct(pooled_logits, labels)
|
1320 |
+
if not return_dict:
|
1321 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1322 |
+
return ((loss,) + output) if loss is not None else output
|
1323 |
+
|
1324 |
+
return SequenceClassifierOutputWithPast(
|
1325 |
+
loss=loss,
|
1326 |
+
logits=pooled_logits,
|
1327 |
+
past_key_values=transformer_outputs.past_key_values,
|
1328 |
+
hidden_states=transformer_outputs.hidden_states,
|
1329 |
+
attentions=transformer_outputs.attentions,
|
1330 |
+
)
|
1331 |
+
|
1332 |
+
|
1333 |
+
@add_start_docstrings(
|
1334 |
+
"""
|
1335 |
+
The Boomer Model transformer with a span classification head on top for extractive question-answering tasks like
|
1336 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1337 |
+
""",
|
1338 |
+
LLAMA_START_DOCSTRING,
|
1339 |
+
)
|
1340 |
+
class BoomerForQuestionAnswering(BoomerPreTrainedModel):
|
1341 |
+
base_model_prefix = "transformer"
|
1342 |
+
|
1343 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Boomer
|
1344 |
+
def __init__(self, config):
|
1345 |
+
super().__init__(config)
|
1346 |
+
self.transformer = BoomerModel(config)
|
1347 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1348 |
+
|
1349 |
+
# Initialize weights and apply final processing
|
1350 |
+
self.post_init()
|
1351 |
+
|
1352 |
+
def get_input_embeddings(self):
|
1353 |
+
return self.transformer.embed_tokens
|
1354 |
+
|
1355 |
+
def set_input_embeddings(self, value):
|
1356 |
+
self.transformer.embed_tokens = value
|
1357 |
+
|
1358 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1359 |
+
def forward(
|
1360 |
+
self,
|
1361 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1362 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1363 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1364 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1365 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1366 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1367 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1368 |
+
output_attentions: Optional[bool] = None,
|
1369 |
+
output_hidden_states: Optional[bool] = None,
|
1370 |
+
return_dict: Optional[bool] = None,
|
1371 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1372 |
+
r"""
|
1373 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1374 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1375 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1376 |
+
are not taken into account for computing the loss.
|
1377 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1378 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1379 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1380 |
+
are not taken into account for computing the loss.
|
1381 |
+
"""
|
1382 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1383 |
+
|
1384 |
+
outputs = self.transformer(
|
1385 |
+
input_ids,
|
1386 |
+
attention_mask=attention_mask,
|
1387 |
+
position_ids=position_ids,
|
1388 |
+
past_key_values=past_key_values,
|
1389 |
+
inputs_embeds=inputs_embeds,
|
1390 |
+
output_attentions=output_attentions,
|
1391 |
+
output_hidden_states=output_hidden_states,
|
1392 |
+
return_dict=return_dict,
|
1393 |
+
)
|
1394 |
+
|
1395 |
+
sequence_output = outputs[0]
|
1396 |
+
|
1397 |
+
logits = self.qa_outputs(sequence_output)
|
1398 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1399 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1400 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1401 |
+
|
1402 |
+
total_loss = None
|
1403 |
+
if start_positions is not None and end_positions is not None:
|
1404 |
+
# If we are on multi-GPU, split add a dimension
|
1405 |
+
if len(start_positions.size()) > 1:
|
1406 |
+
start_positions = start_positions.squeeze(-1).to(start_logits.device)
|
1407 |
+
if len(end_positions.size()) > 1:
|
1408 |
+
end_positions = end_positions.squeeze(-1).to(end_logits.device)
|
1409 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
1410 |
+
ignored_index = start_logits.size(1)
|
1411 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
1412 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
1413 |
+
|
1414 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
1415 |
+
start_loss = loss_fct(start_logits, start_positions)
|
1416 |
+
end_loss = loss_fct(end_logits, end_positions)
|
1417 |
+
total_loss = (start_loss + end_loss) / 2
|
1418 |
+
|
1419 |
+
if not return_dict:
|
1420 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1421 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1422 |
+
|
1423 |
+
return QuestionAnsweringModelOutput(
|
1424 |
+
loss=total_loss,
|
1425 |
+
start_logits=start_logits,
|
1426 |
+
end_logits=end_logits,
|
1427 |
+
hidden_states=outputs.hidden_states,
|
1428 |
+
attentions=outputs.attentions,
|
1429 |
+
)
|
special_tokens_map.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": "<unk>",
|
17 |
+
"unk_token": {
|
18 |
+
"content": "<unk>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": false,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
}
|
24 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b2e509865169c2b4fa56bb12c4f764328d25739891a1cd7f040c07448a9ca175
|
3 |
+
size 1191551
|
tokenizer_config.json
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": true,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"add_prefix_space": true,
|
5 |
+
"added_tokens_decoder": {
|
6 |
+
"0": {
|
7 |
+
"content": "<unk>",
|
8 |
+
"lstrip": false,
|
9 |
+
"normalized": false,
|
10 |
+
"rstrip": false,
|
11 |
+
"single_word": false,
|
12 |
+
"special": true
|
13 |
+
},
|
14 |
+
"1": {
|
15 |
+
"content": "<s>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false,
|
20 |
+
"special": true
|
21 |
+
},
|
22 |
+
"2": {
|
23 |
+
"content": "</s>",
|
24 |
+
"lstrip": false,
|
25 |
+
"normalized": false,
|
26 |
+
"rstrip": false,
|
27 |
+
"single_word": false,
|
28 |
+
"special": true
|
29 |
+
}
|
30 |
+
},
|
31 |
+
"bos_token": "<s>",
|
32 |
+
"clean_up_tokenization_spaces": false,
|
33 |
+
"eos_token": "</s>",
|
34 |
+
"legacy": false,
|
35 |
+
"model_max_length": 1000000000000000019884624838656,
|
36 |
+
"pad_token": "<unk>",
|
37 |
+
"padding_side": "right",
|
38 |
+
"sp_model_kwargs": {},
|
39 |
+
"spaces_between_special_tokens": false,
|
40 |
+
"tokenizer_class": "LlamaTokenizer",
|
41 |
+
"unk_token": "<unk>",
|
42 |
+
"use_default_system_prompt": true
|
43 |
+
}
|