Crystalcareai commited on
Commit
65f6bd0
1 Parent(s): 211e123

Upload 3 files

Browse files
Files changed (3) hide show
  1. configuration_gemmoe.py +165 -0
  2. modeling_gemmoe.py +1509 -0
  3. tokenization_gemmoe.py +313 -0
configuration_gemmoe.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Gemmoe model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ GEMMOE_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "Crystalcareai/GemMoE-Beta-1": "https://huggingface.co/Crystalcareai/GemMoE-Beta-1/resolve/main/config.json",
25
+ }
26
+
27
+
28
+ class GemmoeConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`GemmoeModel`]. It is used to instantiate a Gemmoe
31
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
32
+ defaults will yield a similar configuration to that of the Gemmoe-7B.
33
+
34
+ e.g. [mhenrichsen/gemmoe-7b](https://huggingface.co/mhenrichsen/gemmoe-7b)
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 256000):
41
+ Vocabulary size of the Gemmoe model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`GemmoeModel`]
43
+ hidden_size (`int`, *optional*, defaults to 3072):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 24576):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 28):
48
+ Number of hidden layers in the Transformer decoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 16):
50
+ Number of attention heads for each attention layer in the Transformer decoder.
51
+ num_key_value_heads (`int`, *optional*, defaults to 16):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
58
+ `num_attention_heads`.
59
+ head_dim (`int`, *optional*, defaults to 256):
60
+ The attention head dimension.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
64
+ The maximum sequence length that this model might ever be used with.
65
+ initializer_range (`float`, *optional*, defaults to 0.02):
66
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
67
+ rms_norm_eps (`float`, *optional*, defaults to 1e-6):
68
+ The epsilon used by the rms normalization layers.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+ pad_token_id (`int`, *optional*, defaults to 0):
73
+ Padding token id.
74
+ eos_token_id (`int`, *optional*, defaults to 1):
75
+ End of stream token id.
76
+ bos_token_id (`int`, *optional*, defaults to 2):
77
+ Beginning of stream token id.
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
79
+ Whether to tie weight embeddings
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
83
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
84
+ attention_dropout (`float`, *optional*, defaults to 0.0):
85
+ The dropout ratio for the attention probabilities.
86
+ num_experts_per_tok (`int`, *optional*, defaults to 2):
87
+ The number of experts used in the sparse mixture of experts layer.
88
+ num_local_experts (`int`, *optional*, defaults to 8):
89
+ The number of local experts used in the sparse mixture of experts layer.
90
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.01):
91
+ The coefficient for the auxiliary loss of the router.
92
+ output_router_logits (`bool`, *optional*, defaults to `False`):
93
+ Whether or not to output the logits of the routers. They are useful for computing the router loss, and
94
+ should not be returned during inference.
95
+
96
+ ```python
97
+ >>> from transformers import GemmoeModel, GemmoeConfig
98
+
99
+ >>> # Initializing a Gemmoe gemmoe-7b style configuration
100
+ >>> configuration = GemmoeConfig()
101
+
102
+ >>> # Initializing a model from the gemmoe-7b style configuration
103
+ >>> model = GemmoeModel(configuration)
104
+
105
+ >>> # Accessing the model configuration
106
+ >>> configuration = model.config
107
+ ```"""
108
+
109
+ model_type = "gemmoe"
110
+ keys_to_ignore_at_inference = ["past_key_values"]
111
+
112
+ def __init__(
113
+ self,
114
+ vocab_size=256000,
115
+ hidden_size=3072,
116
+ intermediate_size=24576,
117
+ num_hidden_layers=28,
118
+ num_attention_heads=16,
119
+ num_key_value_heads=16,
120
+ head_dim=256,
121
+ hidden_act="gelu",
122
+ max_position_embeddings=8192,
123
+ initializer_range=0.02,
124
+ rms_norm_eps=1e-6,
125
+ use_cache=True,
126
+ pad_token_id=0,
127
+ eos_token_id=1,
128
+ bos_token_id=2,
129
+ tie_word_embeddings=True,
130
+ rope_theta=10000.0,
131
+ attention_bias=False,
132
+ attention_dropout=0.0,
133
+ num_experts_per_tok=2,
134
+ num_local_experts=8,
135
+ router_aux_loss_coef=0.02,
136
+ output_router_logits=False,
137
+ **kwargs,
138
+ ):
139
+ self.vocab_size = vocab_size
140
+ self.max_position_embeddings = max_position_embeddings
141
+ self.hidden_size = hidden_size
142
+ self.intermediate_size = intermediate_size
143
+ self.num_hidden_layers = num_hidden_layers
144
+ self.num_attention_heads = num_attention_heads
145
+ self.head_dim = head_dim
146
+ self.num_key_value_heads = num_key_value_heads
147
+ self.hidden_act = hidden_act
148
+ self.initializer_range = initializer_range
149
+ self.rms_norm_eps = rms_norm_eps
150
+ self.use_cache = use_cache
151
+ self.rope_theta = rope_theta
152
+ self.attention_bias = attention_bias
153
+ self.attention_dropout = attention_dropout
154
+ self.num_experts_per_tok = num_experts_per_tok
155
+ self.num_local_experts = num_local_experts
156
+ self.router_aux_loss_coef = router_aux_loss_coef
157
+ self.output_router_logits = output_router_logits
158
+
159
+ super().__init__(
160
+ pad_token_id=pad_token_id,
161
+ bos_token_id=bos_token_id,
162
+ eos_token_id=eos_token_id,
163
+ tie_word_embeddings=tie_word_embeddings,
164
+ **kwargs,
165
+ )
modeling_gemmoe.py ADDED
@@ -0,0 +1,1509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch Gemmoe model."""
17
+
18
+ import math
19
+ import warnings
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
30
+ from transformers.modeling_attn_mask_utils import (
31
+ AttentionMaskConverter,
32
+ _prepare_4d_causal_attention_mask,
33
+ )
34
+ from transformers.modeling_outputs import SequenceClassifierOutputWithPast, MoeModelOutputWithPast, MoeCausalLMOutputWithPast
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
37
+ from transformers.utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ is_flash_attn_2_available,
41
+ is_flash_attn_greater_or_equal_2_10,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from transformers.utils.import_utils import is_torch_fx_available
46
+ from .configuration_gemmoe import GemmoeConfig
47
+
48
+ from math import sqrt as math_sqrt
49
+
50
+
51
+ if is_flash_attn_2_available():
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
54
+
55
+
56
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
57
+ # It means that the function will not be traced through and simply appear as a node in the graph.
58
+
59
+ if is_torch_fx_available():
60
+ if not is_torch_greater_or_equal_than_1_13:
61
+ import torch.fx
62
+
63
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
64
+
65
+
66
+ logger = logging.get_logger(__name__)
67
+
68
+ _CONFIG_FOR_DOC = "GemmoeConfig"
69
+
70
+ def load_balancing_loss_func(
71
+ gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2, attention_mask: Optional[torch.Tensor] = None
72
+ ) -> float:
73
+ r"""
74
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
75
+
76
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
77
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
78
+ experts is too unbalanced.
79
+
80
+ Args:
81
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
82
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
83
+ shape [batch_size X sequence_length, num_experts].
84
+ attention_mask (`torch.Tensor`, None):
85
+ The attention_mask used in forward function
86
+ shape [batch_size X sequence_length] if not None.
87
+ num_experts (`int`, *optional*):
88
+ Number of experts
89
+
90
+ Returns:
91
+ The auxiliary loss.
92
+ """
93
+ if gate_logits is None or not isinstance(gate_logits, tuple):
94
+ return 0
95
+
96
+ if isinstance(gate_logits, tuple):
97
+ compute_device = gate_logits[0].device
98
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
99
+
100
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
101
+
102
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
103
+
104
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
105
+
106
+ if attention_mask is None:
107
+ # Compute the percentage of tokens routed to each experts
108
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
109
+
110
+ # Compute the average probability of routing to these experts
111
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
112
+ else:
113
+ batch_size, sequence_length = attention_mask.shape
114
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
115
+
116
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
117
+ expert_attention_mask = (
118
+ attention_mask[None, :, :, None, None]
119
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
120
+ .reshape(-1, top_k, num_experts)
121
+ .to(compute_device)
122
+ )
123
+
124
+ # Compute the percentage of tokens routed to each experts
125
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
126
+ expert_attention_mask, dim=0
127
+ )
128
+
129
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
130
+ router_per_expert_attention_mask = (
131
+ attention_mask[None, :, :, None]
132
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
133
+ .reshape(-1, num_experts)
134
+ .to(compute_device)
135
+ )
136
+
137
+ # Compute the average probability of routing to these experts
138
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
139
+ router_per_expert_attention_mask, dim=0
140
+ )
141
+
142
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
143
+ return overall_loss * num_experts
144
+
145
+
146
+
147
+ def approx_gelu(x):
148
+ return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * x**3)))
149
+
150
+ def _get_unpad_data(attention_mask):
151
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
152
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
153
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
154
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
155
+ return (
156
+ indices,
157
+ cu_seqlens,
158
+ max_seqlen_in_batch,
159
+ )
160
+
161
+
162
+
163
+ class GemmoeRMSNorm(nn.Module):
164
+ def __init__(self, dim: int, eps: float = 1e-6):
165
+ super().__init__()
166
+ self.eps = eps
167
+ self.weight = nn.Parameter(torch.zeros(dim))
168
+
169
+ def _norm(self, x):
170
+ # Ensure the entire normalization is done in float32
171
+ x_float = x.float() # upcast to float32
172
+ mean = x_float.pow(2).mean(-1, keepdim=True)
173
+ normed_x = x_float * torch.rsqrt(mean + self.eps)
174
+ return normed_x
175
+
176
+ def forward(self, x):
177
+ normed_x = self._norm(x)
178
+ # Downcast the result to the original dtype at the end
179
+ normed_x = normed_x.type_as(x)
180
+ return normed_x * (self.weight + 1)
181
+
182
+ ALL_LAYERNORM_LAYERS.append(GemmoeRMSNorm)
183
+
184
+ class GemmoeRotaryEmbedding(nn.Module):
185
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
186
+ super().__init__()
187
+ self.dim = dim
188
+ self.max_position_embeddings = max_position_embeddings
189
+ self.base = base
190
+ self._set_cos_sin_cache(seq_len=max_position_embeddings, device=device, dtype=torch.get_default_dtype())
191
+
192
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
193
+ self.max_seq_len_cached = seq_len
194
+ freq_exponents = (2.0 / self.dim) * (
195
+ torch.arange(self.dim // 2, dtype=torch.int64, device="cpu").float()
196
+ )
197
+ timescale = self.base ** freq_exponents
198
+ positions = torch.arange(self.max_seq_len_cached, device="cpu", dtype=torch.int64).float()
199
+ radians_new = positions[..., None] / timescale[None, None, :]
200
+ radians_new = radians_new.squeeze(0)
201
+ emb = torch.cat((radians_new, radians_new), dim=-1)
202
+ cos = emb.cos().to(device=device, non_blocking=True)
203
+ sin = emb.sin().to(device=device, non_blocking=True)
204
+ self.register_buffer("cos_cached", cos, persistent=False)
205
+ self.register_buffer("sin_cached", sin, persistent=False)
206
+
207
+ def forward(self, x, position_ids=None, seq_len=None):
208
+ if seq_len is None:
209
+ seq_len = x.size(2)
210
+ if seq_len > self.max_seq_len_cached:
211
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
212
+ return (
213
+ self.cos_cached[:seq_len],
214
+ self.sin_cached[:seq_len],
215
+ )
216
+
217
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
218
+ def rotate_half(x):
219
+ """Rotates half the hidden dims of the input."""
220
+ x1 = x[..., : x.shape[-1] // 2]
221
+ x2 = x[..., x.shape[-1] // 2 :]
222
+ return torch.cat((-x2, x1), dim=-1)
223
+
224
+
225
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
226
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
227
+ """Applies Rotary Position Embedding to the query and key tensors.
228
+
229
+ Args:
230
+ q (`torch.Tensor`): The query tensor.
231
+ k (`torch.Tensor`): The key tensor.
232
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
233
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
234
+ position_ids (`torch.Tensor`, *optional*):
235
+ Deprecated and unused.
236
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
237
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
238
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
239
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
240
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
241
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
242
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
243
+ Returns:
244
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
245
+ """
246
+ seq_len, dim = q.shape[-2], q.shape[-1]
247
+ cos = cos[:seq_len].view(1, 1, seq_len, dim)
248
+ sin = sin[:seq_len].view(1, 1, seq_len, dim)
249
+ q_embed = (q * cos) + (rotate_half(q) * sin)
250
+ k_embed = (k * cos) + (rotate_half(k) * sin)
251
+ return q_embed, k_embed
252
+
253
+
254
+
255
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
256
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
257
+ """
258
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
259
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
260
+ """
261
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
262
+ if n_rep == 1:
263
+ return hidden_states
264
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
265
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
266
+
267
+ class GemmoeAttention(nn.Module):
268
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
269
+
270
+ # Ignore copy
271
+ def __init__(self, config: GemmoeConfig, layer_idx: Optional[int] = None):
272
+ super().__init__()
273
+ self.config = config
274
+ self.layer_idx = layer_idx
275
+ if layer_idx is None:
276
+ logger.warning_once(
277
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
278
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
279
+ "when creating this class."
280
+ )
281
+
282
+ self.attention_dropout = config.attention_dropout
283
+ self.hidden_size = config.hidden_size
284
+ self.num_heads = config.num_attention_heads
285
+ self.head_dim = config.head_dim
286
+ self.num_key_value_heads = config.num_key_value_heads
287
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
288
+ self.max_position_embeddings = config.max_position_embeddings
289
+ self.rope_theta = config.rope_theta
290
+ self.is_causal = True
291
+
292
+ if self.hidden_size % self.num_heads != 0:
293
+ raise ValueError(
294
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
295
+ f" and `num_heads`: {self.num_heads})."
296
+ )
297
+
298
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
299
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
300
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
301
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
302
+ self.rotary_emb = GemmoeRotaryEmbedding(
303
+ self.head_dim,
304
+ max_position_embeddings=self.max_position_embeddings,
305
+ base=self.rope_theta,
306
+ )
307
+
308
+ def forward(
309
+ self,
310
+ hidden_states: torch.Tensor,
311
+ attention_mask: Optional[torch.Tensor] = None,
312
+ position_ids: Optional[torch.LongTensor] = None,
313
+ past_key_value: Optional[Cache] = None,
314
+ output_attentions: bool = False,
315
+ use_cache: bool = False,
316
+ cache_position: Optional[torch.LongTensor] = None,
317
+ **kwargs,
318
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
319
+ bsz, q_len, _ = hidden_states.size()
320
+
321
+ query_states = self.q_proj(hidden_states)
322
+ key_states = self.k_proj(hidden_states)
323
+ value_states = self.v_proj(hidden_states)
324
+
325
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
326
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
327
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
328
+
329
+ past_key_value = getattr(self, "past_key_value", past_key_value)
330
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
331
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
332
+
333
+ if past_key_value is not None:
334
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
335
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
336
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
337
+
338
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
339
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
340
+
341
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
342
+
343
+ if attention_mask is not None: # no matter the length, we just slice it
344
+ if cache_position is not None:
345
+ causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]]
346
+ else:
347
+ causal_mask = attention_mask
348
+ attn_weights = attn_weights + causal_mask
349
+
350
+ # upcast attention to fp32
351
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
352
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
353
+ attn_output = torch.matmul(attn_weights, value_states)
354
+
355
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
356
+ raise ValueError(
357
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
358
+ f" {attn_output.size()}"
359
+ )
360
+
361
+ attn_output = attn_output.transpose(1, 2).contiguous()
362
+
363
+ attn_output = attn_output.view(bsz, q_len, -1)
364
+ attn_output = self.o_proj(attn_output)
365
+
366
+ if not output_attentions:
367
+ attn_weights = None
368
+
369
+ return attn_output, attn_weights, past_key_value
370
+
371
+
372
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Gemmoe
373
+ class GemmoeFlashAttention2(GemmoeAttention):
374
+ """
375
+ Gemmoe flash attention module. This module inherits from `GemmoeAttention` as the weights of the module stays
376
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
377
+ flash attention and deal with padding tokens in case the input contains any of them.
378
+ """
379
+
380
+ def __init__(self, *args, **kwargs):
381
+ super().__init__(*args, **kwargs)
382
+
383
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
384
+ # 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.
385
+ # 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).
386
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
387
+
388
+ # Ignore copy
389
+ def forward(
390
+ self,
391
+ hidden_states: torch.Tensor,
392
+ attention_mask: Optional[torch.LongTensor] = None,
393
+ position_ids: Optional[torch.LongTensor] = None,
394
+ past_key_value: Optional[Cache] = None,
395
+ output_attentions: bool = False,
396
+ use_cache: bool = False,
397
+ cache_position: Optional[torch.LongTensor] = None,
398
+ **kwargs,
399
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
400
+ output_attentions = False
401
+
402
+ bsz, q_len, _ = hidden_states.size()
403
+
404
+ query_states = self.q_proj(hidden_states)
405
+ key_states = self.k_proj(hidden_states)
406
+ value_states = self.v_proj(hidden_states)
407
+
408
+ # Flash attention requires the input to have the shape
409
+ # batch_size x seq_length x head_dim x hidden_dim
410
+ # therefore we just need to keep the original shape
411
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
412
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
413
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
414
+
415
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
416
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
417
+
418
+ past_key_value = getattr(self, "past_key_value", past_key_value)
419
+
420
+ if past_key_value is not None:
421
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
422
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
423
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
424
+
425
+ # 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
426
+ # to be able to avoid many of these transpose/reshape/view.
427
+ query_states = query_states.transpose(1, 2)
428
+ key_states = key_states.transpose(1, 2)
429
+ value_states = value_states.transpose(1, 2)
430
+
431
+ dropout_rate = self.attention_dropout if self.training else 0.0
432
+
433
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
434
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
435
+ # cast them back in the correct dtype just to be sure everything works as expected.
436
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
437
+ # in fp32. (GemmoeRMSNorm handles it correctly)
438
+
439
+ input_dtype = query_states.dtype
440
+ if input_dtype == torch.float32:
441
+ if torch.is_autocast_enabled():
442
+ target_dtype = torch.get_autocast_gpu_dtype()
443
+ # Handle the case where the model is quantized
444
+ elif hasattr(self.config, "_pre_quantization_dtype"):
445
+ target_dtype = self.config._pre_quantization_dtype
446
+ else:
447
+ target_dtype = self.q_proj.weight.dtype
448
+
449
+ logger.warning_once(
450
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
451
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
452
+ f" {target_dtype}."
453
+ )
454
+
455
+ query_states = query_states.to(target_dtype)
456
+ key_states = key_states.to(target_dtype)
457
+ value_states = value_states.to(target_dtype)
458
+
459
+ attn_output = self._flash_attention_forward(
460
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
461
+ )
462
+
463
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
464
+ attn_output = self.o_proj(attn_output)
465
+
466
+ if not output_attentions:
467
+ attn_weights = None
468
+
469
+ return attn_output, attn_weights, past_key_value
470
+
471
+ def _flash_attention_forward(
472
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
473
+ ):
474
+ """
475
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
476
+ first unpad the input, then computes the attention scores and pad the final attention scores.
477
+
478
+ Args:
479
+ query_states (`torch.Tensor`):
480
+ Input query states to be passed to Flash Attention API
481
+ key_states (`torch.Tensor`):
482
+ Input key states to be passed to Flash Attention API
483
+ value_states (`torch.Tensor`):
484
+ Input value states to be passed to Flash Attention API
485
+ attention_mask (`torch.Tensor`):
486
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
487
+ position of padding tokens and 1 for the position of non-padding tokens.
488
+ dropout (`float`):
489
+ Attention dropout
490
+ softmax_scale (`float`, *optional*):
491
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
492
+ """
493
+ if not self._flash_attn_uses_top_left_mask:
494
+ causal = self.is_causal
495
+ else:
496
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in GemmoeFlashAttention2 __init__.
497
+ causal = self.is_causal and query_length != 1
498
+
499
+ # Contains at least one padding token in the sequence
500
+ if attention_mask is not None:
501
+ batch_size = query_states.shape[0]
502
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
503
+ query_states, key_states, value_states, attention_mask, query_length
504
+ )
505
+
506
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
507
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
508
+
509
+ attn_output_unpad = flash_attn_varlen_func(
510
+ query_states,
511
+ key_states,
512
+ value_states,
513
+ cu_seqlens_q=cu_seqlens_q,
514
+ cu_seqlens_k=cu_seqlens_k,
515
+ max_seqlen_q=max_seqlen_in_batch_q,
516
+ max_seqlen_k=max_seqlen_in_batch_k,
517
+ dropout_p=dropout,
518
+ softmax_scale=softmax_scale,
519
+ causal=causal,
520
+ )
521
+
522
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
523
+ else:
524
+ attn_output = flash_attn_func(
525
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
526
+ )
527
+
528
+ return attn_output
529
+
530
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
531
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
532
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
533
+
534
+ key_layer = index_first_axis(
535
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
536
+ )
537
+ value_layer = index_first_axis(
538
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
539
+ )
540
+ if query_length == kv_seq_len:
541
+ query_layer = index_first_axis(
542
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
543
+ )
544
+ cu_seqlens_q = cu_seqlens_k
545
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
546
+ indices_q = indices_k
547
+ elif query_length == 1:
548
+ max_seqlen_in_batch_q = 1
549
+ cu_seqlens_q = torch.arange(
550
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
551
+ ) # There is a memcpy here, that is very bad.
552
+ indices_q = cu_seqlens_q[:-1]
553
+ query_layer = query_layer.squeeze(1)
554
+ else:
555
+ # The -q_len: slice assumes left padding.
556
+ attention_mask = attention_mask[:, -query_length:]
557
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
558
+
559
+ return (
560
+ query_layer,
561
+ key_layer,
562
+ value_layer,
563
+ indices_q,
564
+ (cu_seqlens_q, cu_seqlens_k),
565
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
566
+ )
567
+
568
+
569
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Gemmoe
570
+ class GemmoeSdpaAttention(GemmoeAttention):
571
+ """
572
+ Gemmoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
573
+ `GemmoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
574
+ SDPA API.
575
+ """
576
+
577
+ # Ignore copy
578
+ def forward(
579
+ self,
580
+ hidden_states: torch.Tensor,
581
+ attention_mask: Optional[torch.Tensor] = None,
582
+ position_ids: Optional[torch.LongTensor] = None,
583
+ past_key_value: Optional[Cache] = None,
584
+ output_attentions: bool = False,
585
+ use_cache: bool = False,
586
+ cache_position: Optional[torch.LongTensor] = None,
587
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
588
+ if output_attentions:
589
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
590
+ logger.warning_once(
591
+ "GemmoeModel is using GemmoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
592
+ '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.'
593
+ )
594
+ return super().forward(
595
+ hidden_states=hidden_states,
596
+ attention_mask=attention_mask,
597
+ position_ids=position_ids,
598
+ past_key_value=past_key_value,
599
+ output_attentions=output_attentions,
600
+ use_cache=use_cache,
601
+ cache_position=cache_position,
602
+ )
603
+
604
+ bsz, q_len, _ = hidden_states.size()
605
+
606
+ query_states = self.q_proj(hidden_states)
607
+ key_states = self.k_proj(hidden_states)
608
+ value_states = self.v_proj(hidden_states)
609
+
610
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
611
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
612
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
613
+
614
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=None)
615
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, None)
616
+
617
+ past_key_value = getattr(self, "past_key_value", past_key_value)
618
+
619
+ if past_key_value is not None:
620
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
621
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
622
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
623
+
624
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
625
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
626
+
627
+ causal_mask = attention_mask
628
+ if attention_mask is not None and cache_position is not None:
629
+ causal_mask = causal_mask[:, :, cache_position, : key_states.shape[-2]]
630
+
631
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
632
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
633
+ if query_states.device.type == "cuda" and causal_mask is not None:
634
+ query_states = query_states.contiguous()
635
+ key_states = key_states.contiguous()
636
+ value_states = value_states.contiguous()
637
+
638
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
639
+ query_states,
640
+ key_states,
641
+ value_states,
642
+ attn_mask=causal_mask,
643
+ dropout_p=self.attention_dropout if self.training else 0.0,
644
+ )
645
+
646
+ attn_output = attn_output.transpose(1, 2).contiguous()
647
+ attn_output = attn_output.view(bsz, q_len, -1)
648
+
649
+ attn_output = self.o_proj(attn_output)
650
+
651
+ return attn_output, None, past_key_value
652
+
653
+
654
+ GEMMOE_ATTENTION_CLASSES = {
655
+ "eager": GemmoeAttention,
656
+ "flash_attention_2": GemmoeFlashAttention2,
657
+ "sdpa": GemmoeSdpaAttention,
658
+ }
659
+
660
+ class GemmoeBlockSparseTop2MLP(nn.Module):
661
+ def __init__(self, config: GemmoeConfig):
662
+ super().__init__()
663
+ self.ffn_dim = config.intermediate_size
664
+ self.hidden_dim = config.hidden_size
665
+
666
+ self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
667
+ self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
668
+ self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
669
+
670
+ self.act_fn = approx_gelu
671
+
672
+ def forward(self, hidden_states):
673
+ current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
674
+ current_hidden_states = self.w2(current_hidden_states)
675
+ return current_hidden_states
676
+
677
+ class GemmoeBlockSparseTop2MLP(GemmoeBlockSparseTop2MLP):
678
+ def __init__(self, *args, **kwargs):
679
+ logger.warning_once(
680
+ "GemmoeBLockSparseTop2MLP is deprecated by GemmoeBlockSparseTop2MLP and will be removed in v4.40."
681
+ )
682
+ super().__init__(*args, **kwargs)
683
+
684
+ class GemmoeSparseMoeBlock(nn.Module):
685
+ def __init__(self, config):
686
+ super().__init__()
687
+ self.hidden_dim = config.hidden_size
688
+ self.ffn_dim = config.intermediate_size
689
+ self.num_experts = config.num_local_experts
690
+ self.top_k = 2
691
+
692
+ # gating
693
+ self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
694
+
695
+ self.experts = nn.ModuleList([GemmoeBlockSparseTop2MLP(config) for _ in range(self.num_experts)])
696
+
697
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
698
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
699
+ hidden_states = hidden_states.view(-1, hidden_dim)
700
+
701
+ # router_logits: (batch * sequence_length, n_experts)
702
+ router_logits = self.gate(hidden_states)
703
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
704
+ topk_weight, topk_idx = torch.topk(routing_weights, self.top_k, dim=-1, sorted=False)
705
+ topk_weight /= topk_weight.sum(dim=-1, keepdim=True)
706
+
707
+ # we cast back to the input dtype
708
+ topk_weight = topk_weight.to(hidden_states.dtype)
709
+
710
+ hidden_states = hidden_states.repeat_interleave(self.top_k, dim=0)
711
+
712
+ y = torch.empty_like(hidden_states)
713
+
714
+ flat_topk_idx = topk_idx.view(-1)
715
+ for i in range(self.num_experts):
716
+ expert = self.experts[i]
717
+ expert_output = expert(hidden_states[flat_topk_idx == i])
718
+ y[flat_topk_idx == i] = expert_output.to(y.dtype) # Cast expert_output to the same dtype as y
719
+
720
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
721
+
722
+ final_hidden_states = y.reshape(batch_size, sequence_length, hidden_dim)
723
+ return final_hidden_states, router_logits
724
+
725
+
726
+ # Copied from transformers.models.llama.modeling_llama.LlamaDecoderLayer with LLAMA->GEMMOE,Llama->Gemmoe
727
+ class GemmoeDecoderLayer(nn.Module):
728
+ def __init__(self, config: GemmoeConfig, layer_idx: int):
729
+ super().__init__()
730
+ self.hidden_size = config.hidden_size
731
+
732
+ self.self_attn = GEMMOE_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
733
+
734
+ self.block_sparse_moe = GemmoeSparseMoeBlock(config)
735
+ self.input_layernorm = GemmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
736
+ self.post_attention_layernorm = GemmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
737
+
738
+ def forward(
739
+ self,
740
+ hidden_states: torch.Tensor,
741
+ attention_mask: Optional[torch.Tensor] = None,
742
+ position_ids: Optional[torch.LongTensor] = None,
743
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
744
+ output_attentions: Optional[bool] = False,
745
+ output_router_logits: Optional[bool] = False,
746
+ use_cache: Optional[bool] = False,
747
+ **kwargs,
748
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
749
+ if "padding_mask" in kwargs:
750
+ warnings.warn(
751
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
752
+ )
753
+ """
754
+ Args:
755
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
756
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
757
+ `(batch, sequence_length)` where padding elements are indicated by 0.
758
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
759
+ output_attentions (`bool`, *optional*):
760
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
761
+ returned tensors for more detail.
762
+ output_router_logits (`bool`, *optional*):
763
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
764
+ should not be returned during inference.
765
+ use_cache (`bool`, *optional*):
766
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
767
+ (see `past_key_values`).
768
+ """
769
+
770
+ residual = hidden_states
771
+
772
+ hidden_states = self.input_layernorm(hidden_states)
773
+
774
+ # Self Attention
775
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
776
+ hidden_states=hidden_states,
777
+ attention_mask=attention_mask,
778
+ position_ids=position_ids,
779
+ past_key_value=past_key_value,
780
+ output_attentions=output_attentions,
781
+ use_cache=use_cache,
782
+ )
783
+ hidden_states = residual + hidden_states
784
+
785
+ # Fully Connected
786
+ residual = hidden_states
787
+ hidden_states = self.post_attention_layernorm(hidden_states)
788
+ hidden_states, router_logits = self.block_sparse_moe(hidden_states)
789
+ hidden_states = residual + hidden_states
790
+
791
+ outputs = (hidden_states,)
792
+
793
+ if output_attentions:
794
+ outputs += (self_attn_weights,)
795
+
796
+ if use_cache:
797
+ outputs += (present_key_value,)
798
+
799
+ if output_router_logits:
800
+ outputs += (router_logits,)
801
+
802
+ return outputs
803
+
804
+
805
+ GEMMOE_START_DOCSTRING = r"""
806
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
807
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
808
+ etc.)
809
+
810
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
811
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
812
+ and behavior.
813
+
814
+ Parameters:
815
+ config ([`GemmoeConfig`]):
816
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
817
+ load the weights associated with the model, only the configuration. Check out the
818
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
819
+ """
820
+
821
+
822
+ @add_start_docstrings(
823
+ "The bare Gemmoe Model outputting raw hidden-states without any specific head on top.",
824
+ GEMMOE_START_DOCSTRING,
825
+ )
826
+
827
+ class GemmoePreTrainedModel(PreTrainedModel):
828
+ config_class = GemmoeConfig
829
+ base_model_prefix = "model"
830
+ supports_gradient_checkpointing = True
831
+ _keep_in_fp32_modules = ["inv_freq", "rotary_emb", "cos_cached", "sin_cached"]
832
+ _no_split_modules = ["GemmoeDecoderLayer"]
833
+ _skip_keys_device_placement = ["past_key_values", "causal_mask"]
834
+ _supports_flash_attn_2 = True
835
+ _supports_sdpa = True
836
+ _supports_cache_class = True
837
+
838
+ def _init_weights(self, module):
839
+ std = self.config.initializer_range
840
+ if isinstance(module, nn.Linear):
841
+ module.weight.data.normal_(mean=0.0, std=std)
842
+ if module.bias is not None:
843
+ module.bias.data.zero_()
844
+ elif isinstance(module, nn.Embedding):
845
+ module.weight.data.normal_(mean=0.0, std=std)
846
+ if module.padding_idx is not None:
847
+ module.weight.data[module.padding_idx].zero_()
848
+
849
+ def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
850
+ if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
851
+ raise ValueError(
852
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
853
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
854
+ )
855
+
856
+ if max_cache_len > self.model.causal_mask.shape[-1] or self.device != self.model.causal_mask.device:
857
+ causal_mask = torch.full((max_cache_len, max_cache_len), fill_value=1, device=self.device)
858
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
859
+
860
+ for layer in self.model.layers:
861
+ weights = layer.self_attn.o_proj.weight
862
+ layer.self_attn.past_key_value = cache_cls(
863
+ self.config, max_batch_size, max_cache_len, device=weights.device, dtype=weights.dtype
864
+ )
865
+
866
+ def _reset_cache(self):
867
+ for layer in self.model.layers:
868
+ layer.self_attn.past_key_value = None
869
+
870
+
871
+ GEMMOE_INPUTS_DOCSTRING = r"""
872
+ Args:
873
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
874
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
875
+ it.
876
+
877
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
878
+ [`PreTrainedTokenizer.__call__`] for details.
879
+
880
+ [What are input IDs?](../glossary#input-ids)
881
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
882
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
883
+
884
+ - 1 for tokens that are **not masked**,
885
+ - 0 for tokens that are **masked**.
886
+
887
+ [What are attention masks?](../glossary#attention-mask)
888
+
889
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
890
+ [`PreTrainedTokenizer.__call__`] for details.
891
+
892
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
893
+ `past_key_values`).
894
+
895
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
896
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
897
+ information on the default strategy.
898
+
899
+ - 1 indicates the head is **not masked**,
900
+ - 0 indicates the head is **masked**.
901
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
902
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
903
+ config.n_positions - 1]`.
904
+
905
+ [What are position IDs?](../glossary#position-ids)
906
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
907
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
908
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
909
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
910
+
911
+ Two formats are allowed:
912
+ - a [`~cache_utils.Cache`] instance;
913
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
914
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
915
+ cache format.
916
+
917
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
918
+ legacy cache format will be returned.
919
+
920
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
921
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
922
+ of shape `(batch_size, sequence_length)`.
923
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
924
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
925
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
926
+ model's internal embedding lookup matrix.
927
+ use_cache (`bool`, *optional*):
928
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
929
+ `past_key_values`).
930
+ output_attentions (`bool`, *optional*):
931
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
932
+ tensors for more detail.
933
+ output_hidden_states (`bool`, *optional*):
934
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
935
+ more detail.
936
+ return_dict (`bool`, *optional*):
937
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
938
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
939
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
940
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
941
+ the complete sequence length.
942
+ """
943
+
944
+
945
+ @add_start_docstrings(
946
+ "The bare Gemmoe Model outputting raw hidden-states without any specific head on top.",
947
+ GEMMOE_START_DOCSTRING,
948
+ )
949
+
950
+ class GemmoeModel(GemmoePreTrainedModel):
951
+ """
952
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GemmoeDecoderLayer`]
953
+
954
+ Args:
955
+ config: GemmoeConfig
956
+ """
957
+
958
+ def __init__(self, config: GemmoeConfig):
959
+ super().__init__(config)
960
+ self.padding_idx = config.pad_token_id
961
+ self.vocab_size = config.vocab_size
962
+
963
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
964
+ self.layers = nn.ModuleList(
965
+ [GemmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
966
+ )
967
+ self.norm = GemmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
968
+ self.gradient_checkpointing = False
969
+
970
+ # Register a causal mask to separate causal and padding mask creation. Merging happens in the attention class.
971
+ # NOTE: This is not friendly with TorchScript, ONNX, ExportedProgram serialization for very large `max_position_embeddings`.
972
+ causal_mask = torch.full(
973
+ (config.max_position_embeddings, config.max_position_embeddings), fill_value=True, dtype=torch.bool
974
+ )
975
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
976
+ # Initialize weights and apply final processing
977
+ self.post_init()
978
+
979
+ def get_input_embeddings(self):
980
+ return self.embed_tokens
981
+
982
+ def set_input_embeddings(self, value):
983
+ self.embed_tokens = value
984
+
985
+ @add_start_docstrings_to_model_forward(GEMMOE_INPUTS_DOCSTRING)
986
+ # Ignore copy
987
+ def forward(
988
+ self,
989
+ input_ids: torch.LongTensor = None,
990
+ attention_mask: Optional[torch.Tensor] = None,
991
+ position_ids: Optional[torch.LongTensor] = None,
992
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
993
+ inputs_embeds: Optional[torch.FloatTensor] = None,
994
+ use_cache: Optional[bool] = None,
995
+ output_attentions: Optional[bool] = None,
996
+ output_hidden_states: Optional[bool] = None,
997
+ output_router_logits: Optional[bool] = None, # Add this line
998
+ return_dict: Optional[bool] = None,
999
+ cache_position: Optional[torch.LongTensor] = None,
1000
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1001
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1002
+ output_hidden_states = (
1003
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1004
+ )
1005
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1006
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1007
+
1008
+ if (input_ids is None) ^ (inputs_embeds is not None):
1009
+ raise ValueError(
1010
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1011
+ )
1012
+
1013
+ if self.gradient_checkpointing and self.training and use_cache:
1014
+ logger.warning_once(
1015
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1016
+ )
1017
+ use_cache = False
1018
+
1019
+ if inputs_embeds is None:
1020
+ inputs_embeds = self.embed_tokens(input_ids)
1021
+
1022
+ # Scale embeddings
1023
+ # Fix for precision issue when casting to bfloat16
1024
+ hidden_size_sqrt = math.sqrt(self.config.hidden_size)
1025
+ if inputs_embeds.dtype == torch.bfloat16:
1026
+
1027
+ pass
1028
+
1029
+ hidden_states = inputs_embeds * hidden_size_sqrt
1030
+
1031
+ past_seen_tokens = 0
1032
+ if use_cache: # kept for BC (cache positions)
1033
+ if not isinstance(past_key_values, StaticCache):
1034
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1035
+ past_seen_tokens = past_key_values.get_seq_length()
1036
+
1037
+ if cache_position is None:
1038
+ cache_position = torch.arange(
1039
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1040
+ )
1041
+
1042
+ if position_ids is None:
1043
+ position_ids = cache_position.unsqueeze(0)
1044
+
1045
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds)
1046
+
1047
+ # embed positions
1048
+ hidden_states = inputs_embeds
1049
+
1050
+ # normalized
1051
+ hidden_states = hidden_states * (self.config.hidden_size**0.5)
1052
+
1053
+ # decoder layers
1054
+ all_hidden_states = () if output_hidden_states else None
1055
+ all_self_attns = () if output_attentions else None
1056
+ next_decoder_cache = None
1057
+
1058
+ for decoder_layer in self.layers:
1059
+ if output_hidden_states:
1060
+ all_hidden_states += (hidden_states,)
1061
+ layer_outputs = self._gradient_checkpointing_func(
1062
+ decoder_layer.__call__,
1063
+ hidden_states,
1064
+ causal_mask,
1065
+ position_ids,
1066
+ past_key_values,
1067
+ output_attentions,
1068
+ output_router_logits,
1069
+ use_cache.item() if isinstance(use_cache, torch.Tensor) else use_cache,
1070
+ cache_position,
1071
+ output_router_logits,
1072
+ )
1073
+ else:
1074
+ layer_outputs = decoder_layer(
1075
+ hidden_states,
1076
+ attention_mask=causal_mask,
1077
+ position_ids=position_ids,
1078
+ past_key_value=past_key_values,
1079
+ output_attentions=output_attentions,
1080
+ output_router_logits=output_router_logits,
1081
+ use_cache=use_cache.item() if isinstance(use_cache, torch.Tensor) else use_cache,
1082
+ cache_position=cache_position,
1083
+ )
1084
+
1085
+ hidden_states = layer_outputs[0]
1086
+
1087
+ if use_cache:
1088
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1089
+
1090
+ if output_attentions:
1091
+ all_self_attns += (layer_outputs[1],)
1092
+
1093
+ hidden_states = self.norm(hidden_states)
1094
+
1095
+ # add hidden states from the last decoder layer
1096
+ if output_hidden_states:
1097
+ all_hidden_states += (hidden_states,)
1098
+
1099
+ next_cache = None
1100
+ if use_cache:
1101
+ next_cache = (
1102
+ next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
1103
+ )
1104
+ if not return_dict:
1105
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1106
+ return MoeModelOutputWithPast(
1107
+ last_hidden_state=hidden_states,
1108
+ past_key_values=next_cache,
1109
+ hidden_states=all_hidden_states,
1110
+ attentions=all_self_attns,
1111
+ )
1112
+
1113
+ # 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
1114
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1115
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1116
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1117
+ def _update_causal_mask(self, attention_mask, input_tensor):
1118
+ if self.config._attn_implementation == "flash_attention_2":
1119
+ if attention_mask is not None and 0.0 in attention_mask:
1120
+ return attention_mask
1121
+ return None
1122
+
1123
+ batch_size, seq_length = input_tensor.shape[:2]
1124
+ dtype = input_tensor.dtype
1125
+ device = input_tensor.device
1126
+
1127
+ # support going beyond cached `max_position_embedding`
1128
+ if seq_length > self.causal_mask.shape[-1]:
1129
+ causal_mask = torch.full((2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]), fill_value=1)
1130
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
1131
+
1132
+ # We use the current dtype to avoid any overflows
1133
+ min_dtype = torch.finfo(dtype).min
1134
+
1135
+ causal_mask = self.causal_mask[None, None, :, :].to(dtype=dtype, device=device) * min_dtype
1136
+ causal_mask = causal_mask.expand(batch_size, 1, -1, -1)
1137
+ if attention_mask is not None:
1138
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1139
+ if attention_mask.dim() == 2:
1140
+ mask_length = attention_mask.shape[-1]
1141
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1142
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1143
+ elif attention_mask.dim() == 4:
1144
+ mask_shape = attention_mask.shape
1145
+ mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
1146
+ causal_mask[: mask_shape[0], : mask_shape[1], : mask_shape[2], : mask_shape[3]] = mask_slice
1147
+
1148
+ if (
1149
+ self.config._attn_implementation == "sdpa"
1150
+ and attention_mask is not None
1151
+ and attention_mask.device.type == "cuda"
1152
+ ):
1153
+ # TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
1154
+ is_tracing = (
1155
+ torch.jit.is_tracing()
1156
+ or isinstance(input_tensor, torch.fx.Proxy)
1157
+ or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling())
1158
+ )
1159
+ if not is_tracing and torch.any(attention_mask != 1):
1160
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1161
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1162
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1163
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1164
+
1165
+ return causal_mask
1166
+
1167
+ class GemmoeForCausalLM(GemmoePreTrainedModel):
1168
+ _tied_weights_keys = ["lm_head.weight"]
1169
+
1170
+ def __init__(self, config):
1171
+ super().__init__(config)
1172
+ self.model = GemmoeModel(config)
1173
+ self.vocab_size = config.vocab_size
1174
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1175
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1176
+ self.num_experts = config.num_local_experts
1177
+ self.num_experts_per_tok = config.num_experts_per_tok
1178
+ # Initialize weights and apply final processing
1179
+ self.post_init()
1180
+
1181
+ def get_input_embeddings(self):
1182
+ return self.model.embed_tokens
1183
+
1184
+ def set_input_embeddings(self, value):
1185
+ self.model.embed_tokens = value
1186
+
1187
+ def get_output_embeddings(self):
1188
+ return self.lm_head
1189
+
1190
+ def set_output_embeddings(self, new_embeddings):
1191
+ self.lm_head = new_embeddings
1192
+
1193
+ def set_decoder(self, decoder):
1194
+ self.model = decoder
1195
+
1196
+ def get_decoder(self):
1197
+ return self.model
1198
+
1199
+ @add_start_docstrings_to_model_forward(GEMMOE_INPUTS_DOCSTRING)
1200
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1201
+ # Ignore copy
1202
+ def forward(
1203
+ self,
1204
+ input_ids: torch.LongTensor = None,
1205
+ attention_mask: Optional[torch.Tensor] = None,
1206
+ position_ids: Optional[torch.LongTensor] = None,
1207
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1208
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1209
+ labels: Optional[torch.LongTensor] = None,
1210
+ use_cache: Optional[bool] = None,
1211
+ output_attentions: Optional[bool] = None,
1212
+ output_hidden_states: Optional[bool] = None,
1213
+ output_router_logits: Optional[bool] = None,
1214
+ return_dict: Optional[bool] = None,
1215
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1216
+ r"""
1217
+ Args:
1218
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1219
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1220
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1221
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1222
+
1223
+ Returns:
1224
+
1225
+ Example:
1226
+
1227
+ ```python
1228
+ >>> from transformers import AutoTokenizer, GemmoeForCausalLM
1229
+
1230
+ >>> model = GemmoeForCausalLM.from_pretrained("mistralai/Gemmoe-8x7B-v0.1")
1231
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Gemmoe-8x7B-v0.1")
1232
+
1233
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1234
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1235
+
1236
+ >>> # Generate
1237
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1238
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1239
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1240
+ ```"""
1241
+
1242
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1243
+ output_router_logits = (
1244
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1245
+ )
1246
+
1247
+ output_hidden_states = (
1248
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1249
+ )
1250
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1251
+
1252
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1253
+ outputs = self.model(
1254
+ input_ids=input_ids,
1255
+ attention_mask=attention_mask,
1256
+ position_ids=position_ids,
1257
+ past_key_values=past_key_values,
1258
+ inputs_embeds=inputs_embeds,
1259
+ use_cache=use_cache,
1260
+ output_attentions=output_attentions,
1261
+ output_hidden_states=output_hidden_states,
1262
+ output_router_logits=output_router_logits,
1263
+ return_dict=return_dict,
1264
+ )
1265
+
1266
+ hidden_states = outputs[0]
1267
+ logits = self.lm_head(hidden_states)
1268
+ logits = logits.float()
1269
+
1270
+ if self.training:
1271
+ for expert in self.model.layers[-1].block_sparse_moe.experts:
1272
+ for param in expert.parameters():
1273
+ if param.requires_grad and param.grad is None:
1274
+ param.grad = torch.zeros_like(param)
1275
+
1276
+ loss = None
1277
+ if labels is not None:
1278
+ # Shift so that tokens < n predict n
1279
+ shift_logits = logits[..., :-1, :].contiguous()
1280
+ shift_labels = labels[..., 1:].contiguous()
1281
+ # Flatten the tokens
1282
+ loss_fct = CrossEntropyLoss()
1283
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1284
+ shift_labels = shift_labels.view(-1)
1285
+ # Enable model parallelism
1286
+ shift_labels = shift_labels.to(shift_logits.device)
1287
+ loss = loss_fct(shift_logits, shift_labels)
1288
+
1289
+ aux_loss = None
1290
+ if output_router_logits:
1291
+ aux_loss = load_balancing_loss_func(
1292
+ outputs.router_logits if return_dict else outputs[-1],
1293
+ self.num_experts,
1294
+ self.num_experts_per_tok,
1295
+ attention_mask,
1296
+ )
1297
+ if labels is not None:
1298
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1299
+
1300
+ if not return_dict:
1301
+ output = (logits,) + outputs[1:]
1302
+ if output_router_logits:
1303
+ output = (aux_loss,) + output
1304
+ return (loss,) + output if loss is not None else output
1305
+
1306
+ return MoeCausalLMOutputWithPast(
1307
+ loss=loss,
1308
+ aux_loss=aux_loss,
1309
+ logits=logits,
1310
+ past_key_values=outputs.past_key_values,
1311
+ hidden_states=outputs.hidden_states,
1312
+ attentions=outputs.attentions,
1313
+ router_logits=outputs.router_logits,
1314
+ )
1315
+
1316
+ def prepare_inputs_for_generation(
1317
+ self,
1318
+ input_ids,
1319
+ past_key_values=None,
1320
+ attention_mask=None,
1321
+ inputs_embeds=None,
1322
+ output_router_logits=False,
1323
+ **kwargs,
1324
+ ):
1325
+ # Omit tokens covered by past_key_values
1326
+ if past_key_values is not None:
1327
+ if isinstance(past_key_values, Cache):
1328
+ cache_length = past_key_values.get_seq_length()
1329
+ past_length = past_key_values.seen_tokens
1330
+ max_cache_length = past_key_values.get_max_length()
1331
+ else:
1332
+ cache_length = past_length = past_key_values[0][0].shape[2]
1333
+ max_cache_length = None
1334
+
1335
+ # Keep only the unprocessed tokens:
1336
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1337
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1338
+ # input)
1339
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1340
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1341
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1342
+ # input_ids based on the past_length.
1343
+ elif past_length < input_ids.shape[1]:
1344
+ input_ids = input_ids[:, past_length:]
1345
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1346
+
1347
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1348
+ if (
1349
+ max_cache_length is not None
1350
+ and attention_mask is not None
1351
+ and cache_length + input_ids.shape[1] > max_cache_length
1352
+ ):
1353
+ attention_mask = attention_mask[:, -max_cache_length:]
1354
+
1355
+ position_ids = kwargs.get("position_ids", None)
1356
+ if attention_mask is not None and position_ids is None:
1357
+ # create position_ids on the fly for batch generation
1358
+ position_ids = attention_mask.long().cumsum(-1) - 1
1359
+ position_ids.masked_fill_(attention_mask == 0, 1)
1360
+ if past_key_values:
1361
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1362
+
1363
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1364
+ if inputs_embeds is not None and past_key_values is None:
1365
+ model_inputs = {"inputs_embeds": inputs_embeds}
1366
+ else:
1367
+ model_inputs = {"input_ids": input_ids}
1368
+
1369
+ model_inputs.update(
1370
+ {
1371
+ "position_ids": position_ids,
1372
+ "past_key_values": past_key_values,
1373
+ "use_cache": kwargs.get("use_cache"),
1374
+ "attention_mask": attention_mask,
1375
+ "output_router_logits": output_router_logits,
1376
+ }
1377
+ )
1378
+ return model_inputs
1379
+
1380
+ @staticmethod
1381
+ def _reorder_cache(past_key_values, beam_idx):
1382
+ reordered_past = ()
1383
+ for layer_past in past_key_values:
1384
+ reordered_past += (
1385
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1386
+ )
1387
+ return reordered_past
1388
+
1389
+ @add_start_docstrings(
1390
+ """
1391
+ The Gemmoe Model transformer with a sequence classification head on top (linear layer).
1392
+ [`GemmoeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1393
+ (e.g. GPT-2) do.
1394
+
1395
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1396
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1397
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1398
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1399
+ each row of the batch).
1400
+ """,
1401
+ GEMMOE_START_DOCSTRING,
1402
+ )
1403
+
1404
+ class GemmoeForSequenceClassification(GemmoePreTrainedModel):
1405
+ def __init__(self, config):
1406
+ super().__init__(config)
1407
+ self.num_labels = config.num_labels
1408
+ self.model = GemmoeModel(config)
1409
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1410
+
1411
+ # Initialize weights and apply final processing
1412
+ self.post_init()
1413
+
1414
+ def get_input_embeddings(self):
1415
+ return self.model.embed_tokens
1416
+
1417
+ def set_input_embeddings(self, value):
1418
+ self.model.embed_tokens = value
1419
+
1420
+ @add_start_docstrings_to_model_forward(GEMMOE_INPUTS_DOCSTRING)
1421
+ def forward(
1422
+ self,
1423
+ input_ids: torch.LongTensor = None,
1424
+ attention_mask: Optional[torch.Tensor] = None,
1425
+ position_ids: Optional[torch.LongTensor] = None,
1426
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1427
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1428
+ labels: Optional[torch.LongTensor] = None,
1429
+ use_cache: Optional[bool] = None,
1430
+ output_attentions: Optional[bool] = None,
1431
+ output_hidden_states: Optional[bool] = None,
1432
+ return_dict: Optional[bool] = None,
1433
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1434
+ r"""
1435
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1436
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1437
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1438
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1439
+ """
1440
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1441
+
1442
+ transformer_outputs = self.model(
1443
+ input_ids,
1444
+ attention_mask=attention_mask,
1445
+ position_ids=position_ids,
1446
+ past_key_values=past_key_values,
1447
+ inputs_embeds=inputs_embeds,
1448
+ use_cache=use_cache,
1449
+ output_attentions=output_attentions,
1450
+ output_hidden_states=output_hidden_states,
1451
+ return_dict=return_dict,
1452
+ )
1453
+ hidden_states = transformer_outputs[0]
1454
+ logits = self.score(hidden_states)
1455
+
1456
+ if input_ids is not None:
1457
+ batch_size = input_ids.shape[0]
1458
+ else:
1459
+ batch_size = inputs_embeds.shape[0]
1460
+
1461
+ if self.config.pad_token_id is None and batch_size != 1:
1462
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1463
+ if self.config.pad_token_id is None:
1464
+ sequence_lengths = -1
1465
+ else:
1466
+ if input_ids is not None:
1467
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1468
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1469
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1470
+ sequence_lengths = sequence_lengths.to(logits.device)
1471
+ else:
1472
+ sequence_lengths = -1
1473
+
1474
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1475
+
1476
+ loss = None
1477
+ if labels is not None:
1478
+ labels = labels.to(logits.device)
1479
+ if self.config.problem_type is None:
1480
+ if self.num_labels == 1:
1481
+ self.config.problem_type = "regression"
1482
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1483
+ self.config.problem_type = "single_label_classification"
1484
+ else:
1485
+ self.config.problem_type = "multi_label_classification"
1486
+
1487
+ if self.config.problem_type == "regression":
1488
+ loss_fct = MSELoss()
1489
+ if self.num_labels == 1:
1490
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1491
+ else:
1492
+ loss = loss_fct(pooled_logits, labels)
1493
+ elif self.config.problem_type == "single_label_classification":
1494
+ loss_fct = CrossEntropyLoss()
1495
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1496
+ elif self.config.problem_type == "multi_label_classification":
1497
+ loss_fct = BCEWithLogitsLoss()
1498
+ loss = loss_fct(pooled_logits, labels)
1499
+ if not return_dict:
1500
+ output = (pooled_logits,) + transformer_outputs[1:]
1501
+ return ((loss,) + output) if loss is not None else output
1502
+
1503
+ return SequenceClassifierOutputWithPast(
1504
+ loss=loss,
1505
+ logits=pooled_logits,
1506
+ past_key_values=transformer_outputs.past_key_values,
1507
+ hidden_states=transformer_outputs.hidden_states,
1508
+ attentions=transformer_outputs.attentions,
1509
+ )
tokenization_gemmoe.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Gemmoe."""
16
+ import os
17
+ from shutil import copyfile
18
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
19
+
20
+ import sentencepiece as spm
21
+
22
+ from transformers.utils import logging
23
+
24
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
25
+
26
+
27
+ if TYPE_CHECKING:
28
+ pass
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
33
+
34
+ SPIECE_UNDERLINE = "▁"
35
+
36
+ class GemmoeTokenizer(PreTrainedTokenizer):
37
+ """
38
+ Construct a Gemmoe tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
39
+ no padding token in the original model.
40
+
41
+ Args:
42
+ vocab_file (`str`):
43
+ Path to the vocabulary file.
44
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
45
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
46
+ token instead.
47
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<bos>"`):
48
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
49
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<eos>"`):
50
+ The end of sequence token.
51
+ pad_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<pad>"`):
52
+ A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
53
+ attention mechanisms or loss computation.
54
+ sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
55
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
56
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
57
+ to set:
58
+ - `enable_sampling`: Enable subword regularization.
59
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
60
+ - `nbest_size = {0,1}`: No sampling is performed.
61
+ - `nbest_size > 1`: samples from the nbest_size results.
62
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
63
+ using forward-filtering-and-backward-sampling algorithm.
64
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
65
+ BPE-dropout.
66
+ add_bos_token (`bool`, *optional*, defaults to `True`):
67
+ Whether or not to add an `bos_token` at the start of sequences.
68
+ add_eos_token (`bool`, *optional*, defaults to `False`):
69
+ Whether or not to add an `eos_token` at the end of sequences.
70
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
71
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
72
+ extra spaces.
73
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
74
+ Whether or not the default system prompt for Gemmoe should be used.
75
+ spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
76
+ Whether or not to add spaces between special tokens.
77
+ """
78
+
79
+ vocab_files_names = VOCAB_FILES_NAMES
80
+ model_input_names = ["input_ids", "attention_mask"]
81
+
82
+ def __init__(
83
+ self,
84
+ vocab_file,
85
+ unk_token="<unk>",
86
+ bos_token="<bos>",
87
+ eos_token="<eos>",
88
+ pad_token="<pad>",
89
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
90
+ add_bos_token=True,
91
+ add_eos_token=False,
92
+ clean_up_tokenization_spaces=False,
93
+ use_default_system_prompt=False,
94
+ spaces_between_special_tokens=False,
95
+ **kwargs,
96
+ ):
97
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
98
+ bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
99
+ eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
100
+ unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
101
+ pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
102
+
103
+ self.vocab_file = vocab_file
104
+ self.add_bos_token = add_bos_token
105
+ self.add_eos_token = add_eos_token
106
+ self.use_default_system_prompt = use_default_system_prompt
107
+
108
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
109
+ self.sp_model.Load(vocab_file)
110
+
111
+ super().__init__(
112
+ bos_token=bos_token,
113
+ eos_token=eos_token,
114
+ unk_token=unk_token,
115
+ pad_token=pad_token,
116
+ add_bos_token=add_bos_token,
117
+ add_eos_token=add_eos_token,
118
+ sp_model_kwargs=self.sp_model_kwargs,
119
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
120
+ use_default_system_prompt=use_default_system_prompt,
121
+ spaces_between_special_tokens=spaces_between_special_tokens,
122
+ **kwargs,
123
+ )
124
+
125
+ def __getstate__(self):
126
+ state = self.__dict__.copy()
127
+ state["sp_model"] = None
128
+ state["sp_model_proto"] = self.sp_model.serialized_model_proto()
129
+ return state
130
+
131
+ def __setstate__(self, d):
132
+ self.__dict__ = d
133
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
134
+ self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
135
+
136
+ @property
137
+ def vocab_size(self):
138
+ """Returns vocab size"""
139
+ return self.sp_model.get_piece_size()
140
+
141
+ def get_vocab(self):
142
+ """Returns vocab as a dict"""
143
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
144
+ vocab.update(self.added_tokens_encoder)
145
+ return vocab
146
+
147
+ def _tokenize(self, text, **kwargs):
148
+ """
149
+ Returns a tokenized string. The Gemmoe tokenizer never adds a prefix space.
150
+ """
151
+ return self.sp_model.encode(text, out_type=str)
152
+
153
+ def _convert_token_to_id(self, token):
154
+ """Converts a token (str) in an id using the vocab."""
155
+ return self.sp_model.piece_to_id(token)
156
+
157
+ def _convert_id_to_token(self, index):
158
+ """Converts an index (integer) in a token (str) using the vocab."""
159
+ token = self.sp_model.IdToPiece(index)
160
+ return token
161
+
162
+ def _decode(
163
+ self,
164
+ token_ids: List[int],
165
+ skip_special_tokens: bool = False,
166
+ spaces_between_special_tokens: bool = False,
167
+ **kwargs,
168
+ ) -> str:
169
+ sub_texts = []
170
+ current_sub_text = []
171
+ for ids in token_ids:
172
+ if skip_special_tokens and ids in self.all_special_ids:
173
+ continue
174
+ if ids in self._added_tokens_decoder:
175
+ if current_sub_text:
176
+ sub_texts.append(self.sp_model.decode(current_sub_text))
177
+ sub_texts.append(self._added_tokens_decoder[ids].content)
178
+ current_sub_text = []
179
+ else:
180
+ current_sub_text.append(ids)
181
+ if current_sub_text:
182
+ sub_texts.append(self.sp_model.decode(current_sub_text))
183
+ if spaces_between_special_tokens:
184
+ sub_texts = " ".join(sub_texts)
185
+ else:
186
+ sub_texts = "".join(sub_texts)
187
+ return sub_texts
188
+
189
+ def convert_tokens_to_string(self, tokens):
190
+ """Converts a sequence of tokens (string) in a single string."""
191
+ current_sub_tokens = []
192
+ out_string = ""
193
+ for token in tokens:
194
+ # make sure that special tokens are not decoded using sentencepiece model
195
+ if token in self._added_tokens_encoder:
196
+ out_string += self.sp_model.decode(current_sub_tokens) + token
197
+ current_sub_tokens = []
198
+ else:
199
+ current_sub_tokens.append(token)
200
+ out_string += self.sp_model.decode(current_sub_tokens)
201
+ return out_string
202
+
203
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
204
+ """
205
+ Save the vocabulary and special tokens file to a directory.
206
+
207
+ Args:
208
+ save_directory (`str`):
209
+ The directory in which to save the vocabulary.
210
+
211
+ Returns:
212
+ `Tuple(str)`: Paths to the files saved.
213
+ """
214
+ if not os.path.isdir(save_directory):
215
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
216
+ return
217
+ out_vocab_file = os.path.join(
218
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
219
+ )
220
+
221
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
222
+ copyfile(self.vocab_file, out_vocab_file)
223
+ elif not os.path.isfile(self.vocab_file):
224
+ with open(out_vocab_file, "wb") as fi:
225
+ content_spiece_model = self.sp_model.serialized_model_proto()
226
+ fi.write(content_spiece_model)
227
+
228
+ return (out_vocab_file,)
229
+
230
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
231
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
232
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
233
+ output = bos_token_id + token_ids_0 + eos_token_id
234
+ if token_ids_1 is not None:
235
+ output = output + bos_token_id + token_ids_1 + eos_token_id
236
+ return output
237
+
238
+ def get_special_tokens_mask(
239
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
240
+ ) -> List[int]:
241
+ """
242
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
243
+ special tokens using the tokenizer `prepare_for_model` method.
244
+
245
+ Args:
246
+ token_ids_0 (`List[int]`):
247
+ List of IDs.
248
+ token_ids_1 (`List[int]`, *optional*):
249
+ Optional second list of IDs for sequence pairs.
250
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
251
+ Whether or not the token list is already formatted with special tokens for the model.
252
+
253
+ Returns:
254
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
255
+ """
256
+ if already_has_special_tokens:
257
+ return super().get_special_tokens_mask(
258
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
259
+ )
260
+
261
+ bos_token_id = [1] if self.add_bos_token else []
262
+ eos_token_id = [1] if self.add_eos_token else []
263
+
264
+ if token_ids_1 is None:
265
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
266
+ return (
267
+ bos_token_id
268
+ + ([0] * len(token_ids_0))
269
+ + eos_token_id
270
+ + bos_token_id
271
+ + ([0] * len(token_ids_1))
272
+ + eos_token_id
273
+ )
274
+
275
+ def create_token_type_ids_from_sequences(
276
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
277
+ ) -> List[int]:
278
+ """
279
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
280
+ sequence pair mask has the following format:
281
+
282
+ ```
283
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
284
+ | first sequence | second sequence |
285
+ ```
286
+
287
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
288
+
289
+ Args:
290
+ token_ids_0 (`List[int]`):
291
+ List of ids.
292
+ token_ids_1 (`List[int]`, *optional*):
293
+ Optional second list of IDs for sequence pairs.
294
+
295
+ Returns:
296
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
297
+ """
298
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
299
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
300
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
301
+ if token_ids_1 is not None:
302
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
303
+ return output
304
+
305
+ def _build_conversation_input_ids(self, conversation: List[List[int]]) -> List[int]:
306
+ input_ids = []
307
+ for i, history in enumerate(conversation):
308
+ if i % 2 == 0:
309
+ input_ids.extend([self.bos_token_id, self.convert_tokens_to_ids("<start_of_turn>")] + history + [self.convert_tokens_to_ids("<end_of_turn>")])
310
+ else:
311
+ input_ids.extend([self.bos_token_id, self.convert_tokens_to_ids("<start_of_turn>"), self.convert_tokens_to_ids("model")] + history + [self.convert_tokens_to_ids("<end_of_turn>\n")])
312
+ input_ids.append(self.eos_token_id)
313
+ return input_ids