hgissbkh commited on
Commit
9531d75
·
verified ·
1 Parent(s): dde9b50

Upload modeling files

Browse files
Files changed (1) hide show
  1. modeling_sl_model.py +955 -0
modeling_sl_model.py ADDED
@@ -0,0 +1,955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
6
+
7
+ from transformers.activations import ACT2FN
8
+ from transformers.cache_utils import Cache, StaticCache
9
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
10
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
11
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput
12
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
13
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
14
+ from transformers.processing_utils import Unpack
15
+ from transformers.utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
16
+ from .configuration_sl_model import SLModelConfig
17
+
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+ _CONFIG_FOR_DOC = "SLModelConfig"
22
+
23
+
24
+ class SLModelRMSNorm(nn.Module):
25
+ def __init__(self, hidden_size, eps=1e-5):
26
+ """
27
+ SLModelRMSNorm is equivalent to T5LayerNorm
28
+ """
29
+ super().__init__()
30
+ self.weight = nn.Parameter(torch.ones(hidden_size))
31
+ self.variance_epsilon = eps
32
+
33
+ def forward(self, hidden_states):
34
+ input_dtype = hidden_states.dtype
35
+ hidden_states = hidden_states.to(torch.float32)
36
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
37
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
38
+ return self.weight * hidden_states.to(input_dtype)
39
+
40
+ def extra_repr(self):
41
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
42
+
43
+
44
+ def rotate_half(x):
45
+ """Rotates half the hidden dims of the input."""
46
+ x1 = x[..., : x.shape[-1] // 2]
47
+ x2 = x[..., x.shape[-1] // 2 :]
48
+ return torch.cat((-x2, x1), dim=-1)
49
+
50
+
51
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
52
+ """Applies Rotary Position Embedding to the query and key tensors.
53
+
54
+ Args:
55
+ q (`torch.Tensor`): The query tensor.
56
+ k (`torch.Tensor`): The key tensor.
57
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
58
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
59
+ position_ids (`torch.Tensor`, *optional*):
60
+ Deprecated and unused.
61
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
62
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
63
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
64
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
65
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
66
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
67
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
68
+ Returns:
69
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
70
+ """
71
+ cos = cos.unsqueeze(unsqueeze_dim)
72
+ sin = sin.unsqueeze(unsqueeze_dim)
73
+ q_embed = (q * cos) + (rotate_half(q) * sin)
74
+ k_embed = (k * cos) + (rotate_half(k) * sin)
75
+ return q_embed, k_embed
76
+
77
+
78
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
79
+ """
80
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
81
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
82
+ """
83
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
84
+ if n_rep == 1:
85
+ return hidden_states
86
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
87
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
88
+
89
+
90
+ def eager_attention_forward(
91
+ module: nn.Module,
92
+ query: torch.Tensor,
93
+ key: torch.Tensor,
94
+ value: torch.Tensor,
95
+ attention_mask: Optional[torch.Tensor],
96
+ scaling: float,
97
+ dropout: float = 0.0,
98
+ **kwargs,
99
+ ):
100
+ key_states = repeat_kv(key, module.num_key_value_groups)
101
+ value_states = repeat_kv(value, module.num_key_value_groups)
102
+
103
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
104
+ if attention_mask is not None:
105
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
106
+ attn_weights = attn_weights + causal_mask
107
+
108
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
109
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
110
+ attn_output = torch.matmul(attn_weights, value_states)
111
+ attn_output = attn_output.transpose(1, 2).contiguous()
112
+
113
+ return attn_output, attn_weights
114
+
115
+
116
+ class SLModelAttention(nn.Module):
117
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
118
+
119
+ def __init__(self, config: SLModelConfig, layer_idx: int):
120
+ super().__init__()
121
+ self.config = config
122
+ self.is_causal = config.is_causal
123
+ self.layer_idx = layer_idx
124
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
125
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
126
+ self.scaling = self.head_dim**-0.5
127
+ self.attention_dropout = config.attention_dropout
128
+
129
+ self.q_proj = nn.Linear(
130
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
131
+ )
132
+ self.k_proj = nn.Linear(
133
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
134
+ )
135
+ self.v_proj = nn.Linear(
136
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
137
+ )
138
+ self.o_proj = nn.Linear(
139
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
140
+ )
141
+
142
+ def forward(
143
+ self,
144
+ hidden_states: torch.Tensor,
145
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
146
+ attention_mask: Optional[torch.Tensor],
147
+ **kwargs: Unpack[FlashAttentionKwargs],
148
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
149
+ input_shape = hidden_states.shape[:-1]
150
+ hidden_shape = (*input_shape, -1, self.head_dim)
151
+
152
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
153
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
154
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
155
+
156
+ cos, sin = position_embeddings
157
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
158
+
159
+ attention_interface: Callable = eager_attention_forward
160
+ if self.config._attn_implementation != "eager":
161
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
162
+ logger.warning_once(
163
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
164
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
165
+ )
166
+ else:
167
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
168
+
169
+ attn_output, attn_weights = attention_interface(
170
+ self,
171
+ query_states,
172
+ key_states,
173
+ value_states,
174
+ attention_mask=None if self.is_causal and self.config._attn_implementation == "sdpa" else attention_mask,
175
+ dropout=0.0 if not self.training else self.attention_dropout,
176
+ scaling=self.scaling,
177
+ is_causal=self.is_causal,
178
+ **kwargs,
179
+ )
180
+
181
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
182
+ attn_output = self.o_proj(attn_output)
183
+ return attn_output, attn_weights
184
+
185
+
186
+ SL_MODEL_START_DOCSTRING = r"""
187
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
188
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
189
+ etc.)
190
+
191
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
192
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
193
+ and behavior.
194
+
195
+ Parameters:
196
+ config ([`SLModelConfig`]):
197
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
198
+ load the weights associated with the model, only the configuration. Check out the
199
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
200
+ """
201
+
202
+
203
+ @add_start_docstrings(
204
+ "The bare SLModel outputting raw hidden-states without any specific head on top.",
205
+ SL_MODEL_START_DOCSTRING,
206
+ )
207
+ class SLPreTrainedModel(PreTrainedModel):
208
+ config_class = SLModelConfig
209
+ base_model_prefix = "model"
210
+ supports_gradient_checkpointing = True
211
+ _no_split_modules = ["SLModelDecoderLayer"]
212
+ _skip_keys_device_placement = ["past_key_values"]
213
+ _supports_flash_attn_2 = True
214
+ _supports_sdpa = True
215
+ _supports_flex_attn = True
216
+ _supports_cache_class = True
217
+ _supports_quantized_cache = True
218
+ _supports_static_cache = True
219
+ _supports_attention_backend = True
220
+
221
+ def _init_weights(self, module):
222
+ std = self.config.initializer_range
223
+ if isinstance(module, nn.Linear):
224
+ module.weight.data.normal_(mean=0.0, std=std)
225
+ if module.bias is not None:
226
+ module.bias.data.zero_()
227
+ elif isinstance(module, nn.Embedding):
228
+ module.weight.data.normal_(mean=0.0, std=std)
229
+ if module.padding_idx is not None:
230
+ module.weight.data[module.padding_idx].zero_()
231
+
232
+
233
+ class SLModelRotaryEmbedding(nn.Module):
234
+ def __init__(self, config: SLModelConfig, device=None):
235
+ super().__init__()
236
+ # BC: "rope_type" was originally "type"
237
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
238
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
239
+ else:
240
+ self.rope_type = "default"
241
+ self.max_seq_len_cached = config.max_position_embeddings
242
+ self.original_max_seq_len = config.max_position_embeddings
243
+
244
+ self.config = config
245
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
246
+
247
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
248
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
249
+ self.original_inv_freq = self.inv_freq
250
+
251
+ def _dynamic_frequency_update(self, position_ids, device):
252
+ """
253
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
254
+ 1 - growing beyond the cached sequence length (allow scaling)
255
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
256
+ """
257
+ seq_len = torch.max(position_ids) + 1
258
+ if seq_len > self.max_seq_len_cached: # growth
259
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
260
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
261
+ self.max_seq_len_cached = seq_len
262
+
263
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
264
+ # This .to() is needed if the model has been moved to a device after being initialized (because
265
+ # the buffer is automatically moved, but not the original copy)
266
+ self.original_inv_freq = self.original_inv_freq.to(device)
267
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
268
+ self.max_seq_len_cached = self.original_max_seq_len
269
+
270
+ @torch.no_grad()
271
+ def forward(self, x, position_ids):
272
+ if "dynamic" in self.rope_type:
273
+ self._dynamic_frequency_update(position_ids, device=x.device)
274
+
275
+ # Core RoPE block
276
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
277
+ position_ids_expanded = position_ids[:, None, :].float()
278
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
279
+ device_type = x.device.type
280
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
281
+ with torch.autocast(device_type=device_type, enabled=False):
282
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
283
+ emb = torch.cat((freqs, freqs), dim=-1)
284
+ cos = emb.cos()
285
+ sin = emb.sin()
286
+
287
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
288
+ cos = cos * self.attention_scaling
289
+ sin = sin * self.attention_scaling
290
+
291
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
292
+
293
+
294
+ class SLModelMLP(nn.Module):
295
+ def __init__(self, config):
296
+ super().__init__()
297
+ self.config = config
298
+ self.hidden_size = config.hidden_size
299
+ self.intermediate_size = config.intermediate_size
300
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
301
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
302
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
303
+ self.act_fn = ACT2FN[config.hidden_act]
304
+
305
+ def forward(self, x):
306
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
307
+ return down_proj
308
+
309
+
310
+ class SLModelDecoderLayer(nn.Module):
311
+ def __init__(self, config: SLModelConfig, layer_idx: int):
312
+ super().__init__()
313
+ self.hidden_size = config.hidden_size
314
+
315
+ self.self_attn = SLModelAttention(config=config, layer_idx=layer_idx)
316
+
317
+ self.mlp = SLModelMLP(config)
318
+ self.input_layernorm = SLModelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
319
+ self.post_attention_layernorm = SLModelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
320
+
321
+ def forward(
322
+ self,
323
+ hidden_states: torch.Tensor,
324
+ attention_mask: Optional[torch.Tensor] = None,
325
+ position_ids: Optional[torch.LongTensor] = None,
326
+ past_key_value: Optional[Cache] = None,
327
+ output_attentions: Optional[bool] = False,
328
+ use_cache: Optional[bool] = False,
329
+ cache_position: Optional[torch.LongTensor] = None,
330
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
331
+ **kwargs: Unpack[FlashAttentionKwargs],
332
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
333
+ residual = hidden_states
334
+
335
+ hidden_states = self.input_layernorm(hidden_states)
336
+
337
+ # Self Attention
338
+ hidden_states, self_attn_weights = self.self_attn(
339
+ hidden_states=hidden_states,
340
+ attention_mask=attention_mask,
341
+ position_ids=position_ids,
342
+ past_key_value=past_key_value,
343
+ output_attentions=output_attentions,
344
+ use_cache=use_cache,
345
+ cache_position=cache_position,
346
+ position_embeddings=position_embeddings,
347
+ **kwargs,
348
+ )
349
+ hidden_states = residual + hidden_states
350
+
351
+ # Fully Connected
352
+ residual = hidden_states
353
+ hidden_states = self.post_attention_layernorm(hidden_states)
354
+ hidden_states = self.mlp(hidden_states)
355
+ hidden_states = residual + hidden_states
356
+
357
+ outputs = (hidden_states,)
358
+ if output_attentions:
359
+ outputs += (self_attn_weights,)
360
+
361
+ return outputs
362
+
363
+
364
+ SL_MODEL_INPUTS_DOCSTRING = r"""
365
+ Args:
366
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
367
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
368
+ it.
369
+
370
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
371
+ [`PreTrainedTokenizer.__call__`] for details.
372
+
373
+ [What are input IDs?](../glossary#input-ids)
374
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
375
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
376
+
377
+ - 1 for tokens that are **not masked**,
378
+ - 0 for tokens that are **masked**.
379
+
380
+ [What are attention masks?](../glossary#attention-mask)
381
+
382
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
383
+ [`PreTrainedTokenizer.__call__`] for details.
384
+
385
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
386
+ `past_key_values`).
387
+
388
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
389
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
390
+ information on the default strategy.
391
+
392
+ - 1 indicates the head is **not masked**,
393
+ - 0 indicates the head is **masked**.
394
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
395
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
396
+ config.n_positions - 1]`.
397
+
398
+ [What are position IDs?](../glossary#position-ids)
399
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
400
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
401
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
402
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
403
+
404
+ Two formats are allowed:
405
+ - a [`~cache_utils.Cache`] instance, see our
406
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
407
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
408
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
409
+ cache format.
410
+
411
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
412
+ legacy cache format will be returned.
413
+
414
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
415
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
416
+ of shape `(batch_size, sequence_length)`.
417
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
418
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
419
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
420
+ model's internal embedding lookup matrix.
421
+ use_cache (`bool`, *optional*):
422
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
423
+ `past_key_values`).
424
+ output_attentions (`bool`, *optional*):
425
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
426
+ tensors for more detail.
427
+ output_hidden_states (`bool`, *optional*):
428
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
429
+ more detail.
430
+ return_dict (`bool`, *optional*):
431
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
432
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
433
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
434
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
435
+ the complete sequence length.
436
+ """
437
+
438
+
439
+ @add_start_docstrings(
440
+ "The bare SLModel outputting raw hidden-states without any specific head on top.",
441
+ SL_MODEL_START_DOCSTRING,
442
+ )
443
+ class SLModel(SLPreTrainedModel):
444
+ """
445
+ Transformer model consisting of *config.num_hidden_layers* layers. Each layer is a [`SLModelDecoderLayer`]
446
+
447
+ Args:
448
+ config: SLModelConfig
449
+ """
450
+
451
+ def __init__(self, config: SLModelConfig):
452
+ super().__init__(config)
453
+ self.padding_idx = config.pad_token_id
454
+ self.vocab_size = config.vocab_size
455
+
456
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
457
+ self.layers = nn.ModuleList(
458
+ [SLModelDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
459
+ )
460
+ self.norm = SLModelRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
461
+ self.rotary_emb = SLModelRotaryEmbedding(config=config)
462
+ self.gradient_checkpointing = False
463
+ self.mask_converter = AttentionMaskConverter(is_causal=config.is_causal)
464
+
465
+ # Initialize weights and apply final processing
466
+ self.post_init()
467
+
468
+ def get_input_embeddings(self):
469
+ return self.embed_tokens
470
+
471
+ def set_input_embeddings(self, value):
472
+ self.embed_tokens = value
473
+
474
+ @add_start_docstrings_to_model_forward(SL_MODEL_INPUTS_DOCSTRING)
475
+ @add_code_sample_docstrings(
476
+ output_type=BaseModelOutput,
477
+ config_class=_CONFIG_FOR_DOC,
478
+ )
479
+ def forward(
480
+ self,
481
+ input_ids: torch.LongTensor = None,
482
+ attention_mask: Optional[torch.Tensor] = None,
483
+ position_ids: Optional[torch.LongTensor] = None,
484
+ inputs_embeds: Optional[torch.FloatTensor] = None,
485
+ output_attentions: Optional[bool] = None,
486
+ output_hidden_states: Optional[bool] = None,
487
+ return_dict: Optional[bool] = None,
488
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
489
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
490
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
491
+ output_hidden_states = (
492
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
493
+ )
494
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
495
+
496
+ if (input_ids is None) ^ (inputs_embeds is not None):
497
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
498
+
499
+ if inputs_embeds is None:
500
+ inputs_embeds = self.embed_tokens(input_ids)
501
+
502
+ if attention_mask is not None and self.config._attn_implementation != "flash_attention_2":
503
+ mask = self.mask_converter.to_4d(
504
+ attention_mask,
505
+ attention_mask.shape[1],
506
+ inputs_embeds.dtype,
507
+ key_value_length=attention_mask.shape[1],
508
+ )
509
+ else:
510
+ mask = attention_mask
511
+
512
+ hidden_states = inputs_embeds
513
+
514
+ # create position embeddings to be shared across the encoder layers
515
+ if position_ids is None:
516
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
517
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
518
+
519
+ # encoder layers
520
+ all_hidden_states = () if output_hidden_states else None
521
+ all_self_attns = () if output_attentions else None
522
+
523
+ for encoder_layer in self.layers[: self.config.num_hidden_layers]:
524
+ if output_hidden_states:
525
+ all_hidden_states += (hidden_states,)
526
+
527
+ if self.gradient_checkpointing and self.training:
528
+ layer_outputs = self._gradient_checkpointing_func(
529
+ encoder_layer.__call__,
530
+ hidden_states,
531
+ mask,
532
+ position_ids,
533
+ None,
534
+ output_attentions,
535
+ False,
536
+ None,
537
+ position_embeddings,
538
+ )
539
+ else:
540
+ layer_outputs = encoder_layer(
541
+ hidden_states,
542
+ attention_mask=mask,
543
+ position_ids=position_ids,
544
+ output_attentions=output_attentions,
545
+ position_embeddings=position_embeddings,
546
+ **flash_attn_kwargs,
547
+ )
548
+
549
+ hidden_states = layer_outputs[0]
550
+
551
+ if output_attentions:
552
+ all_self_attns += (layer_outputs[1],)
553
+
554
+ hidden_states = self.norm(hidden_states)
555
+
556
+ # add hidden states from the last encoder layer
557
+ if output_hidden_states:
558
+ all_hidden_states += (hidden_states,)
559
+
560
+ output = BaseModelOutput(
561
+ last_hidden_state=hidden_states,
562
+ hidden_states=all_hidden_states,
563
+ attentions=all_self_attns,
564
+ )
565
+ return output if return_dict else output.to_tuple()
566
+
567
+ def _update_causal_mask(
568
+ self,
569
+ attention_mask: torch.Tensor,
570
+ input_tensor: torch.Tensor,
571
+ cache_position: torch.Tensor,
572
+ past_key_values: Cache,
573
+ output_attentions: bool,
574
+ ):
575
+ if self.config._attn_implementation == "flash_attention_2":
576
+ if attention_mask is not None and (attention_mask == 0.0).any():
577
+ return attention_mask
578
+ return None
579
+
580
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
581
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
582
+ # to infer the attention mask.
583
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
584
+ using_static_cache = isinstance(past_key_values, StaticCache)
585
+
586
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
587
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
588
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
589
+ attention_mask,
590
+ inputs_embeds=input_tensor,
591
+ past_key_values_length=past_seen_tokens,
592
+ is_training=self.training,
593
+ ):
594
+ return None
595
+
596
+ dtype, device = input_tensor.dtype, input_tensor.device
597
+ sequence_length = input_tensor.shape[1]
598
+ if using_static_cache:
599
+ target_length = past_key_values.get_max_cache_shape()
600
+ else:
601
+ target_length = (
602
+ attention_mask.shape[-1]
603
+ if isinstance(attention_mask, torch.Tensor)
604
+ else past_seen_tokens + sequence_length + 1
605
+ )
606
+
607
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
608
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
609
+ attention_mask,
610
+ sequence_length=sequence_length,
611
+ target_length=target_length,
612
+ dtype=dtype,
613
+ device=device,
614
+ cache_position=cache_position,
615
+ batch_size=input_tensor.shape[0],
616
+ )
617
+
618
+ if (
619
+ self.config._attn_implementation == "sdpa"
620
+ and attention_mask is not None
621
+ and attention_mask.device.type in ["cuda", "xpu"]
622
+ and not output_attentions
623
+ ):
624
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
625
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
626
+ # Details: https://github.com/pytorch/pytorch/issues/110213
627
+ min_dtype = torch.finfo(dtype).min
628
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
629
+
630
+ return causal_mask
631
+
632
+ @staticmethod
633
+ def _prepare_4d_causal_attention_mask_with_cache_position(
634
+ attention_mask: torch.Tensor,
635
+ sequence_length: int,
636
+ target_length: int,
637
+ dtype: torch.dtype,
638
+ device: torch.device,
639
+ cache_position: torch.Tensor,
640
+ batch_size: int,
641
+ **kwargs,
642
+ ):
643
+ """
644
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
645
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
646
+
647
+ Args:
648
+ attention_mask (`torch.Tensor`):
649
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
650
+ `(batch_size, 1, query_length, key_value_length)`.
651
+ sequence_length (`int`):
652
+ The sequence length being processed.
653
+ target_length (`int`):
654
+ The target length: when generating with static cache, the mask should be as long as the static cache,
655
+ to account for the 0 padding, the part of the cache that is not filled yet.
656
+ dtype (`torch.dtype`):
657
+ The dtype to use for the 4D attention mask.
658
+ device (`torch.device`):
659
+ The device to plcae the 4D attention mask on.
660
+ cache_position (`torch.Tensor`):
661
+ Indices depicting the position of the input sequence tokens in the sequence.
662
+ batch_size (`torch.Tensor`):
663
+ Batch size.
664
+ """
665
+ if attention_mask is not None and attention_mask.dim() == 4:
666
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
667
+ causal_mask = attention_mask
668
+ else:
669
+ min_dtype = torch.finfo(dtype).min
670
+ causal_mask = torch.full(
671
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
672
+ )
673
+ if sequence_length != 1:
674
+ causal_mask = torch.triu(causal_mask, diagonal=1)
675
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
676
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
677
+ if attention_mask is not None:
678
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
679
+ mask_length = attention_mask.shape[-1]
680
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
681
+ causal_mask.device
682
+ )
683
+ padding_mask = padding_mask == 0
684
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
685
+ padding_mask, min_dtype
686
+ )
687
+
688
+ return causal_mask
689
+
690
+
691
+ @add_start_docstrings(
692
+ "The SLModel model with a sequence classification head on top that performs pooling.",
693
+ SL_MODEL_START_DOCSTRING,
694
+ )
695
+ class SLModelForSequenceClassification(SLPreTrainedModel):
696
+ def __init__(self, config: SLModelConfig):
697
+ super().__init__(config)
698
+ self.num_labels = config.num_labels
699
+ self.classifier_pooling = config.classifier_pooling
700
+
701
+ self.model = SLModel(config)
702
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
703
+ self.activation = nn.GELU()
704
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels)
705
+ self.post_init()
706
+
707
+ @add_start_docstrings_to_model_forward(SL_MODEL_INPUTS_DOCSTRING)
708
+ @add_code_sample_docstrings(
709
+ output_type=SequenceClassifierOutput,
710
+ config_class=_CONFIG_FOR_DOC,
711
+ )
712
+ def forward(
713
+ self,
714
+ input_ids: Optional[torch.LongTensor] = None,
715
+ attention_mask: Optional[torch.Tensor] = None,
716
+ position_ids: Optional[torch.LongTensor] = None,
717
+ inputs_embeds: Optional[torch.FloatTensor] = None,
718
+ labels: Optional[torch.LongTensor] = None,
719
+ output_attentions: Optional[bool] = None,
720
+ output_hidden_states: Optional[bool] = None,
721
+ return_dict: Optional[bool] = None,
722
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
723
+ r"""
724
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
725
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
726
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
727
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
728
+ """
729
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
730
+
731
+ encoder_output = self.model(
732
+ input_ids,
733
+ attention_mask=attention_mask,
734
+ position_ids=position_ids,
735
+ inputs_embeds=inputs_embeds,
736
+ output_attentions=output_attentions,
737
+ output_hidden_states=output_hidden_states,
738
+ return_dict=return_dict,
739
+ )
740
+ last_hidden_state = encoder_output[0]
741
+
742
+ if self.classifier_pooling == "mean":
743
+ if attention_mask is None:
744
+ pooled_output = last_hidden_state.mean(dim=1)
745
+ else:
746
+ pooled_output = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1)
747
+ pooled_output /= attention_mask.sum(dim=1, keepdim=True)
748
+
749
+ elif self.classifier_pooling == "eos":
750
+ if attention_mask is None:
751
+ pooled_output = last_hidden_state[:, -1]
752
+ else:
753
+ eos_indices = attention_mask.sum(dim=1) - 1
754
+ pooled_output = last_hidden_state[torch.arange(len(eos_indices)), eos_indices]
755
+
756
+ else:
757
+ raise NotImplementedError
758
+
759
+ pooled_output = self.dense(pooled_output)
760
+ pooled_output = self.activation(pooled_output)
761
+ logits = self.classifier(pooled_output)
762
+
763
+ loss = None
764
+ if labels is not None:
765
+ labels = labels.to(logits.device)
766
+ if self.config.problem_type is None:
767
+ if self.num_labels == 1:
768
+ self.config.problem_type = "regression"
769
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
770
+ self.config.problem_type = "single_label_classification"
771
+ else:
772
+ self.config.problem_type = "multi_label_classification"
773
+
774
+ if self.config.problem_type == "regression":
775
+ loss_fct = MSELoss()
776
+ if self.num_labels == 1:
777
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
778
+ else:
779
+ loss = loss_fct(logits, labels)
780
+ elif self.config.problem_type == "single_label_classification":
781
+ loss_fct = CrossEntropyLoss()
782
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
783
+ elif self.config.problem_type == "multi_label_classification":
784
+ loss_fct = BCEWithLogitsLoss()
785
+ loss = loss_fct(logits, labels)
786
+
787
+ if not return_dict:
788
+ output = (logits,) + encoder_output[1:]
789
+ return ((loss,) + output) if loss is not None else output
790
+
791
+ return SequenceClassifierOutput(
792
+ loss=loss,
793
+ logits=logits,
794
+ hidden_states=encoder_output.hidden_states,
795
+ attentions=encoder_output.attentions,
796
+ )
797
+
798
+
799
+ @add_start_docstrings(
800
+ "The SLModel model with a token classification head.",
801
+ SL_MODEL_START_DOCSTRING,
802
+ )
803
+ class SLModelForTokenClassification(SLPreTrainedModel):
804
+ def __init__(self, config: SLModelConfig):
805
+ super().__init__(config)
806
+ self.num_labels = config.num_labels
807
+ self.model = SLModel(config)
808
+ if getattr(config, "classifier_dropout", None) is not None:
809
+ classifier_dropout = config.classifier_dropout
810
+ elif getattr(config, "hidden_dropout", None) is not None:
811
+ classifier_dropout = config.hidden_dropout
812
+ else:
813
+ classifier_dropout = 0.1
814
+ self.dropout = nn.Dropout(classifier_dropout)
815
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
816
+ self.post_init()
817
+
818
+ def get_input_embeddings(self):
819
+ return self.model.embed_tokens
820
+
821
+ def set_input_embeddings(self, value):
822
+ self.model.embed_tokens = value
823
+
824
+ @add_start_docstrings_to_model_forward(SL_MODEL_INPUTS_DOCSTRING)
825
+ @add_code_sample_docstrings(
826
+ output_type=TokenClassifierOutput,
827
+ config_class=_CONFIG_FOR_DOC,
828
+ )
829
+ def forward(
830
+ self,
831
+ input_ids: Optional[torch.LongTensor] = None,
832
+ attention_mask: Optional[torch.Tensor] = None,
833
+ position_ids: Optional[torch.LongTensor] = None,
834
+ past_key_values: Optional[Cache] = None,
835
+ inputs_embeds: Optional[torch.FloatTensor] = None,
836
+ labels: Optional[torch.LongTensor] = None,
837
+ use_cache: Optional[bool] = None,
838
+ output_attentions: Optional[bool] = None,
839
+ output_hidden_states: Optional[bool] = None,
840
+ ) -> TokenClassifierOutput:
841
+ r"""
842
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
843
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
844
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
845
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
846
+ """
847
+
848
+ encoder_output = self.model(
849
+ input_ids,
850
+ attention_mask=attention_mask,
851
+ position_ids=position_ids,
852
+ past_key_values=past_key_values,
853
+ inputs_embeds=inputs_embeds,
854
+ use_cache=use_cache,
855
+ output_attentions=output_attentions,
856
+ output_hidden_states=output_hidden_states,
857
+ )
858
+ sequence_output = encoder_output.last_hidden_state
859
+ sequence_output = self.dropout(sequence_output)
860
+ logits = self.score(sequence_output)
861
+
862
+ loss = None
863
+ if labels is not None:
864
+ loss = self.loss_function(logits, labels, self.config)
865
+
866
+ return TokenClassifierOutput(
867
+ loss=loss,
868
+ logits=logits,
869
+ hidden_states=encoder_output.hidden_states,
870
+ attentions=encoder_output.attentions,
871
+ )
872
+
873
+
874
+ @add_start_docstrings(
875
+ "The SLModel model for questio answering tasks.",
876
+ SL_MODEL_START_DOCSTRING,
877
+ )
878
+ class SLModelForQuestionAnswering(SLPreTrainedModel):
879
+ def __init__(self, config: SLModelConfig):
880
+ super().__init__(config)
881
+ self.model = SLModel(config)
882
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
883
+ self.post_init()
884
+
885
+ def get_input_embeddings(self):
886
+ return self.transformer.embed_tokens
887
+
888
+ def set_input_embeddings(self, value):
889
+ self.transformer.embed_tokens = value
890
+
891
+ @add_start_docstrings_to_model_forward(SL_MODEL_INPUTS_DOCSTRING)
892
+ @add_code_sample_docstrings(
893
+ output_type=QuestionAnsweringModelOutput,
894
+ config_class=_CONFIG_FOR_DOC,
895
+ )
896
+ def forward(
897
+ self,
898
+ input_ids: Optional[torch.LongTensor] = None,
899
+ attention_mask: Optional[torch.Tensor] = None,
900
+ position_ids: Optional[torch.LongTensor] = None,
901
+ past_key_values: Optional[Cache] = None,
902
+ inputs_embeds: Optional[torch.FloatTensor] = None,
903
+ start_positions: Optional[torch.LongTensor] = None,
904
+ end_positions: Optional[torch.LongTensor] = None,
905
+ output_attentions: Optional[bool] = None,
906
+ output_hidden_states: Optional[bool] = None,
907
+ **kwargs,
908
+ ) -> QuestionAnsweringModelOutput:
909
+ r"""
910
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
911
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
912
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
913
+ are not taken into account for computing the loss.
914
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
915
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
916
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
917
+ are not taken into account for computing the loss.
918
+ """
919
+
920
+ encoder_output = self.model(
921
+ input_ids,
922
+ attention_mask=attention_mask,
923
+ position_ids=position_ids,
924
+ past_key_values=past_key_values,
925
+ inputs_embeds=inputs_embeds,
926
+ output_attentions=output_attentions,
927
+ output_hidden_states=output_hidden_states,
928
+ )
929
+
930
+ sequence_output = encoder_output.last_hidden_state
931
+ logits = self.qa_outputs(sequence_output)
932
+ start_logits, end_logits = logits.split(1, dim=-1)
933
+ start_logits = start_logits.squeeze(-1).contiguous()
934
+ end_logits = end_logits.squeeze(-1).contiguous()
935
+
936
+ loss = None
937
+ if start_positions is not None and end_positions is not None:
938
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
939
+
940
+ return QuestionAnsweringModelOutput(
941
+ loss=loss,
942
+ start_logits=start_logits,
943
+ end_logits=end_logits,
944
+ hidden_states=encoder_output.hidden_states,
945
+ attentions=encoder_output.attentions,
946
+ )
947
+
948
+
949
+ __all__ = [
950
+ "SLPreTrainedModel",
951
+ "SLModel",
952
+ "SLModelForSequenceClassification",
953
+ "SLModelForTokenClassification",
954
+ "SLModelForQuestionAnswering",
955
+ ]