Ubuntu commited on
Commit
4e80aee
·
1 Parent(s): 3508eae

Model file...

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