foamliu commited on
Commit
fefdb7b
·
verified ·
1 Parent(s): 406c721

Add files using upload-large-folder tool

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