ChloeAuYeung commited on
Commit
1e23813
1 Parent(s): f727587

upload model files

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