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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 the Falcon authors and HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""PyTorch Falcon model."""
|
16 |
+
|
17 |
+
import math
|
18 |
+
import warnings
|
19 |
+
from typing import TYPE_CHECKING, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.utils.checkpoint
|
23 |
+
from torch import nn
|
24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
|
25 |
+
from torch.nn import functional as F
|
26 |
+
|
27 |
+
from transformers.modeling_attn_mask_utils import (
|
28 |
+
AttentionMaskConverter,
|
29 |
+
_prepare_4d_causal_attention_mask,
|
30 |
+
_prepare_4d_causal_attention_mask_for_sdpa,
|
31 |
+
)
|
32 |
+
from transformers.modeling_outputs import (
|
33 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
34 |
+
CausalLMOutputWithCrossAttentions,
|
35 |
+
QuestionAnsweringModelOutput,
|
36 |
+
SequenceClassifierOutputWithPast,
|
37 |
+
TokenClassifierOutput,
|
38 |
+
)
|
39 |
+
from transformers.modeling_utils import PreTrainedModel
|
40 |
+
from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_0
|
41 |
+
from transformers.utils import (
|
42 |
+
add_code_sample_docstrings,
|
43 |
+
add_start_docstrings,
|
44 |
+
add_start_docstrings_to_model_forward,
|
45 |
+
is_flash_attn_2_available,
|
46 |
+
is_flash_attn_greater_or_equal_2_10,
|
47 |
+
logging,
|
48 |
+
)
|
49 |
+
from .configuration_falcon import FalconConfig
|
50 |
+
|
51 |
+
|
52 |
+
if TYPE_CHECKING:
|
53 |
+
from transformers.configuration_utils import PretrainedConfig
|
54 |
+
|
55 |
+
if is_flash_attn_2_available():
|
56 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
57 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
58 |
+
|
59 |
+
logger = logging.get_logger(__name__)
|
60 |
+
|
61 |
+
FALCON_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
62 |
+
"tiiuae/falcon-40b",
|
63 |
+
"tiiuae/falcon-40b-instruct",
|
64 |
+
"tiiuae/falcon-7b",
|
65 |
+
"tiiuae/falcon-7b-instruct",
|
66 |
+
"tiiuae/falcon-rw-7b",
|
67 |
+
"tiiuae/falcon-rw-1b",
|
68 |
+
]
|
69 |
+
_CHECKPOINT_FOR_DOC = "Rocketknight1/falcon-rw-1b"
|
70 |
+
_CONFIG_FOR_DOC = "FalconConfig"
|
71 |
+
|
72 |
+
|
73 |
+
# NOTE(Hesslow): Unfortunately we did not fuse matmul and bias during training, this means that there's one additional quantization to bfloat16 between the operations.
|
74 |
+
# In order not to degrade the quality of our HF-port, we keep these characteristics in the final model.
|
75 |
+
class FalconLinear(nn.Linear):
|
76 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
77 |
+
hidden_states = input @ self.weight.T
|
78 |
+
if self.bias is None:
|
79 |
+
return hidden_states
|
80 |
+
return hidden_states + self.bias
|
81 |
+
|
82 |
+
|
83 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
84 |
+
def rotate_half(x):
|
85 |
+
"""Rotates half the hidden dims of the input."""
|
86 |
+
x1 = x[..., : x.shape[-1] // 2]
|
87 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
88 |
+
return torch.cat((-x2, x1), dim=-1)
|
89 |
+
|
90 |
+
|
91 |
+
# Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
|
92 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
93 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
94 |
+
|
95 |
+
Args:
|
96 |
+
q (`torch.Tensor`): The query tensor.
|
97 |
+
k (`torch.Tensor`): The key tensor.
|
98 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
99 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
100 |
+
position_ids (`torch.Tensor`):
|
101 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
102 |
+
used to pass offsetted position ids when working with a KV-cache.
|
103 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
104 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
105 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
106 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
107 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
108 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
109 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
110 |
+
Returns:
|
111 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
112 |
+
"""
|
113 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
114 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
115 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
116 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
117 |
+
return q_embed, k_embed
|
118 |
+
|
119 |
+
|
120 |
+
@torch.jit.script
|
121 |
+
def get_max_seqlen_in_batch(attention_mask: torch.Tensor) -> torch.Tensor:
|
122 |
+
max_num = int(torch.max(attention_mask).item())
|
123 |
+
batch_size, _ = attention_mask.shape
|
124 |
+
counts = torch.zeros((batch_size, max_num), dtype=torch.int32)
|
125 |
+
|
126 |
+
for i in range(1, max_num + 1):
|
127 |
+
mask = attention_mask == i
|
128 |
+
counts[:, i - 1] = torch.sum(mask, dim=-1).to(dtype=torch.int32)
|
129 |
+
|
130 |
+
result = counts.flatten()
|
131 |
+
nonzero_indices = torch.nonzero(result).squeeze(-1)
|
132 |
+
return result[nonzero_indices]
|
133 |
+
|
134 |
+
|
135 |
+
@torch.jit.script
|
136 |
+
def _get_unpad_data(attention_mask: torch.Tensor):
|
137 |
+
device = attention_mask.device
|
138 |
+
seqlens_in_batch = get_max_seqlen_in_batch(attention_mask)
|
139 |
+
indices = torch.nonzero(attention_mask.flatten()).flatten()
|
140 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
141 |
+
cu_seqlens = (
|
142 |
+
F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
143 |
+
.to(device=device)
|
144 |
+
.detach()
|
145 |
+
)
|
146 |
+
return (
|
147 |
+
indices,
|
148 |
+
cu_seqlens,
|
149 |
+
max_seqlen_in_batch,
|
150 |
+
)
|
151 |
+
|
152 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Falcon
|
153 |
+
class FalconRotaryEmbedding(nn.Module):
|
154 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
155 |
+
super().__init__()
|
156 |
+
|
157 |
+
self.dim = dim
|
158 |
+
self.max_position_embeddings = max_position_embeddings
|
159 |
+
self.base = base
|
160 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
161 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
162 |
+
|
163 |
+
# Build here to make `torch.jit.trace` work.
|
164 |
+
self._set_cos_sin_cache(
|
165 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
166 |
+
)
|
167 |
+
|
168 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
169 |
+
self.max_seq_len_cached = seq_len
|
170 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
171 |
+
|
172 |
+
freqs = torch.outer(t, self.inv_freq)
|
173 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
174 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
175 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
176 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
177 |
+
|
178 |
+
def forward(self, x, seq_len=None):
|
179 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
180 |
+
if seq_len > self.max_seq_len_cached:
|
181 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
182 |
+
|
183 |
+
return (
|
184 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
185 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
186 |
+
)
|
187 |
+
|
188 |
+
|
189 |
+
# copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Falcon
|
190 |
+
# TODO @joao no longer copied from LLama after static cache, fix me (copied -> Copied)
|
191 |
+
class FalconLinearScalingRotaryEmbedding(FalconRotaryEmbedding):
|
192 |
+
"""FalconRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
193 |
+
|
194 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
195 |
+
self.scaling_factor = scaling_factor
|
196 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
197 |
+
|
198 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
199 |
+
self.max_seq_len_cached = seq_len
|
200 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
201 |
+
t = t / self.scaling_factor
|
202 |
+
|
203 |
+
freqs = torch.outer(t, self.inv_freq)
|
204 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
205 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
206 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
207 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
208 |
+
|
209 |
+
|
210 |
+
# copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Falcon
|
211 |
+
# TODO @joao no longer copied from LLama after static cache, fix me (copied -> Copied)
|
212 |
+
class FalconDynamicNTKScalingRotaryEmbedding(FalconRotaryEmbedding):
|
213 |
+
"""FalconRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
214 |
+
|
215 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
216 |
+
self.scaling_factor = scaling_factor
|
217 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
218 |
+
|
219 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
220 |
+
self.max_seq_len_cached = seq_len
|
221 |
+
|
222 |
+
if seq_len > self.max_position_embeddings:
|
223 |
+
base = self.base * (
|
224 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
225 |
+
) ** (self.dim / (self.dim - 2))
|
226 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
227 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
228 |
+
|
229 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
230 |
+
|
231 |
+
freqs = torch.outer(t, self.inv_freq)
|
232 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
233 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
234 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
235 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
236 |
+
|
237 |
+
|
238 |
+
def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
|
239 |
+
batch_size, seq_length = attention_mask.shape
|
240 |
+
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
|
241 |
+
base = torch.tensor(
|
242 |
+
2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
|
243 |
+
)
|
244 |
+
powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
|
245 |
+
slopes = torch.pow(base, powers)
|
246 |
+
|
247 |
+
if closest_power_of_2 != num_heads:
|
248 |
+
extra_base = torch.tensor(
|
249 |
+
2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
|
250 |
+
)
|
251 |
+
num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
|
252 |
+
extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
|
253 |
+
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
|
254 |
+
|
255 |
+
# Note: alibi will added to the attention bias that will be applied to the query, key product of attention
|
256 |
+
# => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
|
257 |
+
# => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
|
258 |
+
# => the query_length dimension will then be broadcasted correctly
|
259 |
+
# This is more or less identical to T5's relative position bias:
|
260 |
+
# https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
|
261 |
+
arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
|
262 |
+
alibi = slopes[..., None].bfloat16() * arange_tensor
|
263 |
+
return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
|
264 |
+
|
265 |
+
|
266 |
+
# Copied from transformers.models.bloom.modeling_bloom.dropout_add
|
267 |
+
def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
|
268 |
+
"""
|
269 |
+
Dropout add function
|
270 |
+
|
271 |
+
Args:
|
272 |
+
x (`torch.tensor`, *required*):
|
273 |
+
input tensor
|
274 |
+
residual (`torch.tensor`, *required*):
|
275 |
+
residual tensor
|
276 |
+
prob (`float`, *required*):
|
277 |
+
dropout probability
|
278 |
+
training (`bool`, *required*):
|
279 |
+
training mode
|
280 |
+
"""
|
281 |
+
out = F.dropout(x, p=prob, training=training)
|
282 |
+
out = residual + out
|
283 |
+
return out
|
284 |
+
|
285 |
+
|
286 |
+
class FalconAttention(nn.Module):
|
287 |
+
def __init__(self, config: FalconConfig):
|
288 |
+
super().__init__()
|
289 |
+
|
290 |
+
self.config = config
|
291 |
+
self.hidden_size = config.hidden_size
|
292 |
+
self.num_heads = config.num_attention_heads
|
293 |
+
self.head_dim = self.hidden_size // self.num_heads
|
294 |
+
self.split_size = self.hidden_size
|
295 |
+
self.hidden_dropout = config.hidden_dropout
|
296 |
+
self.max_position_embeddings = config.max_position_embeddings
|
297 |
+
self.rope_theta = config.rope_theta
|
298 |
+
self.is_causal = True
|
299 |
+
self._use_sdpa = config._attn_implementation == "sdpa"
|
300 |
+
|
301 |
+
if self.head_dim * self.num_heads != self.hidden_size:
|
302 |
+
raise ValueError(
|
303 |
+
f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
|
304 |
+
f" {self.num_heads})."
|
305 |
+
)
|
306 |
+
|
307 |
+
if config.rotary:
|
308 |
+
self._init_rope()
|
309 |
+
|
310 |
+
# Layer-wise attention scaling
|
311 |
+
self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
|
312 |
+
self.beta = self.inv_norm_factor
|
313 |
+
if config.new_decoder_architecture:
|
314 |
+
qkv_out_dim = (config.num_kv_heads * 2 + config.num_attention_heads) * self.head_dim
|
315 |
+
elif config.multi_query:
|
316 |
+
qkv_out_dim = self.hidden_size + 2 * self.head_dim
|
317 |
+
else:
|
318 |
+
qkv_out_dim = 3 * self.hidden_size
|
319 |
+
self.query_key_value = FalconLinear(self.hidden_size, qkv_out_dim, bias=config.bias)
|
320 |
+
self.new_decoder_architecture = config.new_decoder_architecture
|
321 |
+
self.multi_query = config.multi_query
|
322 |
+
self.dense = FalconLinear(self.hidden_size, self.hidden_size, bias=config.bias)
|
323 |
+
self.attention_dropout = nn.Dropout(config.attention_dropout)
|
324 |
+
self.num_kv_heads = config.num_kv_heads if (self.new_decoder_architecture or not self.multi_query) else 1
|
325 |
+
|
326 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaAttention._init_rope with Llama->Falcon
|
327 |
+
def _init_rope(self):
|
328 |
+
if self.config.rope_scaling is None:
|
329 |
+
self.rotary_emb = FalconRotaryEmbedding(
|
330 |
+
self.head_dim,
|
331 |
+
max_position_embeddings=self.max_position_embeddings,
|
332 |
+
base=self.rope_theta,
|
333 |
+
)
|
334 |
+
else:
|
335 |
+
scaling_type = self.config.rope_scaling["type"]
|
336 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
337 |
+
if scaling_type == "linear":
|
338 |
+
self.rotary_emb = FalconLinearScalingRotaryEmbedding(
|
339 |
+
self.head_dim,
|
340 |
+
max_position_embeddings=self.max_position_embeddings,
|
341 |
+
scaling_factor=scaling_factor,
|
342 |
+
base=self.rope_theta,
|
343 |
+
)
|
344 |
+
elif scaling_type == "dynamic":
|
345 |
+
self.rotary_emb = FalconDynamicNTKScalingRotaryEmbedding(
|
346 |
+
self.head_dim,
|
347 |
+
max_position_embeddings=self.max_position_embeddings,
|
348 |
+
scaling_factor=scaling_factor,
|
349 |
+
base=self.rope_theta,
|
350 |
+
)
|
351 |
+
else:
|
352 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
353 |
+
|
354 |
+
def _split_heads(self, fused_qkv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
355 |
+
"""
|
356 |
+
Split the last dimension into (num_heads, head_dim), results share same memory storage as `fused_qkv`
|
357 |
+
|
358 |
+
Args:
|
359 |
+
fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim]
|
360 |
+
|
361 |
+
Returns:
|
362 |
+
query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
|
363 |
+
value: [batch_size, seq_length, num_heads, head_dim]
|
364 |
+
"""
|
365 |
+
if self.new_decoder_architecture:
|
366 |
+
batch, seq_len, _ = fused_qkv.shape
|
367 |
+
qkv = fused_qkv.view(batch, seq_len, -1, self.num_heads // self.num_kv_heads + 2, self.head_dim)
|
368 |
+
query = qkv[:, :, :, :-2]
|
369 |
+
key = qkv[:, :, :, [-2]]
|
370 |
+
value = qkv[:, :, :, [-1]]
|
371 |
+
key = torch.broadcast_to(key, query.shape)
|
372 |
+
value = torch.broadcast_to(value, query.shape)
|
373 |
+
|
374 |
+
query, key, value = [x.flatten(2, 3) for x in (query, key, value)]
|
375 |
+
return query, key, value
|
376 |
+
elif not self.multi_query:
|
377 |
+
batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
|
378 |
+
fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
|
379 |
+
return fused_qkv[..., 0, :], fused_qkv[..., 1, :], fused_qkv[..., 2, :]
|
380 |
+
else:
|
381 |
+
batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
|
382 |
+
fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads + 2, self.head_dim)
|
383 |
+
return fused_qkv[..., :-2, :], fused_qkv[..., [-2], :], fused_qkv[..., [-1], :]
|
384 |
+
|
385 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomAttention._merge_heads
|
386 |
+
def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
|
387 |
+
"""
|
388 |
+
Merge heads together over the last dimension
|
389 |
+
|
390 |
+
Args:
|
391 |
+
x (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim]
|
392 |
+
|
393 |
+
Returns:
|
394 |
+
torch.tensor: [batch_size, seq_length, num_heads * head_dim]
|
395 |
+
"""
|
396 |
+
# What we want to achieve is:
|
397 |
+
# batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
|
398 |
+
batch_size_and_num_heads, seq_length, _ = x.shape
|
399 |
+
batch_size = batch_size_and_num_heads // self.num_heads
|
400 |
+
|
401 |
+
# First view to decompose the batch size
|
402 |
+
# batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
|
403 |
+
x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
|
404 |
+
|
405 |
+
# batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
|
406 |
+
x = x.permute(0, 2, 1, 3)
|
407 |
+
|
408 |
+
# batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
|
409 |
+
return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
|
410 |
+
|
411 |
+
def forward(
|
412 |
+
self,
|
413 |
+
hidden_states: torch.Tensor,
|
414 |
+
alibi: Optional[torch.Tensor],
|
415 |
+
attention_mask: torch.Tensor,
|
416 |
+
position_ids: Optional[torch.LongTensor] = None,
|
417 |
+
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
418 |
+
head_mask: Optional[torch.Tensor] = None,
|
419 |
+
use_cache: bool = False,
|
420 |
+
output_attentions: bool = False,
|
421 |
+
**kwargs,
|
422 |
+
):
|
423 |
+
if "padding_mask" in kwargs:
|
424 |
+
warnings.warn(
|
425 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
426 |
+
)
|
427 |
+
|
428 |
+
fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
|
429 |
+
num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads
|
430 |
+
# 3 x [batch_size, seq_length, num_heads, head_dim]
|
431 |
+
(query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
|
432 |
+
|
433 |
+
batch_size, query_length, _, _ = query_layer.shape
|
434 |
+
|
435 |
+
query_layer = query_layer.transpose(1, 2).reshape(batch_size, self.num_heads, query_length, self.head_dim)
|
436 |
+
key_layer = key_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
|
437 |
+
value_layer = value_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
|
438 |
+
|
439 |
+
kv_seq_len = key_layer.shape[-2]
|
440 |
+
if layer_past is not None:
|
441 |
+
kv_seq_len += layer_past[0].shape[-2]
|
442 |
+
if alibi is None:
|
443 |
+
cos, sin = self.rotary_emb(value_layer, seq_len=kv_seq_len)
|
444 |
+
query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, position_ids)
|
445 |
+
|
446 |
+
if layer_past is not None:
|
447 |
+
past_key, past_value = layer_past
|
448 |
+
# concatenate along seq_length dimension:
|
449 |
+
# - key: [batch_size, self.num_heads, kv_length, head_dim]
|
450 |
+
# - value: [batch_size, self.num_heads, kv_length, head_dim]
|
451 |
+
key_layer = torch.cat((past_key, key_layer), dim=-2)
|
452 |
+
value_layer = torch.cat((past_value, value_layer), dim=-2)
|
453 |
+
|
454 |
+
kv_length = key_layer.shape[-2]
|
455 |
+
if use_cache:
|
456 |
+
present = (key_layer, value_layer)
|
457 |
+
else:
|
458 |
+
present = None
|
459 |
+
|
460 |
+
if self._use_sdpa and query_layer.device.type == "cuda" and attention_mask is not None:
|
461 |
+
# For torch<=2.1.2, SDPA with memory-efficient backend is bugged with non-contiguous inputs with custom attn_mask,
|
462 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
463 |
+
query_layer = query_layer.contiguous()
|
464 |
+
key_layer = key_layer.contiguous()
|
465 |
+
value_layer = value_layer.contiguous()
|
466 |
+
|
467 |
+
if alibi is None:
|
468 |
+
if self._use_sdpa and not output_attentions:
|
469 |
+
attn_output = F.scaled_dot_product_attention(
|
470 |
+
query_layer,
|
471 |
+
key_layer,
|
472 |
+
value_layer,
|
473 |
+
attention_mask,
|
474 |
+
0.0,
|
475 |
+
# The query_length > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case query_length == 1.
|
476 |
+
is_causal=self.is_causal and attention_mask is None and query_length > 1,
|
477 |
+
)
|
478 |
+
|
479 |
+
attention_scores = None
|
480 |
+
else:
|
481 |
+
attention_scores = query_layer @ key_layer.transpose(-1, -2)
|
482 |
+
attention_scores /= math.sqrt(self.head_dim)
|
483 |
+
|
484 |
+
attention_scores = F.softmax(attention_scores + attention_mask, dim=-1, dtype=hidden_states.dtype)
|
485 |
+
# It is unclear why neither dropout nor head_mask is applied here (while it is with alibi).
|
486 |
+
attn_output = attention_scores @ value_layer
|
487 |
+
|
488 |
+
attn_output = attn_output.view(batch_size, self.num_heads, query_length, self.head_dim)
|
489 |
+
attn_output = attn_output.permute(0, 2, 1, 3)
|
490 |
+
attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
|
491 |
+
|
492 |
+
attn_output = self.dense(attn_output)
|
493 |
+
|
494 |
+
if output_attentions:
|
495 |
+
return attn_output, present, attention_scores
|
496 |
+
else:
|
497 |
+
return attn_output, present
|
498 |
+
|
499 |
+
else:
|
500 |
+
if self._use_sdpa and not output_attentions and head_mask is None:
|
501 |
+
attn_output = F.scaled_dot_product_attention(
|
502 |
+
query_layer,
|
503 |
+
key_layer,
|
504 |
+
value_layer,
|
505 |
+
attn_mask=attention_mask,
|
506 |
+
dropout_p=self.attention_dropout.p if self.training else 0.0,
|
507 |
+
is_causal=self.is_causal and attention_mask is None and query_length > 1,
|
508 |
+
)
|
509 |
+
attn_output = attn_output.transpose(1, 2)
|
510 |
+
attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
|
511 |
+
|
512 |
+
attn_output = self.dense(attn_output)
|
513 |
+
else:
|
514 |
+
matmul_result = query_layer @ key_layer.transpose(-1, -2)
|
515 |
+
|
516 |
+
# change view to [batch_size, num_heads, q_length, kv_length]
|
517 |
+
attention_scores = matmul_result.view(batch_size, self.num_heads, query_length, kv_length)
|
518 |
+
|
519 |
+
# cast attention scores to fp32, compute scaled softmax and cast back to initial dtype - [batch_size, num_heads, q_length, kv_length]
|
520 |
+
input_dtype = attention_scores.dtype
|
521 |
+
# `float16` has a minimum value of -65504.0, whereas `bfloat16` and `float32` have a minimum value of `-3.4e+38`
|
522 |
+
if input_dtype == torch.float16 or input_dtype == torch.bfloat16:
|
523 |
+
attention_scores = attention_scores.to(torch.float32)
|
524 |
+
|
525 |
+
attention_logits = attention_scores + alibi.view(batch_size, self.num_heads, 1, -1)
|
526 |
+
attention_logits *= self.inv_norm_factor
|
527 |
+
attention_probs = F.softmax(attention_logits + attention_mask, dim=-1, dtype=hidden_states.dtype)
|
528 |
+
# [batch_size, num_heads, q_length, kv_length]
|
529 |
+
attention_probs = self.attention_dropout(attention_probs)
|
530 |
+
|
531 |
+
if head_mask is not None:
|
532 |
+
attention_probs = attention_probs * head_mask
|
533 |
+
|
534 |
+
# change view [batch_size, num_heads, q_length, kv_length]
|
535 |
+
attention_probs_reshaped = attention_probs.view(batch_size, self.num_heads, query_length, kv_length)
|
536 |
+
|
537 |
+
# matmul: [batch_size * num_heads, q_length, head_dim]
|
538 |
+
attn_output = (attention_probs_reshaped @ value_layer).flatten(0, 1)
|
539 |
+
|
540 |
+
# change view [batch_size, q_length, num_heads * head_dim]
|
541 |
+
attn_output = self._merge_heads(attn_output)
|
542 |
+
|
543 |
+
attn_output = self.dense(attn_output)
|
544 |
+
|
545 |
+
if output_attentions:
|
546 |
+
return attn_output, present, attention_probs
|
547 |
+
else:
|
548 |
+
return attn_output, present
|
549 |
+
|
550 |
+
|
551 |
+
class FalconFlashAttention2(FalconAttention):
|
552 |
+
"""
|
553 |
+
Falcon flash attention module. This module inherits from `FalconAttention` as the weights of the module stays
|
554 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
555 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
556 |
+
"""
|
557 |
+
|
558 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
559 |
+
def __init__(self, *args, **kwargs):
|
560 |
+
super().__init__(*args, **kwargs)
|
561 |
+
|
562 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
563 |
+
# 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.
|
564 |
+
# 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).
|
565 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
566 |
+
|
567 |
+
def forward(
|
568 |
+
self,
|
569 |
+
hidden_states: torch.Tensor,
|
570 |
+
alibi: Optional[torch.Tensor],
|
571 |
+
attention_mask: torch.Tensor,
|
572 |
+
position_ids: Optional[torch.LongTensor] = None,
|
573 |
+
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
574 |
+
head_mask: Optional[torch.Tensor] = None,
|
575 |
+
use_cache: bool = False,
|
576 |
+
output_attentions: bool = False,
|
577 |
+
**kwargs,
|
578 |
+
):
|
579 |
+
if "padding_mask" in kwargs:
|
580 |
+
warnings.warn(
|
581 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
582 |
+
)
|
583 |
+
|
584 |
+
# overwrite attention_mask with padding_mask
|
585 |
+
attention_mask = kwargs.pop("padding_mask")
|
586 |
+
|
587 |
+
fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
|
588 |
+
num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads
|
589 |
+
# 3 x [batch_size, seq_length, num_heads, head_dim]
|
590 |
+
(query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
|
591 |
+
|
592 |
+
batch_size, query_length, _, _ = query_layer.shape
|
593 |
+
|
594 |
+
query_layer = query_layer.transpose(1, 2).reshape(batch_size, self.num_heads, query_length, self.head_dim)
|
595 |
+
key_layer = key_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
|
596 |
+
value_layer = value_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
|
597 |
+
|
598 |
+
kv_seq_len = key_layer.shape[-2]
|
599 |
+
if layer_past is not None:
|
600 |
+
kv_seq_len += layer_past[0].shape[-2]
|
601 |
+
if alibi is None:
|
602 |
+
cos, sin = self.rotary_emb(value_layer, seq_len=kv_seq_len)
|
603 |
+
query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, position_ids)
|
604 |
+
|
605 |
+
if layer_past is not None and use_cache:
|
606 |
+
past_key, past_value = layer_past
|
607 |
+
# concatenate along seq_length dimension:
|
608 |
+
# - key: [batch_size, self.num_heads, kv_length, head_dim]
|
609 |
+
# - value: [batch_size, self.num_heads, kv_length, head_dim]
|
610 |
+
key_layer = torch.cat((past_key, key_layer), dim=-2)
|
611 |
+
value_layer = torch.cat((past_value, value_layer), dim=-2)
|
612 |
+
|
613 |
+
past_key_value = (key_layer, value_layer) if use_cache else None
|
614 |
+
|
615 |
+
# 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
|
616 |
+
# to be able to avoid many of these transpose/reshape/view.
|
617 |
+
query_layer = query_layer.transpose(1, 2)
|
618 |
+
key_layer = key_layer.transpose(1, 2)
|
619 |
+
value_layer = value_layer.transpose(1, 2)
|
620 |
+
|
621 |
+
if alibi is not None:
|
622 |
+
raise ValueError("`alibi` is not supported when `use_flash_attn` is True")
|
623 |
+
|
624 |
+
attn_dropout = self.config.attention_dropout if self.training else 0.0
|
625 |
+
|
626 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
627 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
628 |
+
# cast them back in float16 just to be sure everything works as expected.
|
629 |
+
input_dtype = query_layer.dtype
|
630 |
+
if input_dtype == torch.float32:
|
631 |
+
if torch.is_autocast_enabled():
|
632 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
633 |
+
# Handle the case where the model is quantized
|
634 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
635 |
+
target_dtype = self.config._pre_quantization_dtype
|
636 |
+
else:
|
637 |
+
target_dtype = self.query_key_value.weight.dtype
|
638 |
+
|
639 |
+
logger.warning_once(
|
640 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
641 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
642 |
+
f" {target_dtype}."
|
643 |
+
)
|
644 |
+
|
645 |
+
query_layer = query_layer.to(target_dtype)
|
646 |
+
key_layer = key_layer.to(target_dtype)
|
647 |
+
value_layer = value_layer.to(target_dtype)
|
648 |
+
|
649 |
+
attn_output = self._flash_attention_forward(
|
650 |
+
query_layer, key_layer, value_layer, attention_mask, query_length, dropout=attn_dropout
|
651 |
+
)
|
652 |
+
|
653 |
+
attn_weights = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
|
654 |
+
attn_output = self.dense(attn_weights)
|
655 |
+
|
656 |
+
if not output_attentions:
|
657 |
+
attn_weights = None
|
658 |
+
|
659 |
+
return attn_output, past_key_value, attn_weights
|
660 |
+
|
661 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
|
662 |
+
def _flash_attention_forward(
|
663 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
664 |
+
):
|
665 |
+
"""
|
666 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
667 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
668 |
+
|
669 |
+
Args:
|
670 |
+
query_states (`torch.Tensor`):
|
671 |
+
Input query states to be passed to Flash Attention API
|
672 |
+
key_states (`torch.Tensor`):
|
673 |
+
Input key states to be passed to Flash Attention API
|
674 |
+
value_states (`torch.Tensor`):
|
675 |
+
Input value states to be passed to Flash Attention API
|
676 |
+
attention_mask (`torch.Tensor`):
|
677 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
678 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
679 |
+
dropout (`float`):
|
680 |
+
Attention dropout
|
681 |
+
softmax_scale (`float`, *optional*):
|
682 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
683 |
+
"""
|
684 |
+
if not self._flash_attn_uses_top_left_mask:
|
685 |
+
causal = self.is_causal
|
686 |
+
else:
|
687 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
688 |
+
causal = self.is_causal and query_length != 1
|
689 |
+
|
690 |
+
# Contains at least one padding token in the sequence
|
691 |
+
if attention_mask is not None:
|
692 |
+
batch_size = query_states.shape[0]
|
693 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
694 |
+
query_states, key_states, value_states, attention_mask, query_length
|
695 |
+
)
|
696 |
+
|
697 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
698 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
699 |
+
|
700 |
+
attn_output_unpad = flash_attn_varlen_func(
|
701 |
+
query_states,
|
702 |
+
key_states,
|
703 |
+
value_states,
|
704 |
+
cu_seqlens_q=cu_seqlens_q,
|
705 |
+
cu_seqlens_k=cu_seqlens_k,
|
706 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
707 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
708 |
+
dropout_p=dropout,
|
709 |
+
softmax_scale=softmax_scale,
|
710 |
+
causal=causal,
|
711 |
+
)
|
712 |
+
|
713 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
714 |
+
else:
|
715 |
+
attn_output = flash_attn_func(
|
716 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
717 |
+
)
|
718 |
+
|
719 |
+
return attn_output
|
720 |
+
|
721 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
|
722 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
723 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
724 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
725 |
+
|
726 |
+
key_layer = index_first_axis(
|
727 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
728 |
+
)
|
729 |
+
value_layer = index_first_axis(
|
730 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
731 |
+
)
|
732 |
+
if query_length == kv_seq_len:
|
733 |
+
query_layer = index_first_axis(
|
734 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
735 |
+
)
|
736 |
+
cu_seqlens_q = cu_seqlens_k
|
737 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
738 |
+
indices_q = indices_k
|
739 |
+
elif query_length == 1:
|
740 |
+
max_seqlen_in_batch_q = 1
|
741 |
+
cu_seqlens_q = torch.arange(
|
742 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
743 |
+
) # There is a memcpy here, that is very bad.
|
744 |
+
indices_q = cu_seqlens_q[:-1]
|
745 |
+
query_layer = query_layer.squeeze(1)
|
746 |
+
else:
|
747 |
+
# The -q_len: slice assumes left padding.
|
748 |
+
attention_mask = attention_mask[:, -query_length:]
|
749 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
750 |
+
|
751 |
+
return (
|
752 |
+
query_layer,
|
753 |
+
key_layer,
|
754 |
+
value_layer,
|
755 |
+
indices_q,
|
756 |
+
(cu_seqlens_q, cu_seqlens_k),
|
757 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
758 |
+
)
|
759 |
+
|
760 |
+
|
761 |
+
class FalconMLP(nn.Module):
|
762 |
+
def __init__(self, config: FalconConfig):
|
763 |
+
super().__init__()
|
764 |
+
hidden_size = config.hidden_size
|
765 |
+
|
766 |
+
self.dense_h_to_4h = FalconLinear(
|
767 |
+
hidden_size, config.ff_factor * hidden_size, bias=config.bias
|
768 |
+
)
|
769 |
+
self.act = nn.GELU()
|
770 |
+
self.dense_4h_to_h = FalconLinear(
|
771 |
+
config.ff_factor * hidden_size, hidden_size, bias=config.bias
|
772 |
+
)
|
773 |
+
self.hidden_dropout = config.hidden_dropout
|
774 |
+
|
775 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
776 |
+
x = self.act(self.dense_h_to_4h(x))
|
777 |
+
x = self.dense_4h_to_h(x)
|
778 |
+
return x
|
779 |
+
|
780 |
+
FALCON_ATTENTION_CLASSES = {
|
781 |
+
"eager": FalconAttention,
|
782 |
+
"sdpa": FalconAttention, # FalconAttention originally implemented both a forward with & without SDPA
|
783 |
+
"flash_attention_2": FalconFlashAttention2,
|
784 |
+
}
|
785 |
+
|
786 |
+
|
787 |
+
class FalconDecoderLayer(nn.Module):
|
788 |
+
def __init__(self, config: FalconConfig):
|
789 |
+
super().__init__()
|
790 |
+
hidden_size = config.hidden_size
|
791 |
+
self.num_heads = config.num_attention_heads
|
792 |
+
|
793 |
+
self.self_attention = FALCON_ATTENTION_CLASSES[config._attn_implementation](config)
|
794 |
+
self.mlp = FalconMLP(config)
|
795 |
+
self.hidden_dropout = config.hidden_dropout
|
796 |
+
self.config = config
|
797 |
+
|
798 |
+
if config.new_decoder_architecture and config.num_ln_in_parallel_attn == 2:
|
799 |
+
# The layer norm before self-attention
|
800 |
+
self.ln_attn = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
801 |
+
# The layer norm before the MLP
|
802 |
+
self.ln_mlp = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
803 |
+
else:
|
804 |
+
self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
805 |
+
if not config.parallel_attn:
|
806 |
+
self.post_attention_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
807 |
+
|
808 |
+
def forward(
|
809 |
+
self,
|
810 |
+
hidden_states: torch.Tensor,
|
811 |
+
alibi: Optional[torch.Tensor],
|
812 |
+
attention_mask: torch.Tensor,
|
813 |
+
position_ids: Optional[torch.LongTensor] = None,
|
814 |
+
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
815 |
+
head_mask: Optional[torch.Tensor] = None,
|
816 |
+
use_cache: bool = False,
|
817 |
+
output_attentions: bool = False,
|
818 |
+
**kwargs,
|
819 |
+
):
|
820 |
+
if "padding_mask" in kwargs:
|
821 |
+
warnings.warn(
|
822 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
823 |
+
)
|
824 |
+
|
825 |
+
residual = hidden_states
|
826 |
+
|
827 |
+
if self.config.num_ln_in_parallel_attn == 2:
|
828 |
+
attention_layernorm_out = self.ln_attn(hidden_states)
|
829 |
+
mlp_layernorm_out = self.ln_mlp(hidden_states)
|
830 |
+
else:
|
831 |
+
attention_layernorm_out = self.input_layernorm(hidden_states)
|
832 |
+
|
833 |
+
# Self attention.
|
834 |
+
attn_outputs = self.self_attention(
|
835 |
+
attention_layernorm_out,
|
836 |
+
layer_past=layer_past,
|
837 |
+
attention_mask=attention_mask,
|
838 |
+
position_ids=position_ids,
|
839 |
+
alibi=alibi,
|
840 |
+
head_mask=head_mask,
|
841 |
+
use_cache=use_cache,
|
842 |
+
output_attentions=output_attentions,
|
843 |
+
**kwargs,
|
844 |
+
)
|
845 |
+
|
846 |
+
attention_output = attn_outputs[0]
|
847 |
+
|
848 |
+
if self.config.num_ln_in_parallel_attn == 1:
|
849 |
+
if self.config.parallel_attn:
|
850 |
+
mlp_layernorm_out = attention_layernorm_out
|
851 |
+
else:
|
852 |
+
residual = dropout_add(
|
853 |
+
attention_output, residual, self.config.attention_dropout, training=self.training
|
854 |
+
)
|
855 |
+
mlp_layernorm_out = self.post_attention_layernorm(residual)
|
856 |
+
|
857 |
+
outputs = attn_outputs[1:]
|
858 |
+
|
859 |
+
# MLP.
|
860 |
+
mlp_output = self.mlp(mlp_layernorm_out)
|
861 |
+
|
862 |
+
if self.config.new_decoder_architecture or self.config.parallel_attn:
|
863 |
+
mlp_output += attention_output
|
864 |
+
|
865 |
+
output = dropout_add(mlp_output, residual, self.config.hidden_dropout, training=self.training)
|
866 |
+
|
867 |
+
if use_cache:
|
868 |
+
outputs = (output,) + outputs
|
869 |
+
else:
|
870 |
+
outputs = (output,) + outputs[1:]
|
871 |
+
|
872 |
+
return outputs # hidden_states, present, attentions
|
873 |
+
|
874 |
+
|
875 |
+
FALCON_START_DOCSTRING = r"""
|
876 |
+
|
877 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
878 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings etc.)
|
879 |
+
|
880 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
881 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
882 |
+
and behavior.
|
883 |
+
|
884 |
+
Parameters:
|
885 |
+
config ([`FalconConfig`]): Model configuration class with all the parameters of the model.
|
886 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
887 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
888 |
+
"""
|
889 |
+
|
890 |
+
FALCON_INPUTS_DOCSTRING = r"""
|
891 |
+
Args:
|
892 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
893 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[2]`
|
894 |
+
(`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
|
895 |
+
|
896 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
897 |
+
`input_ids`.
|
898 |
+
|
899 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
900 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
901 |
+
|
902 |
+
[What are input IDs?](../glossary#input-ids)
|
903 |
+
past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.num_hidden_layers`):
|
904 |
+
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
|
905 |
+
`past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
|
906 |
+
their past given to this model should not be passed as `input_ids` as they have already been computed.
|
907 |
+
|
908 |
+
Each element of `past_key_values` is a tuple (past_key, past_value):
|
909 |
+
- past_key: [batch_size * num_heads, head_dim, kv_length]
|
910 |
+
- past_value: [batch_size * num_heads, kv_length, head_dim]
|
911 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
912 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
913 |
+
|
914 |
+
- 1 for tokens that are **not masked**,
|
915 |
+
- 0 for tokens that are **masked**.
|
916 |
+
|
917 |
+
[What are attention masks?](../glossary#attention-mask)
|
918 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
919 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
920 |
+
config.n_positions - 1]`.
|
921 |
+
|
922 |
+
[What are position IDs?](../glossary#position-ids)
|
923 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
924 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
925 |
+
|
926 |
+
- 1 indicates the head is **not masked**,
|
927 |
+
- 0 indicates the head is **masked**.
|
928 |
+
|
929 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
930 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
931 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
932 |
+
model's internal embedding lookup matrix.
|
933 |
+
|
934 |
+
If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
|
935 |
+
`past_key_values`).
|
936 |
+
use_cache (`bool`, *optional*):
|
937 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
938 |
+
`past_key_values`).
|
939 |
+
output_attentions (`bool`, *optional*):
|
940 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
941 |
+
tensors for more detail.
|
942 |
+
output_hidden_states (`bool`, *optional*):
|
943 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
944 |
+
more detail.
|
945 |
+
return_dict (`bool`, *optional*):
|
946 |
+
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
|
947 |
+
"""
|
948 |
+
|
949 |
+
|
950 |
+
class FalconPreTrainedModel(PreTrainedModel):
|
951 |
+
"""
|
952 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
953 |
+
models.
|
954 |
+
"""
|
955 |
+
|
956 |
+
config_class = FalconConfig
|
957 |
+
base_model_prefix = "transformer"
|
958 |
+
supports_gradient_checkpointing = True
|
959 |
+
_no_split_modules = ["FalconDecoderLayer"]
|
960 |
+
_supports_flash_attn_2 = True
|
961 |
+
_supports_sdpa = True
|
962 |
+
|
963 |
+
def __init__(self, *inputs, **kwargs):
|
964 |
+
super().__init__(*inputs, **kwargs)
|
965 |
+
|
966 |
+
def _init_weights(self, module: nn.Module):
|
967 |
+
"""Initialize the weights."""
|
968 |
+
if isinstance(module, nn.Linear) or isinstance(module, FalconLinear):
|
969 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
970 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
971 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
972 |
+
if module.bias is not None:
|
973 |
+
module.bias.data.zero_()
|
974 |
+
elif isinstance(module, nn.Embedding):
|
975 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
976 |
+
if module.padding_idx is not None:
|
977 |
+
module.weight.data[module.padding_idx].zero_()
|
978 |
+
elif isinstance(module, LayerNorm):
|
979 |
+
module.bias.data.zero_()
|
980 |
+
module.weight.data.fill_(1.0)
|
981 |
+
|
982 |
+
# Adapted from transformers.modeling_utils.PreTrainedModel._check_and_enable_sdpa
|
983 |
+
@classmethod
|
984 |
+
def _check_and_enable_sdpa(cls, config, hard_check_only: bool = False) -> "PretrainedConfig":
|
985 |
+
# NOTE: Falcon supported SDPA from PyTorch 2.0. We keep it like that for backward compatibility (automatically use SDPA for torch>=2.0).
|
986 |
+
if hard_check_only:
|
987 |
+
if not is_torch_greater_or_equal_than_2_0:
|
988 |
+
raise ImportError("PyTorch SDPA requirements in Transformers are not met. Please install torch>=2.0.")
|
989 |
+
|
990 |
+
if not is_torch_greater_or_equal_than_2_0:
|
991 |
+
return config
|
992 |
+
|
993 |
+
_is_bettertransformer = getattr(cls, "use_bettertransformer", False)
|
994 |
+
if _is_bettertransformer:
|
995 |
+
return config
|
996 |
+
|
997 |
+
if not hard_check_only:
|
998 |
+
config._attn_implementation = "sdpa"
|
999 |
+
return config
|
1000 |
+
|
1001 |
+
|
1002 |
+
@add_start_docstrings(
|
1003 |
+
"The bare Falcon Model transformer outputting raw hidden-states without any specific head on top.",
|
1004 |
+
FALCON_START_DOCSTRING,
|
1005 |
+
)
|
1006 |
+
class FalconModel(FalconPreTrainedModel):
|
1007 |
+
def __init__(self, config: FalconConfig):
|
1008 |
+
super().__init__(config)
|
1009 |
+
|
1010 |
+
self.embed_dim = config.hidden_size
|
1011 |
+
self.num_heads = config.num_attention_heads
|
1012 |
+
self.use_alibi = config.alibi
|
1013 |
+
|
1014 |
+
# Embedding + LN Embedding
|
1015 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
|
1016 |
+
|
1017 |
+
# Transformer blocks
|
1018 |
+
self.h = nn.ModuleList([FalconDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
1019 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
1020 |
+
self._use_sdpa = config._attn_implementation == "sdpa"
|
1021 |
+
|
1022 |
+
# Final Layer Norm
|
1023 |
+
self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
|
1024 |
+
|
1025 |
+
self.gradient_checkpointing = False
|
1026 |
+
|
1027 |
+
# Initialize weights and apply final processing
|
1028 |
+
self.post_init()
|
1029 |
+
|
1030 |
+
def get_input_embeddings(self):
|
1031 |
+
return self.word_embeddings
|
1032 |
+
|
1033 |
+
def set_input_embeddings(self, new_embeddings: torch.Tensor):
|
1034 |
+
self.word_embeddings = new_embeddings
|
1035 |
+
|
1036 |
+
@add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
|
1037 |
+
@add_code_sample_docstrings(
|
1038 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1039 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
1040 |
+
config_class=_CONFIG_FOR_DOC,
|
1041 |
+
)
|
1042 |
+
def forward(
|
1043 |
+
self,
|
1044 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1045 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
1046 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1047 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1048 |
+
head_mask: Optional[torch.LongTensor] = None,
|
1049 |
+
inputs_embeds: Optional[torch.LongTensor] = None,
|
1050 |
+
use_cache: Optional[bool] = None,
|
1051 |
+
output_attentions: Optional[bool] = None,
|
1052 |
+
output_hidden_states: Optional[bool] = None,
|
1053 |
+
return_dict: Optional[bool] = None,
|
1054 |
+
) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
|
1055 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1056 |
+
output_hidden_states = (
|
1057 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1058 |
+
)
|
1059 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1060 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1061 |
+
|
1062 |
+
if input_ids is not None and inputs_embeds is not None:
|
1063 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
1064 |
+
elif input_ids is not None:
|
1065 |
+
batch_size, seq_length = input_ids.shape
|
1066 |
+
elif inputs_embeds is not None:
|
1067 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
1068 |
+
else:
|
1069 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1070 |
+
|
1071 |
+
if past_key_values is None:
|
1072 |
+
past_key_values = tuple([None] * len(self.h))
|
1073 |
+
|
1074 |
+
if inputs_embeds is None:
|
1075 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
1076 |
+
|
1077 |
+
hidden_states = inputs_embeds
|
1078 |
+
|
1079 |
+
if self.gradient_checkpointing and self.training:
|
1080 |
+
if use_cache:
|
1081 |
+
logger.warning(
|
1082 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
1083 |
+
)
|
1084 |
+
use_cache = False
|
1085 |
+
presents = () if use_cache else None
|
1086 |
+
all_self_attentions = () if output_attentions else None
|
1087 |
+
all_hidden_states = () if output_hidden_states else None
|
1088 |
+
|
1089 |
+
# Compute alibi tensor: check build_alibi_tensor documentation
|
1090 |
+
past_key_values_length = 0
|
1091 |
+
if past_key_values[0] is not None:
|
1092 |
+
past_key_values_length = past_key_values[0][0].shape[-2]
|
1093 |
+
|
1094 |
+
if self.use_alibi:
|
1095 |
+
mask = (
|
1096 |
+
torch.ones(
|
1097 |
+
(batch_size, seq_length + past_key_values_length), device=inputs_embeds.device, dtype=torch.long
|
1098 |
+
)
|
1099 |
+
if attention_mask is None
|
1100 |
+
else attention_mask
|
1101 |
+
)
|
1102 |
+
alibi = build_alibi_tensor(mask, self.num_heads, dtype=hidden_states.dtype)
|
1103 |
+
else:
|
1104 |
+
alibi = None
|
1105 |
+
if position_ids is None:
|
1106 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1107 |
+
position_ids = torch.arange(
|
1108 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
1109 |
+
)
|
1110 |
+
position_ids = position_ids.unsqueeze(0)
|
1111 |
+
|
1112 |
+
if self._use_flash_attention_2:
|
1113 |
+
# 2d mask is passed through the layers
|
1114 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
1115 |
+
elif self._use_sdpa and not output_attentions:
|
1116 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
1117 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
1118 |
+
if alibi is None:
|
1119 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
1120 |
+
attention_mask,
|
1121 |
+
(batch_size, seq_length),
|
1122 |
+
inputs_embeds,
|
1123 |
+
past_key_values_length,
|
1124 |
+
)
|
1125 |
+
elif head_mask is None:
|
1126 |
+
alibi = alibi.reshape(batch_size, -1, *alibi.shape[1:])
|
1127 |
+
|
1128 |
+
attention_mask_2d = attention_mask
|
1129 |
+
# We don't call _prepare_4d_causal_attention_mask_for_sdpa as we need to mask alibi using the 4D attention_mask untouched.
|
1130 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1131 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
1132 |
+
)
|
1133 |
+
|
1134 |
+
# We take care to integrate alibi bias in the attention_mask here.
|
1135 |
+
if attention_mask_2d is None:
|
1136 |
+
attention_mask = alibi / math.sqrt(self.config.hidden_size // self.num_heads)
|
1137 |
+
else:
|
1138 |
+
min_dtype = torch.finfo(alibi.dtype).min
|
1139 |
+
attention_mask = torch.masked_fill(
|
1140 |
+
alibi / math.sqrt(self.config.hidden_size // self.num_heads),
|
1141 |
+
attention_mask < -1,
|
1142 |
+
min_dtype,
|
1143 |
+
)
|
1144 |
+
|
1145 |
+
# From PyTorch 2.1 onwards, F.scaled_dot_product_attention with the memory-efficient attention backend
|
1146 |
+
# produces nans if sequences are completely unattended in the attention mask. Details: https://github.com/pytorch/pytorch/issues/110213
|
1147 |
+
if seq_length > 1 and attention_mask.device.type == "cuda":
|
1148 |
+
attention_mask = AttentionMaskConverter._unmask_unattended(attention_mask, min_dtype=min_dtype)
|
1149 |
+
else:
|
1150 |
+
# PyTorch SDPA does not support head_mask, we fall back on the eager implementation in this case.
|
1151 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1152 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
1153 |
+
)
|
1154 |
+
else:
|
1155 |
+
# 4d mask is passed through the layers
|
1156 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1157 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
1158 |
+
)
|
1159 |
+
|
1160 |
+
# Prepare head mask if needed
|
1161 |
+
# 1.0 in head_mask indicate we keep the head
|
1162 |
+
# attention_probs has shape batch_size x num_heads x N x N
|
1163 |
+
# head_mask has shape n_layer x batch x num_heads x N x N
|
1164 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
1165 |
+
|
1166 |
+
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
1167 |
+
if output_hidden_states:
|
1168 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
1169 |
+
|
1170 |
+
if self.gradient_checkpointing and self.training:
|
1171 |
+
outputs = self._gradient_checkpointing_func(
|
1172 |
+
block.__call__,
|
1173 |
+
hidden_states,
|
1174 |
+
alibi,
|
1175 |
+
attention_mask,
|
1176 |
+
position_ids,
|
1177 |
+
head_mask[i],
|
1178 |
+
layer_past,
|
1179 |
+
use_cache,
|
1180 |
+
output_attentions,
|
1181 |
+
)
|
1182 |
+
else:
|
1183 |
+
outputs = block(
|
1184 |
+
hidden_states,
|
1185 |
+
layer_past=layer_past,
|
1186 |
+
attention_mask=attention_mask,
|
1187 |
+
position_ids=position_ids,
|
1188 |
+
head_mask=head_mask[i],
|
1189 |
+
use_cache=use_cache,
|
1190 |
+
output_attentions=output_attentions,
|
1191 |
+
alibi=alibi,
|
1192 |
+
)
|
1193 |
+
|
1194 |
+
hidden_states = outputs[0]
|
1195 |
+
if use_cache is True:
|
1196 |
+
presents = presents + (outputs[1],)
|
1197 |
+
|
1198 |
+
if output_attentions:
|
1199 |
+
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
|
1200 |
+
|
1201 |
+
# Add last hidden state
|
1202 |
+
hidden_states = self.ln_f(hidden_states)
|
1203 |
+
|
1204 |
+
if output_hidden_states:
|
1205 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
1206 |
+
|
1207 |
+
if not return_dict:
|
1208 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
|
1209 |
+
|
1210 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
1211 |
+
last_hidden_state=hidden_states,
|
1212 |
+
past_key_values=presents,
|
1213 |
+
hidden_states=all_hidden_states,
|
1214 |
+
attentions=all_self_attentions,
|
1215 |
+
)
|
1216 |
+
|
1217 |
+
|
1218 |
+
@add_start_docstrings(
|
1219 |
+
"The Falcon Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).",
|
1220 |
+
FALCON_START_DOCSTRING,
|
1221 |
+
)
|
1222 |
+
class FalconForCausalLM(FalconPreTrainedModel):
|
1223 |
+
_tied_weights_keys = None # ["lm_head.weight"]
|
1224 |
+
|
1225 |
+
def __init__(self, config: FalconConfig):
|
1226 |
+
super().__init__(config)
|
1227 |
+
self.transformer = FalconModel(config)
|
1228 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1229 |
+
|
1230 |
+
# Initialize weights and apply final processing
|
1231 |
+
self.post_init()
|
1232 |
+
|
1233 |
+
def get_output_embeddings(self):
|
1234 |
+
return self.lm_head
|
1235 |
+
|
1236 |
+
def set_output_embeddings(self, new_embeddings: torch.Tensor):
|
1237 |
+
self.lm_head = new_embeddings
|
1238 |
+
|
1239 |
+
def prepare_inputs_for_generation(
|
1240 |
+
self,
|
1241 |
+
input_ids: torch.LongTensor,
|
1242 |
+
past_key_values: Optional[torch.Tensor] = None,
|
1243 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1244 |
+
position_ids: Optional[torch.Tensor] = None,
|
1245 |
+
**kwargs,
|
1246 |
+
) -> dict:
|
1247 |
+
if past_key_values is not None:
|
1248 |
+
past_length = past_key_values[0][0].shape[2]
|
1249 |
+
|
1250 |
+
# Some generation methods already pass only the last input ID
|
1251 |
+
if input_ids.shape[1] > past_length:
|
1252 |
+
remove_prefix_length = past_length
|
1253 |
+
else:
|
1254 |
+
# Default to old behavior: keep only final ID
|
1255 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
1256 |
+
|
1257 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
1258 |
+
|
1259 |
+
# Note: versions of Falcon with alibi do not use position_ids. It is used with RoPE.
|
1260 |
+
if not self.transformer.use_alibi and attention_mask is not None and position_ids is None:
|
1261 |
+
# create position_ids on the fly for batch generation
|
1262 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1263 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1264 |
+
if past_key_values:
|
1265 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1266 |
+
|
1267 |
+
return {
|
1268 |
+
"input_ids": input_ids,
|
1269 |
+
"position_ids": position_ids,
|
1270 |
+
"past_key_values": past_key_values,
|
1271 |
+
"use_cache": kwargs.get("use_cache"),
|
1272 |
+
"attention_mask": attention_mask,
|
1273 |
+
}
|
1274 |
+
|
1275 |
+
@add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
|
1276 |
+
@add_code_sample_docstrings(
|
1277 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1278 |
+
output_type=CausalLMOutputWithCrossAttentions,
|
1279 |
+
config_class=_CONFIG_FOR_DOC,
|
1280 |
+
)
|
1281 |
+
def forward(
|
1282 |
+
self,
|
1283 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1284 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
1285 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1286 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1287 |
+
head_mask: Optional[torch.Tensor] = None,
|
1288 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1289 |
+
labels: Optional[torch.Tensor] = None,
|
1290 |
+
use_cache: Optional[bool] = None,
|
1291 |
+
output_attentions: Optional[bool] = None,
|
1292 |
+
output_hidden_states: Optional[bool] = None,
|
1293 |
+
return_dict: Optional[bool] = None,
|
1294 |
+
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
1295 |
+
r"""
|
1296 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1297 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
1298 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
1299 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
1300 |
+
"""
|
1301 |
+
|
1302 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1303 |
+
|
1304 |
+
transformer_outputs = self.transformer(
|
1305 |
+
input_ids,
|
1306 |
+
past_key_values=past_key_values,
|
1307 |
+
attention_mask=attention_mask,
|
1308 |
+
position_ids=position_ids,
|
1309 |
+
head_mask=head_mask,
|
1310 |
+
inputs_embeds=inputs_embeds,
|
1311 |
+
use_cache=use_cache,
|
1312 |
+
output_attentions=output_attentions,
|
1313 |
+
output_hidden_states=output_hidden_states,
|
1314 |
+
return_dict=return_dict,
|
1315 |
+
)
|
1316 |
+
hidden_states = transformer_outputs[0]
|
1317 |
+
|
1318 |
+
lm_logits = self.lm_head(hidden_states)
|
1319 |
+
|
1320 |
+
loss = None
|
1321 |
+
if labels is not None:
|
1322 |
+
# Shift so that tokens < n predict n
|
1323 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
1324 |
+
shift_labels = labels[..., 1:].contiguous()
|
1325 |
+
batch_size, seq_length, vocab_size = shift_logits.shape
|
1326 |
+
# Flatten the tokens
|
1327 |
+
loss_fct = CrossEntropyLoss()
|
1328 |
+
loss = loss_fct(
|
1329 |
+
shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
|
1330 |
+
)
|
1331 |
+
|
1332 |
+
if not return_dict:
|
1333 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
1334 |
+
return ((loss,) + output) if loss is not None else output
|
1335 |
+
|
1336 |
+
return CausalLMOutputWithCrossAttentions(
|
1337 |
+
loss=loss,
|
1338 |
+
logits=lm_logits,
|
1339 |
+
past_key_values=transformer_outputs.past_key_values,
|
1340 |
+
hidden_states=transformer_outputs.hidden_states,
|
1341 |
+
attentions=transformer_outputs.attentions,
|
1342 |
+
)
|
1343 |
+
|
1344 |
+
def _reorder_cache(
|
1345 |
+
self, past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
|
1346 |
+
) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
|
1347 |
+
"""
|
1348 |
+
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
|
1349 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
1350 |
+
beam_idx at every generation step.
|
1351 |
+
|
1352 |
+
Output shares the same memory storage as `past`.
|
1353 |
+
"""
|
1354 |
+
|
1355 |
+
# Get a copy of `beam_idx` on all the devices where we need those indices.
|
1356 |
+
device_to_beam_idx = {
|
1357 |
+
past_state.device: beam_idx.to(past_state.device) for layer_past in past for past_state in layer_past
|
1358 |
+
}
|
1359 |
+
reordered_past = tuple(
|
1360 |
+
(
|
1361 |
+
layer_past[0].index_select(0, device_to_beam_idx[layer_past[0].device]),
|
1362 |
+
layer_past[1].index_select(0, device_to_beam_idx[layer_past[0].device]),
|
1363 |
+
)
|
1364 |
+
for layer_past in past
|
1365 |
+
)
|
1366 |
+
return reordered_past
|
1367 |
+
|
1368 |
+
|
1369 |
+
@add_start_docstrings(
|
1370 |
+
"""
|
1371 |
+
The Falcon Model transformer with a sequence classification head on top (linear layer).
|
1372 |
+
|
1373 |
+
[`FalconForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1374 |
+
(e.g. GPT-1) do.
|
1375 |
+
|
1376 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1377 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1378 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1379 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1380 |
+
each row of the batch).
|
1381 |
+
""",
|
1382 |
+
FALCON_START_DOCSTRING,
|
1383 |
+
)
|
1384 |
+
class FalconForSequenceClassification(FalconPreTrainedModel):
|
1385 |
+
def __init__(self, config: FalconConfig):
|
1386 |
+
super().__init__(config)
|
1387 |
+
self.num_labels = config.num_labels
|
1388 |
+
self.transformer = FalconModel(config)
|
1389 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
|
1390 |
+
|
1391 |
+
# Initialize weights and apply final processing
|
1392 |
+
self.post_init()
|
1393 |
+
|
1394 |
+
@add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
|
1395 |
+
@add_code_sample_docstrings(
|
1396 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1397 |
+
output_type=SequenceClassifierOutputWithPast,
|
1398 |
+
config_class=_CONFIG_FOR_DOC,
|
1399 |
+
)
|
1400 |
+
def forward(
|
1401 |
+
self,
|
1402 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1403 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
1404 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1405 |
+
head_mask: Optional[torch.Tensor] = None,
|
1406 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1407 |
+
labels: Optional[torch.Tensor] = None,
|
1408 |
+
use_cache: Optional[bool] = None,
|
1409 |
+
output_attentions: Optional[bool] = None,
|
1410 |
+
output_hidden_states: Optional[bool] = None,
|
1411 |
+
return_dict: Optional[bool] = None,
|
1412 |
+
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
|
1413 |
+
r"""
|
1414 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1415 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1416 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1417 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1418 |
+
"""
|
1419 |
+
|
1420 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1421 |
+
|
1422 |
+
transformer_outputs = self.transformer(
|
1423 |
+
input_ids,
|
1424 |
+
past_key_values=past_key_values,
|
1425 |
+
attention_mask=attention_mask,
|
1426 |
+
head_mask=head_mask,
|
1427 |
+
inputs_embeds=inputs_embeds,
|
1428 |
+
use_cache=use_cache,
|
1429 |
+
output_attentions=output_attentions,
|
1430 |
+
output_hidden_states=output_hidden_states,
|
1431 |
+
return_dict=return_dict,
|
1432 |
+
)
|
1433 |
+
|
1434 |
+
hidden_states = transformer_outputs[0]
|
1435 |
+
logits = self.score(hidden_states)
|
1436 |
+
|
1437 |
+
if input_ids is not None:
|
1438 |
+
batch_size = input_ids.shape[0]
|
1439 |
+
else:
|
1440 |
+
batch_size = inputs_embeds.shape[0]
|
1441 |
+
|
1442 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1443 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1444 |
+
if self.config.pad_token_id is None:
|
1445 |
+
sequence_lengths = -1
|
1446 |
+
else:
|
1447 |
+
if input_ids is not None:
|
1448 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1449 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1450 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1451 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1452 |
+
else:
|
1453 |
+
sequence_lengths = -1
|
1454 |
+
logger.warning(
|
1455 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
1456 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
1457 |
+
)
|
1458 |
+
|
1459 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1460 |
+
|
1461 |
+
loss = None
|
1462 |
+
if labels is not None:
|
1463 |
+
if self.config.problem_type is None:
|
1464 |
+
if self.num_labels == 1:
|
1465 |
+
self.config.problem_type = "regression"
|
1466 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1467 |
+
self.config.problem_type = "single_label_classification"
|
1468 |
+
else:
|
1469 |
+
self.config.problem_type = "multi_label_classification"
|
1470 |
+
|
1471 |
+
if self.config.problem_type == "regression":
|
1472 |
+
loss_fct = MSELoss()
|
1473 |
+
if self.num_labels == 1:
|
1474 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1475 |
+
else:
|
1476 |
+
loss = loss_fct(pooled_logits, labels)
|
1477 |
+
elif self.config.problem_type == "single_label_classification":
|
1478 |
+
loss_fct = CrossEntropyLoss()
|
1479 |
+
loss = loss_fct(pooled_logits, labels)
|
1480 |
+
elif self.config.problem_type == "multi_label_classification":
|
1481 |
+
loss_fct = BCEWithLogitsLoss()
|
1482 |
+
loss = loss_fct(pooled_logits, labels)
|
1483 |
+
if not return_dict:
|
1484 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1485 |
+
return ((loss,) + output) if loss is not None else output
|
1486 |
+
|
1487 |
+
return SequenceClassifierOutputWithPast(
|
1488 |
+
loss=loss,
|
1489 |
+
logits=pooled_logits,
|
1490 |
+
past_key_values=transformer_outputs.past_key_values,
|
1491 |
+
hidden_states=transformer_outputs.hidden_states,
|
1492 |
+
attentions=transformer_outputs.attentions,
|
1493 |
+
)
|
1494 |
+
|
1495 |
+
|
1496 |
+
@add_start_docstrings(
|
1497 |
+
"""
|
1498 |
+
Falcon Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
1499 |
+
Named-Entity-Recognition (NER) tasks.
|
1500 |
+
""",
|
1501 |
+
FALCON_START_DOCSTRING,
|
1502 |
+
)
|
1503 |
+
class FalconForTokenClassification(FalconPreTrainedModel):
|
1504 |
+
def __init__(self, config: FalconConfig):
|
1505 |
+
super().__init__(config)
|
1506 |
+
self.num_labels = config.num_labels
|
1507 |
+
|
1508 |
+
self.transformer = FalconModel(config)
|
1509 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
1510 |
+
classifier_dropout = config.classifier_dropout
|
1511 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
1512 |
+
classifier_dropout = config.hidden_dropout
|
1513 |
+
else:
|
1514 |
+
classifier_dropout = 0.1
|
1515 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1516 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1517 |
+
|
1518 |
+
# Initialize weights and apply final processing
|
1519 |
+
self.post_init()
|
1520 |
+
|
1521 |
+
@add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
|
1522 |
+
@add_code_sample_docstrings(
|
1523 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1524 |
+
output_type=TokenClassifierOutput,
|
1525 |
+
config_class=_CONFIG_FOR_DOC,
|
1526 |
+
)
|
1527 |
+
def forward(
|
1528 |
+
self,
|
1529 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1530 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
1531 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1532 |
+
head_mask: Optional[torch.Tensor] = None,
|
1533 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1534 |
+
labels: Optional[torch.Tensor] = None,
|
1535 |
+
use_cache: Optional[bool] = None,
|
1536 |
+
output_attentions: Optional[bool] = None,
|
1537 |
+
output_hidden_states: Optional[bool] = None,
|
1538 |
+
return_dict: Optional[bool] = None,
|
1539 |
+
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
1540 |
+
r"""
|
1541 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1542 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1543 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1544 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1545 |
+
"""
|
1546 |
+
|
1547 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1548 |
+
|
1549 |
+
transformer_outputs = self.transformer(
|
1550 |
+
input_ids,
|
1551 |
+
past_key_values=past_key_values,
|
1552 |
+
attention_mask=attention_mask,
|
1553 |
+
head_mask=head_mask,
|
1554 |
+
inputs_embeds=inputs_embeds,
|
1555 |
+
use_cache=use_cache,
|
1556 |
+
output_attentions=output_attentions,
|
1557 |
+
output_hidden_states=output_hidden_states,
|
1558 |
+
return_dict=return_dict,
|
1559 |
+
)
|
1560 |
+
|
1561 |
+
hidden_states = transformer_outputs[0]
|
1562 |
+
hidden_states = self.dropout(hidden_states)
|
1563 |
+
logits = self.classifier(hidden_states)
|
1564 |
+
|
1565 |
+
loss = None
|
1566 |
+
if labels is not None:
|
1567 |
+
batch_size, seq_length = labels.shape
|
1568 |
+
loss_fct = CrossEntropyLoss()
|
1569 |
+
loss = loss_fct(
|
1570 |
+
logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
|
1571 |
+
)
|
1572 |
+
|
1573 |
+
if not return_dict:
|
1574 |
+
output = (logits,) + transformer_outputs[2:]
|
1575 |
+
return ((loss,) + output) if loss is not None else output
|
1576 |
+
|
1577 |
+
return TokenClassifierOutput(
|
1578 |
+
loss=loss,
|
1579 |
+
logits=logits,
|
1580 |
+
hidden_states=transformer_outputs.hidden_states,
|
1581 |
+
attentions=transformer_outputs.attentions,
|
1582 |
+
)
|
1583 |
+
|
1584 |
+
|
1585 |
+
@add_start_docstrings(
|
1586 |
+
"""
|
1587 |
+
The Falcon Model transformer with a span classification head on top for extractive question-answering tasks like
|
1588 |
+
SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1589 |
+
""",
|
1590 |
+
FALCON_START_DOCSTRING,
|
1591 |
+
)
|
1592 |
+
class FalconForQuestionAnswering(FalconPreTrainedModel):
|
1593 |
+
def __init__(self, config):
|
1594 |
+
super().__init__(config)
|
1595 |
+
self.transformer = FalconModel(config)
|
1596 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1597 |
+
|
1598 |
+
# Initialize weights and apply final processing
|
1599 |
+
self.post_init()
|
1600 |
+
|
1601 |
+
@add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
|
1602 |
+
def forward(
|
1603 |
+
self,
|
1604 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1605 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1606 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1607 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1608 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1609 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1610 |
+
output_attentions: Optional[bool] = None,
|
1611 |
+
output_hidden_states: Optional[bool] = None,
|
1612 |
+
return_dict: Optional[bool] = None,
|
1613 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1614 |
+
r"""
|
1615 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1616 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1617 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1618 |
+
are not taken into account for computing the loss.
|
1619 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1620 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1621 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1622 |
+
are not taken into account for computing the loss.
|
1623 |
+
"""
|
1624 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1625 |
+
|
1626 |
+
outputs = self.transformer(
|
1627 |
+
input_ids,
|
1628 |
+
attention_mask=attention_mask,
|
1629 |
+
head_mask=head_mask,
|
1630 |
+
inputs_embeds=inputs_embeds,
|
1631 |
+
output_attentions=output_attentions,
|
1632 |
+
output_hidden_states=output_hidden_states,
|
1633 |
+
return_dict=return_dict,
|
1634 |
+
)
|
1635 |
+
|
1636 |
+
sequence_output = outputs[0]
|
1637 |
+
|
1638 |
+
logits = self.qa_outputs(sequence_output)
|
1639 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1640 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1641 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1642 |
+
|
1643 |
+
total_loss = None
|
1644 |
+
if start_positions is not None and end_positions is not None:
|
1645 |
+
# If we are on multi-GPU, split add a dimension
|
1646 |
+
if len(start_positions.size()) > 1:
|
1647 |
+
start_positions = start_positions.squeeze(-1)
|
1648 |
+
if len(end_positions.size()) > 1:
|
1649 |
+
end_positions = end_positions.squeeze(-1)
|
1650 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
1651 |
+
ignored_index = start_logits.size(1)
|
1652 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
1653 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
1654 |
+
|
1655 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
1656 |
+
start_loss = loss_fct(start_logits, start_positions)
|
1657 |
+
end_loss = loss_fct(end_logits, end_positions)
|
1658 |
+
total_loss = (start_loss + end_loss) / 2
|
1659 |
+
|
1660 |
+
if not return_dict:
|
1661 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1662 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1663 |
+
|
1664 |
+
return QuestionAnsweringModelOutput(
|
1665 |
+
loss=total_loss,
|
1666 |
+
start_logits=start_logits,
|
1667 |
+
end_logits=end_logits,
|
1668 |
+
hidden_states=outputs.hidden_states,
|
1669 |
+
attentions=outputs.attentions,
|
1670 |
+
)
|
special_tokens_map.json
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
">>TITLE<<",
|
4 |
+
">>ABSTRACT<<",
|
5 |
+
">>INTRODUCTION<<",
|
6 |
+
">>SUMMARY<<",
|
7 |
+
">>COMMENT<<",
|
8 |
+
">>ANSWER<<",
|
9 |
+
">>QUESTION<<",
|
10 |
+
">>DOMAIN<<",
|
11 |
+
">>PREFIX<<",
|
12 |
+
">>SUFFIX<<",
|
13 |
+
">>MIDDLE<<"
|
14 |
+
],
|
15 |
+
"bos_token": {
|
16 |
+
"content": ">>",
|
17 |
+
"lstrip": false,
|
18 |
+
"normalized": false,
|
19 |
+
"rstrip": false,
|
20 |
+
"single_word": false
|
21 |
+
},
|
22 |
+
"eos_token": {
|
23 |
+
"content": "<|endoftext|>",
|
24 |
+
"lstrip": false,
|
25 |
+
"normalized": false,
|
26 |
+
"rstrip": false,
|
27 |
+
"single_word": false
|
28 |
+
},
|
29 |
+
"pad_token": {
|
30 |
+
"content": "<|endoftext|>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false
|
35 |
+
}
|
36 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_prefix_space": false,
|
3 |
+
"added_tokens_decoder": {
|
4 |
+
"0": {
|
5 |
+
"content": ">>TITLE<<",
|
6 |
+
"lstrip": false,
|
7 |
+
"normalized": false,
|
8 |
+
"rstrip": false,
|
9 |
+
"single_word": false,
|
10 |
+
"special": true
|
11 |
+
},
|
12 |
+
"1": {
|
13 |
+
"content": ">>ABSTRACT<<",
|
14 |
+
"lstrip": false,
|
15 |
+
"normalized": false,
|
16 |
+
"rstrip": false,
|
17 |
+
"single_word": false,
|
18 |
+
"special": true
|
19 |
+
},
|
20 |
+
"2": {
|
21 |
+
"content": ">>INTRODUCTION<<",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": false,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": false,
|
26 |
+
"special": true
|
27 |
+
},
|
28 |
+
"3": {
|
29 |
+
"content": ">>SUMMARY<<",
|
30 |
+
"lstrip": false,
|
31 |
+
"normalized": false,
|
32 |
+
"rstrip": false,
|
33 |
+
"single_word": false,
|
34 |
+
"special": true
|
35 |
+
},
|
36 |
+
"4": {
|
37 |
+
"content": ">>COMMENT<<",
|
38 |
+
"lstrip": false,
|
39 |
+
"normalized": false,
|
40 |
+
"rstrip": false,
|
41 |
+
"single_word": false,
|
42 |
+
"special": true
|
43 |
+
},
|
44 |
+
"5": {
|
45 |
+
"content": ">>ANSWER<<",
|
46 |
+
"lstrip": false,
|
47 |
+
"normalized": false,
|
48 |
+
"rstrip": false,
|
49 |
+
"single_word": false,
|
50 |
+
"special": true
|
51 |
+
},
|
52 |
+
"6": {
|
53 |
+
"content": ">>QUESTION<<",
|
54 |
+
"lstrip": false,
|
55 |
+
"normalized": false,
|
56 |
+
"rstrip": false,
|
57 |
+
"single_word": false,
|
58 |
+
"special": true
|
59 |
+
},
|
60 |
+
"7": {
|
61 |
+
"content": ">>DOMAIN<<",
|
62 |
+
"lstrip": false,
|
63 |
+
"normalized": false,
|
64 |
+
"rstrip": false,
|
65 |
+
"single_word": false,
|
66 |
+
"special": true
|
67 |
+
},
|
68 |
+
"8": {
|
69 |
+
"content": ">>PREFIX<<",
|
70 |
+
"lstrip": false,
|
71 |
+
"normalized": false,
|
72 |
+
"rstrip": false,
|
73 |
+
"single_word": false,
|
74 |
+
"special": true
|
75 |
+
},
|
76 |
+
"9": {
|
77 |
+
"content": ">>SUFFIX<<",
|
78 |
+
"lstrip": false,
|
79 |
+
"normalized": false,
|
80 |
+
"rstrip": false,
|
81 |
+
"single_word": false,
|
82 |
+
"special": true
|
83 |
+
},
|
84 |
+
"10": {
|
85 |
+
"content": ">>MIDDLE<<",
|
86 |
+
"lstrip": false,
|
87 |
+
"normalized": false,
|
88 |
+
"rstrip": false,
|
89 |
+
"single_word": false,
|
90 |
+
"special": true
|
91 |
+
},
|
92 |
+
"11": {
|
93 |
+
"content": "<|endoftext|>",
|
94 |
+
"lstrip": false,
|
95 |
+
"normalized": false,
|
96 |
+
"rstrip": false,
|
97 |
+
"single_word": false,
|
98 |
+
"special": true
|
99 |
+
},
|
100 |
+
"500": {
|
101 |
+
"content": ">>",
|
102 |
+
"lstrip": false,
|
103 |
+
"normalized": false,
|
104 |
+
"rstrip": false,
|
105 |
+
"single_word": false,
|
106 |
+
"special": true
|
107 |
+
}
|
108 |
+
},
|
109 |
+
"additional_special_tokens": [
|
110 |
+
">>TITLE<<",
|
111 |
+
">>ABSTRACT<<",
|
112 |
+
">>INTRODUCTION<<",
|
113 |
+
">>SUMMARY<<",
|
114 |
+
">>COMMENT<<",
|
115 |
+
">>ANSWER<<",
|
116 |
+
">>QUESTION<<",
|
117 |
+
">>DOMAIN<<",
|
118 |
+
">>PREFIX<<",
|
119 |
+
">>SUFFIX<<",
|
120 |
+
">>MIDDLE<<"
|
121 |
+
],
|
122 |
+
"bos_token": ">>",
|
123 |
+
"chat_template": "{% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{% endif %}{% if system_message is defined %}{{ system_message + '\n' }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ 'Human: ' + content + '\nAssistant:' }}{% elif message['role'] == 'assistant' %}{{ content + '<|endoftext|>' + '\n' }}{% endif %}{% endfor %}",
|
124 |
+
"clean_up_tokenization_spaces": true,
|
125 |
+
"device_map": "cuda:2",
|
126 |
+
"eos_token": "<|endoftext|>",
|
127 |
+
"model_input_names": [
|
128 |
+
"input_ids",
|
129 |
+
"attention_mask"
|
130 |
+
],
|
131 |
+
"model_max_length": 1000000000000000019884624838656,
|
132 |
+
"pad_token": "<|endoftext|>",
|
133 |
+
"padding_side": "left",
|
134 |
+
"split_special_tokens": false,
|
135 |
+
"tokenizer_class": "PreTrainedTokenizerFast"
|
136 |
+
}
|