pom commited on
Commit
7bd7fc3
1 Parent(s): e88ab5f
README.md CHANGED
@@ -1,3 +1,70 @@
1
  ---
2
  license: apache-2.0
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+
4
+ inference: false
5
+
6
  ---
7
+
8
+ # XVERSE-MoE-A4.2B-Chat
9
+
10
+ ## 使用方法
11
+
12
+ ### Transformers 加载方式
13
+
14
+ 可通过以下代码加载 XVERSE-MoE-A4.2B-Chat 模型来进行推理:
15
+
16
+ ```python
17
+ import torch
18
+ from transformers import AutoTokenizer, AutoModelForCausalLM
19
+ tokenizer = AutoTokenizer.from_pretrained("xverse/XVERSE-MoE-A4.2B-Chat")
20
+ model = AutoModelForCausalLM.from_pretrained("xverse/XVERSE-MoE-A4.2B-Chat", trust_remote_code=True, torch_dtype=torch.bfloat16, device_map='auto')
21
+ model = model.eval()
22
+ inputs = tokenizer('北京的景点:故宫、天坛、万里长城等。\n深圳的景点:', return_tensors='pt').input_ids
23
+ inputs = inputs.cuda()
24
+ generated_ids = model.generate(inputs, max_new_tokens=64, eos_token_id=tokenizer.eos_token_id, repetition_penalty=1.1)
25
+ print(tokenizer.batch_decode(generated_ids, skip_special_tokens=True))
26
+ ```
27
+
28
+
29
+ ## Usage
30
+
31
+ ### Loading with Transformers
32
+
33
+ The XVERSE-MoE-A4.2B-Chat model can be loaded for inference using the following code:
34
+
35
+ ```python
36
+ import torch
37
+ from transformers import AutoTokenizer, AutoModelForCausalLM
38
+ tokenizer = AutoTokenizer.from_pretrained("xverse/XVERSE-MoE-A4.2B-Chat")
39
+ model = AutoModelForCausalLM.from_pretrained("xverse/XVERSE-MoE-A4.2B-Chat", trust_remote_code=True, torch_dtype=torch.bfloat16, device_map='auto')
40
+ model = model.eval()
41
+ inputs = tokenizer('北京的景点:故宫、天坛、万里长城等。\n深圳的景点:', return_tensors='pt').input_ids
42
+ inputs = inputs.cuda()
43
+ generated_ids = model.generate(inputs, max_new_tokens=64, eos_token_id=tokenizer.eos_token_id, repetition_penalty=1.1)
44
+ print(tokenizer.batch_decode(generated_ids, skip_special_tokens=True))
45
+ ```
46
+
47
+
48
+ ## 局限性与免责申明
49
+
50
+ XVERSE-MoE-A4.2B-Chat 与其他所有 LLM 一样,在某些情况下可能会产生不准确、有偏见或其他令人反感的内容。因此,请谨慎使用模型生成的内容,请勿将生成的有害内容进行传播,在部署任何 XVERSE-MoE-A4.2B-Chat 的应用之前,开发人员应根据其具体应用对模型进行安全测试和调优。
51
+
52
+ 我们强烈警告不要将 XVERSE-MoE-A4.2B-Chat 模型用于制造或传播有害信息,或进行任何可能损害公众、国家、社会安全或违反法规的活动。如果使用 XVERSE-MoE-A4.2B-Chat 模型产生任何问题,无论是数据安全问题、公共舆论风险,还是模型被误解、滥用、传播或不合规使用所引发的任何风险和问题,我们将不承担任何责任。
53
+
54
+ ## 模型开源协议
55
+
56
+ 使用本仓库的源码需要遵循 [Apache-2.0](https://github.com/xverse-ai/XVERSE-MoE-A4.2B/blob/main/LICENSE) 开源协议,使用 XVERSE-MoE-A4.2B-Chat 的模型权重则需要遵循[模型许可协议](https://github.com/xverse-ai/XVERSE-MoE-A4.2B/blob/main/MODEL_LICENSE.pdf)。
57
+
58
+ XVERSE-MoE-A4.2B-Chat 模型权重对学术研究**完全开放**,并且支持**免费商用**。如需申请商业许可证,请填写【[申请表](https://chat.xverse.cn/home/business.html)】,如有其他问题或合作,请联系 <[email protected]>。
59
+
60
+ ## Limitations and Disclaimer
61
+
62
+ Like all other Large Language Models (LLMs), XVERSE-MoE-A4.2B-Chat may produce inaccurate, biased, or otherwise offensive content under certain circumstances. Therefore, please use the content generated by the model with caution and refrain from disseminating harmful content. Before deploying any application of XVERSE-MoE-A4.2B-Chat, developers should conduct safety tests and optimization of the model according to its specific application.
63
+
64
+ We strongly warn against the use of the XVERSE-MoE-A4.2B-Chat model for producing or spreading harmful information, or conducting any activities that might harm the public, national, or social security, or violate regulations. We assume no responsibility for any problems arising from the use of the XVERSE-MoE-A4.2B-Chat model, whether it be data security issues, public opinion risks, or any risks and issues caused by misunderstanding, misuse, dissemination, or non-compliance with the model.
65
+
66
+ ## Open Source License
67
+
68
+ The use of the source code in this repository must follow the [Apache-2.0](https://github.com/xverse-ai/XVERSE-MoE-A4.2B/blob/main/LICENSE) open-source license, while the use of the model weights of XVERSE-MoE-A4.2B-Chat needs to adhere to the [Model License Agreement](https://github.com/xverse-ai/XVERSE-MoE-A4.2B/blob/main/MODEL_LICENSE.pdf).
69
+
70
+ The XVERSE-MoE-A4.2B-Chat model weights are **fully open** to academic research and support **free commercial use**. To apply for a commercial license, please fill in the [application form](https://chat.xverse.cn/home/business.html). For other questions or collaborations, please contact <[email protected]>.
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "XverseForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_xverse.XverseConfig",
7
+ "AutoModelForCausalLM": "modeling_xverse.XverseForCausalLM"
8
+ },
9
+ "pad_token_id": 1,
10
+ "bos_token_id": 2,
11
+ "eos_token_id": 3,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 2560,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 1728,
16
+ "max_position_embeddings": 8192,
17
+ "max_tokenizer_truncation": 6144,
18
+ "model_type": "xverse",
19
+ "num_attention_heads": 32,
20
+ "num_hidden_layers": 28,
21
+ "rms_norm_eps": 1e-06,
22
+ "tie_word_embeddings": false,
23
+ "rope_theta": 500000,
24
+ "moe_top_k": 6,
25
+ "num_experts": 64,
26
+ "num_shared_experts": 2,
27
+ "output_router_logits": false,
28
+ "router_aux_loss_coef": 0.01,
29
+ "torch_dtype": "bfloat16",
30
+ "transformers_version": "4.38.2",
31
+ "use_cache": true,
32
+ "vocab_size": 100534
33
+ }
34
+
configuration_xverse.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI 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
+ """ XVERSE model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ XVERSE_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class XverseConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`XverseModel`]. It is used to instantiate an Xverse
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the XVERSE-13B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 100278):
43
+ Vocabulary size of the XVERSE model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`XverseModel`]
45
+ hidden_size (`int`, *optional*, defaults to 5120):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 13824):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 40):
50
+ Number of hidden layers in the Transformer encoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 40):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
54
+ The non-linear activation function (function or string) in the decoder.
55
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
56
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
57
+ just in case (e.g., 512 or 1024 or 2048).
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-6):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ pad_token_id (`int`, *optional*):
66
+ Padding token id.
67
+ bos_token_id (`int`, *optional*, defaults to 1):
68
+ Beginning of stream token id.
69
+ eos_token_id (`int`, *optional*, defaults to 2):
70
+ End of stream token id.
71
+ pretraining_tp (`int`, *optional*, defaults to 1):
72
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
73
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
74
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
75
+ issue](https://github.com/pytorch/pytorch/issues/76232).
76
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
77
+ Whether to tie weight embeddings
78
+ rope_theta (`float`, *optional*, defaults to 10000.0):
79
+ The base period of the RoPE embeddings.
80
+ rope_scaling (`Dict`, *optional*):
81
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
82
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
83
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
84
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
85
+ these scaling strategies behave:
86
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
87
+ experimental feature, subject to breaking API changes in future versions.
88
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
89
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
90
+ attention_dropout (`float`, *optional*, defaults to 0.0):
91
+ The dropout ratio for the attention probabilities.
92
+ moe_top_k (`int`, defaults to 6):
93
+ Number of selected experts.
94
+ num_experts (`int`, defaults to 64):
95
+ Number of routed experts.
96
+ num_shared_experts (`int`, defaults to 64):
97
+ Number of shared experts, None for no shared experts.
98
+ output_router_logits (`bool`, optional):
99
+ Whether or not to return the router logits.
100
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.01):
101
+ The aux loss factor for the total loss.
102
+ Example:
103
+
104
+ ```python
105
+ >>> from transformers import XverseModel, XverseConfig
106
+
107
+ >>> # Initializing a Xverse XVERSE-13B style configuration
108
+ >>> configuration = XverseConfig()
109
+
110
+ >>> # Initializing a model from the XVERSE-13B style configuration
111
+ >>> model = XverseModel(configuration)
112
+
113
+ >>> # Accessing the model configuration
114
+ >>> configuration = model.config
115
+ ```"""
116
+ model_type = "xverse"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=100278,
122
+ hidden_size=5120,
123
+ intermediate_size=13824,
124
+ num_hidden_layers=40,
125
+ num_attention_heads=40,
126
+ num_key_value_heads=None,
127
+ hidden_act="silu",
128
+ max_position_embeddings=8192,
129
+ initializer_range=0.02,
130
+ rms_norm_eps=1e-6,
131
+ use_cache=True,
132
+ pad_token_id=None,
133
+ bos_token_id=1,
134
+ eos_token_id=2,
135
+ pretraining_tp=1,
136
+ tie_word_embeddings=False,
137
+ rope_theta=10000.0,
138
+ rope_scaling=None,
139
+ attention_bias=False,
140
+ attention_dropout=0.0,
141
+ moe_top_k=6,
142
+ num_experts=64,
143
+ num_shared_experts=2,
144
+ output_router_logits=False,
145
+ router_aux_loss_coef=0.01,
146
+ **kwargs,
147
+ ):
148
+ self.vocab_size = vocab_size
149
+ self.max_position_embeddings = max_position_embeddings
150
+ self.hidden_size = hidden_size
151
+ self.intermediate_size = intermediate_size
152
+ self.num_hidden_layers = num_hidden_layers
153
+ self.num_attention_heads = num_attention_heads
154
+
155
+ # for backward compatibility
156
+ if num_key_value_heads is None:
157
+ num_key_value_heads = num_attention_heads
158
+
159
+ self.num_key_value_heads = num_key_value_heads
160
+ self.hidden_act = hidden_act
161
+ self.initializer_range = initializer_range
162
+ self.rms_norm_eps = rms_norm_eps
163
+ self.pretraining_tp = pretraining_tp
164
+ self.use_cache = use_cache
165
+ self.rope_theta = rope_theta
166
+ self.rope_scaling = rope_scaling
167
+ self._rope_scaling_validation()
168
+ self.attention_bias = attention_bias
169
+ self.attention_dropout = attention_dropout
170
+
171
+ self.moe_top_k = moe_top_k
172
+ self.num_experts = num_experts
173
+ self.num_shared_experts = num_shared_experts
174
+ self.output_router_logits = output_router_logits
175
+ self.router_aux_loss_coef = router_aux_loss_coef
176
+
177
+ super().__init__(
178
+ pad_token_id=pad_token_id,
179
+ bos_token_id=bos_token_id,
180
+ eos_token_id=eos_token_id,
181
+ tie_word_embeddings=tie_word_embeddings,
182
+ **kwargs,
183
+ )
184
+
185
+ def _rope_scaling_validation(self):
186
+ """
187
+ Validate the `rope_scaling` configuration.
188
+ """
189
+ if self.rope_scaling is None:
190
+ return
191
+
192
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
193
+ raise ValueError(
194
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
195
+ f"got {self.rope_scaling}"
196
+ )
197
+ rope_scaling_type = self.rope_scaling.get("type", None)
198
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
199
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
200
+ raise ValueError(
201
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
202
+ )
203
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
204
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "pad_token_id": 1,
3
+ "bos_token_id": 2,
4
+ "eos_token_id": 3,
5
+ "max_new_tokens": 2048,
6
+ "temperature": 0.5,
7
+ "top_k": 30,
8
+ "top_p": 0.85,
9
+ "repetition_penalty": 1.1,
10
+ "do_sample": true,
11
+ "transformers_version": "4.29.1"
12
+ }
modeling_xverse.py ADDED
@@ -0,0 +1,1598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
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 xverse 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, StaticCache
33
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
34
+ from transformers.modeling_outputs import (
35
+ MoeModelOutputWithPast,
36
+ MoeCausalLMOutputWithPast
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from transformers.generation.utils import GenerationConfig
49
+ from .configuration_xverse import XverseConfig
50
+
51
+
52
+ if is_flash_attn_2_available():
53
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CONFIG_FOR_DOC = "XverseConfig"
60
+
61
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
62
+ def load_balancing_loss_func(
63
+ gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2, attention_mask: Optional[torch.Tensor] = None
64
+ ) -> float:
65
+ r"""
66
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
67
+
68
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
69
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
70
+ experts is too unbalanced.
71
+
72
+ Args:
73
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
74
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
75
+ shape [batch_size X sequence_length, num_experts].
76
+ attention_mask (`torch.Tensor`, None):
77
+ The attention_mask used in forward function
78
+ shape [batch_size X sequence_length] if not None.
79
+ num_experts (`int`, *optional*):
80
+ Number of experts
81
+
82
+ Returns:
83
+ The auxiliary loss.
84
+ """
85
+ if gate_logits is None or not isinstance(gate_logits, tuple):
86
+ return 0
87
+
88
+ if isinstance(gate_logits, tuple):
89
+ compute_device = gate_logits[0].device
90
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
91
+
92
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
93
+
94
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
95
+
96
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
97
+
98
+ if attention_mask is None:
99
+ # Compute the percentage of tokens routed to each experts
100
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
101
+
102
+ # Compute the average probability of routing to these experts
103
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
104
+ else:
105
+ batch_size, sequence_length = attention_mask.shape
106
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
107
+
108
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
109
+ expert_attention_mask = (
110
+ attention_mask[None, :, :, None, None]
111
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
112
+ .reshape(-1, top_k, num_experts)
113
+ .to(compute_device)
114
+ )
115
+
116
+ # Compute the percentage of tokens routed to each experts
117
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
118
+ expert_attention_mask, dim=0
119
+ )
120
+
121
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
122
+ router_per_expert_attention_mask = (
123
+ attention_mask[None, :, :, None]
124
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
125
+ .reshape(-1, num_experts)
126
+ .to(compute_device)
127
+ )
128
+
129
+ # Compute the average probability of routing to these experts
130
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
131
+ router_per_expert_attention_mask, dim=0
132
+ )
133
+
134
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
135
+ return overall_loss * num_experts
136
+
137
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
138
+ def _get_unpad_data(attention_mask):
139
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
140
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
141
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
142
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
143
+ return (
144
+ indices,
145
+ cu_seqlens,
146
+ max_seqlen_in_batch,
147
+ )
148
+
149
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Xverse
150
+ class XverseRMSNorm(nn.Module):
151
+ def __init__(self, hidden_size, eps=1e-6):
152
+ """
153
+ XverseRMSNorm is equivalent to T5LayerNorm
154
+ """
155
+ super().__init__()
156
+ self.weight = nn.Parameter(torch.ones(hidden_size))
157
+ self.variance_epsilon = eps
158
+
159
+ def forward(self, hidden_states):
160
+ input_dtype = hidden_states.dtype
161
+ hidden_states = hidden_states.to(torch.float32)
162
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
163
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
164
+ return self.weight * hidden_states.to(input_dtype)
165
+
166
+
167
+ ALL_LAYERNORM_LAYERS.append(XverseRMSNorm)
168
+
169
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Xverse
170
+ class XverseRotaryEmbedding(nn.Module):
171
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
172
+ super().__init__()
173
+ self.scaling_factor = scaling_factor
174
+ self.dim = dim
175
+ self.max_position_embeddings = max_position_embeddings
176
+ self.base = base
177
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
178
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
179
+ # For BC we register cos and sin cached
180
+ self.max_seq_len_cached = max_position_embeddings
181
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
182
+ t = t / self.scaling_factor
183
+ freqs = torch.outer(t, self.inv_freq)
184
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
185
+ emb = torch.cat((freqs, freqs), dim=-1)
186
+ self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False)
187
+ self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False)
188
+
189
+ @property
190
+ def sin_cached(self):
191
+ logger.warning_once(
192
+ "The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
193
+ "the forward method of RoPE from now on instead. It is not used in the `LlamaAttention` class"
194
+ )
195
+ return self._sin_cached
196
+
197
+ @property
198
+ def cos_cached(self):
199
+ logger.warning_once(
200
+ "The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
201
+ "the forward method of RoPE from now on instead. It is not used in the `LlamaAttention` class"
202
+ )
203
+ return self._cos_cached
204
+
205
+ @torch.no_grad()
206
+ def forward(self, x, position_ids, seq_len=None):
207
+ if seq_len is not None:
208
+ logger.warning_once("The `seq_len` argument is deprecated and unused. It will be removed in v4.39.")
209
+
210
+ # x: [bs, num_attention_heads, seq_len, head_size]
211
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
212
+ position_ids_expanded = position_ids[:, None, :].float()
213
+ # Force float32 since bfloat16 loses precision on long contexts
214
+ # See https://github.com/huggingface/transformers/pull/29285
215
+ device_type = x.device.type
216
+ device_type = device_type if isinstance(device_type, str) else "cpu"
217
+ with torch.autocast(device_type=device_type, enabled=False):
218
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
219
+ emb = torch.cat((freqs, freqs), dim=-1)
220
+ cos = emb.cos()
221
+ sin = emb.sin()
222
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
223
+
224
+
225
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Xverse
226
+ class XverseLinearScalingRotaryEmbedding(XverseRotaryEmbedding):
227
+ """XverseRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
228
+
229
+ def forward(self, x, position_ids, seq_len=None):
230
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
231
+ position_ids = position_ids.float() / self.scaling_factor
232
+ cos, sin = super().forward(x, position_ids, seq_len)
233
+ return cos, sin
234
+
235
+
236
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Xverse
237
+ class XverseDynamicNTKScalingRotaryEmbedding(XverseRotaryEmbedding):
238
+ """XverseRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
239
+
240
+ def forward(self, x, position_ids, seq_len=None):
241
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
242
+ seq_len = torch.max(position_ids) + 1
243
+ if seq_len > self.max_position_embeddings:
244
+ base = self.base * (
245
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
246
+ ) ** (self.dim / (self.dim - 2))
247
+ inv_freq = 1.0 / (
248
+ base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
249
+ )
250
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
251
+
252
+ cos, sin = super().forward(x, position_ids, seq_len)
253
+ return cos, sin
254
+
255
+
256
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
257
+ def rotate_half(x):
258
+ """Rotates half the hidden dims of the input."""
259
+ x1 = x[..., : x.shape[-1] // 2]
260
+ x2 = x[..., x.shape[-1] // 2 :]
261
+ return torch.cat((-x2, x1), dim=-1)
262
+
263
+
264
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
265
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
266
+ """Applies Rotary Position Embedding to the query and key tensors.
267
+
268
+ Args:
269
+ q (`torch.Tensor`): The query tensor.
270
+ k (`torch.Tensor`): The key tensor.
271
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
272
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
273
+ position_ids (`torch.Tensor`, *optional*):
274
+ Deprecated and unused.
275
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
276
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
277
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
278
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
279
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
280
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
281
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
282
+ Returns:
283
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
284
+ """
285
+ cos = cos.unsqueeze(unsqueeze_dim)
286
+ sin = sin.unsqueeze(unsqueeze_dim)
287
+ q_embed = (q * cos) + (rotate_half(q) * sin)
288
+ k_embed = (k * cos) + (rotate_half(k) * sin)
289
+ return q_embed, k_embed
290
+
291
+
292
+ # Copied from transformers.models.llama.modeling_llama.LlamaMLP with Llama->Xverse
293
+ class XverseMLP(nn.Module):
294
+ def __init__(self, config, hidden_size=None, intermediate_size=None, hidden_act=None):
295
+ super().__init__()
296
+ self.config = config
297
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
298
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
299
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
300
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
301
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
302
+ self.act_fn = ACT2FN[config.hidden_act] if hidden_act is None else ACT2FN[hidden_act]
303
+
304
+ def forward(self, x):
305
+ if self.config.pretraining_tp > 1:
306
+ slice = self.intermediate_size // self.config.pretraining_tp
307
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
308
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
309
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
310
+
311
+ gate_proj = torch.cat(
312
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
313
+ )
314
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
315
+
316
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
317
+ down_proj = [
318
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
319
+ ]
320
+ down_proj = sum(down_proj)
321
+ else:
322
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
323
+
324
+ return down_proj
325
+
326
+ class XverseMoEMLP(nn.Module):
327
+ def __init__(
328
+ self,
329
+ config: XverseConfig,
330
+ hidden_size: int,
331
+ intermediate_size: int,
332
+ hidden_act: str,
333
+ ):
334
+ super().__init__()
335
+ self.config = config
336
+ self.top_k = config.moe_top_k
337
+ self.num_experts = config.num_experts
338
+ self.num_shared_experts = config.num_shared_experts if config.num_shared_experts is not None else None
339
+
340
+ self.router = nn.Linear(hidden_size, self.num_experts, bias=False, dtype=torch.float)
341
+ self.experts = nn.ModuleList([XverseMLP(config, hidden_size, intermediate_size, hidden_act) for _ in range(self.num_experts)])
342
+ if self.num_shared_experts is not None:
343
+ self.shared_experts = XverseMLP(config, hidden_size, self.num_shared_experts * intermediate_size, hidden_act)
344
+
345
+ def forward(self, hidden_states):
346
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
347
+
348
+ final_hidden_states = torch.zeros(
349
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
350
+ )
351
+
352
+ input_dtype = hidden_states.dtype
353
+ hidden_states = hidden_states.view(-1, hidden_dim).float()
354
+
355
+ router_logits = self.router(hidden_states)
356
+
357
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
358
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
359
+
360
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts)
361
+ expert_mask = expert_mask.permute(2, 1, 0)
362
+
363
+ routing_weights /= (routing_weights.sum(dim=-1, keepdim=True) + 1e-06)
364
+
365
+ routing_weights = routing_weights.to(input_dtype)
366
+ hidden_states = hidden_states.to(input_dtype)
367
+
368
+ for expert_idx, expert_layer in enumerate(self.experts):
369
+ idx, top_x = torch.where(expert_mask[expert_idx])
370
+
371
+ if top_x.shape[0] == 0:
372
+ continue
373
+
374
+ top_x_list = top_x.tolist()
375
+ idx_list = idx.tolist()
376
+
377
+ current_state = hidden_states[None, top_x_list].view(-1, hidden_dim)
378
+ current_hidden_states = expert_layer(current_state)
379
+ current_hidden_states = current_hidden_states * routing_weights[top_x_list, idx_list, None]
380
+
381
+ final_hidden_states.index_add_(0, top_x, current_hidden_states)
382
+
383
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
384
+
385
+ if self.num_shared_experts is not None:
386
+ hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim)
387
+ shared_hidden = self.shared_experts(hidden_states)
388
+ final_hidden_states = final_hidden_states + shared_hidden
389
+
390
+ return final_hidden_states, router_logits
391
+
392
+
393
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
394
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
395
+ """
396
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
397
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
398
+ """
399
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
400
+ if n_rep == 1:
401
+ return hidden_states
402
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
403
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
404
+
405
+
406
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->Xverse
407
+ class XverseAttention(nn.Module):
408
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
409
+
410
+ def __init__(self, config: XverseConfig, layer_idx: Optional[int] = None):
411
+ super().__init__()
412
+ self.config = config
413
+ self.layer_idx = layer_idx
414
+ if layer_idx is None:
415
+ logger.warning_once(
416
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
417
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
418
+ "when creating this class."
419
+ )
420
+
421
+ self.attention_dropout = config.attention_dropout
422
+ self.hidden_size = config.hidden_size
423
+ self.num_heads = config.num_attention_heads
424
+ self.head_dim = self.hidden_size // self.num_heads
425
+ self.num_key_value_heads = config.num_key_value_heads
426
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
427
+ self.max_position_embeddings = config.max_position_embeddings
428
+ self.rope_theta = config.rope_theta
429
+ self.is_causal = True
430
+
431
+ if (self.head_dim * self.num_heads) != self.hidden_size:
432
+ raise ValueError(
433
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
434
+ f" and `num_heads`: {self.num_heads})."
435
+ )
436
+
437
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
438
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
439
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
440
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
441
+ self._init_rope()
442
+
443
+ def _init_rope(self):
444
+ if self.config.rope_scaling is None:
445
+ self.rotary_emb = XverseRotaryEmbedding(
446
+ self.head_dim,
447
+ max_position_embeddings=self.max_position_embeddings,
448
+ base=self.rope_theta,
449
+ )
450
+ else:
451
+ scaling_type = self.config.rope_scaling["type"]
452
+ scaling_factor = self.config.rope_scaling["factor"]
453
+ if scaling_type == "linear":
454
+ self.rotary_emb = XverseLinearScalingRotaryEmbedding(
455
+ self.head_dim,
456
+ max_position_embeddings=self.max_position_embeddings,
457
+ scaling_factor=scaling_factor,
458
+ base=self.rope_theta,
459
+ )
460
+ elif scaling_type == "dynamic":
461
+ self.rotary_emb = XverseDynamicNTKScalingRotaryEmbedding(
462
+ self.head_dim,
463
+ max_position_embeddings=self.max_position_embeddings,
464
+ scaling_factor=scaling_factor,
465
+ base=self.rope_theta,
466
+ )
467
+ else:
468
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
469
+
470
+ def forward(
471
+ self,
472
+ hidden_states: torch.Tensor,
473
+ attention_mask: Optional[torch.Tensor] = None,
474
+ position_ids: Optional[torch.LongTensor] = None,
475
+ past_key_value: Optional[Cache] = None,
476
+ output_attentions: bool = False,
477
+ use_cache: bool = False,
478
+ cache_position: Optional[torch.LongTensor] = None,
479
+ **kwargs,
480
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
481
+ bsz, q_len, _ = hidden_states.size()
482
+
483
+ if self.config.pretraining_tp > 1:
484
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
485
+ query_slices = self.q_proj.weight.split(
486
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
487
+ )
488
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
489
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
490
+
491
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
492
+ query_states = torch.cat(query_states, dim=-1)
493
+
494
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
495
+ key_states = torch.cat(key_states, dim=-1)
496
+
497
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
498
+ value_states = torch.cat(value_states, dim=-1)
499
+
500
+ else:
501
+ query_states = self.q_proj(hidden_states)
502
+ key_states = self.k_proj(hidden_states)
503
+ value_states = self.v_proj(hidden_states)
504
+
505
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
506
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
507
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
508
+
509
+ past_key_value = getattr(self, "past_key_value", past_key_value)
510
+ cos, sin = self.rotary_emb(value_states, position_ids)
511
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
512
+
513
+ if past_key_value is not None:
514
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
515
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
516
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
517
+
518
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
519
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
520
+
521
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
522
+
523
+ if attention_mask is not None: # no matter the length, we just slice it
524
+ causal_mask = attention_mask
525
+ if cache_position is not None:
526
+ causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]]
527
+ attn_weights = attn_weights + causal_mask
528
+
529
+ # upcast attention to fp32
530
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
531
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
532
+ attn_output = torch.matmul(attn_weights, value_states)
533
+
534
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
535
+ raise ValueError(
536
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
537
+ f" {attn_output.size()}"
538
+ )
539
+
540
+ attn_output = attn_output.transpose(1, 2).contiguous()
541
+
542
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
543
+
544
+ if self.config.pretraining_tp > 1:
545
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
546
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
547
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
548
+ else:
549
+ attn_output = self.o_proj(attn_output)
550
+
551
+ if not output_attentions:
552
+ attn_weights = None
553
+
554
+ return attn_output, attn_weights, past_key_value
555
+
556
+
557
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Xverse
558
+ class XverseFlashAttention2(XverseAttention):
559
+ """
560
+ xverse flash attention module. This module inherits from `XverseAttention` as the weights of the module stays
561
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
562
+ flash attention and deal with padding tokens in case the input contains any of them.
563
+ """
564
+
565
+ def __init__(self, *args, **kwargs):
566
+ super().__init__(*args, **kwargs)
567
+
568
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
569
+ # 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.
570
+ # 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).
571
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
572
+
573
+ def forward(
574
+ self,
575
+ hidden_states: torch.Tensor,
576
+ attention_mask: Optional[torch.LongTensor] = None,
577
+ position_ids: Optional[torch.LongTensor] = None,
578
+ past_key_value: Optional[Cache] = None,
579
+ output_attentions: bool = False,
580
+ use_cache: bool = False,
581
+ cache_position: Optional[torch.LongTensor] = None,
582
+ **kwargs,
583
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
584
+ output_attentions = False
585
+
586
+ bsz, q_len, _ = hidden_states.size()
587
+
588
+ query_states = self.q_proj(hidden_states)
589
+ key_states = self.k_proj(hidden_states)
590
+ value_states = self.v_proj(hidden_states)
591
+
592
+ # Flash attention requires the input to have the shape
593
+ # batch_size x seq_length x head_dim x hidden_dim
594
+ # therefore we just need to keep the original shape
595
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
596
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
597
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
598
+
599
+ cos, sin = self.rotary_emb(value_states, position_ids)
600
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
601
+
602
+ past_key_value = getattr(self, "past_key_value", past_key_value)
603
+
604
+ if past_key_value is not None:
605
+ # sin and cos are specific to RoPE models; position_ids 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
+ # 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
610
+ # to be able to avoid many of these transpose/reshape/view.
611
+ query_states = query_states.transpose(1, 2)
612
+ key_states = key_states.transpose(1, 2)
613
+ value_states = value_states.transpose(1, 2)
614
+
615
+ dropout_rate = self.attention_dropout if self.training else 0.0
616
+
617
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
618
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
619
+ # cast them back in the correct dtype just to be sure everything works as expected.
620
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
621
+ # in fp32. (XverseRMSNorm handles it correctly)
622
+
623
+ input_dtype = query_states.dtype
624
+ if input_dtype == torch.float32:
625
+ if torch.is_autocast_enabled():
626
+ target_dtype = torch.get_autocast_gpu_dtype()
627
+ # Handle the case where the model is quantized
628
+ elif hasattr(self.config, "_pre_quantization_dtype"):
629
+ target_dtype = self.config._pre_quantization_dtype
630
+ else:
631
+ target_dtype = self.q_proj.weight.dtype
632
+
633
+ logger.warning_once(
634
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
635
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
636
+ f" {target_dtype}."
637
+ )
638
+
639
+ query_states = query_states.to(target_dtype)
640
+ key_states = key_states.to(target_dtype)
641
+ value_states = value_states.to(target_dtype)
642
+
643
+ attn_output = self._flash_attention_forward(
644
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
645
+ )
646
+
647
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
648
+ attn_output = self.o_proj(attn_output)
649
+
650
+ if not output_attentions:
651
+ attn_weights = None
652
+
653
+ return attn_output, attn_weights, past_key_value
654
+
655
+ def _flash_attention_forward(
656
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
657
+ ):
658
+ """
659
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
660
+ first unpad the input, then computes the attention scores and pad the final attention scores.
661
+
662
+ Args:
663
+ query_states (`torch.Tensor`):
664
+ Input query states to be passed to Flash Attention API
665
+ key_states (`torch.Tensor`):
666
+ Input key states to be passed to Flash Attention API
667
+ value_states (`torch.Tensor`):
668
+ Input value states to be passed to Flash Attention API
669
+ attention_mask (`torch.Tensor`):
670
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
671
+ position of padding tokens and 1 for the position of non-padding tokens.
672
+ dropout (`int`, *optional*):
673
+ Attention dropout
674
+ softmax_scale (`float`, *optional*):
675
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
676
+ """
677
+ if not self._flash_attn_uses_top_left_mask:
678
+ causal = self.is_causal
679
+ else:
680
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in XverseFlashAttention2 __init__.
681
+ causal = self.is_causal and query_length != 1
682
+
683
+ # Contains at least one padding token in the sequence
684
+ if attention_mask is not None:
685
+ batch_size = query_states.shape[0]
686
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
687
+ query_states, key_states, value_states, attention_mask, query_length
688
+ )
689
+
690
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
691
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
692
+
693
+ attn_output_unpad = flash_attn_varlen_func(
694
+ query_states,
695
+ key_states,
696
+ value_states,
697
+ cu_seqlens_q=cu_seqlens_q,
698
+ cu_seqlens_k=cu_seqlens_k,
699
+ max_seqlen_q=max_seqlen_in_batch_q,
700
+ max_seqlen_k=max_seqlen_in_batch_k,
701
+ dropout_p=dropout,
702
+ softmax_scale=softmax_scale,
703
+ causal=causal,
704
+ )
705
+
706
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
707
+ else:
708
+ attn_output = flash_attn_func(
709
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
710
+ )
711
+
712
+ return attn_output
713
+
714
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
715
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
716
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
717
+
718
+ key_layer = index_first_axis(
719
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
720
+ )
721
+ value_layer = index_first_axis(
722
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
723
+ )
724
+ if query_length == kv_seq_len:
725
+ query_layer = index_first_axis(
726
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
727
+ )
728
+ cu_seqlens_q = cu_seqlens_k
729
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
730
+ indices_q = indices_k
731
+ elif query_length == 1:
732
+ max_seqlen_in_batch_q = 1
733
+ cu_seqlens_q = torch.arange(
734
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
735
+ ) # There is a memcpy here, that is very bad.
736
+ indices_q = cu_seqlens_q[:-1]
737
+ query_layer = query_layer.squeeze(1)
738
+ else:
739
+ # The -q_len: slice assumes left padding.
740
+ attention_mask = attention_mask[:, -query_length:]
741
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
742
+
743
+ return (
744
+ query_layer,
745
+ key_layer,
746
+ value_layer,
747
+ indices_q,
748
+ (cu_seqlens_q, cu_seqlens_k),
749
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
750
+ )
751
+
752
+
753
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Xverse
754
+ class XverseSdpaAttention(XverseAttention):
755
+ """
756
+ xverse attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
757
+ `XverseAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
758
+ SDPA API.
759
+ """
760
+
761
+ # Adapted from XverseAttention.forward
762
+ def forward(
763
+ self,
764
+ hidden_states: torch.Tensor,
765
+ attention_mask: Optional[torch.Tensor] = None,
766
+ position_ids: Optional[torch.LongTensor] = None,
767
+ past_key_value: Optional[Cache] = None,
768
+ output_attentions: bool = False,
769
+ use_cache: bool = False,
770
+ cache_position: Optional[torch.LongTensor] = None,
771
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
772
+ if output_attentions:
773
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
774
+ logger.warning_once(
775
+ "XverseMoEModel is using XverseSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
776
+ '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.'
777
+ )
778
+ return super().forward(
779
+ hidden_states=hidden_states,
780
+ attention_mask=attention_mask,
781
+ position_ids=position_ids,
782
+ past_key_value=past_key_value,
783
+ output_attentions=output_attentions,
784
+ use_cache=use_cache,
785
+ cache_position=cache_position,
786
+ )
787
+
788
+ bsz, q_len, _ = hidden_states.size()
789
+
790
+ query_states = self.q_proj(hidden_states)
791
+ key_states = self.k_proj(hidden_states)
792
+ value_states = self.v_proj(hidden_states)
793
+
794
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
795
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
796
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
797
+
798
+ cos, sin = self.rotary_emb(value_states, position_ids)
799
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
800
+
801
+ # In case static cache is used, it is an instance attribute.
802
+ past_key_value = getattr(self, "past_key_value", past_key_value)
803
+
804
+ if past_key_value is not None:
805
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
806
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
807
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
808
+
809
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
810
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
811
+
812
+ causal_mask = attention_mask
813
+ if attention_mask is not None and cache_position is not None:
814
+ causal_mask = causal_mask[:, :, cache_position, : key_states.shape[-2]]
815
+
816
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
817
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
818
+ if query_states.device.type == "cuda" and causal_mask is not None:
819
+ query_states = query_states.contiguous()
820
+ key_states = key_states.contiguous()
821
+ value_states = value_states.contiguous()
822
+
823
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
824
+ query_states,
825
+ key_states,
826
+ value_states,
827
+ attn_mask=causal_mask,
828
+ dropout_p=self.attention_dropout if self.training else 0.0,
829
+ )
830
+
831
+ attn_output = attn_output.transpose(1, 2).contiguous()
832
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
833
+
834
+ attn_output = self.o_proj(attn_output)
835
+
836
+ return attn_output, None, past_key_value
837
+
838
+
839
+ XVERSE_ATTENTION_CLASSES = {
840
+ "eager": XverseAttention,
841
+ "flash_attention_2": XverseFlashAttention2,
842
+ "sdpa": XverseSdpaAttention,
843
+ }
844
+
845
+
846
+ class XverseMoEDecoderLayer(nn.Module):
847
+ def __init__(self, config: XverseConfig, layer_idx: int):
848
+ super().__init__()
849
+ self.hidden_size = config.hidden_size
850
+
851
+ self.self_attn = XVERSE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
852
+
853
+ self.mlp = XverseMoEMLP(
854
+ config=config,
855
+ hidden_size=self.hidden_size,
856
+ intermediate_size=config.intermediate_size,
857
+ hidden_act=config.hidden_act,
858
+ )
859
+ self.input_layernorm = XverseRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
860
+ self.post_attention_layernorm = XverseRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
861
+
862
+ def forward(
863
+ self,
864
+ hidden_states: torch.Tensor,
865
+ attention_mask: Optional[torch.Tensor] = None,
866
+ position_ids: Optional[torch.LongTensor] = None,
867
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
868
+ output_attentions: Optional[bool] = False,
869
+ output_router_logits: Optional[bool] = False,
870
+ use_cache: Optional[bool] = False,
871
+ cache_position: Optional[torch.LongTensor] = None,
872
+ **kwargs,
873
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
874
+ """
875
+ Args:
876
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
877
+ attention_mask (`torch.FloatTensor`, *optional*):
878
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
879
+ query_sequence_length, key_sequence_length)` if default attention is used.
880
+ output_attentions (`bool`, *optional*):
881
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
882
+ returned tensors for more detail.
883
+ output_router_logits (`bool`, optional): Whether or not to return the router logits.
884
+ use_cache (`bool`, *optional*):
885
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
886
+ (see `past_key_values`).
887
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
888
+ """
889
+ if "padding_mask" in kwargs:
890
+ warnings.warn(
891
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
892
+ )
893
+
894
+ residual = hidden_states
895
+
896
+ hidden_states = self.input_layernorm(hidden_states)
897
+
898
+ # Self Attention
899
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
900
+ hidden_states=hidden_states,
901
+ attention_mask=attention_mask,
902
+ position_ids=position_ids,
903
+ past_key_value=past_key_value,
904
+ output_attentions=output_attentions,
905
+ use_cache=use_cache,
906
+ cache_position=cache_position,
907
+ **kwargs,
908
+ )
909
+ hidden_states = residual + hidden_states
910
+
911
+ # Fully Connected
912
+ residual = hidden_states
913
+ hidden_states = self.post_attention_layernorm(hidden_states)
914
+
915
+ hidden_states, router_logits = self.mlp(hidden_states)
916
+ # if isinstance(hidden_states, tuple):
917
+ # hidden_states, router_logits = hidden_states
918
+ # else:
919
+ # router_logits = None
920
+
921
+ hidden_states = residual + hidden_states
922
+
923
+ outputs = (hidden_states,)
924
+
925
+ if output_attentions:
926
+ outputs += (self_attn_weights,)
927
+
928
+ if use_cache:
929
+ outputs += (present_key_value,)
930
+
931
+ if output_router_logits:
932
+ outputs += (router_logits,)
933
+
934
+ return outputs
935
+
936
+
937
+ XVERSE_START_DOCSTRING = r"""
938
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
939
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
940
+ etc.)
941
+
942
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
943
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
944
+ and behavior.
945
+
946
+ Parameters:
947
+ config ([`XverseConfig`]):
948
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
949
+ load the weights associated with the model, only the configuration. Check out the
950
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
951
+ """
952
+
953
+
954
+ @add_start_docstrings(
955
+ "The bare Xverse Model outputting raw hidden-states without any specific head on top.",
956
+ XVERSE_START_DOCSTRING,
957
+ )
958
+ class XversePreTrainedModel(PreTrainedModel):
959
+ config_class = XverseConfig
960
+ base_model_prefix = "model"
961
+ supports_gradient_checkpointing = True
962
+ _no_split_modules = ["XverseMoEDecoderLayer"]
963
+ _skip_keys_device_placement = ["past_key_values"]
964
+ _supports_flash_attn_2 = True
965
+ _supports_sdpa = True
966
+ _supports_cache_class = True
967
+
968
+ def _init_weights(self, module):
969
+ std = self.config.initializer_range
970
+ if isinstance(module, nn.Linear):
971
+ module.weight.data.normal_(mean=0.0, std=std)
972
+ if module.bias is not None:
973
+ module.bias.data.zero_()
974
+ elif isinstance(module, nn.Embedding):
975
+ module.weight.data.normal_(mean=0.0, std=std)
976
+ if module.padding_idx is not None:
977
+ module.weight.data[module.padding_idx].zero_()
978
+
979
+ def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
980
+ if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
981
+ raise ValueError(
982
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
983
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
984
+ )
985
+
986
+ if max_cache_len > self.model.causal_mask.shape[-1] or self.device != self.model.causal_mask.device:
987
+ causal_mask = torch.full(
988
+ (max_cache_len, max_cache_len), fill_value=True, device=self.device, dtype=torch.bool
989
+ )
990
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
991
+
992
+ for layer in self.model.layers:
993
+ weights = layer.self_attn.o_proj.weight
994
+ layer.self_attn.past_key_value = cache_cls(
995
+ self.config, max_batch_size, max_cache_len, device=weights.device, dtype=weights.dtype
996
+ )
997
+
998
+ def _reset_cache(self):
999
+ for layer in self.model.layers:
1000
+ layer.self_attn.past_key_value = None
1001
+
1002
+
1003
+ XVERSE_INPUTS_DOCSTRING = r"""
1004
+ Args:
1005
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1006
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1007
+ it.
1008
+
1009
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1010
+ [`PreTrainedTokenizer.__call__`] for details.
1011
+
1012
+ [What are input IDs?](../glossary#input-ids)
1013
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1014
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1015
+
1016
+ - 1 for tokens that are **not masked**,
1017
+ - 0 for tokens that are **masked**.
1018
+
1019
+ [What are attention masks?](../glossary#attention-mask)
1020
+
1021
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1022
+ [`PreTrainedTokenizer.__call__`] for details.
1023
+
1024
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1025
+ `past_key_values`).
1026
+
1027
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1028
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1029
+ information on the default strategy.
1030
+
1031
+ - 1 indicates the head is **not masked**,
1032
+ - 0 indicates the head is **masked**.
1033
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1034
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1035
+ config.n_positions - 1]`.
1036
+
1037
+ [What are position IDs?](../glossary#position-ids)
1038
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1039
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1040
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1041
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1042
+
1043
+ Two formats are allowed:
1044
+ - a [`~cache_utils.Cache`] instance;
1045
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1046
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1047
+ cache format.
1048
+
1049
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1050
+ legacy cache format will be returned.
1051
+
1052
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1053
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1054
+ of shape `(batch_size, sequence_length)`.
1055
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1056
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1057
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1058
+ model's internal embedding lookup matrix.
1059
+ use_cache (`bool`, *optional*):
1060
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1061
+ `past_key_values`).
1062
+ output_attentions (`bool`, *optional*):
1063
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1064
+ tensors for more detail.
1065
+ output_hidden_states (`bool`, *optional*):
1066
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1067
+ more detail.
1068
+ return_dict (`bool`, *optional*):
1069
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1070
+ """
1071
+
1072
+
1073
+ @add_start_docstrings(
1074
+ "The bare xverse Model outputting raw hidden-states without any specific head on top.",
1075
+ XVERSE_START_DOCSTRING,
1076
+ )
1077
+ class XverseMoEModel(XversePreTrainedModel):
1078
+ """
1079
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`XverseMoEDecoderLayer`]
1080
+
1081
+ Args:
1082
+ config: XverseConfig
1083
+ """
1084
+
1085
+ def __init__(self, config: XverseConfig):
1086
+ super().__init__(config)
1087
+ self.padding_idx = config.pad_token_id
1088
+ self.vocab_size = config.vocab_size
1089
+
1090
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1091
+ self.layers = nn.ModuleList(
1092
+ [XverseMoEDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1093
+ )
1094
+ self.norm = XverseRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1095
+ self.gradient_checkpointing = False
1096
+
1097
+ # Register a causal mask to separate causal and padding mask creation. Merging happens in the attention class.
1098
+ # NOTE: This is not friendly with TorchScript, ONNX, ExportedProgram serialization for very large `max_position_embeddings`.
1099
+ causal_mask = torch.full(
1100
+ (config.max_position_embeddings, config.max_position_embeddings), fill_value=True, dtype=torch.bool
1101
+ )
1102
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
1103
+ # Initialize weights and apply final processing
1104
+ self.post_init()
1105
+
1106
+ def get_input_embeddings(self):
1107
+ return self.embed_tokens
1108
+
1109
+ def set_input_embeddings(self, value):
1110
+ self.embed_tokens = value
1111
+
1112
+ @add_start_docstrings_to_model_forward(XVERSE_INPUTS_DOCSTRING)
1113
+ def forward(
1114
+ self,
1115
+ input_ids: torch.LongTensor = None,
1116
+ attention_mask: Optional[torch.Tensor] = None,
1117
+ position_ids: Optional[torch.LongTensor] = None,
1118
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1119
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1120
+ use_cache: Optional[bool] = None,
1121
+ output_attentions: Optional[bool] = None,
1122
+ output_hidden_states: Optional[bool] = None,
1123
+ output_router_logits: Optional[bool] = None,
1124
+ return_dict: Optional[bool] = None,
1125
+ cache_position: Optional[torch.LongTensor] = None,
1126
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1127
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1128
+ output_router_logits = (
1129
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1130
+ )
1131
+ output_hidden_states = (
1132
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1133
+ )
1134
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1135
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1136
+
1137
+ if (input_ids is None) ^ (inputs_embeds is not None):
1138
+ raise ValueError(
1139
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1140
+ )
1141
+
1142
+ if self.gradient_checkpointing and self.training and use_cache:
1143
+ logger.warning_once(
1144
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1145
+ )
1146
+ use_cache = False
1147
+
1148
+ if inputs_embeds is None:
1149
+ inputs_embeds = self.embed_tokens(input_ids)
1150
+
1151
+ past_seen_tokens = 0
1152
+ if use_cache: # kept for BC (cache positions)
1153
+ if not isinstance(past_key_values, StaticCache):
1154
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1155
+ past_seen_tokens = past_key_values.get_seq_length()
1156
+
1157
+ if cache_position is None:
1158
+ if isinstance(past_key_values, StaticCache):
1159
+ raise ValueError("cache_position is a required argument when using StaticCache.")
1160
+ cache_position = torch.arange(
1161
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1162
+ )
1163
+
1164
+ if position_ids is None:
1165
+ position_ids = cache_position.unsqueeze(0)
1166
+
1167
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds)
1168
+
1169
+ # embed positions
1170
+ hidden_states = inputs_embeds
1171
+
1172
+ # decoder layers
1173
+ all_hidden_states = () if output_hidden_states else None
1174
+ all_self_attns = () if output_attentions else None
1175
+ all_router_logits = () if output_router_logits else None
1176
+ next_decoder_cache = None
1177
+
1178
+ for decoder_layer in self.layers:
1179
+ if output_hidden_states:
1180
+ all_hidden_states += (hidden_states,)
1181
+
1182
+ if self.gradient_checkpointing and self.training:
1183
+ layer_outputs = self._gradient_checkpointing_func(
1184
+ decoder_layer.__call__,
1185
+ hidden_states,
1186
+ causal_mask,
1187
+ position_ids,
1188
+ past_key_values,
1189
+ output_attentions,
1190
+ output_router_logits,
1191
+ use_cache,
1192
+ cache_position,
1193
+ )
1194
+ else:
1195
+ layer_outputs = decoder_layer(
1196
+ hidden_states,
1197
+ attention_mask=causal_mask,
1198
+ position_ids=position_ids,
1199
+ past_key_value=past_key_values,
1200
+ output_attentions=output_attentions,
1201
+ output_router_logits=output_router_logits,
1202
+ use_cache=use_cache,
1203
+ cache_position=cache_position,
1204
+ )
1205
+
1206
+ hidden_states = layer_outputs[0]
1207
+
1208
+ if use_cache:
1209
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1210
+
1211
+ if output_attentions:
1212
+ all_self_attns += (layer_outputs[1],)
1213
+
1214
+ if output_router_logits:
1215
+ all_router_logits += (layer_outputs[-1],)
1216
+
1217
+ hidden_states = self.norm(hidden_states)
1218
+
1219
+ # add hidden states from the last decoder layer
1220
+ if output_hidden_states:
1221
+ all_hidden_states += (hidden_states,)
1222
+
1223
+ next_cache = None
1224
+ if use_cache:
1225
+ next_cache = (
1226
+ next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
1227
+ )
1228
+ if not return_dict:
1229
+ return tuple(v for v in [
1230
+ hidden_states, next_cache, all_hidden_states, all_self_attns,
1231
+ all_router_logits
1232
+ ] if v is not None)
1233
+
1234
+ return MoeModelOutputWithPast(
1235
+ last_hidden_state=hidden_states,
1236
+ past_key_values=next_cache,
1237
+ hidden_states=all_hidden_states,
1238
+ attentions=all_self_attns,
1239
+ router_logits=all_router_logits,
1240
+ )
1241
+
1242
+ # 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
1243
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1244
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1245
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1246
+ def _update_causal_mask(self, attention_mask, input_tensor):
1247
+ if self.config._attn_implementation == "flash_attention_2":
1248
+ if attention_mask is not None and 0.0 in attention_mask:
1249
+ return attention_mask
1250
+ return None
1251
+
1252
+ batch_size, seq_length = input_tensor.shape[:2]
1253
+ dtype = input_tensor.dtype
1254
+ device = input_tensor.device
1255
+
1256
+ # support going beyond cached `max_position_embedding`
1257
+ if seq_length > self.causal_mask.shape[-1]:
1258
+ causal_mask = torch.full((2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]), fill_value=1)
1259
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
1260
+
1261
+ # We use the current dtype to avoid any overflows
1262
+ min_dtype = torch.finfo(dtype).min
1263
+ causal_mask = self.causal_mask[None, None, :, :].repeat(batch_size, 1, 1, 1).to(dtype) * min_dtype
1264
+
1265
+ causal_mask = causal_mask.to(dtype=dtype, device=device)
1266
+ if attention_mask is not None and attention_mask.dim() == 2:
1267
+ mask_length = attention_mask.shape[-1]
1268
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1269
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1270
+
1271
+ if self.config._attn_implementation == "sdpa" and attention_mask is not None:
1272
+ # TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
1273
+ is_tracing = (
1274
+ torch.jit.is_tracing()
1275
+ or isinstance(input_tensor, torch.fx.Proxy)
1276
+ or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling())
1277
+ )
1278
+ if not is_tracing and torch.any(attention_mask != 1):
1279
+ # Attend to all tokens in masked rows from the causal_mask, for example the relevant first rows when
1280
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1281
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1282
+ causal_mask = causal_mask.mul(~torch.all(causal_mask == min_dtype, dim=-1, keepdim=True)).to(dtype)
1283
+
1284
+ return causal_mask
1285
+ class XverseForCausalLM(XversePreTrainedModel):
1286
+ _tied_weights_keys = ["lm_head.weight"]
1287
+
1288
+ def __init__(self, config):
1289
+ super().__init__(config)
1290
+ self.model = XverseMoEModel(config)
1291
+ self.vocab_size = config.vocab_size
1292
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1293
+
1294
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1295
+ self.num_experts = config.num_experts
1296
+ self.moe_top_k = config.moe_top_k
1297
+ # Initialize weights and apply final processing
1298
+ self.post_init()
1299
+
1300
+ def get_input_embeddings(self):
1301
+ return self.model.embed_tokens
1302
+
1303
+ def set_input_embeddings(self, value):
1304
+ self.model.embed_tokens = value
1305
+
1306
+ def get_output_embeddings(self):
1307
+ return self.lm_head
1308
+
1309
+ def set_output_embeddings(self, new_embeddings):
1310
+ self.lm_head = new_embeddings
1311
+
1312
+ def set_decoder(self, decoder):
1313
+ self.model = decoder
1314
+
1315
+ def get_decoder(self):
1316
+ return self.model
1317
+
1318
+ @add_start_docstrings_to_model_forward(XVERSE_INPUTS_DOCSTRING)
1319
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1320
+ def forward(
1321
+ self,
1322
+ input_ids: torch.LongTensor = None,
1323
+ attention_mask: Optional[torch.Tensor] = None,
1324
+ position_ids: Optional[torch.LongTensor] = None,
1325
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1326
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1327
+ labels: Optional[torch.LongTensor] = None,
1328
+ use_cache: Optional[bool] = None,
1329
+ output_attentions: Optional[bool] = None,
1330
+ output_hidden_states: Optional[bool] = None,
1331
+ output_router_logits: Optional[bool] = None,
1332
+ return_dict: Optional[bool] = None,
1333
+ cache_position: Optional[torch.LongTensor] = None,
1334
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1335
+ r"""
1336
+ Args:
1337
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1338
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1339
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1340
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1341
+
1342
+ Returns:
1343
+
1344
+ Example:
1345
+
1346
+ ```python
1347
+ >>> from transformers import AutoTokenizer, XverseForCausalLM
1348
+
1349
+ >>> model = XverseForCausalLM.from_pretrained("meta-xverse/xverse-2-7b-hf")
1350
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-xverse/xverse-2-7b-hf")
1351
+
1352
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1353
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1354
+
1355
+ >>> # Generate
1356
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1357
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1358
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1359
+ ```"""
1360
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1361
+ output_router_logits = (
1362
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1363
+ )
1364
+ output_hidden_states = (
1365
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1366
+ )
1367
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1368
+
1369
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1370
+ outputs = self.model(
1371
+ input_ids=input_ids,
1372
+ attention_mask=attention_mask,
1373
+ position_ids=position_ids,
1374
+ past_key_values=past_key_values,
1375
+ inputs_embeds=inputs_embeds,
1376
+ use_cache=use_cache,
1377
+ output_attentions=output_attentions,
1378
+ output_hidden_states=output_hidden_states,
1379
+ output_router_logits=output_router_logits,
1380
+ return_dict=return_dict,
1381
+ cache_position=cache_position,
1382
+ )
1383
+
1384
+ hidden_states = outputs[0]
1385
+ if self.config.pretraining_tp > 1:
1386
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1387
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1388
+ logits = torch.cat(logits, dim=-1)
1389
+ else:
1390
+ logits = self.lm_head(hidden_states)
1391
+ logits = logits.float()
1392
+
1393
+ loss = None
1394
+ if labels is not None:
1395
+ # Shift so that tokens < n predict n
1396
+ shift_logits = logits[..., :-1, :].contiguous()
1397
+ shift_labels = labels[..., 1:].contiguous()
1398
+ # Flatten the tokens
1399
+ loss_fct = CrossEntropyLoss()
1400
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1401
+ shift_labels = shift_labels.view(-1)
1402
+ # Enable model parallelism
1403
+ shift_labels = shift_labels.to(shift_logits.device)
1404
+ loss = loss_fct(shift_logits, shift_labels)
1405
+
1406
+ aux_loss = None
1407
+ if output_router_logits:
1408
+ aux_loss = load_balancing_loss_func(
1409
+ outputs.router_logits if return_dict else outputs[-1],
1410
+ self.num_experts,
1411
+ self.moe_top_k,
1412
+ attention_mask,
1413
+ )
1414
+ if labels is not None:
1415
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1416
+
1417
+ if not return_dict:
1418
+ output = (logits,) + outputs[1:]
1419
+ if output_router_logits:
1420
+ output = (aux_loss,) + output
1421
+ return (loss,) + output if loss is not None else output
1422
+
1423
+ return MoeCausalLMOutputWithPast(
1424
+ loss=loss,
1425
+ aux_loss=aux_loss,
1426
+ logits=logits,
1427
+ past_key_values=outputs.past_key_values,
1428
+ hidden_states=outputs.hidden_states,
1429
+ attentions=outputs.attentions,
1430
+ router_logits=outputs.router_logits,
1431
+ )
1432
+
1433
+ def _build_chat_input(self, tokenizer, messages: List[dict], max_new_tokens: int=2048):
1434
+ max_new_tokens = max_new_tokens or self.generation_config.max_new_tokens
1435
+ max_input_tokens = self.config.max_position_embeddings - max_new_tokens
1436
+ max_input_tokens = max(self.config.max_position_embeddings // 2, max_input_tokens)
1437
+ max_input_tokens = min(self.config.max_tokenizer_truncation, max_input_tokens)
1438
+
1439
+ total_input, round_input = [], []
1440
+ system_prompt_tokens = tokenizer.encode("system: ", return_token_type_ids=False)
1441
+ user_prompt_tokens = tokenizer.encode("user: ", return_token_type_ids=False)
1442
+ exec_prompt_tokens = tokenizer.encode("exec: ", return_token_type_ids=False)
1443
+ assist_prompt_tokens = tokenizer.encode("assistant: ", return_token_type_ids=False)
1444
+ assist_prompt_len = len(assist_prompt_tokens)
1445
+
1446
+ for i, message in enumerate(messages[::-1]):
1447
+ if message['role'] == 'user' or message['role'] == 'exec':
1448
+ user_content = f"{message['content']}\n"
1449
+ content_tokens = user_prompt_tokens + tokenizer.encode(user_content, return_token_type_ids=False) if message['role'] == 'user' else \
1450
+ exec_prompt_tokens + tokenizer.encode(user_content, return_token_type_ids=False)
1451
+ if i == 0:
1452
+ content_tokens = content_tokens[:max_input_tokens-assist_prompt_len]
1453
+ content_tokens += assist_prompt_tokens
1454
+ round_input = content_tokens + round_input
1455
+
1456
+ if i != 0:
1457
+ if len(total_input) + len(round_input) > max_input_tokens:
1458
+ break
1459
+ else:
1460
+ total_input = round_input + total_input
1461
+ else:
1462
+ total_input = round_input + total_input
1463
+ if len(total_input) >= max_input_tokens:
1464
+ break
1465
+ round_input = []
1466
+ elif message['role'] == 'assistant':
1467
+ assist_content = f"{message['content']}"
1468
+ content_tokens = assist_prompt_tokens + tokenizer.encode(assist_content, return_token_type_ids=False)
1469
+ round_input = content_tokens + [self.generation_config.eos_token_id] + round_input
1470
+ elif message['role'] == 'system':
1471
+ assert i == len(messages) - 1
1472
+ user_content = f"{message['content']}\n"
1473
+ content_tokens = tokenizer.encode(user_content, return_token_type_ids=False)
1474
+ round_input = system_prompt_tokens + content_tokens + round_input
1475
+ if len(total_input) + len(round_input) > max_input_tokens:
1476
+ break
1477
+ else:
1478
+ total_input = round_input + total_input
1479
+ else:
1480
+ raise ValueError(f"message role not supported yet: {message['role']}")
1481
+ total_input = torch.LongTensor([total_input]).to(self.device)
1482
+ return total_input
1483
+
1484
+ @torch.no_grad()
1485
+ def chat(self, tokenizer, messages: List[dict], stream=False,
1486
+ generation_config: Optional[GenerationConfig]=None):
1487
+ generation_config = generation_config or self.generation_config
1488
+ input_ids = self._build_chat_input(tokenizer, messages, generation_config.max_new_tokens)
1489
+ if stream:
1490
+ from transformers import TextIteratorStreamer
1491
+ from threading import Thread
1492
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True)
1493
+ self.__class__.generate = PreTrainedModel.generate
1494
+
1495
+ def stream_generator():
1496
+ generation_kwargs = dict(inputs=input_ids, generation_config=generation_config, streamer=streamer)
1497
+ thread = Thread(target=self.generate, kwargs=generation_kwargs)
1498
+ thread.start()
1499
+ for next_text in streamer:
1500
+ yield next_text.replace(tokenizer.eos_token, "")
1501
+
1502
+ return stream_generator()
1503
+ else:
1504
+ self.__class__.generate = PreTrainedModel.generate # disable stream
1505
+ outputs = self.generate(input_ids, generation_config=generation_config)
1506
+ response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
1507
+ return response
1508
+
1509
+ def prepare_inputs_for_generation(
1510
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
1511
+ ):
1512
+ # With static cache, the `past_key_values` is None
1513
+ # TODO joao: standardize interface for the different Cache classes and remove of this if
1514
+ has_static_cache = False
1515
+ if past_key_values is None:
1516
+ past_key_values = getattr(getattr(self.model.layers[0], "self_attn", {}), "past_key_value", None)
1517
+ has_static_cache = past_key_values is not None
1518
+
1519
+ past_length = 0
1520
+ if past_key_values is not None:
1521
+ if isinstance(past_key_values, Cache):
1522
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1523
+ max_cache_length = (
1524
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1525
+ if past_key_values.get_max_length() is not None
1526
+ else None
1527
+ )
1528
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1529
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1530
+ else:
1531
+ cache_length = past_length = past_key_values[0][0].shape[2]
1532
+ max_cache_length = None
1533
+
1534
+ # Keep only the unprocessed tokens:
1535
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1536
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1537
+ # input)
1538
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1539
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1540
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1541
+ # input_ids based on the past_length.
1542
+ elif past_length < input_ids.shape[1]:
1543
+ input_ids = input_ids[:, past_length:]
1544
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1545
+
1546
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1547
+ if (
1548
+ max_cache_length is not None
1549
+ and attention_mask is not None
1550
+ and cache_length + input_ids.shape[1] > max_cache_length
1551
+ ):
1552
+ attention_mask = attention_mask[:, -max_cache_length:]
1553
+
1554
+ position_ids = kwargs.get("position_ids", None)
1555
+ if attention_mask is not None and position_ids is None:
1556
+ # create position_ids on the fly for batch generation
1557
+ position_ids = attention_mask.long().cumsum(-1) - 1
1558
+ position_ids.masked_fill_(attention_mask == 0, 1)
1559
+ if past_key_values:
1560
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1561
+
1562
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1563
+ if inputs_embeds is not None and past_key_values is None:
1564
+ model_inputs = {"inputs_embeds": inputs_embeds}
1565
+ else:
1566
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1567
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1568
+ # TODO: use `next_tokens` directly instead.
1569
+ model_inputs = {"input_ids": input_ids.contiguous()}
1570
+
1571
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1572
+ if cache_position is None:
1573
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1574
+ else:
1575
+ cache_position = cache_position[-input_length:]
1576
+
1577
+ if has_static_cache:
1578
+ past_key_values = None
1579
+
1580
+ model_inputs.update(
1581
+ {
1582
+ "position_ids": position_ids,
1583
+ "cache_position": cache_position,
1584
+ "past_key_values": past_key_values,
1585
+ "use_cache": kwargs.get("use_cache"),
1586
+ "attention_mask": attention_mask,
1587
+ }
1588
+ )
1589
+ return model_inputs
1590
+
1591
+ @staticmethod
1592
+ def _reorder_cache(past_key_values, beam_idx):
1593
+ reordered_past = ()
1594
+ for layer_past in past_key_values:
1595
+ reordered_past += (
1596
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1597
+ )
1598
+ return reordered_past
pytorch_model-00001-of-00009.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7017be7940fc9c0971bb0349723e57dd612125a104bf41e3913beacfeaf9d7bc
3
+ size 6089080734
pytorch_model-00002-of-00009.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0839d2494d052021005b9bc64da22ecce5d80e07619a4c8f3e6c83c6d87427cd
3
+ size 5998698635
pytorch_model-00003-of-00009.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4579382eeae2fae94c78e5c417b960f79d8bc8671847660ce3a9c0a5777453b
3
+ size 5998698955
pytorch_model-00004-of-00009.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:167a56ac4b0c25f5c1683059343d9da28e8667df77afa5bd1d73feea111780f1
3
+ size 5998699083
pytorch_model-00005-of-00009.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb37be3b134f47bfe7ab6187405172858f9d93b0a5f25f6adacbe2892e46cf25
3
+ size 5998699083
pytorch_model-00006-of-00009.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46fc44e3467d3dc6ab5d11c331d6c6cf6c810f186bb6e6c0ff9dbea83ea61cf0
3
+ size 5998699083
pytorch_model-00007-of-00009.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8ef06d6ec757b78af47433bc93389e30917d0804b66d589ee27c6d645659219
3
+ size 5998699083
pytorch_model-00008-of-00009.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb093b3e238d73df7ae34c3ddb9764565f3857bb50ed40f78915d0dfac6f4579
3
+ size 5998699083
pytorch_model-00009-of-00009.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3cae48f8d86790626ae208e18e669c514d59de1d9a8da98932e1cca97b29a2f6
3
+ size 3487596785
pytorch_model.bin.index.json ADDED
The diff for this file is too large to render. See raw diff
 
quantization.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bz2
2
+ import torch
3
+ import base64
4
+ import ctypes
5
+ from transformers.utils import logging
6
+ from typing import List
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+ try:
11
+ from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
12
+
13
+ class Kernel:
14
+ def __init__(self, code: bytes, function_names: List[str]):
15
+ self.code = code
16
+ self._function_names = function_names
17
+ self._cmodule = LazyKernelCModule(self.code)
18
+
19
+ for name in self._function_names:
20
+ setattr(self, name, KernelFunction(self._cmodule, name))
21
+
22
+ quantization_code = "QlpoOTFBWS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e8nYOww6SmqwRlZCysNdLaej4FTwo9nwXBZaWl5uatmmrfbrZbHBYNmrFtbJ7xtbTG6xYerb7LL2UmT9ur54D+5V6tPU3ozGSyZPEV4S6JYfyT7qaNGzVNDs8Feer6i9gfBrFpbzjfYr0Z4huT5zJk5VWwfzX45uNljyNDG05zZZKdtWi/ecFpYbIu+m0cllZZVlZHQPYDnh469YW+YyzGOs1S5DzmlyGLc62l2rDyDKuQ9jai4VknV0tK2tS0sZjDWVzstxY3VaP4afXf6L6++rhYwx42nFYXeLpTqVp3DHVMeFwJplHv2RyzDe41pTmr9dquVk5WI+7tqN7xMY51NrCwxYxWMMMUODVd94IflreuiuDS4Q8B+01PdWIeR7Z2PSboDmZBzTZbm0vlm+YamDe71cHDeLe3NLQx35tNze/Zd4OtZJ4H5jleDtaO1dLTc/Yf6Tit0uDFV/VZHc77k3njf+BwXQY7l3VpE6HQ1bjTVdzLwTiWkXW61jv/bfz2MftP2mn8hsbNmnfe1dlci/cpeBZe9O9Mb3ad5J4ZMoeVvXnvE3Vf8IfuPGfXMf/K309N6h2v/Rji5HmfdXovWedzucx3N7e+s7GzZvK6n3jxvabNmzc+0/BWl3nefl8G5cr7RzMaaP8jFsvuXMcFe0713O7ZfWn3pPaq4rdKejPByrzPUN6cBH6LZsTzcXrHkrrdfMONXA5hhyybH4Ru4LktC3T4dvvdXM7ThXPdPp7m9yTlH6VdKvbzBd4ZjJll3nAi+2sX31iU4m52d+92rlq6g9cftu+HkO1bx/+LuSKcKEhVMDc/A="
23
+
24
+ kernels = Kernel(
25
+ bz2.decompress(base64.b64decode(quantization_code)),
26
+ [
27
+ "weightInt8_int4",
28
+ "weightInt4_fp16",
29
+ "weightInt4_bf16"
30
+ ],
31
+ )
32
+ except Exception as exception:
33
+ kernels = None
34
+ logger.warning("Failed to load cpm_kernels:" + str(exception))
35
+
36
+
37
+ def quantize_int8(weight: torch.Tensor, bit_length: int):
38
+ weight_scale = weight.abs().max(dim=-1).values / ((2 ** (bit_length - 1)) - 1)
39
+ weight_scale = weight_scale.to(torch.float32)
40
+
41
+ weight = torch.round(weight.to(weight_scale.dtype) / weight_scale[:, None]).to(torch.int8)
42
+ return weight, weight_scale
43
+
44
+
45
+ def compress_int4_weight(weight: torch.Tensor):
46
+ with torch.cuda.device(weight.device):
47
+ num_row, num_chan = weight.size(0), weight.size(1)
48
+ num_chan = num_chan // 2
49
+
50
+ int8_weight = torch.empty(num_row, num_chan, dtype=torch.int8, device="cuda")
51
+ stream = torch.cuda.current_stream()
52
+ dim_grid = (num_row, 1, 1)
53
+ dim_block = (min(round_up(num_chan, 32), 1024), 1, 1)
54
+
55
+ kernels.weightInt8_int4(
56
+ dim_grid,
57
+ dim_block,
58
+ 0,
59
+ stream,
60
+ [
61
+ ctypes.c_void_p(weight.data_ptr()),
62
+ ctypes.c_void_p(int8_weight.data_ptr()),
63
+ ctypes.c_int32(num_row),
64
+ ctypes.c_int32(num_chan)
65
+ ],
66
+ )
67
+
68
+ return int8_weight
69
+
70
+
71
+ def dequantize_float(weight: torch.Tensor, weight_scale: torch.Tensor, bit_length: int, input: torch.Tensor):
72
+ if bit_length == 8:
73
+ float_weight = weight.to(input.dtype) * weight_scale.to(input.dtype)[:, None]
74
+ return float_weight
75
+
76
+ assert bit_length == 4, f"unsupported bit length: {bit_length}"
77
+
78
+ func = (
79
+ kernels.weightInt4_fp16 if input.dtype == torch.half else kernels.weightInt4_bf16
80
+ )
81
+ with torch.cuda.device(weight.device):
82
+ num_row, num_chan = weight.size(0), weight.size(1)
83
+
84
+ float_weight = torch.empty(num_row, num_chan * 2, dtype=input.dtype, device="cuda")
85
+ stream = torch.cuda.current_stream()
86
+ dim_grid = (num_row, 1, 1)
87
+ dim_block = (min(round_up(num_chan, 32), 1024), 1, 1)
88
+
89
+ func(
90
+ dim_grid,
91
+ dim_block,
92
+ 0,
93
+ stream,
94
+ [
95
+ ctypes.c_void_p(weight.data_ptr()),
96
+ ctypes.c_void_p(weight_scale.data_ptr()),
97
+ ctypes.c_void_p(float_weight.data_ptr()),
98
+ ctypes.c_int32(num_row),
99
+ ctypes.c_int32(num_chan),
100
+ ],
101
+ )
102
+ return float_weight
103
+
104
+ class QuantizationLinear(torch.nn.Module):
105
+ def __init__(self, bit_length: int, weight: torch.Tensor, device="cuda"):
106
+ super().__init__()
107
+
108
+ self.bit_length = bit_length
109
+
110
+ weight, weight_scale = quantize_int8(weight=weight, bit_length=bit_length)
111
+ if bit_length == 4:
112
+ weight = compress_int4_weight(weight)
113
+
114
+ self.weight = torch.nn.Parameter(weight.to(device), requires_grad=False)
115
+ self.weight_scale = torch.nn.Parameter(weight_scale.to(device), requires_grad=False)
116
+
117
+ def forward(self, input: torch.Tensor):
118
+ input_size = input.size()
119
+
120
+ input = input.contiguous().view(-1, input.size(-1))
121
+ original_weight = dequantize_float(self.weight, self.weight_scale, self.bit_length, input)
122
+
123
+ output = torch.matmul(input, original_weight.t())
124
+ return output.view(*(input_size[:-1] + (self.weight.size(0),)))
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<pad>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "clean_up_tokenization_spaces": true,
3
+ "model_max_length": 1000000000000000019884624838656,
4
+ "tokenizer_class": "PreTrainedTokenizerFast"
5
+ }