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