dad1909 commited on
Commit
6837b9b
1 Parent(s): 86bad45

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_cyberai.py +106 -0
  2. modeling_cyberai.py +1845 -0
configuration_cyberai.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ logger = logging.get_logger(__name__)
5
+
6
+ CYBERAI_PRETRAINED_CONFIG_ARCHIVE_MAP = {
7
+ "CyberCapstone/CyberAI": "https://huggingface.co/CyberCapstone/CyberAI/blob/main/config.json"
8
+ }
9
+
10
+ class CyberAIConfig(PretrainedConfig):
11
+ r"""
12
+ This is the configuration class to store the configuration of a [`CyberAIModel`]. It is used to instantiate a CyberAI
13
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
14
+ defaults will yield a similar configuration to that of the CyberCapstone/CyberAI architecture.
15
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
16
+ documentation from [`PretrainedConfig`] for more information.
17
+
18
+ Args:
19
+ vocab_size (`int`, *optional*, defaults to 65024):
20
+ Vocabulary size of the CyberAI model. Defines the number of different tokens that can be represented by the
21
+ `inputs_ids` passed when calling [`CyberAIModel`].
22
+ hidden_size (`int`, *optional*, defaults to 4096):
23
+ Dimension of the hidden representations.
24
+ num_hidden_layers (`int`, *optional*, defaults to 32):
25
+ Number of hidden layers in the Transformer decoder.
26
+ num_attention_heads (`int`, *optional*, defaults to 64):
27
+ Number of attention heads for each attention layer in the Transformer encoder.
28
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
29
+ The epsilon used by the layer normalization layers.
30
+ initializer_range (`float`, *optional*, defaults to 0.02):
31
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
32
+ use_cache (`bool`, *optional*, defaults to `True`):
33
+ Whether the model should return the last key/values attentions (not used by all models). Only relevant if
34
+ `config.is_decoder=True`.
35
+ hidden_dropout (`float`, *optional*, defaults to 0.1):
36
+ The dropout probability for MLP layers.
37
+ attention_dropout (`float`, *optional*, defaults to 0.1):
38
+ The dropout probability for attention layers.
39
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
40
+ The maximum sequence length that this model might ever be used with.
41
+ pad_token_id (`int`, *optional*, defaults to 0):
42
+ Padding token id.
43
+ bos_token_id (`int`, *optional*, defaults to 1):
44
+ Beginning of stream token id.
45
+ eos_token_id (`int`, *optional*, defaults to 2):
46
+ End of stream token id.
47
+ attention_bias (`bool`, defaults to `True`, *optional*):
48
+ Whether to use a bias in the query, key, value, and output projection layers during self-attention.
49
+ Example:
50
+ ```python
51
+ >>> from transformers import CyberAIModel, CyberAIConfig
52
+ >>> # Initializing a CyberCapstone/CyberAI configuration
53
+ >>> configuration = CyberAIConfig()
54
+ >>> # Initializing a model from the configuration
55
+ >>> model = CyberAIModel(configuration)
56
+ >>> # Accessing the model configuration
57
+ >>> configuration = model.config
58
+ ```"""
59
+
60
+ model_type = "cyberai"
61
+ keys_to_ignore_at_inference = ["past_key_values"]
62
+
63
+ def __init__(
64
+ self,
65
+ vocab_size=65024,
66
+ hidden_size=4096,
67
+ num_hidden_layers=32,
68
+ num_attention_heads=64,
69
+ layer_norm_epsilon=1e-5,
70
+ initializer_range=0.02,
71
+ use_cache=True,
72
+ hidden_dropout=0.1,
73
+ attention_dropout=0.1,
74
+ max_position_embeddings=2048,
75
+ pad_token_id=0,
76
+ bos_token_id=1,
77
+ eos_token_id=2,
78
+ attention_bias=True,
79
+ **kwargs,
80
+ ):
81
+ self.vocab_size = vocab_size
82
+ self.hidden_size = hidden_size
83
+ self.num_hidden_layers = num_hidden_layers
84
+ self.num_attention_heads = num_attention_heads
85
+ self.layer_norm_epsilon = layer_norm_epsilon
86
+ self.initializer_range = initializer_range
87
+ self.use_cache = use_cache
88
+ self.hidden_dropout = hidden_dropout
89
+ self.attention_dropout = attention_dropout
90
+ self.max_position_embeddings = max_position_embeddings
91
+ self.pad_token_id = pad_token_id
92
+ self.bos_token_id = bos_token_id
93
+ self.eos_token_id = eos_token_id
94
+ self.attention_bias = attention_bias
95
+
96
+ super().__init__(
97
+ pad_token_id=pad_token_id,
98
+ bos_token_id=bos_token_id,
99
+ eos_token_id=eos_token_id,
100
+ **kwargs,
101
+ )
102
+
103
+ # Example usage
104
+ if __name__ == "__main__":
105
+ config = CyberAIConfig()
106
+ print(config)
modeling_cyberai.py ADDED
@@ -0,0 +1,1845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch CyberAI model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ )
38
+ from transformers.modeling_outputs import (
39
+ BaseModelOutputWithPast,
40
+ CausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+ from .configuration_cyberai import CyberAIConfig
58
+ import torch.distributed as dist
59
+ import numpy as np
60
+
61
+ if is_flash_attn_2_available():
62
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
64
+
65
+
66
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
67
+ # It means that the function will not be traced through and simply appear as a node in the graph.
68
+ if is_torch_fx_available():
69
+ if not is_torch_greater_or_equal_than_1_13:
70
+ import torch.fx
71
+
72
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
73
+
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+
78
+ _CONFIG_FOR_DOC = "CyberAIConfig"
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+ class CyberAIRMSNorm(nn.Module):
94
+ def __init__(self, hidden_size, eps=1e-6):
95
+ super().__init__()
96
+ self.weight = nn.Parameter(torch.ones(hidden_size))
97
+ self.variance_epsilon = eps
98
+
99
+ def forward(self, hidden_states):
100
+ input_dtype = hidden_states.dtype
101
+ hidden_states = hidden_states.to(torch.float32)
102
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
103
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
104
+ return self.weight * hidden_states.to(input_dtype)
105
+
106
+ ALL_LAYERNORM_LAYERS.append(CyberAIRMSNorm)
107
+
108
+ class CyberAIRotaryEmbedding(nn.Module):
109
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
110
+ super().__init__()
111
+
112
+ self.dim = dim
113
+ self.max_position_embeddings = max_position_embeddings
114
+ self.base = base
115
+ inv_freq = 1.0 / (
116
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
117
+ )
118
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
119
+
120
+ # Build here to make `torch.jit.trace` work.
121
+ self._set_cos_sin_cache(
122
+ seq_len=max_position_embeddings,
123
+ device=self.inv_freq.device,
124
+ dtype=torch.get_default_dtype(),
125
+ )
126
+ self.max_seq_len_cached = None
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(
131
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
132
+ )
133
+
134
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
135
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
138
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
139
+
140
+ def forward(self, x, seq_len=None):
141
+ # x: [bs, num_attention_heads, seq_len, head_size]
142
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
143
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
144
+
145
+ return (
146
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
147
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
148
+ )
149
+
150
+ class CyberAILinearScalingRotaryEmbedding(CyberAIRotaryEmbedding):
151
+ def __init__(
152
+ self,
153
+ dim,
154
+ max_position_embeddings=2048,
155
+ base=10000,
156
+ device=None,
157
+ scaling_factor=1.0,
158
+ ):
159
+ self.scaling_factor = scaling_factor
160
+ super().__init__(dim, max_position_embeddings, base, device)
161
+
162
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
163
+ self.max_seq_len_cached = seq_len
164
+ t = torch.arange(
165
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
166
+ )
167
+ t = t / self.scaling_factor
168
+
169
+ freqs = torch.outer(t, self.inv_freq)
170
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
171
+ emb = torch.cat((freqs, freqs), dim=-1)
172
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
173
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
174
+
175
+ class CyberAIDynamicNTKScalingRotaryEmbedding(CyberAIRotaryEmbedding):
176
+ def __init__(
177
+ self,
178
+ dim,
179
+ max_position_embeddings=2048,
180
+ base=10000,
181
+ device=None,
182
+ scaling_factor=1.0,
183
+ ):
184
+ self.scaling_factor = scaling_factor
185
+ super().__init__(dim, max_position_embeddings, base, device)
186
+
187
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
188
+ self.max_seq_len_cached = seq_len
189
+
190
+ if seq_len > self.max_position_embeddings:
191
+ base = self.base * (
192
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
193
+ - (self.scaling_factor - 1)
194
+ ) ** (self.dim / (self.dim - 2))
195
+ inv_freq = 1.0 / (
196
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
197
+ )
198
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
199
+
200
+ t = torch.arange(
201
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
202
+ )
203
+
204
+ freqs = torch.outer(t, self.inv_freq)
205
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
206
+ emb = torch.cat((freqs, freqs), dim=-1)
207
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
208
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
209
+
210
+ def yarn_find_correction_dim(
211
+ num_rotations, dim, base=10000, max_position_embeddings=2048
212
+ ):
213
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
214
+ 2 * math.log(base)
215
+ )
216
+
217
+
218
+ # Find dim range bounds based on rotations
219
+ def yarn_find_correction_range(
220
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
221
+ ):
222
+ low = math.floor(
223
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
224
+ )
225
+ high = math.ceil(
226
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
227
+ )
228
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
229
+
230
+
231
+ def yarn_get_mscale(scale=1, mscale=1):
232
+ if scale <= 1:
233
+ return 1.0
234
+ return 0.1 * mscale * math.log(scale) + 1.0
235
+
236
+
237
+ def yarn_linear_ramp_mask(min, max, dim):
238
+ if min == max:
239
+ max += 0.001 # Prevent singularity
240
+
241
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
242
+ ramp_func = torch.clamp(linear_func, 0, 1)
243
+ return ramp_func
244
+
245
+ class CyberAIYarnRotaryEmbedding(CyberAIRotaryEmbedding):
246
+
247
+ def __init__(
248
+ self,
249
+ dim,
250
+ max_position_embeddings=2048,
251
+ base=10000,
252
+ device=None,
253
+ scaling_factor=1.0,
254
+ original_max_position_embeddings=4096,
255
+ beta_fast=32,
256
+ beta_slow=1,
257
+ mscale=1,
258
+ mscale_all_dim=0,
259
+ ):
260
+ self.scaling_factor = scaling_factor
261
+ self.original_max_position_embeddings = original_max_position_embeddings
262
+ self.beta_fast = beta_fast
263
+ self.beta_slow = beta_slow
264
+ self.mscale = mscale
265
+ self.mscale_all_dim = mscale_all_dim
266
+ super().__init__(dim, max_position_embeddings, base, device)
267
+
268
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
269
+ self.max_seq_len_cached = seq_len
270
+ dim = self.dim
271
+
272
+ freq_extra = 1.0 / (
273
+ self.base
274
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
275
+ )
276
+ freq_inter = 1.0 / (
277
+ self.scaling_factor
278
+ * self.base
279
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
280
+ )
281
+
282
+ low, high = yarn_find_correction_range(
283
+ self.beta_fast,
284
+ self.beta_slow,
285
+ dim,
286
+ self.base,
287
+ self.original_max_position_embeddings,
288
+ )
289
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
290
+ device=device, dtype=torch.float32
291
+ )
292
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
293
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
294
+
295
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
296
+
297
+ freqs = torch.outer(t, inv_freq)
298
+
299
+ _mscale = float(
300
+ yarn_get_mscale(self.scaling_factor, self.mscale)
301
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
302
+ )
303
+
304
+ emb = torch.cat((freqs, freqs), dim=-1)
305
+ self.register_buffer(
306
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
307
+ )
308
+ self.register_buffer(
309
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
310
+ )
311
+
312
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
313
+ def rotate_half(x):
314
+ """Rotates half the hidden dims of the input."""
315
+ x1 = x[..., : x.shape[-1] // 2]
316
+ x2 = x[..., x.shape[-1] // 2 :]
317
+ return torch.cat((-x2, x1), dim=-1)
318
+
319
+
320
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
321
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
322
+ """Applies Rotary Position Embedding to the query and key tensors.
323
+ Args:
324
+ q (`torch.Tensor`): The query tensor.
325
+ k (`torch.Tensor`): The key tensor.
326
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
327
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
328
+ position_ids (`torch.Tensor`):
329
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
330
+ used to pass offsetted position ids when working with a KV-cache.
331
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
332
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
333
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
334
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
335
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
336
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
337
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
338
+ Returns:
339
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
340
+ """
341
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
342
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
343
+
344
+ b, h, s, d = q.shape
345
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
346
+
347
+ b, h, s, d = k.shape
348
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
349
+
350
+ q_embed = (q * cos) + (rotate_half(q) * sin)
351
+ k_embed = (k * cos) + (rotate_half(k) * sin)
352
+ return q_embed, k_embed
353
+
354
+ class CyberAIVMLP(nn.Module):
355
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
356
+ super().__init__()
357
+ self.config = config
358
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
359
+ self.intermediate_size = (
360
+ config.intermediate_size if intermediate_size is None else intermediate_size
361
+ )
362
+
363
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
364
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
365
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
366
+ self.act_fn = ACT2FN[config.hidden_act]
367
+
368
+ def forward(self, x):
369
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
370
+ return down_proj
371
+
372
+ class MoEGate(nn.Module):
373
+ def __init__(self, config):
374
+ super().__init__()
375
+ self.config = config
376
+ self.top_k = config.num_experts_per_tok
377
+ self.n_routed_experts = config.n_routed_experts
378
+ self.routed_scaling_factor = config.routed_scaling_factor
379
+ self.scoring_func = config.scoring_func
380
+ self.alpha = config.aux_loss_alpha
381
+ self.seq_aux = config.seq_aux
382
+ self.topk_method = config.topk_method
383
+ self.n_group = config.n_group
384
+ self.topk_group = config.topk_group
385
+
386
+ # topk selection algorithm
387
+ self.norm_topk_prob = config.norm_topk_prob
388
+ self.gating_dim = config.hidden_size
389
+ self.weight = nn.Parameter(
390
+ torch.empty((self.n_routed_experts, self.gating_dim))
391
+ )
392
+ self.reset_parameters()
393
+
394
+ def reset_parameters(self) -> None:
395
+ import torch.nn.init as init
396
+
397
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
398
+
399
+ def forward(self, hidden_states):
400
+ bsz, seq_len, h = hidden_states.shape
401
+ ### compute gating score
402
+ hidden_states = hidden_states.view(-1, h)
403
+ logits = F.linear(
404
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
405
+ )
406
+ if self.scoring_func == "softmax":
407
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
408
+ else:
409
+ raise NotImplementedError(
410
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
411
+ )
412
+
413
+ ### select top-k experts
414
+ if self.topk_method == "gready":
415
+ topk_weight, topk_idx = torch.topk(
416
+ scores, k=self.top_k, dim=-1, sorted=False
417
+ )
418
+ elif self.topk_method == "group_limited_greedy":
419
+ group_scores = (
420
+ scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
421
+ ) # [n, n_group]
422
+ group_idx = torch.topk(
423
+ group_scores, k=self.topk_group, dim=-1, sorted=False
424
+ )[
425
+ 1
426
+ ] # [n, top_k_group]
427
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
428
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
429
+ score_mask = (
430
+ group_mask.unsqueeze(-1)
431
+ .expand(
432
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
433
+ )
434
+ .reshape(bsz * seq_len, -1)
435
+ ) # [n, e]
436
+ tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
437
+ topk_weight, topk_idx = torch.topk(
438
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
439
+ )
440
+
441
+ ### norm gate to sum 1
442
+ if self.top_k > 1 and self.norm_topk_prob:
443
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
444
+ topk_weight = topk_weight / denominator
445
+ else:
446
+ topk_weight = topk_weight * self.routed_scaling_factor
447
+ ### expert-level computation auxiliary loss
448
+ if self.training and self.alpha > 0.0:
449
+ scores_for_aux = scores
450
+ aux_topk = self.top_k
451
+ # always compute aux loss based on the naive greedy topk method
452
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
453
+ if self.seq_aux:
454
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
455
+ ce = torch.zeros(
456
+ bsz, self.n_routed_experts, device=hidden_states.device
457
+ )
458
+ ce.scatter_add_(
459
+ 1,
460
+ topk_idx_for_aux_loss,
461
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
462
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
463
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
464
+ dim=1
465
+ ).mean() * self.alpha
466
+ else:
467
+ mask_ce = F.one_hot(
468
+ topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
469
+ )
470
+ ce = mask_ce.float().mean(0)
471
+ Pi = scores_for_aux.mean(0)
472
+ fi = ce * self.n_routed_experts
473
+ aux_loss = (Pi * fi).sum() * self.alpha
474
+ else:
475
+ aux_loss = None
476
+ return topk_idx, topk_weight, aux_loss
477
+
478
+ class AddAuxiliaryLoss(torch.autograd.Function):
479
+ """
480
+ The trick function of adding auxiliary (aux) loss,
481
+ which includes the gradient of the aux loss during backpropagation.
482
+ """
483
+
484
+ @staticmethod
485
+ def forward(ctx, x, loss):
486
+ assert loss.numel() == 1
487
+ ctx.dtype = loss.dtype
488
+ ctx.required_aux_loss = loss.requires_grad
489
+ return x
490
+
491
+ @staticmethod
492
+ def backward(ctx, grad_output):
493
+ grad_loss = None
494
+ if ctx.required_aux_loss:
495
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
496
+ return grad_output, grad_loss
497
+
498
+ class CyberAIVMoE(nn.Module):
499
+ """
500
+ A mixed expert module containing shared experts.
501
+ """
502
+
503
+ def __init__(self, config):
504
+ super().__init__()
505
+ self.config = config
506
+ self.num_experts_per_tok = config.num_experts_per_tok
507
+
508
+ if hasattr(config, "ep_size") and config.ep_size > 1:
509
+ assert config.ep_size == dist.get_world_size()
510
+ self.ep_size = config.ep_size
511
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
512
+ self.ep_rank = dist.get_rank()
513
+ self.experts = nn.ModuleList(
514
+ [
515
+ (
516
+ CyberAIV2MLP(
517
+ config, intermediate_size=config.moe_intermediate_size
518
+ )
519
+ if i >= self.ep_rank * self.experts_per_rank
520
+ and i < (self.ep_rank + 1) * self.experts_per_rank
521
+ else None
522
+ )
523
+ for i in range(config.n_routed_experts)
524
+ ]
525
+ )
526
+ else:
527
+ self.ep_size = 1
528
+ self.experts_per_rank = config.n_routed_experts
529
+ self.ep_rank = 0
530
+ self.experts = nn.ModuleList(
531
+ [
532
+ CyberAIV2MLP(config, intermediate_size=config.moe_intermediate_size)
533
+ for i in range(config.n_routed_experts)
534
+ ]
535
+ )
536
+ self.gate = MoEGate(config)
537
+ if config.n_shared_experts is not None:
538
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
539
+ self.shared_experts = CyberAIV2MLP(
540
+ config=config, intermediate_size=intermediate_size
541
+ )
542
+
543
+ def forward(self, hidden_states):
544
+ identity = hidden_states
545
+ orig_shape = hidden_states.shape
546
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
547
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
548
+ flat_topk_idx = topk_idx.view(-1)
549
+ if self.training:
550
+ hidden_states = hidden_states.repeat_interleave(
551
+ self.num_experts_per_tok, dim=0
552
+ )
553
+ y = torch.empty_like(hidden_states)
554
+ for i, expert in enumerate(self.experts):
555
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
556
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
557
+ y = y.view(*orig_shape)
558
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
559
+ else:
560
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
561
+ if self.config.n_shared_experts is not None:
562
+ y = y + self.shared_experts(identity)
563
+ return y
564
+
565
+ @torch.no_grad()
566
+ def moe_infer(self, x, topk_ids, topk_weight):
567
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
568
+ cnts.scatter_(1, topk_ids, 1)
569
+ tokens_per_expert = cnts.sum(dim=0)
570
+ idxs = topk_ids.view(-1).argsort()
571
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
572
+ sorted_tokens_shape = sorted_tokens.shape
573
+ if self.ep_size > 1:
574
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
575
+ tokens_per_expert_group = tokens_per_expert.new_empty(
576
+ tokens_per_expert.shape[0]
577
+ )
578
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
579
+ output_splits = (
580
+ tokens_per_expert_group.view(self.ep_size, -1)
581
+ .sum(1)
582
+ .cpu()
583
+ .numpy()
584
+ .tolist()
585
+ )
586
+ gathered_tokens = sorted_tokens.new_empty(
587
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
588
+ )
589
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
590
+ dist.all_to_all(
591
+ list(gathered_tokens.split(output_splits)),
592
+ list(sorted_tokens.split(input_split_sizes)),
593
+ )
594
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
595
+ self.ep_size, self.experts_per_rank
596
+ ).sum(dim=0)
597
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
598
+ s = 0
599
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
600
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
601
+ s += k
602
+ gatherd_idxs = gatherd_idxs.argsort()
603
+ sorted_tokens = gathered_tokens[gatherd_idxs]
604
+ tokens_per_expert = tokens_per_expert_post_gather
605
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
606
+
607
+ outputs = []
608
+ start_idx = 0
609
+ for i, num_tokens in enumerate(tokens_per_expert):
610
+ end_idx = start_idx + num_tokens
611
+ if num_tokens == 0:
612
+ continue
613
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
614
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
615
+ expert_out = expert(tokens_for_this_expert)
616
+ outputs.append(expert_out)
617
+ start_idx = end_idx
618
+
619
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
620
+ if self.ep_size > 1:
621
+ new_x = torch.empty_like(outs)
622
+ new_x[gatherd_idxs] = outs
623
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
624
+ dist.all_to_all(
625
+ list(gathered_tokens.split(input_split_sizes)),
626
+ list(new_x.split(output_splits)),
627
+ )
628
+ outs = gathered_tokens
629
+
630
+ new_x = torch.empty_like(outs)
631
+ new_x[idxs] = outs
632
+ final_out = (
633
+ new_x.view(*topk_ids.shape, -1)
634
+ .type(topk_weight.dtype)
635
+ .mul_(topk_weight.unsqueeze(dim=-1))
636
+ .sum(dim=1)
637
+ .type(new_x.dtype)
638
+ )
639
+ return final_out
640
+
641
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
642
+ """
643
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
644
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
645
+ """
646
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
647
+ if n_rep == 1:
648
+ return hidden_states
649
+ hidden_states = hidden_states[:, :, None, :, :].expand(
650
+ batch, num_key_value_heads, n_rep, slen, head_dim
651
+ )
652
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
653
+
654
+ class CyberAIAttention(nn.Module):
655
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
656
+
657
+ def __init__(self, config: CyberAIConfig, layer_idx: Optional[int] = None):
658
+ super().__init__()
659
+ self.config = config
660
+ self.layer_idx = layer_idx
661
+ if layer_idx is None:
662
+ logger.warning_once(
663
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
664
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
665
+ "when creating this class."
666
+ )
667
+
668
+ self.attention_dropout = config.attention_dropout
669
+ self.hidden_size = config.hidden_size
670
+ self.num_heads = config.num_attention_heads
671
+
672
+ self.max_position_embeddings = config.max_position_embeddings
673
+ self.rope_theta = config.rope_theta
674
+ self.q_lora_rank = config.q_lora_rank
675
+ self.qk_rope_head_dim = config.qk_rope_head_dim
676
+ self.kv_lora_rank = config.kv_lora_rank
677
+ self.v_head_dim = config.v_head_dim
678
+ self.qk_nope_head_dim = config.qk_nope_head_dim
679
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
680
+
681
+ self.is_causal = True
682
+
683
+ self.q_a_proj = nn.Linear(
684
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
685
+ )
686
+ self.q_a_layernorm = CyberAIRMSNorm(config.q_lora_rank)
687
+ self.q_b_proj = nn.Linear(
688
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
689
+ )
690
+
691
+ self.kv_a_proj_with_mqa = nn.Linear(
692
+ self.hidden_size,
693
+ config.kv_lora_rank + config.qk_rope_head_dim,
694
+ bias=config.attention_bias,
695
+ )
696
+ self.kv_a_layernorm = CyberAIRMSNorm(config.kv_lora_rank)
697
+ self.kv_b_proj = nn.Linear(
698
+ config.kv_lora_rank,
699
+ self.num_heads
700
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
701
+ bias=False,
702
+ )
703
+
704
+ self.o_proj = nn.Linear(
705
+ self.num_heads * self.v_head_dim,
706
+ self.hidden_size,
707
+ bias=config.attention_bias,
708
+ )
709
+ self._init_rope()
710
+
711
+ self.softmax_scale = self.q_head_dim ** (-0.5)
712
+ if self.config.rope_scaling is not None:
713
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
714
+ scaling_factor = self.config.rope_scaling["factor"]
715
+ if mscale_all_dim:
716
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
717
+ self.softmax_scale = self.softmax_scale * mscale * mscale
718
+
719
+ def _init_rope(self):
720
+ if self.config.rope_scaling is None:
721
+ self.rotary_emb = CyberAIRotaryEmbedding(
722
+ self.qk_rope_head_dim,
723
+ max_position_embeddings=self.max_position_embeddings,
724
+ base=self.rope_theta,
725
+ )
726
+ else:
727
+ scaling_type = self.config.rope_scaling["type"]
728
+ scaling_factor = self.config.rope_scaling["factor"]
729
+ if scaling_type == "linear":
730
+ self.rotary_emb = CyberAILinearScalingRotaryEmbedding(
731
+ self.qk_rope_head_dim,
732
+ max_position_embeddings=self.max_position_embeddings,
733
+ scaling_factor=scaling_factor,
734
+ base=self.rope_theta,
735
+ )
736
+ elif scaling_type == "dynamic":
737
+ self.rotary_emb = CyberAIDynamicNTKScalingRotaryEmbedding(
738
+ self.qk_rope_head_dim,
739
+ max_position_embeddings=self.max_position_embeddings,
740
+ scaling_factor=scaling_factor,
741
+ base=self.rope_theta,
742
+ )
743
+ elif scaling_type == "yarn":
744
+ kwargs = {
745
+ key: self.config.rope_scaling[key]
746
+ for key in [
747
+ "original_max_position_embeddings",
748
+ "beta_fast",
749
+ "beta_slow",
750
+ "mscale",
751
+ "mscale_all_dim",
752
+ ]
753
+ if key in self.config.rope_scaling
754
+ }
755
+ self.rotary_emb = CyberAIYarnRotaryEmbedding(
756
+ self.qk_rope_head_dim,
757
+ max_position_embeddings=self.max_position_embeddings,
758
+ scaling_factor=scaling_factor,
759
+ base=self.rope_theta,
760
+ **kwargs,
761
+ )
762
+ else:
763
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
764
+
765
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
766
+ return (
767
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
768
+ .transpose(1, 2)
769
+ .contiguous()
770
+ )
771
+
772
+ def forward(
773
+ self,
774
+ hidden_states: torch.Tensor,
775
+ attention_mask: Optional[torch.Tensor] = None,
776
+ position_ids: Optional[torch.LongTensor] = None,
777
+ past_key_value: Optional[Cache] = None,
778
+ output_attentions: bool = False,
779
+ use_cache: bool = False,
780
+ **kwargs,
781
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
782
+ if "padding_mask" in kwargs:
783
+ warnings.warn(
784
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
785
+ )
786
+ bsz, q_len, _ = hidden_states.size()
787
+
788
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
789
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
790
+ q_nope, q_pe = torch.split(
791
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
792
+ )
793
+
794
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
795
+ compressed_kv, k_pe = torch.split(
796
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
797
+ )
798
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
799
+ kv = (
800
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
801
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
802
+ .transpose(1, 2)
803
+ )
804
+
805
+ k_nope, value_states = torch.split(
806
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
807
+ )
808
+ kv_seq_len = value_states.shape[-2]
809
+ if past_key_value is not None:
810
+ if self.layer_idx is None:
811
+ raise ValueError(
812
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
813
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
814
+ "with a layer index."
815
+ )
816
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
817
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
818
+
819
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
820
+
821
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
822
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
823
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
824
+
825
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
826
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
827
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
828
+ if past_key_value is not None:
829
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
830
+ key_states, value_states = past_key_value.update(
831
+ key_states, value_states, self.layer_idx, cache_kwargs
832
+ )
833
+
834
+ attn_weights = (
835
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
836
+ )
837
+
838
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
839
+ raise ValueError(
840
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
841
+ f" {attn_weights.size()}"
842
+ )
843
+ assert attention_mask is not None
844
+ if attention_mask is not None:
845
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
846
+ raise ValueError(
847
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
848
+ )
849
+ attn_weights = attn_weights + attention_mask
850
+
851
+ # upcast attention to fp32
852
+ attn_weights = nn.functional.softmax(
853
+ attn_weights, dim=-1, dtype=torch.float32
854
+ ).to(query_states.dtype)
855
+ attn_weights = nn.functional.dropout(
856
+ attn_weights, p=self.attention_dropout, training=self.training
857
+ )
858
+ attn_output = torch.matmul(attn_weights, value_states)
859
+
860
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
861
+ raise ValueError(
862
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
863
+ f" {attn_output.size()}"
864
+ )
865
+
866
+ attn_output = attn_output.transpose(1, 2).contiguous()
867
+
868
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
869
+
870
+ attn_output = self.o_proj(attn_output)
871
+
872
+ if not output_attentions:
873
+ attn_weights = None
874
+
875
+ return attn_output, attn_weights, past_key_value
876
+
877
+ class CyberAIFlashAttention2(CyberAIAttention):
878
+ """
879
+ DeepseekV2 flash attention module. This module inherits from `CyberAIV2Attention` as the weights of the module stays
880
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
881
+ flash attention and deal with padding tokens in case the input contains any of them.
882
+ """
883
+
884
+ def __init__(self, *args, **kwargs):
885
+ super().__init__(*args, **kwargs)
886
+
887
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
888
+ # 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.
889
+ # 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).
890
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
891
+
892
+ def forward(
893
+ self,
894
+ hidden_states: torch.Tensor,
895
+ attention_mask: Optional[torch.LongTensor] = None,
896
+ position_ids: Optional[torch.LongTensor] = None,
897
+ past_key_value: Optional[Cache] = None,
898
+ output_attentions: bool = False,
899
+ use_cache: bool = False,
900
+ **kwargs,
901
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
902
+ # DeepseekV2FlashAttention2 attention does not support output_attentions
903
+ if "padding_mask" in kwargs:
904
+ warnings.warn(
905
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
906
+ )
907
+
908
+ # overwrite attention_mask with padding_mask
909
+ attention_mask = kwargs.pop("padding_mask")
910
+
911
+ output_attentions = False
912
+
913
+ bsz, q_len, _ = hidden_states.size()
914
+
915
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
916
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
917
+ q_nope, q_pe = torch.split(
918
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
919
+ )
920
+
921
+ # Flash attention requires the input to have the shape
922
+ # batch_size x seq_length x head_dim x hidden_dim
923
+ # therefore we just need to keep the original shape
924
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
925
+ compressed_kv, k_pe = torch.split(
926
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
927
+ )
928
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
929
+ kv = (
930
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
931
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
932
+ .transpose(1, 2)
933
+ )
934
+
935
+ k_nope, value_states = torch.split(
936
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
937
+ )
938
+ kv_seq_len = value_states.shape[-2]
939
+
940
+ kv_seq_len = value_states.shape[-2]
941
+ if past_key_value is not None:
942
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
943
+
944
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
945
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
946
+
947
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
948
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
949
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
950
+
951
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
952
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
953
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
954
+
955
+ if self.q_head_dim != self.v_head_dim:
956
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
957
+
958
+ if past_key_value is not None:
959
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
960
+ key_states, value_states = past_key_value.update(
961
+ key_states, value_states, self.layer_idx, cache_kwargs
962
+ )
963
+
964
+ # 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
965
+ # to be able to avoid many of these transpose/reshape/view.
966
+ query_states = query_states.transpose(1, 2)
967
+ key_states = key_states.transpose(1, 2)
968
+ value_states = value_states.transpose(1, 2)
969
+
970
+ dropout_rate = self.attention_dropout if self.training else 0.0
971
+
972
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
973
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
974
+ # cast them back in the correct dtype just to be sure everything works as expected.
975
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
976
+ # in fp32. (CyberAIRMSNorm handles it correctly)
977
+
978
+ input_dtype = query_states.dtype
979
+ if input_dtype == torch.float32:
980
+ # Handle the case where the model is quantized
981
+ if hasattr(self.config, "_pre_quantization_dtype"):
982
+ target_dtype = self.config._pre_quantization_dtype
983
+ elif torch.is_autocast_enabled():
984
+ target_dtype = torch.get_autocast_gpu_dtype()
985
+ else:
986
+ target_dtype = self.q_a_proj.weight.dtype
987
+
988
+ logger.warning_once(
989
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
990
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
991
+ f" {target_dtype}."
992
+ )
993
+
994
+ query_states = query_states.to(target_dtype)
995
+ key_states = key_states.to(target_dtype)
996
+ value_states = value_states.to(target_dtype)
997
+
998
+ attn_output = self._flash_attention_forward(
999
+ query_states,
1000
+ key_states,
1001
+ value_states,
1002
+ attention_mask,
1003
+ q_len,
1004
+ dropout=dropout_rate,
1005
+ softmax_scale=self.softmax_scale,
1006
+ )
1007
+ if self.q_head_dim != self.v_head_dim:
1008
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1009
+
1010
+ attn_output = attn_output.reshape(
1011
+ bsz, q_len, self.num_heads * self.v_head_dim
1012
+ ).contiguous()
1013
+ attn_output = self.o_proj(attn_output)
1014
+
1015
+ if not output_attentions:
1016
+ attn_weights = None
1017
+
1018
+ return attn_output, attn_weights, past_key_value
1019
+
1020
+ def _flash_attention_forward(
1021
+ self,
1022
+ query_states,
1023
+ key_states,
1024
+ value_states,
1025
+ attention_mask,
1026
+ query_length,
1027
+ dropout=0.0,
1028
+ softmax_scale=None,
1029
+ ):
1030
+ """
1031
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1032
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1033
+ Args:
1034
+ query_states (`torch.Tensor`):
1035
+ Input query states to be passed to Flash Attention API
1036
+ key_states (`torch.Tensor`):
1037
+ Input key states to be passed to Flash Attention API
1038
+ value_states (`torch.Tensor`):
1039
+ Input value states to be passed to Flash Attention API
1040
+ attention_mask (`torch.Tensor`):
1041
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1042
+ position of padding tokens and 1 for the position of non-padding tokens.
1043
+ dropout (`int`, *optional*):
1044
+ Attention dropout
1045
+ softmax_scale (`float`, *optional*):
1046
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1047
+ """
1048
+ if not self._flash_attn_uses_top_left_mask:
1049
+ causal = self.is_causal
1050
+ else:
1051
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
1052
+ causal = self.is_causal and query_length != 1
1053
+
1054
+ # Contains at least one padding token in the sequence
1055
+ if attention_mask is not None:
1056
+ batch_size = query_states.shape[0]
1057
+ (
1058
+ query_states,
1059
+ key_states,
1060
+ value_states,
1061
+ indices_q,
1062
+ cu_seq_lens,
1063
+ max_seq_lens,
1064
+ ) = self._upad_input(
1065
+ query_states, key_states, value_states, attention_mask, query_length
1066
+ )
1067
+
1068
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1069
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1070
+
1071
+ attn_output_unpad = flash_attn_varlen_func(
1072
+ query_states,
1073
+ key_states,
1074
+ value_states,
1075
+ cu_seqlens_q=cu_seqlens_q,
1076
+ cu_seqlens_k=cu_seqlens_k,
1077
+ max_seqlen_q=max_seqlen_in_batch_q,
1078
+ max_seqlen_k=max_seqlen_in_batch_k,
1079
+ dropout_p=dropout,
1080
+ softmax_scale=softmax_scale,
1081
+ causal=causal,
1082
+ )
1083
+
1084
+ attn_output = pad_input(
1085
+ attn_output_unpad, indices_q, batch_size, query_length
1086
+ )
1087
+ else:
1088
+ attn_output = flash_attn_func(
1089
+ query_states,
1090
+ key_states,
1091
+ value_states,
1092
+ dropout,
1093
+ softmax_scale=softmax_scale,
1094
+ causal=causal,
1095
+ )
1096
+
1097
+ return attn_output
1098
+
1099
+ def _upad_input(
1100
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1101
+ ):
1102
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1103
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1104
+
1105
+ key_layer = index_first_axis(
1106
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1107
+ indices_k,
1108
+ )
1109
+ value_layer = index_first_axis(
1110
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1111
+ indices_k,
1112
+ )
1113
+ if query_length == kv_seq_len:
1114
+ query_layer = index_first_axis(
1115
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1116
+ indices_k,
1117
+ )
1118
+ cu_seqlens_q = cu_seqlens_k
1119
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1120
+ indices_q = indices_k
1121
+ elif query_length == 1:
1122
+ max_seqlen_in_batch_q = 1
1123
+ cu_seqlens_q = torch.arange(
1124
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1125
+ ) # There is a memcpy here, that is very bad.
1126
+ indices_q = cu_seqlens_q[:-1]
1127
+ query_layer = query_layer.squeeze(1)
1128
+ else:
1129
+ # The -q_len: slice assumes left padding.
1130
+ attention_mask = attention_mask[:, -query_length:]
1131
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1132
+ query_layer, attention_mask
1133
+ )
1134
+
1135
+ return (
1136
+ query_layer,
1137
+ key_layer,
1138
+ value_layer,
1139
+ indices_q,
1140
+ (cu_seqlens_q, cu_seqlens_k),
1141
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1142
+ )
1143
+
1144
+ ATTENTION_CLASSES = {
1145
+ "eager": CyberAIAttention,
1146
+ "flash_attention_2": CyberAIFlashAttention2,
1147
+ }
1148
+
1149
+ class CyberAIDecoderLayer(nn.Module):
1150
+ def __init__(self, config: CyberAIConfig, layer_idx: int):
1151
+ super().__init__()
1152
+ self.hidden_size = config.hidden_size
1153
+
1154
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1155
+ config=config, layer_idx=layer_idx
1156
+ )
1157
+
1158
+ self.mlp = (
1159
+ CyberAIVMoE(config)
1160
+ if (
1161
+ config.n_routed_experts is not None
1162
+ and layer_idx >= config.first_k_dense_replace
1163
+ and layer_idx % config.moe_layer_freq == 0
1164
+ )
1165
+ else CyberAIVMLP(config)
1166
+ )
1167
+ self.input_layernorm = CyberAIRMSNorm(
1168
+ config.hidden_size, eps=config.rms_norm_eps
1169
+ )
1170
+ self.post_attention_layernorm = CyberAIRMSNorm(
1171
+ config.hidden_size, eps=config.rms_norm_eps
1172
+ )
1173
+
1174
+ def forward(
1175
+ self,
1176
+ hidden_states: torch.Tensor,
1177
+ attention_mask: Optional[torch.Tensor] = None,
1178
+ position_ids: Optional[torch.LongTensor] = None,
1179
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1180
+ output_attentions: Optional[bool] = False,
1181
+ use_cache: Optional[bool] = False,
1182
+ **kwargs,
1183
+ ) -> Tuple[
1184
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1185
+ ]:
1186
+ """
1187
+ Args:
1188
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1189
+ attention_mask (`torch.FloatTensor`, *optional*):
1190
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1191
+ query_sequence_length, key_sequence_length)` if default attention is used.
1192
+ output_attentions (`bool`, *optional*):
1193
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1194
+ returned tensors for more detail.
1195
+ use_cache (`bool`, *optional*):
1196
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1197
+ (see `past_key_values`).
1198
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1199
+ """
1200
+ if "padding_mask" in kwargs:
1201
+ warnings.warn(
1202
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1203
+ )
1204
+ residual = hidden_states
1205
+
1206
+ hidden_states = self.input_layernorm(hidden_states)
1207
+
1208
+ # Self Attention
1209
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1210
+ hidden_states=hidden_states,
1211
+ attention_mask=attention_mask,
1212
+ position_ids=position_ids,
1213
+ past_key_value=past_key_value,
1214
+ output_attentions=output_attentions,
1215
+ use_cache=use_cache,
1216
+ **kwargs,
1217
+ )
1218
+ hidden_states = residual + hidden_states
1219
+
1220
+ # Fully Connected
1221
+ residual = hidden_states
1222
+ hidden_states = self.post_attention_layernorm(hidden_states)
1223
+ hidden_states = self.mlp(hidden_states)
1224
+ hidden_states = residual + hidden_states
1225
+
1226
+ outputs = (hidden_states,)
1227
+
1228
+ if output_attentions:
1229
+ outputs += (self_attn_weights,)
1230
+
1231
+ if use_cache:
1232
+ outputs += (present_key_value,)
1233
+
1234
+ return outputs
1235
+
1236
+ CyberAI_START_DOCSTRING = r"""
1237
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1238
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1239
+ etc.)
1240
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1241
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1242
+ and behavior.
1243
+ Parameters:
1244
+ config ([`CyberConfig`]):
1245
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1246
+ load the weights associated with the model, only the configuration. Check out the
1247
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1248
+ """
1249
+
1250
+
1251
+ @add_start_docstrings(
1252
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1253
+ CyberAI_START_DOCSTRING,
1254
+ )
1255
+ class CyberAIPreTrainedModel(PreTrainedModel):
1256
+ config_class = CyberAIConfig
1257
+ base_model_prefix = "model"
1258
+ supports_gradient_checkpointing = True
1259
+ _no_split_modules = ["CyberAIDecoderLayer"]
1260
+ _skip_keys_device_placement = "past_key_values"
1261
+ _supports_flash_attn_2 = True
1262
+ _supports_cache_class = True
1263
+
1264
+ def _init_weights(self, module):
1265
+ std = self.config.initializer_range
1266
+ if isinstance(module, nn.Linear):
1267
+ module.weight.data.normal_(mean=0.0, std=std)
1268
+ if module.bias is not None:
1269
+ module.bias.data.zero_()
1270
+ elif isinstance(module, nn.Embedding):
1271
+ module.weight.data.normal_(mean=0.0, std=std)
1272
+ if module.padding_idx is not None:
1273
+ module.weight.data[module.padding_idx].zero_()
1274
+
1275
+ CyberAI_INPUTS_DOCSTRING = r"""
1276
+ Args:
1277
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1278
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1279
+ it.
1280
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1281
+ [`PreTrainedTokenizer.__call__`] for details.
1282
+ [What are input IDs?](../glossary#input-ids)
1283
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1284
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1285
+ - 1 for tokens that are **not masked**,
1286
+ - 0 for tokens that are **masked**.
1287
+ [What are attention masks?](../glossary#attention-mask)
1288
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1289
+ [`PreTrainedTokenizer.__call__`] for details.
1290
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1291
+ `past_key_values`).
1292
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1293
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1294
+ information on the default strategy.
1295
+ - 1 indicates the head is **not masked**,
1296
+ - 0 indicates the head is **masked**.
1297
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1298
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1299
+ config.n_positions - 1]`.
1300
+ [What are position IDs?](../glossary#position-ids)
1301
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1302
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1303
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1304
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1305
+ Two formats are allowed:
1306
+ - a [`~cache_utils.Cache`] instance;
1307
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1308
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1309
+ cache format.
1310
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1311
+ legacy cache format will be returned.
1312
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1313
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1314
+ of shape `(batch_size, sequence_length)`.
1315
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1316
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1317
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1318
+ model's internal embedding lookup matrix.
1319
+ use_cache (`bool`, *optional*):
1320
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1321
+ `past_key_values`).
1322
+ output_attentions (`bool`, *optional*):
1323
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1324
+ tensors for more detail.
1325
+ output_hidden_states (`bool`, *optional*):
1326
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1327
+ more detail.
1328
+ return_dict (`bool`, *optional*):
1329
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1330
+ """
1331
+
1332
+ @add_start_docstrings(
1333
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1334
+ CyberAI_INPUTS_DOCSTRING,
1335
+ )
1336
+ class CyberModel(CyberAIPreTrainedModel):
1337
+ """
1338
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`CyberAIDecoderLayer`]
1339
+ Args:
1340
+ config: CyberAIConfig
1341
+ """
1342
+
1343
+ def __init__(self, config: CyberAIConfig):
1344
+ super().__init__(config)
1345
+ self.padding_idx = config.pad_token_id
1346
+ self.vocab_size = config.vocab_size
1347
+
1348
+ self.embed_tokens = nn.Embedding(
1349
+ config.vocab_size, config.hidden_size, self.padding_idx
1350
+ )
1351
+ self.layers = nn.ModuleList(
1352
+ [
1353
+ CyberAIDecoderLayer(config, layer_idx)
1354
+ for layer_idx in range(config.num_hidden_layers)
1355
+ ]
1356
+ )
1357
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1358
+ self.norm = CyberAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1359
+
1360
+ self.gradient_checkpointing = False
1361
+ # Initialize weights and apply final processing
1362
+ self.post_init()
1363
+
1364
+ def get_input_embeddings(self):
1365
+ return self.embed_tokens
1366
+
1367
+ def set_input_embeddings(self, value):
1368
+ self.embed_tokens = value
1369
+
1370
+ @add_start_docstrings_to_model_forward(CyberAI_INPUTS_DOCSTRING)
1371
+ def forward(
1372
+ self,
1373
+ input_ids: torch.LongTensor = None,
1374
+ attention_mask: Optional[torch.Tensor] = None,
1375
+ position_ids: Optional[torch.LongTensor] = None,
1376
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1377
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1378
+ use_cache: Optional[bool] = None,
1379
+ output_attentions: Optional[bool] = None,
1380
+ output_hidden_states: Optional[bool] = None,
1381
+ return_dict: Optional[bool] = None,
1382
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1383
+ output_attentions = (
1384
+ output_attentions
1385
+ if output_attentions is not None
1386
+ else self.config.output_attentions
1387
+ )
1388
+ output_hidden_states = (
1389
+ output_hidden_states
1390
+ if output_hidden_states is not None
1391
+ else self.config.output_hidden_states
1392
+ )
1393
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1394
+
1395
+ return_dict = (
1396
+ return_dict if return_dict is not None else self.config.use_return_dict
1397
+ )
1398
+
1399
+ # retrieve input_ids and inputs_embeds
1400
+ if input_ids is not None and inputs_embeds is not None:
1401
+ raise ValueError(
1402
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1403
+ )
1404
+ elif input_ids is not None:
1405
+ batch_size, seq_length = input_ids.shape[:2]
1406
+ elif inputs_embeds is not None:
1407
+ batch_size, seq_length = inputs_embeds.shape[:2]
1408
+ else:
1409
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1410
+
1411
+ if self.gradient_checkpointing and self.training:
1412
+ if use_cache:
1413
+ logger.warning_once(
1414
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1415
+ )
1416
+ use_cache = False
1417
+
1418
+ past_key_values_length = 0
1419
+ if use_cache:
1420
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1421
+ if use_legacy_cache:
1422
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1423
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1424
+
1425
+ if position_ids is None:
1426
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1427
+ position_ids = torch.arange(
1428
+ past_key_values_length,
1429
+ seq_length + past_key_values_length,
1430
+ dtype=torch.long,
1431
+ device=device,
1432
+ )
1433
+ position_ids = position_ids.unsqueeze(0)
1434
+
1435
+ if inputs_embeds is None:
1436
+ inputs_embeds = self.embed_tokens(input_ids)
1437
+
1438
+ if self._use_flash_attention_2:
1439
+ # 2d mask is passed through the layers
1440
+ attention_mask = (
1441
+ attention_mask
1442
+ if (attention_mask is not None and 0 in attention_mask)
1443
+ else None
1444
+ )
1445
+ else:
1446
+ # 4d mask is passed through the layers
1447
+ attention_mask = _prepare_4d_causal_attention_mask(
1448
+ attention_mask,
1449
+ (batch_size, seq_length),
1450
+ inputs_embeds,
1451
+ past_key_values_length,
1452
+ )
1453
+
1454
+ # embed positions
1455
+ hidden_states = inputs_embeds
1456
+
1457
+ # decoder layers
1458
+ all_hidden_states = () if output_hidden_states else None
1459
+ all_self_attns = () if output_attentions else None
1460
+ next_decoder_cache = None
1461
+
1462
+ for decoder_layer in self.layers:
1463
+ if output_hidden_states:
1464
+ all_hidden_states += (hidden_states,)
1465
+
1466
+ if self.gradient_checkpointing and self.training:
1467
+ layer_outputs = self._gradient_checkpointing_func(
1468
+ decoder_layer.__call__,
1469
+ hidden_states,
1470
+ attention_mask,
1471
+ position_ids,
1472
+ past_key_values,
1473
+ output_attentions,
1474
+ use_cache,
1475
+ )
1476
+ else:
1477
+ layer_outputs = decoder_layer(
1478
+ hidden_states,
1479
+ attention_mask=attention_mask,
1480
+ position_ids=position_ids,
1481
+ past_key_value=past_key_values,
1482
+ output_attentions=output_attentions,
1483
+ use_cache=use_cache,
1484
+ )
1485
+
1486
+ hidden_states = layer_outputs[0]
1487
+
1488
+ if use_cache:
1489
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1490
+
1491
+ if output_attentions:
1492
+ all_self_attns += (layer_outputs[1],)
1493
+
1494
+ hidden_states = self.norm(hidden_states)
1495
+
1496
+ # add hidden states from the last decoder layer
1497
+ if output_hidden_states:
1498
+ all_hidden_states += (hidden_states,)
1499
+
1500
+ next_cache = None
1501
+ if use_cache:
1502
+ next_cache = (
1503
+ next_decoder_cache.to_legacy_cache()
1504
+ if use_legacy_cache
1505
+ else next_decoder_cache
1506
+ )
1507
+ if not return_dict:
1508
+ return tuple(
1509
+ v
1510
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1511
+ if v is not None
1512
+ )
1513
+ return BaseModelOutputWithPast(
1514
+ last_hidden_state=hidden_states,
1515
+ past_key_values=next_cache,
1516
+ hidden_states=all_hidden_states,
1517
+ attentions=all_self_attns,
1518
+ )
1519
+
1520
+ class CyberAIForCausalLM(CyberAIPreTrainedModel):
1521
+ _tied_weights_keys = ["lm_head.weight"]
1522
+
1523
+ def __init__(self, config):
1524
+ super().__init__(config)
1525
+ self.model = CyberModel(config)
1526
+ self.vocab_size = config.vocab_size
1527
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1528
+
1529
+ # Initialize weights and apply final processing
1530
+ self.post_init()
1531
+
1532
+ def get_input_embeddings(self):
1533
+ return self.model.embed_tokens
1534
+
1535
+ def set_input_embeddings(self, value):
1536
+ self.model.embed_tokens = value
1537
+
1538
+ def get_output_embeddings(self):
1539
+ return self.lm_head
1540
+
1541
+ def set_output_embeddings(self, new_embeddings):
1542
+ self.lm_head = new_embeddings
1543
+
1544
+ def set_decoder(self, decoder):
1545
+ self.model = decoder
1546
+
1547
+ def get_decoder(self):
1548
+ return self.model
1549
+
1550
+ @add_start_docstrings_to_model_forward(CyberAI_INPUTS_DOCSTRING)
1551
+ @replace_return_docstrings(
1552
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1553
+ )
1554
+ def forward(
1555
+ self,
1556
+ input_ids: torch.LongTensor = None,
1557
+ attention_mask: Optional[torch.Tensor] = None,
1558
+ position_ids: Optional[torch.LongTensor] = None,
1559
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1560
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1561
+ labels: Optional[torch.LongTensor] = None,
1562
+ use_cache: Optional[bool] = None,
1563
+ output_attentions: Optional[bool] = None,
1564
+ output_hidden_states: Optional[bool] = None,
1565
+ return_dict: Optional[bool] = None,
1566
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1567
+ r"""
1568
+ Args:
1569
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1570
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1571
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1572
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1573
+ Returns:
1574
+ Example:
1575
+ ```python
1576
+ >>> from transformers import AutoTokenizer, CyberAIForCausalLM
1577
+ >>> model = CyberAIForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1578
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1579
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1580
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1581
+ >>> # Generate
1582
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1583
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1584
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1585
+ ```"""
1586
+ output_attentions = (
1587
+ output_attentions
1588
+ if output_attentions is not None
1589
+ else self.config.output_attentions
1590
+ )
1591
+ output_hidden_states = (
1592
+ output_hidden_states
1593
+ if output_hidden_states is not None
1594
+ else self.config.output_hidden_states
1595
+ )
1596
+ return_dict = (
1597
+ return_dict if return_dict is not None else self.config.use_return_dict
1598
+ )
1599
+
1600
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1601
+ outputs = self.model(
1602
+ input_ids=input_ids,
1603
+ attention_mask=attention_mask,
1604
+ position_ids=position_ids,
1605
+ past_key_values=past_key_values,
1606
+ inputs_embeds=inputs_embeds,
1607
+ use_cache=use_cache,
1608
+ output_attentions=output_attentions,
1609
+ output_hidden_states=output_hidden_states,
1610
+ return_dict=return_dict,
1611
+ )
1612
+
1613
+ hidden_states = outputs[0]
1614
+ logits = self.lm_head(hidden_states)
1615
+ logits = logits.float()
1616
+
1617
+ loss = None
1618
+ if labels is not None:
1619
+ # Shift so that tokens < n predict n
1620
+ shift_logits = logits[..., :-1, :].contiguous()
1621
+ shift_labels = labels[..., 1:].contiguous()
1622
+ # Flatten the tokens
1623
+ loss_fct = CrossEntropyLoss()
1624
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1625
+ shift_labels = shift_labels.view(-1)
1626
+ # Enable model parallelism
1627
+ shift_labels = shift_labels.to(shift_logits.device)
1628
+ loss = loss_fct(shift_logits, shift_labels)
1629
+
1630
+ if not return_dict:
1631
+ output = (logits,) + outputs[1:]
1632
+ return (loss,) + output if loss is not None else output
1633
+
1634
+ return CausalLMOutputWithPast(
1635
+ loss=loss,
1636
+ logits=logits,
1637
+ past_key_values=outputs.past_key_values,
1638
+ hidden_states=outputs.hidden_states,
1639
+ attentions=outputs.attentions,
1640
+ )
1641
+
1642
+ def prepare_inputs_for_generation(
1643
+ self,
1644
+ input_ids,
1645
+ past_key_values=None,
1646
+ attention_mask=None,
1647
+ inputs_embeds=None,
1648
+ **kwargs,
1649
+ ):
1650
+ if past_key_values is not None:
1651
+ if isinstance(past_key_values, Cache):
1652
+ cache_length = past_key_values.get_seq_length()
1653
+ past_length = past_key_values.seen_tokens
1654
+ max_cache_length = past_key_values.get_max_length()
1655
+ else:
1656
+ cache_length = past_length = past_key_values[0][0].shape[2]
1657
+ max_cache_length = None
1658
+
1659
+ # Keep only the unprocessed tokens:
1660
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1661
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1662
+ # input)
1663
+ if (
1664
+ attention_mask is not None
1665
+ and attention_mask.shape[1] > input_ids.shape[1]
1666
+ ):
1667
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1668
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1669
+ # input_ids based on the past_length.
1670
+ elif past_length < input_ids.shape[1]:
1671
+ input_ids = input_ids[:, past_length:]
1672
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1673
+
1674
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1675
+ if (
1676
+ max_cache_length is not None
1677
+ and attention_mask is not None
1678
+ and cache_length + input_ids.shape[1] > max_cache_length
1679
+ ):
1680
+ attention_mask = attention_mask[:, -max_cache_length:]
1681
+
1682
+ position_ids = kwargs.get("position_ids", None)
1683
+ if attention_mask is not None and position_ids is None:
1684
+ # create position_ids on the fly for batch generation
1685
+ position_ids = attention_mask.long().cumsum(-1) - 1
1686
+ position_ids.masked_fill_(attention_mask == 0, 1)
1687
+ if past_key_values:
1688
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1689
+
1690
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1691
+ if inputs_embeds is not None and past_key_values is None:
1692
+ model_inputs = {"inputs_embeds": inputs_embeds}
1693
+ else:
1694
+ model_inputs = {"input_ids": input_ids}
1695
+
1696
+ model_inputs.update(
1697
+ {
1698
+ "position_ids": position_ids,
1699
+ "past_key_values": past_key_values,
1700
+ "use_cache": kwargs.get("use_cache"),
1701
+ "attention_mask": attention_mask,
1702
+ }
1703
+ )
1704
+ return model_inputs
1705
+
1706
+ @staticmethod
1707
+ def _reorder_cache(past_key_values, beam_idx):
1708
+ reordered_past = ()
1709
+ for layer_past in past_key_values:
1710
+ reordered_past += (
1711
+ tuple(
1712
+ past_state.index_select(0, beam_idx.to(past_state.device))
1713
+ for past_state in layer_past
1714
+ ),
1715
+ )
1716
+ return reordered_past
1717
+
1718
+ @add_start_docstrings(
1719
+ """
1720
+ The CyberAI Model transformer with a sequence classification head on top (linear layer).
1721
+ [`CyberAIForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1722
+ (e.g. GPT-2) do.
1723
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1724
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1725
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1726
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1727
+ each row of the batch).
1728
+ """,
1729
+ CyberAI_START_DOCSTRING,
1730
+ )
1731
+ class DeepseekV2ForSequenceClassification(CyberAIPreTrainedModel):
1732
+ def __init__(self, config):
1733
+ super().__init__(config)
1734
+ self.num_labels = config.num_labels
1735
+ self.model = CyberModel(config)
1736
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1737
+
1738
+ # Initialize weights and apply final processing
1739
+ self.post_init()
1740
+
1741
+ def get_input_embeddings(self):
1742
+ return self.model.embed_tokens
1743
+
1744
+ def set_input_embeddings(self, value):
1745
+ self.model.embed_tokens = value
1746
+
1747
+ @add_start_docstrings_to_model_forward(CyberAI_INPUTS_DOCSTRING)
1748
+ def forward(
1749
+ self,
1750
+ input_ids: torch.LongTensor = None,
1751
+ attention_mask: Optional[torch.Tensor] = None,
1752
+ position_ids: Optional[torch.LongTensor] = None,
1753
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1754
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1755
+ labels: Optional[torch.LongTensor] = None,
1756
+ use_cache: Optional[bool] = None,
1757
+ output_attentions: Optional[bool] = None,
1758
+ output_hidden_states: Optional[bool] = None,
1759
+ return_dict: Optional[bool] = None,
1760
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1761
+ r"""
1762
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1763
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1764
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1765
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1766
+ """
1767
+ return_dict = (
1768
+ return_dict if return_dict is not None else self.config.use_return_dict
1769
+ )
1770
+
1771
+ transformer_outputs = self.model(
1772
+ input_ids,
1773
+ attention_mask=attention_mask,
1774
+ position_ids=position_ids,
1775
+ past_key_values=past_key_values,
1776
+ inputs_embeds=inputs_embeds,
1777
+ use_cache=use_cache,
1778
+ output_attentions=output_attentions,
1779
+ output_hidden_states=output_hidden_states,
1780
+ return_dict=return_dict,
1781
+ )
1782
+ hidden_states = transformer_outputs[0]
1783
+ logits = self.score(hidden_states)
1784
+
1785
+ if input_ids is not None:
1786
+ batch_size = input_ids.shape[0]
1787
+ else:
1788
+ batch_size = inputs_embeds.shape[0]
1789
+
1790
+ if self.config.pad_token_id is None and batch_size != 1:
1791
+ raise ValueError(
1792
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1793
+ )
1794
+ if self.config.pad_token_id is None:
1795
+ sequence_lengths = -1
1796
+ else:
1797
+ if input_ids is not None:
1798
+ sequence_lengths = (
1799
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1800
+ ).to(logits.device)
1801
+ else:
1802
+ sequence_lengths = -1
1803
+
1804
+ pooled_logits = logits[
1805
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1806
+ ]
1807
+
1808
+ loss = None
1809
+ if labels is not None:
1810
+ labels = labels.to(logits.device)
1811
+ if self.config.problem_type is None:
1812
+ if self.num_labels == 1:
1813
+ self.config.problem_type = "regression"
1814
+ elif self.num_labels > 1 and (
1815
+ labels.dtype == torch.long or labels.dtype == torch.int
1816
+ ):
1817
+ self.config.problem_type = "single_label_classification"
1818
+ else:
1819
+ self.config.problem_type = "multi_label_classification"
1820
+
1821
+ if self.config.problem_type == "regression":
1822
+ loss_fct = MSELoss()
1823
+ if self.num_labels == 1:
1824
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1825
+ else:
1826
+ loss = loss_fct(pooled_logits, labels)
1827
+ elif self.config.problem_type == "single_label_classification":
1828
+ loss_fct = CrossEntropyLoss()
1829
+ loss = loss_fct(
1830
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1831
+ )
1832
+ elif self.config.problem_type == "multi_label_classification":
1833
+ loss_fct = BCEWithLogitsLoss()
1834
+ loss = loss_fct(pooled_logits, labels)
1835
+ if not return_dict:
1836
+ output = (pooled_logits,) + transformer_outputs[1:]
1837
+ return ((loss,) + output) if loss is not None else output
1838
+
1839
+ return SequenceClassifierOutputWithPast(
1840
+ loss=loss,
1841
+ logits=pooled_logits,
1842
+ past_key_values=transformer_outputs.past_key_values,
1843
+ hidden_states=transformer_outputs.hidden_states,
1844
+ attentions=transformer_outputs.attentions,
1845
+ )