cognitivess commited on
Commit
e942e2b
1 Parent(s): a50a629

Rename cognitivess_model/modeling_Cognitivess.py to cognitivess_model/modeling_cognitivess.py

Browse files
cognitivess_model/modeling_Cognitivess.py DELETED
@@ -1,1459 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2022 Cognitivess and the 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
- import math
16
- from typing import List, Optional, Tuple, Union
17
-
18
- import torch
19
- import torch.nn.functional as F
20
- import torch.utils.checkpoint
21
- from torch import nn
22
- from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
23
-
24
- from ...activations import ACT2FN
25
- from ...cache_utils import Cache, DynamicCache, StaticCache
26
- from ...modeling_attn_mask_utils import AttentionMaskConverter
27
- from ...modeling_flash_attention_utils import _flash_attention_forward
28
- from ...modeling_outputs import (
29
- BaseModelOutputWithPast,
30
- CausalLMOutputWithPast,
31
- QuestionAnsweringModelOutput,
32
- SequenceClassifierOutputWithPast,
33
- TokenClassifierOutput,
34
- )
35
- from ...modeling_utils import PreTrainedModel
36
- from ...pytorch_utils import ALL_LAYERNORM_LAYERS
37
- from ...utils import (
38
- add_start_docstrings,
39
- add_start_docstrings_to_model_forward,
40
- is_flash_attn_greater_or_equal_2_10,
41
- logging,
42
- replace_return_docstrings,
43
- )
44
- from .configuration_Cognitivess import CognitivessConfig
45
-
46
-
47
- logger = logging.get_logger(__name__)
48
-
49
- _CONFIG_FOR_DOC = "CognitivessConfig"
50
-
51
-
52
- class CognitivessRMSNorm(nn.Module):
53
- def __init__(self, hidden_size, eps=1e-6):
54
- """
55
- CognitivessRMSNorm is equivalent to T5LayerNorm
56
- """
57
- super().__init__()
58
- self.weight = nn.Parameter(torch.ones(hidden_size))
59
- self.variance_epsilon = eps
60
-
61
- def forward(self, hidden_states):
62
- input_dtype = hidden_states.dtype
63
- hidden_states = hidden_states.to(torch.float32)
64
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
65
- hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
66
- return self.weight * hidden_states.to(input_dtype)
67
-
68
-
69
- ALL_LAYERNORM_LAYERS.append(CognitivessRMSNorm)
70
-
71
-
72
- class CognitivessRotaryEmbedding(nn.Module):
73
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
74
- super().__init__()
75
- self.scaling_factor = scaling_factor
76
- self.dim = dim
77
- self.max_position_embeddings = max_position_embeddings
78
- self.base = base
79
- inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
80
- self.register_buffer("inv_freq", inv_freq, persistent=False)
81
- # For BC we register cos and sin cached
82
- self.max_seq_len_cached = max_position_embeddings
83
-
84
- @torch.no_grad()
85
- def forward(self, x, position_ids):
86
- # x: [bs, num_attention_heads, seq_len, head_size]
87
- inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
88
- position_ids_expanded = position_ids[:, None, :].float()
89
- # Force float32 since bfloat16 loses precision on long contexts
90
- # See https://github.com/huggingface/transformers/pull/29285
91
- device_type = x.device.type
92
- device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
93
- with torch.autocast(device_type=device_type, enabled=False):
94
- freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
95
- emb = torch.cat((freqs, freqs), dim=-1)
96
- cos = emb.cos()
97
- sin = emb.sin()
98
- return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
99
-
100
-
101
- class CognitivessLinearScalingRotaryEmbedding(CognitivessRotaryEmbedding):
102
- """CognitivessRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
103
-
104
- def forward(self, x, position_ids):
105
- # difference to the original RoPE: a scaling factor is aplied to the position ids
106
- position_ids = position_ids.float() / self.scaling_factor
107
- cos, sin = super().forward(x, position_ids)
108
- return cos, sin
109
-
110
-
111
- class CognitivessDynamicNTKScalingRotaryEmbedding(CognitivessRotaryEmbedding):
112
- """CognitivessRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
113
-
114
- def forward(self, x, position_ids):
115
- # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
116
- seq_len = torch.max(position_ids) + 1
117
- if seq_len > self.max_position_embeddings:
118
- base = self.base * (
119
- (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
120
- ) ** (self.dim / (self.dim - 2))
121
- inv_freq = 1.0 / (
122
- base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
123
- )
124
- self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
125
-
126
- cos, sin = super().forward(x, position_ids)
127
- return cos, sin
128
-
129
-
130
- def rotate_half(x):
131
- """Rotates half the hidden dims of the input."""
132
- x1 = x[..., : x.shape[-1] // 2]
133
- x2 = x[..., x.shape[-1] // 2 :]
134
- return torch.cat((-x2, x1), dim=-1)
135
-
136
-
137
- def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
138
- """Applies Rotary Position Embedding to the query and key tensors.
139
-
140
- Args:
141
- q (`torch.Tensor`): The query tensor.
142
- k (`torch.Tensor`): The key tensor.
143
- cos (`torch.Tensor`): The cosine part of the rotary embedding.
144
- sin (`torch.Tensor`): The sine part of the rotary embedding.
145
- position_ids (`torch.Tensor`, *optional*):
146
- Deprecated and unused.
147
- unsqueeze_dim (`int`, *optional*, defaults to 1):
148
- The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
149
- sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
150
- that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
151
- k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
152
- cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
153
- the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
154
- Returns:
155
- `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
156
- """
157
- cos = cos.unsqueeze(unsqueeze_dim)
158
- sin = sin.unsqueeze(unsqueeze_dim)
159
- q_embed = (q * cos) + (rotate_half(q) * sin)
160
- k_embed = (k * cos) + (rotate_half(k) * sin)
161
- return q_embed, k_embed
162
-
163
-
164
- class CognitivessMLP(nn.Module):
165
- def __init__(self, config):
166
- super().__init__()
167
- self.config = config
168
- self.hidden_size = config.hidden_size
169
- self.intermediate_size = config.intermediate_size
170
- self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
171
- self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
172
- self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
173
- self.act_fn = ACT2FN[config.hidden_act]
174
-
175
- def forward(self, x):
176
- if self.config.pretraining_tp > 1:
177
- slice = self.intermediate_size // self.config.pretraining_tp
178
- gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
179
- up_proj_slices = self.up_proj.weight.split(slice, dim=0)
180
- down_proj_slices = self.down_proj.weight.split(slice, dim=1)
181
-
182
- gate_proj = torch.cat(
183
- [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
184
- )
185
- up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
186
-
187
- intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
188
- down_proj = [
189
- F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
190
- ]
191
- down_proj = sum(down_proj)
192
- else:
193
- down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
194
-
195
- return down_proj
196
-
197
-
198
- def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
199
- """
200
- This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
201
- num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
202
- """
203
- batch, num_key_value_heads, slen, head_dim = hidden_states.shape
204
- if n_rep == 1:
205
- return hidden_states
206
- hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
207
- return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
208
-
209
-
210
- class CognitivessAttention(nn.Module):
211
- """Multi-headed attention from 'Attention Is All You Need' paper"""
212
-
213
- def __init__(self, config: CognitivessConfig, layer_idx: Optional[int] = None):
214
- super().__init__()
215
- self.config = config
216
- self.layer_idx = layer_idx
217
- if layer_idx is None:
218
- logger.warning_once(
219
- f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
220
- "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
221
- "when creating this class."
222
- )
223
-
224
- self.attention_dropout = config.attention_dropout
225
- self.hidden_size = config.hidden_size
226
- self.num_heads = config.num_attention_heads
227
- self.head_dim = self.hidden_size // self.num_heads
228
- self.num_key_value_heads = config.num_key_value_heads
229
- self.num_key_value_groups = self.num_heads // self.num_key_value_heads
230
- self.max_position_embeddings = config.max_position_embeddings
231
- self.rope_theta = config.rope_theta
232
- self.is_causal = True
233
-
234
- if (self.head_dim * self.num_heads) != self.hidden_size:
235
- raise ValueError(
236
- f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
237
- f" and `num_heads`: {self.num_heads})."
238
- )
239
-
240
- self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
241
- self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
242
- self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
243
- self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
244
- self._init_rope()
245
-
246
- def _init_rope(self):
247
- if self.config.rope_scaling is None:
248
- self.rotary_emb = CognitivessRotaryEmbedding(
249
- self.head_dim,
250
- max_position_embeddings=self.max_position_embeddings,
251
- base=self.rope_theta,
252
- )
253
- else:
254
- scaling_type = self.config.rope_scaling["type"]
255
- scaling_factor = self.config.rope_scaling["factor"]
256
- if scaling_type == "linear":
257
- self.rotary_emb = CognitivessLinearScalingRotaryEmbedding(
258
- self.head_dim,
259
- max_position_embeddings=self.max_position_embeddings,
260
- scaling_factor=scaling_factor,
261
- base=self.rope_theta,
262
- )
263
- elif scaling_type == "dynamic":
264
- self.rotary_emb = CognitivessDynamicNTKScalingRotaryEmbedding(
265
- self.head_dim,
266
- max_position_embeddings=self.max_position_embeddings,
267
- scaling_factor=scaling_factor,
268
- base=self.rope_theta,
269
- )
270
- else:
271
- raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
272
-
273
- def forward(
274
- self,
275
- hidden_states: torch.Tensor,
276
- attention_mask: Optional[torch.Tensor] = None,
277
- position_ids: Optional[torch.LongTensor] = None,
278
- past_key_value: Optional[Cache] = None,
279
- output_attentions: bool = False,
280
- use_cache: bool = False,
281
- cache_position: Optional[torch.LongTensor] = None,
282
- **kwargs,
283
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
284
- bsz, q_len, _ = hidden_states.size()
285
-
286
- if self.config.pretraining_tp > 1:
287
- key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
288
- query_slices = self.q_proj.weight.split(
289
- (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
290
- )
291
- key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
292
- value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
293
-
294
- query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
295
- query_states = torch.cat(query_states, dim=-1)
296
-
297
- key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
298
- key_states = torch.cat(key_states, dim=-1)
299
-
300
- value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
301
- value_states = torch.cat(value_states, dim=-1)
302
-
303
- else:
304
- query_states = self.q_proj(hidden_states)
305
- key_states = self.k_proj(hidden_states)
306
- value_states = self.v_proj(hidden_states)
307
-
308
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
309
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
310
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
311
-
312
- cos, sin = self.rotary_emb(value_states, position_ids)
313
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
314
-
315
- if past_key_value is not None:
316
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
317
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
318
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
319
-
320
- key_states = repeat_kv(key_states, self.num_key_value_groups)
321
- value_states = repeat_kv(value_states, self.num_key_value_groups)
322
-
323
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
324
-
325
- if attention_mask is not None: # no matter the length, we just slice it
326
- causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
327
- attn_weights = attn_weights + causal_mask
328
-
329
- # upcast attention to fp32
330
- attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
331
- attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
332
- attn_output = torch.matmul(attn_weights, value_states)
333
-
334
- if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
335
- raise ValueError(
336
- f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
337
- f" {attn_output.size()}"
338
- )
339
-
340
- attn_output = attn_output.transpose(1, 2).contiguous()
341
-
342
- attn_output = attn_output.reshape(bsz, q_len, -1)
343
-
344
- if self.config.pretraining_tp > 1:
345
- attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
346
- o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
347
- attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
348
- else:
349
- attn_output = self.o_proj(attn_output)
350
-
351
- if not output_attentions:
352
- attn_weights = None
353
-
354
- return attn_output, attn_weights, past_key_value
355
-
356
-
357
- class CognitivessFlashAttention2(CognitivessAttention):
358
- """
359
- Cognitivess flash attention module. This module inherits from `CognitivessAttention` as the weights of the module stays
360
- untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
361
- flash attention and deal with padding tokens in case the input contains any of them.
362
- """
363
-
364
- def __init__(self, *args, **kwargs):
365
- super().__init__(*args, **kwargs)
366
-
367
- # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
368
- # 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.
369
- # 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).
370
- self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
371
-
372
- def forward(
373
- self,
374
- hidden_states: torch.Tensor,
375
- attention_mask: Optional[torch.LongTensor] = None,
376
- position_ids: Optional[torch.LongTensor] = None,
377
- past_key_value: Optional[Cache] = None,
378
- output_attentions: bool = False,
379
- use_cache: bool = False,
380
- cache_position: Optional[torch.LongTensor] = None,
381
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
382
- if isinstance(past_key_value, StaticCache):
383
- raise ValueError(
384
- "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
385
- "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
386
- )
387
-
388
- output_attentions = False
389
-
390
- bsz, q_len, _ = hidden_states.size()
391
-
392
- query_states = self.q_proj(hidden_states)
393
- key_states = self.k_proj(hidden_states)
394
- value_states = self.v_proj(hidden_states)
395
-
396
- # Flash attention requires the input to have the shape
397
- # batch_size x seq_length x head_dim x hidden_dim
398
- # therefore we just need to keep the original shape
399
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
400
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
401
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
402
-
403
- cos, sin = self.rotary_emb(value_states, position_ids)
404
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
405
-
406
- if past_key_value is not None:
407
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
408
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
409
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
410
-
411
- # 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
412
- # to be able to avoid many of these transpose/reshape/view.
413
- query_states = query_states.transpose(1, 2)
414
- key_states = key_states.transpose(1, 2)
415
- value_states = value_states.transpose(1, 2)
416
-
417
- dropout_rate = self.attention_dropout if self.training else 0.0
418
-
419
- # In PEFT, usually we cast the layer norms in float32 for training stability reasons
420
- # therefore the input hidden states gets silently casted in float32. Hence, we need
421
- # cast them back in the correct dtype just to be sure everything works as expected.
422
- # This might slowdown training & inference so it is recommended to not cast the LayerNorms
423
- # in fp32. (CognitivessRMSNorm handles it correctly)
424
-
425
- input_dtype = query_states.dtype
426
- if input_dtype == torch.float32:
427
- if torch.is_autocast_enabled():
428
- target_dtype = torch.get_autocast_gpu_dtype()
429
- # Handle the case where the model is quantized
430
- elif hasattr(self.config, "_pre_quantization_dtype"):
431
- target_dtype = self.config._pre_quantization_dtype
432
- else:
433
- target_dtype = self.q_proj.weight.dtype
434
-
435
- logger.warning_once(
436
- f"The input hidden states seems to be silently casted in float32, this might be related to"
437
- f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
438
- f" {target_dtype}."
439
- )
440
-
441
- query_states = query_states.to(target_dtype)
442
- key_states = key_states.to(target_dtype)
443
- value_states = value_states.to(target_dtype)
444
-
445
- attn_output = _flash_attention_forward(
446
- query_states,
447
- key_states,
448
- value_states,
449
- attention_mask,
450
- q_len,
451
- dropout=dropout_rate,
452
- sliding_window=getattr(self, "sliding_window", None),
453
- use_top_left_mask=self._flash_attn_uses_top_left_mask,
454
- is_causal=self.is_causal,
455
- )
456
-
457
- attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
458
- attn_output = self.o_proj(attn_output)
459
-
460
- if not output_attentions:
461
- attn_weights = None
462
-
463
- return attn_output, attn_weights, past_key_value
464
-
465
-
466
- class CognitivessSdpaAttention(CognitivessAttention):
467
- """
468
- Cognitivess attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
469
- `CognitivessAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
470
- SDPA API.
471
- """
472
-
473
- # Adapted from CognitivessAttention.forward
474
- def forward(
475
- self,
476
- hidden_states: torch.Tensor,
477
- attention_mask: Optional[torch.Tensor] = None,
478
- position_ids: Optional[torch.LongTensor] = None,
479
- past_key_value: Optional[Cache] = None,
480
- output_attentions: bool = False,
481
- use_cache: bool = False,
482
- cache_position: Optional[torch.LongTensor] = None,
483
- **kwargs,
484
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
485
- if output_attentions:
486
- # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
487
- logger.warning_once(
488
- "CognitivessModel is using CognitivessSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
489
- 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
490
- )
491
- return super().forward(
492
- hidden_states=hidden_states,
493
- attention_mask=attention_mask,
494
- position_ids=position_ids,
495
- past_key_value=past_key_value,
496
- output_attentions=output_attentions,
497
- use_cache=use_cache,
498
- cache_position=cache_position,
499
- )
500
-
501
- bsz, q_len, _ = hidden_states.size()
502
-
503
- query_states = self.q_proj(hidden_states)
504
- key_states = self.k_proj(hidden_states)
505
- value_states = self.v_proj(hidden_states)
506
-
507
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
508
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
509
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
510
-
511
- cos, sin = self.rotary_emb(value_states, position_ids)
512
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
513
-
514
- if past_key_value is not None:
515
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
516
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
517
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
518
-
519
- key_states = repeat_kv(key_states, self.num_key_value_groups)
520
- value_states = repeat_kv(value_states, self.num_key_value_groups)
521
-
522
- causal_mask = attention_mask
523
- if attention_mask is not None:
524
- causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
525
-
526
- # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
527
- # Reference: https://github.com/pytorch/pytorch/issues/112577.
528
- if query_states.device.type == "cuda" and causal_mask is not None:
529
- query_states = query_states.contiguous()
530
- key_states = key_states.contiguous()
531
- value_states = value_states.contiguous()
532
-
533
- # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
534
- # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
535
- is_causal = True if causal_mask is None and q_len > 1 else False
536
-
537
- attn_output = torch.nn.functional.scaled_dot_product_attention(
538
- query_states,
539
- key_states,
540
- value_states,
541
- attn_mask=causal_mask,
542
- dropout_p=self.attention_dropout if self.training else 0.0,
543
- is_causal=is_causal,
544
- )
545
-
546
- attn_output = attn_output.transpose(1, 2).contiguous()
547
- attn_output = attn_output.view(bsz, q_len, -1)
548
-
549
- attn_output = self.o_proj(attn_output)
550
-
551
- return attn_output, None, past_key_value
552
-
553
-
554
- Cognitivess_ATTENTION_CLASSES = {
555
- "eager": CognitivessAttention,
556
- "flash_attention_2": CognitivessFlashAttention2,
557
- "sdpa": CognitivessSdpaAttention,
558
- }
559
-
560
-
561
- class CognitivessDecoderLayer(nn.Module):
562
- def __init__(self, config: CognitivessConfig, layer_idx: int):
563
- super().__init__()
564
- self.hidden_size = config.hidden_size
565
-
566
- self.self_attn = Cognitivess_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
567
-
568
- self.mlp = CognitivessMLP(config)
569
- self.input_layernorm = CognitivessRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
570
- self.post_attention_layernorm = CognitivessRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
571
-
572
- def forward(
573
- self,
574
- hidden_states: torch.Tensor,
575
- attention_mask: Optional[torch.Tensor] = None,
576
- position_ids: Optional[torch.LongTensor] = None,
577
- past_key_value: Optional[Cache] = None,
578
- output_attentions: Optional[bool] = False,
579
- use_cache: Optional[bool] = False,
580
- cache_position: Optional[torch.LongTensor] = None,
581
- **kwargs,
582
- ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
583
- """
584
- Args:
585
- hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
586
- attention_mask (`torch.FloatTensor`, *optional*):
587
- attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
588
- query_sequence_length, key_sequence_length)` if default attention is used.
589
- output_attentions (`bool`, *optional*):
590
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
591
- returned tensors for more detail.
592
- use_cache (`bool`, *optional*):
593
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
594
- (see `past_key_values`).
595
- past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
596
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
597
- Indices depicting the position of the input sequence tokens in the sequence
598
- kwargs (`dict`, *optional*):
599
- Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
600
- into the model
601
- """
602
- residual = hidden_states
603
-
604
- hidden_states = self.input_layernorm(hidden_states)
605
-
606
- # Self Attention
607
- hidden_states, self_attn_weights, present_key_value = self.self_attn(
608
- hidden_states=hidden_states,
609
- attention_mask=attention_mask,
610
- position_ids=position_ids,
611
- past_key_value=past_key_value,
612
- output_attentions=output_attentions,
613
- use_cache=use_cache,
614
- cache_position=cache_position,
615
- **kwargs,
616
- )
617
- hidden_states = residual + hidden_states
618
-
619
- # Fully Connected
620
- residual = hidden_states
621
- hidden_states = self.post_attention_layernorm(hidden_states)
622
- hidden_states = self.mlp(hidden_states)
623
- hidden_states = residual + hidden_states
624
-
625
- outputs = (hidden_states,)
626
-
627
- if output_attentions:
628
- outputs += (self_attn_weights,)
629
-
630
- if use_cache:
631
- outputs += (present_key_value,)
632
-
633
- return outputs
634
-
635
-
636
- Cognitivess_START_DOCSTRING = r"""
637
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
638
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
639
- etc.)
640
-
641
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
642
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
643
- and behavior.
644
-
645
- Parameters:
646
- config ([`CognitivessConfig`]):
647
- Model configuration class with all the parameters of the model. Initializing with a config file does not
648
- load the weights associated with the model, only the configuration. Check out the
649
- [`~PreTrainedModel.from_pretrained`] method to load the model weights.
650
- """
651
-
652
-
653
- @add_start_docstrings(
654
- "The bare Cognitivess Model outputting raw hidden-states without any specific head on top.",
655
- Cognitivess_START_DOCSTRING,
656
- )
657
- class CognitivessPreTrainedModel(PreTrainedModel):
658
- config_class = CognitivessConfig
659
- base_model_prefix = "model"
660
- supports_gradient_checkpointing = True
661
- _no_split_modules = ["CognitivessDecoderLayer"]
662
- _skip_keys_device_placement = ["past_key_values"]
663
- _supports_flash_attn_2 = True
664
- _supports_sdpa = True
665
- _supports_cache_class = True
666
- _supports_quantized_cache = True
667
- _supports_static_cache = True
668
-
669
- def _init_weights(self, module):
670
- std = self.config.initializer_range
671
- if isinstance(module, nn.Linear):
672
- module.weight.data.normal_(mean=0.0, std=std)
673
- if module.bias is not None:
674
- module.bias.data.zero_()
675
- elif isinstance(module, nn.Embedding):
676
- module.weight.data.normal_(mean=0.0, std=std)
677
- if module.padding_idx is not None:
678
- module.weight.data[module.padding_idx].zero_()
679
-
680
-
681
- Cognitivess_INPUTS_DOCSTRING = r"""
682
- Args:
683
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
684
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
685
- it.
686
-
687
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
688
- [`PreTrainedTokenizer.__call__`] for details.
689
-
690
- [What are input IDs?](../glossary#input-ids)
691
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
692
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
693
-
694
- - 1 for tokens that are **not masked**,
695
- - 0 for tokens that are **masked**.
696
-
697
- [What are attention masks?](../glossary#attention-mask)
698
-
699
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
700
- [`PreTrainedTokenizer.__call__`] for details.
701
-
702
- If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
703
- `past_key_values`).
704
-
705
- If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
706
- and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
707
- information on the default strategy.
708
-
709
- - 1 indicates the head is **not masked**,
710
- - 0 indicates the head is **masked**.
711
- position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
712
- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
713
- config.n_positions - 1]`.
714
-
715
- [What are position IDs?](../glossary#position-ids)
716
- past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
717
- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
718
- blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
719
- returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
720
-
721
- Two formats are allowed:
722
- - a [`~cache_utils.Cache`] instance;
723
- - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
724
- shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
725
- cache format.
726
-
727
- The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
728
- legacy cache format will be returned.
729
-
730
- If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
731
- have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
732
- of shape `(batch_size, sequence_length)`.
733
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
734
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
735
- is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
736
- model's internal embedding lookup matrix.
737
- use_cache (`bool`, *optional*):
738
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
739
- `past_key_values`).
740
- output_attentions (`bool`, *optional*):
741
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
742
- tensors for more detail.
743
- output_hidden_states (`bool`, *optional*):
744
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
745
- more detail.
746
- return_dict (`bool`, *optional*):
747
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
748
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
749
- Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
750
- this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
751
- the complete sequence length.
752
- """
753
-
754
-
755
- @add_start_docstrings(
756
- "The bare Cognitivess Model outputting raw hidden-states without any specific head on top.",
757
- Cognitivess_START_DOCSTRING,
758
- )
759
- class CognitivessModel(CognitivessPreTrainedModel):
760
- """
761
- Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`CognitivessDecoderLayer`]
762
-
763
- Args:
764
- config: CognitivessConfig
765
- """
766
-
767
- def __init__(self, config: CognitivessConfig):
768
- super().__init__(config)
769
- self.padding_idx = config.pad_token_id
770
- self.vocab_size = config.vocab_size
771
-
772
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
773
- self.layers = nn.ModuleList(
774
- [CognitivessDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
775
- )
776
- self.norm = CognitivessRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
777
- self.gradient_checkpointing = False
778
-
779
- # Initialize weights and apply final processing
780
- self.post_init()
781
-
782
- def get_input_embeddings(self):
783
- return self.embed_tokens
784
-
785
- def set_input_embeddings(self, value):
786
- self.embed_tokens = value
787
-
788
- @add_start_docstrings_to_model_forward(Cognitivess_INPUTS_DOCSTRING)
789
- def forward(
790
- self,
791
- input_ids: torch.LongTensor = None,
792
- attention_mask: Optional[torch.Tensor] = None,
793
- position_ids: Optional[torch.LongTensor] = None,
794
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
795
- inputs_embeds: Optional[torch.FloatTensor] = None,
796
- use_cache: Optional[bool] = None,
797
- output_attentions: Optional[bool] = None,
798
- output_hidden_states: Optional[bool] = None,
799
- return_dict: Optional[bool] = None,
800
- cache_position: Optional[torch.LongTensor] = None,
801
- ) -> Union[Tuple, BaseModelOutputWithPast]:
802
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
803
- output_hidden_states = (
804
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
805
- )
806
- use_cache = use_cache if use_cache is not None else self.config.use_cache
807
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
808
-
809
- if (input_ids is None) ^ (inputs_embeds is not None):
810
- raise ValueError(
811
- "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
812
- )
813
-
814
- if self.gradient_checkpointing and self.training and use_cache:
815
- logger.warning_once(
816
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
817
- )
818
- use_cache = False
819
-
820
- if inputs_embeds is None:
821
- inputs_embeds = self.embed_tokens(input_ids)
822
-
823
- return_legacy_cache = False
824
- if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)
825
- return_legacy_cache = True
826
- past_key_values = DynamicCache.from_legacy_cache(past_key_values)
827
- logger.warning_once(
828
- "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
829
- "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
830
- )
831
-
832
- if cache_position is None:
833
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
834
- cache_position = torch.arange(
835
- past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
836
- )
837
- if position_ids is None:
838
- position_ids = cache_position.unsqueeze(0)
839
-
840
- causal_mask = self._update_causal_mask(
841
- attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
842
- )
843
-
844
- # embed positions
845
- hidden_states = inputs_embeds
846
-
847
- # decoder layers
848
- all_hidden_states = () if output_hidden_states else None
849
- all_self_attns = () if output_attentions else None
850
- next_decoder_cache = None
851
-
852
- for decoder_layer in self.layers:
853
- if output_hidden_states:
854
- all_hidden_states += (hidden_states,)
855
-
856
- if self.gradient_checkpointing and self.training:
857
- layer_outputs = self._gradient_checkpointing_func(
858
- decoder_layer.__call__,
859
- hidden_states,
860
- causal_mask,
861
- position_ids,
862
- past_key_values,
863
- output_attentions,
864
- use_cache,
865
- cache_position,
866
- )
867
- else:
868
- layer_outputs = decoder_layer(
869
- hidden_states,
870
- attention_mask=causal_mask,
871
- position_ids=position_ids,
872
- past_key_value=past_key_values,
873
- output_attentions=output_attentions,
874
- use_cache=use_cache,
875
- cache_position=cache_position,
876
- )
877
-
878
- hidden_states = layer_outputs[0]
879
-
880
- if use_cache:
881
- next_decoder_cache = layer_outputs[2 if output_attentions else 1]
882
-
883
- if output_attentions:
884
- all_self_attns += (layer_outputs[1],)
885
-
886
- hidden_states = self.norm(hidden_states)
887
-
888
- # add hidden states from the last decoder layer
889
- if output_hidden_states:
890
- all_hidden_states += (hidden_states,)
891
-
892
- next_cache = next_decoder_cache if use_cache else None
893
- if return_legacy_cache:
894
- next_cache = next_cache.to_legacy_cache()
895
-
896
- if not return_dict:
897
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
898
- return BaseModelOutputWithPast(
899
- last_hidden_state=hidden_states,
900
- past_key_values=next_cache,
901
- hidden_states=all_hidden_states,
902
- attentions=all_self_attns,
903
- )
904
-
905
- def _update_causal_mask(
906
- self,
907
- attention_mask: torch.Tensor,
908
- input_tensor: torch.Tensor,
909
- cache_position: torch.Tensor,
910
- past_key_values: Cache,
911
- output_attentions: bool,
912
- ):
913
- # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
914
- # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
915
- # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
916
- # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
917
-
918
- if self.config._attn_implementation == "flash_attention_2":
919
- if attention_mask is not None and 0.0 in attention_mask:
920
- return attention_mask
921
- return None
922
-
923
- # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
924
- # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
925
- # to infer the attention mask.
926
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
927
- using_static_cache = isinstance(past_key_values, StaticCache)
928
-
929
- # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
930
- if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
931
- if AttentionMaskConverter._ignore_causal_mask_sdpa(
932
- attention_mask,
933
- inputs_embeds=input_tensor,
934
- past_key_values_length=past_seen_tokens,
935
- is_training=self.training,
936
- ):
937
- return None
938
-
939
- dtype, device = input_tensor.dtype, input_tensor.device
940
- min_dtype = torch.finfo(dtype).min
941
- sequence_length = input_tensor.shape[1]
942
- if using_static_cache:
943
- target_length = past_key_values.get_max_length()
944
- else:
945
- target_length = (
946
- attention_mask.shape[-1]
947
- if isinstance(attention_mask, torch.Tensor)
948
- else past_seen_tokens + sequence_length + 1
949
- )
950
-
951
- if attention_mask is not None and attention_mask.dim() == 4:
952
- # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
953
- if attention_mask.max() != 0:
954
- raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
955
- causal_mask = attention_mask
956
- else:
957
- causal_mask = torch.full(
958
- (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
959
- )
960
- if sequence_length != 1:
961
- causal_mask = torch.triu(causal_mask, diagonal=1)
962
- causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
963
- causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
964
- if attention_mask is not None:
965
- causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
966
- mask_length = attention_mask.shape[-1]
967
- padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
968
- padding_mask = padding_mask == 0
969
- causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
970
- padding_mask, min_dtype
971
- )
972
- if (
973
- self.config._attn_implementation == "sdpa"
974
- and attention_mask is not None
975
- and attention_mask.device.type == "cuda"
976
- and not output_attentions
977
- ):
978
- # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
979
- # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
980
- # Details: https://github.com/pytorch/pytorch/issues/110213
981
- causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
982
-
983
- return causal_mask
984
-
985
-
986
- class CognitivessForCausalLM(CognitivessPreTrainedModel):
987
- _tied_weights_keys = ["lm_head.weight"]
988
-
989
- def __init__(self, config):
990
- super().__init__(config)
991
- self.model = CognitivessModel(config)
992
- self.vocab_size = config.vocab_size
993
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
994
-
995
- # Initialize weights and apply final processing
996
- self.post_init()
997
-
998
- def get_input_embeddings(self):
999
- return self.model.embed_tokens
1000
-
1001
- def set_input_embeddings(self, value):
1002
- self.model.embed_tokens = value
1003
-
1004
- def get_output_embeddings(self):
1005
- return self.lm_head
1006
-
1007
- def set_output_embeddings(self, new_embeddings):
1008
- self.lm_head = new_embeddings
1009
-
1010
- def set_decoder(self, decoder):
1011
- self.model = decoder
1012
-
1013
- def get_decoder(self):
1014
- return self.model
1015
-
1016
- @add_start_docstrings_to_model_forward(Cognitivess_INPUTS_DOCSTRING)
1017
- @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1018
- def forward(
1019
- self,
1020
- input_ids: torch.LongTensor = None,
1021
- attention_mask: Optional[torch.Tensor] = None,
1022
- position_ids: Optional[torch.LongTensor] = None,
1023
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1024
- inputs_embeds: Optional[torch.FloatTensor] = None,
1025
- labels: Optional[torch.LongTensor] = None,
1026
- use_cache: Optional[bool] = None,
1027
- output_attentions: Optional[bool] = None,
1028
- output_hidden_states: Optional[bool] = None,
1029
- return_dict: Optional[bool] = None,
1030
- cache_position: Optional[torch.LongTensor] = None,
1031
- ) -> Union[Tuple, CausalLMOutputWithPast]:
1032
- r"""
1033
- Args:
1034
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1035
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1036
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1037
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1038
-
1039
- Returns:
1040
-
1041
- Example:
1042
-
1043
- ```python
1044
- >>> from transformers import AutoTokenizer, CognitivessForCausalLM
1045
-
1046
- >>> model = CognitivessForCausalLM.from_pretrained("CognitivessAI/cognitivess")
1047
- >>> tokenizer = AutoTokenizer.from_pretrained("CognitivessAI/cognitivess")
1048
-
1049
- >>> prompt = "Hey, are you conscious? Can you talk to me?"
1050
- >>> inputs = tokenizer(prompt, return_tensors="pt")
1051
-
1052
- >>> # Generate
1053
- >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1054
- >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1055
- "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1056
- ```"""
1057
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1058
- output_hidden_states = (
1059
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1060
- )
1061
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1062
-
1063
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1064
- outputs = self.model(
1065
- input_ids=input_ids,
1066
- attention_mask=attention_mask,
1067
- position_ids=position_ids,
1068
- past_key_values=past_key_values,
1069
- inputs_embeds=inputs_embeds,
1070
- use_cache=use_cache,
1071
- output_attentions=output_attentions,
1072
- output_hidden_states=output_hidden_states,
1073
- return_dict=return_dict,
1074
- cache_position=cache_position,
1075
- )
1076
-
1077
- hidden_states = outputs[0]
1078
- if self.config.pretraining_tp > 1:
1079
- lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1080
- logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1081
- logits = torch.cat(logits, dim=-1)
1082
- else:
1083
- logits = self.lm_head(hidden_states)
1084
- logits = logits.float()
1085
-
1086
- loss = None
1087
- if labels is not None:
1088
- # Shift so that tokens < n predict n
1089
- shift_logits = logits[..., :-1, :].contiguous()
1090
- shift_labels = labels[..., 1:].contiguous()
1091
- # Flatten the tokens
1092
- loss_fct = CrossEntropyLoss()
1093
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
1094
- shift_labels = shift_labels.view(-1)
1095
- # Enable model parallelism
1096
- shift_labels = shift_labels.to(shift_logits.device)
1097
- loss = loss_fct(shift_logits, shift_labels)
1098
-
1099
- if not return_dict:
1100
- output = (logits,) + outputs[1:]
1101
- return (loss,) + output if loss is not None else output
1102
-
1103
- return CausalLMOutputWithPast(
1104
- loss=loss,
1105
- logits=logits,
1106
- past_key_values=outputs.past_key_values,
1107
- hidden_states=outputs.hidden_states,
1108
- attentions=outputs.attentions,
1109
- )
1110
-
1111
- def prepare_inputs_for_generation(
1112
- self,
1113
- input_ids,
1114
- past_key_values=None,
1115
- attention_mask=None,
1116
- inputs_embeds=None,
1117
- cache_position=None,
1118
- position_ids=None,
1119
- use_cache=True,
1120
- **kwargs,
1121
- ):
1122
- # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1123
- # Exception 1: when passing input_embeds, input_ids may be missing entries
1124
- # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1125
- if past_key_values is not None:
1126
- if inputs_embeds is not None: # Exception 1
1127
- input_ids = input_ids[:, -cache_position.shape[0] :]
1128
- elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1129
- input_ids = input_ids[:, cache_position]
1130
-
1131
- if attention_mask is not None and position_ids is None:
1132
- # create position_ids on the fly for batch generation
1133
- position_ids = attention_mask.long().cumsum(-1) - 1
1134
- position_ids.masked_fill_(attention_mask == 0, 1)
1135
- if past_key_values:
1136
- position_ids = position_ids[:, -input_ids.shape[1] :]
1137
-
1138
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1139
- if inputs_embeds is not None and cache_position[0] == 0:
1140
- model_inputs = {"inputs_embeds": inputs_embeds}
1141
- else:
1142
- model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1143
-
1144
- model_inputs.update(
1145
- {
1146
- "position_ids": position_ids,
1147
- "cache_position": cache_position,
1148
- "past_key_values": past_key_values,
1149
- "use_cache": use_cache,
1150
- "attention_mask": attention_mask,
1151
- }
1152
- )
1153
- return model_inputs
1154
-
1155
-
1156
- @add_start_docstrings(
1157
- """
1158
- The Cognitivess Model transformer with a sequence classification head on top (linear layer).
1159
-
1160
- [`CognitivessForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1161
- (e.g. GPT-2) do.
1162
-
1163
- Since it does classification on the last token, it requires to know the position of the last token. If a
1164
- `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1165
- no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1166
- padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1167
- each row of the batch).
1168
- """,
1169
- Cognitivess_START_DOCSTRING,
1170
- )
1171
- class CognitivessForSequenceClassification(CognitivessPreTrainedModel):
1172
- def __init__(self, config):
1173
- super().__init__(config)
1174
- self.num_labels = config.num_labels
1175
- self.model = CognitivessModel(config)
1176
- self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1177
-
1178
- # Initialize weights and apply final processing
1179
- self.post_init()
1180
-
1181
- def get_input_embeddings(self):
1182
- return self.model.embed_tokens
1183
-
1184
- def set_input_embeddings(self, value):
1185
- self.model.embed_tokens = value
1186
-
1187
- @add_start_docstrings_to_model_forward(Cognitivess_INPUTS_DOCSTRING)
1188
- def forward(
1189
- self,
1190
- input_ids: torch.LongTensor = None,
1191
- attention_mask: Optional[torch.Tensor] = None,
1192
- position_ids: Optional[torch.LongTensor] = None,
1193
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1194
- inputs_embeds: Optional[torch.FloatTensor] = None,
1195
- labels: Optional[torch.LongTensor] = None,
1196
- use_cache: Optional[bool] = None,
1197
- output_attentions: Optional[bool] = None,
1198
- output_hidden_states: Optional[bool] = None,
1199
- return_dict: Optional[bool] = None,
1200
- ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1201
- r"""
1202
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1203
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1204
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1205
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1206
- """
1207
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1208
-
1209
- transformer_outputs = self.model(
1210
- input_ids,
1211
- attention_mask=attention_mask,
1212
- position_ids=position_ids,
1213
- past_key_values=past_key_values,
1214
- inputs_embeds=inputs_embeds,
1215
- use_cache=use_cache,
1216
- output_attentions=output_attentions,
1217
- output_hidden_states=output_hidden_states,
1218
- return_dict=return_dict,
1219
- )
1220
- hidden_states = transformer_outputs[0]
1221
- logits = self.score(hidden_states)
1222
-
1223
- if input_ids is not None:
1224
- batch_size = input_ids.shape[0]
1225
- else:
1226
- batch_size = inputs_embeds.shape[0]
1227
-
1228
- if self.config.pad_token_id is None and batch_size != 1:
1229
- raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1230
- if self.config.pad_token_id is None:
1231
- sequence_lengths = -1
1232
- else:
1233
- if input_ids is not None:
1234
- # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1235
- sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1236
- sequence_lengths = sequence_lengths % input_ids.shape[-1]
1237
- sequence_lengths = sequence_lengths.to(logits.device)
1238
- else:
1239
- sequence_lengths = -1
1240
-
1241
- pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1242
-
1243
- loss = None
1244
- if labels is not None:
1245
- labels = labels.to(logits.device)
1246
- if self.config.problem_type is None:
1247
- if self.num_labels == 1:
1248
- self.config.problem_type = "regression"
1249
- elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1250
- self.config.problem_type = "single_label_classification"
1251
- else:
1252
- self.config.problem_type = "multi_label_classification"
1253
-
1254
- if self.config.problem_type == "regression":
1255
- loss_fct = MSELoss()
1256
- if self.num_labels == 1:
1257
- loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1258
- else:
1259
- loss = loss_fct(pooled_logits, labels)
1260
- elif self.config.problem_type == "single_label_classification":
1261
- loss_fct = CrossEntropyLoss()
1262
- loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1263
- elif self.config.problem_type == "multi_label_classification":
1264
- loss_fct = BCEWithLogitsLoss()
1265
- loss = loss_fct(pooled_logits, labels)
1266
- if not return_dict:
1267
- output = (pooled_logits,) + transformer_outputs[1:]
1268
- return ((loss,) + output) if loss is not None else output
1269
-
1270
- return SequenceClassifierOutputWithPast(
1271
- loss=loss,
1272
- logits=pooled_logits,
1273
- past_key_values=transformer_outputs.past_key_values,
1274
- hidden_states=transformer_outputs.hidden_states,
1275
- attentions=transformer_outputs.attentions,
1276
- )
1277
-
1278
-
1279
- @add_start_docstrings(
1280
- """
1281
- The Cognitivess Model transformer with a span classification head on top for extractive question-answering tasks like
1282
- SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1283
- """,
1284
- Cognitivess_START_DOCSTRING,
1285
- )
1286
- class CognitivessForQuestionAnswering(CognitivessPreTrainedModel):
1287
- base_model_prefix = "transformer"
1288
-
1289
- # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Cognitivess
1290
- def __init__(self, config):
1291
- super().__init__(config)
1292
- self.transformer = CognitivessModel(config)
1293
- self.qa_outputs = nn.Linear(config.hidden_size, 2)
1294
-
1295
- # Initialize weights and apply final processing
1296
- self.post_init()
1297
-
1298
- def get_input_embeddings(self):
1299
- return self.transformer.embed_tokens
1300
-
1301
- def set_input_embeddings(self, value):
1302
- self.transformer.embed_tokens = value
1303
-
1304
- @add_start_docstrings_to_model_forward(Cognitivess_INPUTS_DOCSTRING)
1305
- def forward(
1306
- self,
1307
- input_ids: Optional[torch.LongTensor] = None,
1308
- attention_mask: Optional[torch.FloatTensor] = None,
1309
- position_ids: Optional[torch.LongTensor] = None,
1310
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1311
- inputs_embeds: Optional[torch.FloatTensor] = None,
1312
- start_positions: Optional[torch.LongTensor] = None,
1313
- end_positions: Optional[torch.LongTensor] = None,
1314
- output_attentions: Optional[bool] = None,
1315
- output_hidden_states: Optional[bool] = None,
1316
- return_dict: Optional[bool] = None,
1317
- ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1318
- r"""
1319
- start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1320
- Labels for position (index) of the start of the labelled span for computing the token classification loss.
1321
- Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1322
- are not taken into account for computing the loss.
1323
- end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1324
- Labels for position (index) of the end of the labelled span for computing the token classification loss.
1325
- Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1326
- are not taken into account for computing the loss.
1327
- """
1328
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1329
-
1330
- outputs = self.transformer(
1331
- input_ids,
1332
- attention_mask=attention_mask,
1333
- position_ids=position_ids,
1334
- past_key_values=past_key_values,
1335
- inputs_embeds=inputs_embeds,
1336
- output_attentions=output_attentions,
1337
- output_hidden_states=output_hidden_states,
1338
- return_dict=return_dict,
1339
- )
1340
-
1341
- sequence_output = outputs[0]
1342
-
1343
- logits = self.qa_outputs(sequence_output)
1344
- start_logits, end_logits = logits.split(1, dim=-1)
1345
- start_logits = start_logits.squeeze(-1).contiguous()
1346
- end_logits = end_logits.squeeze(-1).contiguous()
1347
-
1348
- total_loss = None
1349
- if start_positions is not None and end_positions is not None:
1350
- # If we are on multi-GPU, split add a dimension
1351
- if len(start_positions.size()) > 1:
1352
- start_positions = start_positions.squeeze(-1).to(start_logits.device)
1353
- if len(end_positions.size()) > 1:
1354
- end_positions = end_positions.squeeze(-1).to(end_logits.device)
1355
- # sometimes the start/end positions are outside our model inputs, we ignore these terms
1356
- ignored_index = start_logits.size(1)
1357
- start_positions = start_positions.clamp(0, ignored_index)
1358
- end_positions = end_positions.clamp(0, ignored_index)
1359
-
1360
- loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1361
- start_loss = loss_fct(start_logits, start_positions)
1362
- end_loss = loss_fct(end_logits, end_positions)
1363
- total_loss = (start_loss + end_loss) / 2
1364
-
1365
- if not return_dict:
1366
- output = (start_logits, end_logits) + outputs[2:]
1367
- return ((total_loss,) + output) if total_loss is not None else output
1368
-
1369
- return QuestionAnsweringModelOutput(
1370
- loss=total_loss,
1371
- start_logits=start_logits,
1372
- end_logits=end_logits,
1373
- hidden_states=outputs.hidden_states,
1374
- attentions=outputs.attentions,
1375
- )
1376
-
1377
-
1378
- @add_start_docstrings(
1379
- """
1380
- The Cognitivess Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1381
- output) e.g. for Named-Entity-Recognition (NER) tasks.
1382
- """,
1383
- Cognitivess_START_DOCSTRING,
1384
- )
1385
- class CognitivessForTokenClassification(CognitivessPreTrainedModel):
1386
- def __init__(self, config):
1387
- super().__init__(config)
1388
- self.num_labels = config.num_labels
1389
- self.model = CognitivessModel(config)
1390
- if getattr(config, "classifier_dropout", None) is not None:
1391
- classifier_dropout = config.classifier_dropout
1392
- elif getattr(config, "hidden_dropout", None) is not None:
1393
- classifier_dropout = config.hidden_dropout
1394
- else:
1395
- classifier_dropout = 0.1
1396
- self.dropout = nn.Dropout(classifier_dropout)
1397
- self.score = nn.Linear(config.hidden_size, config.num_labels)
1398
-
1399
- # Initialize weights and apply final processing
1400
- self.post_init()
1401
-
1402
- def get_input_embeddings(self):
1403
- return self.model.embed_tokens
1404
-
1405
- def set_input_embeddings(self, value):
1406
- self.model.embed_tokens = value
1407
-
1408
- @add_start_docstrings_to_model_forward(Cognitivess_INPUTS_DOCSTRING)
1409
- def forward(
1410
- self,
1411
- input_ids: Optional[torch.LongTensor] = None,
1412
- attention_mask: Optional[torch.Tensor] = None,
1413
- position_ids: Optional[torch.LongTensor] = None,
1414
- past_key_values: Optional[List[torch.FloatTensor]] = None,
1415
- inputs_embeds: Optional[torch.FloatTensor] = None,
1416
- labels: Optional[torch.LongTensor] = None,
1417
- use_cache: Optional[bool] = None,
1418
- output_attentions: Optional[bool] = None,
1419
- output_hidden_states: Optional[bool] = None,
1420
- return_dict: Optional[bool] = None,
1421
- ) -> Union[Tuple, TokenClassifierOutput]:
1422
- r"""
1423
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1424
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1425
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1426
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1427
- """
1428
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1429
-
1430
- outputs = self.model(
1431
- input_ids,
1432
- attention_mask=attention_mask,
1433
- position_ids=position_ids,
1434
- past_key_values=past_key_values,
1435
- inputs_embeds=inputs_embeds,
1436
- use_cache=use_cache,
1437
- output_attentions=output_attentions,
1438
- output_hidden_states=output_hidden_states,
1439
- return_dict=return_dict,
1440
- )
1441
- sequence_output = outputs[0]
1442
- sequence_output = self.dropout(sequence_output)
1443
- logits = self.score(sequence_output)
1444
-
1445
- loss = None
1446
- if labels is not None:
1447
- loss_fct = CrossEntropyLoss()
1448
- loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1449
-
1450
- if not return_dict:
1451
- output = (logits,) + outputs[2:]
1452
- return ((loss,) + output) if loss is not None else output
1453
-
1454
- return TokenClassifierOutput(
1455
- loss=loss,
1456
- logits=logits,
1457
- hidden_states=outputs.hidden_states,
1458
- attentions=outputs.attentions,
1459
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cognitivess_model/modeling_cognitivess.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import CrossEntropyLoss
4
+ from transformers.modeling_outputs import (
5
+ CausalLMOutputWithCrossAttentions,
6
+ SequenceClassifierOutput,
7
+ TokenClassifierOutput,
8
+ QuestionAnsweringModelOutput,
9
+ )
10
+ from transformers import LlamaModel, LlamaPreTrainedModel
11
+ from .configuration_cognitivess import CognitivessConfig
12
+
13
+ class CognitivessModel(LlamaModel):
14
+ config_class = CognitivessConfig
15
+
16
+ class CognitivessForCausalLM(LlamaPreTrainedModel):
17
+ config_class = CognitivessConfig
18
+
19
+ def __init__(self, config):
20
+ super().__init__(config)
21
+ self.model = CognitivessModel(config)
22
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
23
+
24
+ self.init_weights()
25
+
26
+ def forward(
27
+ self,
28
+ input_ids=None,
29
+ attention_mask=None,
30
+ position_ids=None,
31
+ head_mask=None,
32
+ inputs_embeds=None,
33
+ labels=None,
34
+ use_cache=None,
35
+ output_attentions=None,
36
+ output_hidden_states=None,
37
+ return_dict=None,
38
+ ):
39
+ outputs = self.model(
40
+ input_ids,
41
+ attention_mask=attention_mask,
42
+ position_ids=position_ids,
43
+ head_mask=head_mask,
44
+ inputs_embeds=inputs_embeds,
45
+ use_cache=use_cache,
46
+ output_attentions=output_attentions,
47
+ output_hidden_states=output_hidden_states,
48
+ return_dict=return_dict,
49
+ )
50
+
51
+ hidden_states = outputs[0]
52
+ lm_logits = self.lm_head(hidden_states)
53
+
54
+ loss = None
55
+ if labels is not None:
56
+ # Shift so that tokens < n predict n
57
+ shift_logits = lm_logits[..., :-1, :].contiguous()
58
+ shift_labels = labels[..., 1:].contiguous()
59
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
60
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
61
+
62
+ if not return_dict:
63
+ output = (lm_logits,) + outputs[1:]
64
+ return ((loss,) + output) if loss is not None else output
65
+
66
+ return CausalLMOutputWithCrossAttentions(
67
+ loss=loss,
68
+ logits=lm_logits,
69
+ past_key_values=outputs.past_key_values,
70
+ hidden_states=outputs.hidden_states,
71
+ attentions=outputs.attentions,
72
+ cross_attentions=outputs.cross_attentions,
73
+ )
74
+
75
+ class CognitivessForSequenceClassification(LlamaPreTrainedModel):
76
+ config_class = CognitivessConfig
77
+
78
+ def __init__(self, config):
79
+ super().__init__(config)
80
+ self.num_labels = config.num_labels
81
+ self.model = CognitivessModel(config)
82
+ self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
83
+
84
+ self.init_weights()
85
+
86
+ def forward(
87
+ self,
88
+ input_ids=None,
89
+ attention_mask=None,
90
+ position_ids=None,
91
+ head_mask=None,
92
+ inputs_embeds=None,
93
+ labels=None,
94
+ output_attentions=None,
95
+ output_hidden_states=None,
96
+ return_dict=None,
97
+ ):
98
+ outputs = self.model(
99
+ input_ids,
100
+ attention_mask=attention_mask,
101
+ position_ids=position_ids,
102
+ head_mask=head_mask,
103
+ inputs_embeds=inputs_embeds,
104
+ output_attentions=output_attentions,
105
+ output_hidden_states=output_hidden_states,
106
+ return_dict=return_dict,
107
+ )
108
+
109
+ hidden_states = outputs[0]
110
+ logits = self.score(hidden_states[:, 0, :])
111
+
112
+ loss = None
113
+ if labels is not None:
114
+ if self.num_labels == 1:
115
+ loss_fct = nn.MSELoss()
116
+ loss = loss_fct(logits.view(-1), labels.view(-1))
117
+ else:
118
+ loss_fct = CrossEntropyLoss()
119
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
120
+
121
+ if not return_dict:
122
+ output = (logits,) + outputs[1:]
123
+ return ((loss,) + output) if loss is not None else output
124
+
125
+ return SequenceClassifierOutput(
126
+ loss=loss,
127
+ logits=logits,
128
+ hidden_states=outputs.hidden_states,
129
+ attentions=outputs.attentions,
130
+ )
131
+
132
+ class CognitivessForTokenClassification(LlamaPreTrainedModel):
133
+ config_class = CognitivessConfig
134
+
135
+ def __init__(self, config):
136
+ super().__init__(config)
137
+ self.num_labels = config.num_labels
138
+ self.model = CognitivessModel(config)
139
+ self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
140
+
141
+ self.init_weights()
142
+
143
+ def forward(
144
+ self,
145
+ input_ids=None,
146
+ attention_mask=None,
147
+ position_ids=None,
148
+ head_mask=None,
149
+ inputs_embeds=None,
150
+ labels=None,
151
+ output_attentions=None,
152
+ output_hidden_states=None,
153
+ return_dict=None,
154
+ ):
155
+ outputs = self.model(
156
+ input_ids,
157
+ attention_mask=attention_mask,
158
+ position_ids=position_ids,
159
+ head_mask=head_mask,
160
+ inputs_embeds=inputs_embeds,
161
+ output_attentions=output_attentions,
162
+ output_hidden_states=output_hidden_states,
163
+ return_dict=return_dict,
164
+ )
165
+
166
+ hidden_states = outputs[0]
167
+ logits = self.score(hidden_states)
168
+
169
+ loss = None
170
+ if labels is not None:
171
+ loss_fct = CrossEntropyLoss()
172
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
173
+
174
+ if not return_dict:
175
+ output = (logits,) + outputs[1:]
176
+ return ((loss,) + output) if loss is not None else output
177
+
178
+ return TokenClassifierOutput(
179
+ loss=loss,
180
+ logits=logits,
181
+ hidden_states=outputs.hidden_states,
182
+ attentions=outputs.attentions,
183
+ )
184
+
185
+ class CognitivessForQuestionAnswering(LlamaPreTrainedModel):
186
+ config_class = CognitivessConfig
187
+
188
+ def __init__(self, config):
189
+ super().__init__(config)
190
+ self.model = CognitivessModel(config)
191
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
192
+
193
+ self.init_weights()
194
+
195
+ def forward(
196
+ self,
197
+ input_ids=None,
198
+ attention_mask=None,
199
+ position_ids=None,
200
+ head_mask=None,
201
+ inputs_embeds=None,
202
+ start_positions=None,
203
+ end_positions=None,
204
+ output_attentions=None,
205
+ output_hidden_states=None,
206
+ return_dict=None,
207
+ ):
208
+ outputs = self.model(
209
+ input_ids,
210
+ attention_mask=attention_mask,
211
+ position_ids=position_ids,
212
+ head_mask=head_mask,
213
+ inputs_embeds=inputs_embeds,
214
+ output_attentions=output_attentions,
215
+ output_hidden_states=output_hidden_states,
216
+ return_dict=return_dict,
217
+ )
218
+
219
+ sequence_output = outputs[0]
220
+ logits = self.qa_outputs(sequence_output)
221
+ start_logits, end_logits = logits.split(1, dim=-1)
222
+ start_logits = start_logits.squeeze(-1).contiguous()
223
+ end_logits = end_logits.squeeze(-1).contiguous()
224
+
225
+ loss = None
226
+ if start_positions is not None and end_positions is not None:
227
+ if len(start_positions.size()) > 1:
228
+ start_positions = start_positions.squeeze(-1)
229
+ if len(end_positions.size()) > 1:
230
+ end_positions = end_positions.squeeze(-1)
231
+ ignored_index = start_logits.size(1)
232
+ start_positions.clamp_(0, ignored_index)
233
+ end_positions.clamp_(0, ignored_index)
234
+
235
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
236
+ start_loss = loss_fct(start_logits, start_positions)
237
+ end_loss = loss_fct(end_logits, end_positions)
238
+ loss = (start_loss + end_loss) / 2
239
+
240
+ if not return_dict:
241
+ output = (start_logits, end_logits) + outputs[1:]
242
+ return ((loss,) + output) if loss is not None else output
243
+
244
+ return QuestionAnsweringModelOutput(
245
+ loss=loss,
246
+ start_logits=start_logits,
247
+ end_logits=end_logits,
248
+ hidden_states=outputs.hidden_states,
249
+ attentions=outputs.attentions,
250
+ )