Add files using upload-large-folder tool
Browse files- config.json +37 -0
- configuration_longcat.py +210 -0
- generation_config.json +7 -0
- model.safetensors.index.json +0 -0
- model_00001-of-00075.safetensors +3 -0
- model_00002-of-00075.safetensors +3 -0
- model_00003-of-00075.safetensors +3 -0
- model_00004-of-00075.safetensors +3 -0
- model_00005-of-00075.safetensors +3 -0
- model_00006-of-00075.safetensors +3 -0
- model_00007-of-00075.safetensors +3 -0
- model_00008-of-00075.safetensors +3 -0
- model_00009-of-00075.safetensors +3 -0
- model_00010-of-00075.safetensors +3 -0
- model_00011-of-00075.safetensors +3 -0
- model_00012-of-00075.safetensors +3 -0
- model_00013-of-00075.safetensors +3 -0
- model_00014-of-00075.safetensors +3 -0
- model_00015-of-00075.safetensors +3 -0
- model_00016-of-00075.safetensors +3 -0
- model_00017-of-00075.safetensors +3 -0
- model_00018-of-00075.safetensors +3 -0
- model_00019-of-00075.safetensors +3 -0
- model_00020-of-00075.safetensors +3 -0
- model_00021-of-00075.safetensors +3 -0
- model_00022-of-00075.safetensors +3 -0
- model_00023-of-00075.safetensors +3 -0
- model_00024-of-00075.safetensors +3 -0
- model_00025-of-00075.safetensors +3 -0
- model_00026-of-00075.safetensors +3 -0
- model_00027-of-00075.safetensors +3 -0
- model_00028-of-00075.safetensors +3 -0
- model_00029-of-00075.safetensors +3 -0
- model_00030-of-00075.safetensors +3 -0
- model_00031-of-00075.safetensors +3 -0
- model_00032-of-00075.safetensors +3 -0
- model_00033-of-00075.safetensors +3 -0
- model_00034-of-00075.safetensors +3 -0
- model_00035-of-00075.safetensors +3 -0
- model_00036-of-00075.safetensors +3 -0
- model_00037-of-00075.safetensors +3 -0
- model_00038-of-00075.safetensors +3 -0
- model_00039-of-00075.safetensors +3 -0
- model_00040-of-00075.safetensors +3 -0
- model_00041-of-00075.safetensors +3 -0
- model_00042-of-00075.safetensors +3 -0
- modeling_longcat.py +1097 -0
- special_tokens_map.json +30 -0
- tokenizer.json +0 -0
- tokenizer_config.json +42 -0
config.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"LongcatCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_longcat.LongcatConfig",
|
| 9 |
+
"AutoModel": "modeling_longcat.LongcatModel",
|
| 10 |
+
"AutoModelForCausalLM": "modeling_longcat.LongcatForCausalLM"
|
| 11 |
+
},
|
| 12 |
+
"vocab_size": 131072,
|
| 13 |
+
"hidden_size": 6144,
|
| 14 |
+
"ffn_hidden_size": 12288,
|
| 15 |
+
"expert_ffn_hidden_size": 2048,
|
| 16 |
+
"num_layers": 28,
|
| 17 |
+
"num_attention_heads": 64,
|
| 18 |
+
"kv_lora_rank": 512,
|
| 19 |
+
"q_lora_rank": 1536,
|
| 20 |
+
"qk_rope_head_dim": 64,
|
| 21 |
+
"v_head_dim": 128,
|
| 22 |
+
"qk_nope_head_dim": 128,
|
| 23 |
+
"mla_scale_q_lora": true,
|
| 24 |
+
"mla_scale_kv_lora": true,
|
| 25 |
+
"routed_scaling_factor": 6.0,
|
| 26 |
+
"n_routed_experts": 512,
|
| 27 |
+
"max_position_embeddings": 131072,
|
| 28 |
+
"rms_norm_eps": 1e-5,
|
| 29 |
+
"use_cache": true,
|
| 30 |
+
"bos_token_id": 1,
|
| 31 |
+
"eos_token_id": 2,
|
| 32 |
+
"rope_theta": 10000000.0,
|
| 33 |
+
"attention_method": "M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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 bzantium and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
|
| 5 |
+
"""Longcat model configuration"""
|
| 6 |
+
|
| 7 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 8 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
LONGCAT_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class LongcatConfig(PretrainedConfig):
|
| 15 |
+
r"""
|
| 16 |
+
This is the configuration class to store the configuration of a [`LongcatModel`]. It is used to instantiate an Longcat
|
| 17 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 18 |
+
defaults will yield a similar configuration to that of the Longcat.
|
| 19 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 20 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
vocab_size (`int`, *optional*, defaults to 131072):
|
| 25 |
+
Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
|
| 26 |
+
`inputs_ids` passed when calling [`LongcatModel`]
|
| 27 |
+
hidden_size (`int`, *optional*, defaults to 7168):
|
| 28 |
+
Dimension of the hidden representations.
|
| 29 |
+
ffn_hidden_size (`int`, *optional*, defaults to 18432):
|
| 30 |
+
Dimension of the MLP representations.
|
| 31 |
+
expert_ffn_hidden_size (`int`, *optional*, defaults to 2048):
|
| 32 |
+
Dimension of the MoE representations.
|
| 33 |
+
num_layers (`int`, *optional*, defaults to 61):
|
| 34 |
+
Number of hidden layers in the Transformer decoder.
|
| 35 |
+
num_attention_heads (`int`, *optional*, defaults to 128):
|
| 36 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 37 |
+
num_key_value_heads (`int`, *optional*, defaults to 128):
|
| 38 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 39 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 40 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 41 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 42 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 43 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
| 44 |
+
`num_attention_heads`.
|
| 45 |
+
n_routed_experts (`int`, *optional*, defaults to 256):
|
| 46 |
+
Number of routed experts.
|
| 47 |
+
routed_scaling_factor (`float`, *optional*, defaults to 2.5):
|
| 48 |
+
Scaling factor or routed experts.
|
| 49 |
+
kv_lora_rank (`int`, *optional*, defaults to 512):
|
| 50 |
+
Rank of the LoRA matrices for key and value projections.
|
| 51 |
+
q_lora_rank (`int`, *optional*, defaults to 1536):
|
| 52 |
+
Rank of the LoRA matrices for query projections.
|
| 53 |
+
qk_rope_head_dim (`int`, *optional*, defaults to 64):
|
| 54 |
+
Dimension of the query/key heads that use rotary position embeddings.
|
| 55 |
+
v_head_dim (`int`, *optional*, defaults to 128):
|
| 56 |
+
Dimension of the value heads.
|
| 57 |
+
qk_nope_head_dim (`int`, *optional*, defaults to 128):
|
| 58 |
+
Dimension of the query/key heads that don't use rotary position embeddings.
|
| 59 |
+
norm_topk_prob (`bool`, *optional*, defaults to `True`):
|
| 60 |
+
Whether to normalize the weights of the routed experts.
|
| 61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 62 |
+
The non-linear activation function (function or string) in the decoder.
|
| 63 |
+
max_position_embeddings (`int`, *optional*, defaults to 4096):
|
| 64 |
+
The maximum sequence length that this model might ever be used with.
|
| 65 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 66 |
+
The epsilon used by the rms normalization layers.
|
| 67 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 68 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 69 |
+
relevant if `config.is_decoder=True`.
|
| 70 |
+
pad_token_id (`int`, *optional*):
|
| 71 |
+
Padding token id.
|
| 72 |
+
bos_token_id (`int`, *optional*, defaults to 0):
|
| 73 |
+
Beginning of stream token id.
|
| 74 |
+
eos_token_id (`int`, *optional*, defaults to 1):
|
| 75 |
+
End of stream token id.
|
| 76 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 77 |
+
Whether to tie weight embeddings
|
| 78 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 79 |
+
The base period of the RoPE embeddings.
|
| 80 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
| 81 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 82 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 83 |
+
The dropout ratio for the attention probabilities.
|
| 84 |
+
|
| 85 |
+
```python
|
| 86 |
+
>>> from transformers import LongcatModel, LongcatConfig
|
| 87 |
+
|
| 88 |
+
>>> # Initializing a Longcat style configuration
|
| 89 |
+
>>> configuration = LongcatConfig()
|
| 90 |
+
|
| 91 |
+
>>> # Accessing the model configuration
|
| 92 |
+
>>> configuration = model.config
|
| 93 |
+
```"""
|
| 94 |
+
|
| 95 |
+
model_type = "longcat"
|
| 96 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 97 |
+
base_model_tp_plan = { # TODO: only replicate attention layers when > first_k_dense_replace
|
| 98 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 99 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 100 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 101 |
+
"layers.*.mlp.experts.*.gate_proj": "local_colwise",
|
| 102 |
+
"layers.*.mlp.experts.*.up_proj": "local_colwise",
|
| 103 |
+
"layers.*.mlp.experts.*.down_proj": "local_rowwise",
|
| 104 |
+
"layers.*.mlps.*.gate_proj": "local_colwise",
|
| 105 |
+
"layers.*.mlps.*.up_proj": "local_colwise",
|
| 106 |
+
"layers.*.mlps.*.down_proj": "local_rowwise",
|
| 107 |
+
}
|
| 108 |
+
base_model_pp_plan = {
|
| 109 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 110 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 111 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
def __init__(
|
| 115 |
+
self,
|
| 116 |
+
vocab_size=131072,
|
| 117 |
+
hidden_size=7168,
|
| 118 |
+
ffn_hidden_size=18432,
|
| 119 |
+
expert_ffn_hidden_size=2048,
|
| 120 |
+
num_layers=61,
|
| 121 |
+
num_attention_heads=128,
|
| 122 |
+
num_key_value_heads=None,
|
| 123 |
+
n_routed_experts=256,
|
| 124 |
+
routed_scaling_factor=1,
|
| 125 |
+
kv_lora_rank=512,
|
| 126 |
+
q_lora_rank=1536,
|
| 127 |
+
qk_rope_head_dim=64,
|
| 128 |
+
v_head_dim=128,
|
| 129 |
+
head_dim=128,
|
| 130 |
+
qk_nope_head_dim=128,
|
| 131 |
+
mla_scale_q_lora=True,
|
| 132 |
+
mla_scale_kv_lora=True,
|
| 133 |
+
moe_topk=8,
|
| 134 |
+
norm_topk_prob=False,
|
| 135 |
+
hidden_act="silu",
|
| 136 |
+
max_position_embeddings=4096,
|
| 137 |
+
rms_norm_eps=1e-6,
|
| 138 |
+
use_cache=True,
|
| 139 |
+
pad_token_id=None,
|
| 140 |
+
bos_token_id=0,
|
| 141 |
+
eos_token_id=1,
|
| 142 |
+
tie_word_embeddings=False,
|
| 143 |
+
rope_theta=10000.0,
|
| 144 |
+
attention_bias=False,
|
| 145 |
+
attention_dropout=0.0,
|
| 146 |
+
attention_method='GQA',
|
| 147 |
+
initializer_range=0.006,
|
| 148 |
+
router_bias=False,
|
| 149 |
+
zero_expert_num=None,
|
| 150 |
+
zero_expert_type=None,
|
| 151 |
+
**kwargs,
|
| 152 |
+
):
|
| 153 |
+
self.vocab_size = vocab_size
|
| 154 |
+
self.max_position_embeddings = max_position_embeddings
|
| 155 |
+
self.hidden_size = hidden_size
|
| 156 |
+
self.ffn_hidden_size = ffn_hidden_size
|
| 157 |
+
self.expert_ffn_hidden_size = expert_ffn_hidden_size
|
| 158 |
+
self.num_layers = num_layers
|
| 159 |
+
self.num_attention_heads = num_attention_heads
|
| 160 |
+
self.n_routed_experts = n_routed_experts
|
| 161 |
+
self.routed_scaling_factor = routed_scaling_factor
|
| 162 |
+
self.kv_lora_rank = kv_lora_rank
|
| 163 |
+
self.q_lora_rank = q_lora_rank
|
| 164 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
| 165 |
+
self.v_head_dim = v_head_dim
|
| 166 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
| 167 |
+
self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
|
| 168 |
+
self.moe_topk = moe_topk
|
| 169 |
+
self.norm_topk_prob = norm_topk_prob
|
| 170 |
+
self.mla_scale_q_lora = mla_scale_q_lora
|
| 171 |
+
self.mla_scale_kv_lora = mla_scale_kv_lora
|
| 172 |
+
self.attention_method = attention_method
|
| 173 |
+
self.initializer_range = initializer_range
|
| 174 |
+
self.router_bias = router_bias
|
| 175 |
+
self.zero_expert_num = zero_expert_num
|
| 176 |
+
self.zero_expert_type = zero_expert_type
|
| 177 |
+
|
| 178 |
+
if self.attention_method == "GQA":
|
| 179 |
+
self.head_dim = head_dim
|
| 180 |
+
elif self.attention_method == "MLA":
|
| 181 |
+
self.head_dim = qk_rope_head_dim
|
| 182 |
+
else:
|
| 183 |
+
ValueError("attention_method should be one of [\"GQA\", \"MLA\"]")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# for backward compatibility
|
| 187 |
+
if num_key_value_heads is None:
|
| 188 |
+
num_key_value_heads = num_attention_heads
|
| 189 |
+
|
| 190 |
+
self.num_key_value_heads = num_key_value_heads
|
| 191 |
+
self.hidden_act = hidden_act
|
| 192 |
+
self.rms_norm_eps = rms_norm_eps
|
| 193 |
+
self.use_cache = use_cache
|
| 194 |
+
self.rope_theta = rope_theta
|
| 195 |
+
self.attention_bias = attention_bias
|
| 196 |
+
self.attention_dropout = attention_dropout
|
| 197 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 198 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
| 199 |
+
rope_config_validation(self)
|
| 200 |
+
|
| 201 |
+
super().__init__(
|
| 202 |
+
pad_token_id=pad_token_id,
|
| 203 |
+
bos_token_id=bos_token_id,
|
| 204 |
+
eos_token_id=eos_token_id,
|
| 205 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 206 |
+
**kwargs,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
__all__ = ["LongcatConfig"]
|
generation_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"pad_token_id": 0,
|
| 6 |
+
"transformers_version": "4.36.0"
|
| 7 |
+
}
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model_00001-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e704cb9980f02881a338bcab69fe57b26818bd5532a95160e035a48afb6bbca9
|
| 3 |
+
size 1610640880
|
model_00002-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ef0b9af4225dfa0785ba45668e5dcab60ba2565090a1007204cc6894bcc14bdc
|
| 3 |
+
size 1950351880
|
model_00003-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dfa915de26252706f7444ad86a0544c37ccb585e6e4c631cf07528e484db51e3
|
| 3 |
+
size 151021016
|
model_00004-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:42612161461787ec89262200c56b7f6407fd5f00fda0a02b60b11e6677b49b1d
|
| 3 |
+
size 1797259776
|
model_00005-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e2a9e62d9f84ccdda96192e8cf256b14f72c760ca31fe6120a340f10237fa10e
|
| 3 |
+
size 107766232
|
model_00006-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e1c396815c9bc2850ddce45c8342a223d71845964b84c62e86d59ac304a58b95
|
| 3 |
+
size 16104910872
|
model_00007-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:55822e0c3553b7c129b824846a46083be03834f9045d1350595e0067a1a3736b
|
| 3 |
+
size 16050410488
|
model_00008-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5ee474858019b88837bdcd48ccba6aa0794a4ae616b21d319b09310047dd5ff1
|
| 3 |
+
size 15852491800
|
model_00009-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8c79d62cdf400fdfbc1e45f8964f432e8703c786c72c39fc5e651a736d5d31be
|
| 3 |
+
size 15960208416
|
model_00010-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bb4aa648daaab1660e03fa4eb66e4027203e90125a9f53436d019996d43421d5
|
| 3 |
+
size 15916158872
|
model_00011-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cd549779f08e2678750274434c0d9eba624ed82d37bdddf4a3436f0e0adc1ffc
|
| 3 |
+
size 16104910872
|
model_00012-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:01b2d609e649fff84e786b822622aa88091b18ee47a98d82297dcaccc79b233b
|
| 3 |
+
size 16050410488
|
model_00013-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d1b8aa94ab6261ee6c9bdebf829aef6754cdd8ce3b4ce35edb7d6e3f60201e2e
|
| 3 |
+
size 15852491800
|
model_00014-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:02fedb6e8ef2c76a3bd8f9f9cf313992cb34e46c01c4bdc647fcdd33f6d5864d
|
| 3 |
+
size 15960208416
|
model_00015-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c42623ea52be9860976ef7d3b31d265dfc111c574efab7234a7f898581a7cfe0
|
| 3 |
+
size 15916158872
|
model_00016-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c5af69854e7fd28452799e48eb6374f0a13c6e6e344899cc040ee0866df1198b
|
| 3 |
+
size 16104910872
|
model_00017-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5a63f4935149d8d45629ff2f1507f26d34cb2206cc8e64b18d7b2307753ffeab
|
| 3 |
+
size 16050410488
|
model_00018-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e14ae63e7004c9bc774660a72ac11a1e1dbf8fbadbdc70ba9b657852d676ef8a
|
| 3 |
+
size 15852491800
|
model_00019-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1d30f98b5d6f0d3e28b047c2524ca60289f9cd1b796e83a9bda31e2e27d51204
|
| 3 |
+
size 15960208416
|
model_00020-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a9f65fa8c0a27cb9c364238fe7b3f0e257ecef41fc3a340940f3831b65901406
|
| 3 |
+
size 15916158872
|
model_00021-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e6f580ea5c34a6991cb2e97f27811eaaf25d6dd0b364f88aabe3ce3288a6c794
|
| 3 |
+
size 16104910856
|
model_00022-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:27dc23abf3cf04f1c9e957cc7586b0b4c24b5cdeea604ac658e7ff3a54c52aac
|
| 3 |
+
size 16050410512
|
model_00023-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:93acbbd722f720bf66a3682897985c31e2b41c377154d476655dec1159c4b94b
|
| 3 |
+
size 15852491784
|
model_00024-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:baa183067ac8e3324aea5e55eb90e27716bbbadb0f7200d5d40c68245bcc9b16
|
| 3 |
+
size 15960208416
|
model_00025-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e0502fa16482331c5ce050566a9a782681452121388875ceb08d75057fb92735
|
| 3 |
+
size 15916158872
|
model_00026-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bb74d6eee28f1df0fd596b7ccce95587baf9b2f8cb8e8ac9e5b71d06db6ec9de
|
| 3 |
+
size 16104910856
|
model_00027-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2feae66f2d3c0f195b597c54a5352e97741f789494421d9e74d54f9f801fb570
|
| 3 |
+
size 16050410512
|
model_00028-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c082c412d54be36b5aeebe6cc0fadc10381ff3efa0bce28b14149e2b112372de
|
| 3 |
+
size 15852491784
|
model_00029-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:23587de486896f98f64d83d1f18ee855825fa289b61d0173e639e4a8796f5e34
|
| 3 |
+
size 15960208416
|
model_00030-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9074d2392623cd21eec8296e8d251c3383ed6f298bb5fc7f5e3e6eefd1451bbd
|
| 3 |
+
size 15916158872
|
model_00031-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6d6d46b7f422474594dc6f8fb536f93fcfd6e866df90930f7163f373977d76d6
|
| 3 |
+
size 16104910856
|
model_00032-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9a54bb18a3661cefad82771846ca977a74547c56f3e3a429ac7ed703274fc76a
|
| 3 |
+
size 16050410512
|
model_00033-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1cd2bbf2ece638b3fd374c70acbcb4467cba6dac576d31130b8c4ef06f398e03
|
| 3 |
+
size 15852491784
|
model_00034-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:56de3ae9731c699552e866ce2e4d0fa600fa735303eccee7f36a0d522affe026
|
| 3 |
+
size 15960208416
|
model_00035-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2025c8af0936b6ca12734b0da72c84728c32c6224e0070ba60e1422567e9362c
|
| 3 |
+
size 15916158872
|
model_00036-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b0aa1043c059805590b811282bd2dc0963fcad0c6fcb0f9de5753293069f96a
|
| 3 |
+
size 16104910856
|
model_00037-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8c3653888967b2eb8f0084dd1c36b04fe7c016bf371969867cb0b778850bffcf
|
| 3 |
+
size 16050410512
|
model_00038-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8166f3277f580d8d114b4e67889be291974f3e1a89cd781549906da3de021469
|
| 3 |
+
size 15852491784
|
model_00039-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:af253e4dce4ebe364be108c83c730b42ded3ca8cfbd18d60d11910a57f525a18
|
| 3 |
+
size 15960208416
|
model_00040-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8051f3ee7967f20e98d367e0d0923ff895c27bdd2df9525b1a4e7c9dfbc89dd0
|
| 3 |
+
size 15916158872
|
model_00041-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d5477888162d0408950aea00ba96e19acfffbd2dfafd7efb6e3615d189909dad
|
| 3 |
+
size 16104910856
|
model_00042-of-00075.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:64d4df3e185a159c7a130fce53ef621f88eac0c0acf99ed423a5b8f71c38603c
|
| 3 |
+
size 16050410512
|
modeling_longcat.py
ADDED
|
@@ -0,0 +1,1097 @@
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/longcat/modular_longcat.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_longcat.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
from functools import partial
|
| 8 |
+
from typing import Callable, Optional, Tuple, Union
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from torch import nn
|
| 13 |
+
|
| 14 |
+
from transformers.activations import ACT2FN
|
| 15 |
+
from transformers.cache_utils import Cache
|
| 16 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 17 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 18 |
+
from transformers.processing_utils import Unpack
|
| 19 |
+
from transformers.utils import logging
|
| 20 |
+
|
| 21 |
+
from transformers.cache_utils import DynamicCache, StaticCache
|
| 22 |
+
from transformers.generation import GenerationMixin
|
| 23 |
+
from transformers.integrations import use_kernel_forward_from_hub
|
| 24 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
| 25 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 26 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 27 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 28 |
+
from transformers.utils import (
|
| 29 |
+
LossKwargs,
|
| 30 |
+
add_start_docstrings,
|
| 31 |
+
add_start_docstrings_to_model_forward,
|
| 32 |
+
can_return_tuple,
|
| 33 |
+
is_torch_flex_attn_available,
|
| 34 |
+
replace_return_docstrings,
|
| 35 |
+
)
|
| 36 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 37 |
+
from .configuration_longcat import LongcatConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if is_torch_flex_attn_available():
|
| 41 |
+
from torch.nn.attention.flex_attention import BlockMask
|
| 42 |
+
|
| 43 |
+
from transformers.integrations.flex_attention import make_flex_block_causal_mask
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
_CONFIG_FOR_DOC = "LongcatConfig"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 51 |
+
class LongcatRMSNorm(nn.Module):
|
| 52 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 53 |
+
"""
|
| 54 |
+
LongcatRMSNorm is equivalent to T5LayerNorm
|
| 55 |
+
"""
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 58 |
+
self.variance_epsilon = eps
|
| 59 |
+
|
| 60 |
+
def forward(self, hidden_states):
|
| 61 |
+
input_dtype = hidden_states.dtype
|
| 62 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 63 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 64 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 65 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 66 |
+
|
| 67 |
+
def extra_repr(self):
|
| 68 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class LongcatRotaryEmbedding(nn.Module):
|
| 72 |
+
def __init__(self, config: LongcatConfig, device=None):
|
| 73 |
+
super().__init__()
|
| 74 |
+
# BC: "rope_type" was originally "type"
|
| 75 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
| 76 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 77 |
+
else:
|
| 78 |
+
self.rope_type = "default"
|
| 79 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 80 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 81 |
+
|
| 82 |
+
self.config = config
|
| 83 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 84 |
+
|
| 85 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 86 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 87 |
+
self.original_inv_freq = self.inv_freq
|
| 88 |
+
|
| 89 |
+
@torch.no_grad()
|
| 90 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 91 |
+
def forward(self, x, position_ids):
|
| 92 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 93 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 94 |
+
|
| 95 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 96 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 97 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 98 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 99 |
+
cos = emb.cos() * self.attention_scaling
|
| 100 |
+
sin = emb.sin() * self.attention_scaling
|
| 101 |
+
|
| 102 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class LongcatMLP(nn.Module):
|
| 106 |
+
def __init__(self, config, hidden_size=None, intermediate_size=None):
|
| 107 |
+
super().__init__()
|
| 108 |
+
self.config = config
|
| 109 |
+
self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
|
| 110 |
+
self.intermediate_size = config.ffn_hidden_size if intermediate_size is None else intermediate_size
|
| 111 |
+
|
| 112 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 113 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 114 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 115 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 116 |
+
|
| 117 |
+
def forward(self, x):
|
| 118 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 119 |
+
return down_proj
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class LongcatTopkRouter(nn.Module):
|
| 123 |
+
def __init__(self, config):
|
| 124 |
+
super().__init__()
|
| 125 |
+
self.config = config
|
| 126 |
+
self.top_k = config.moe_topk
|
| 127 |
+
self.n_routed_experts = config.n_routed_experts if config.zero_expert_num is None else config.n_routed_experts + config.zero_expert_num
|
| 128 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
| 129 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 130 |
+
self.router_bias = config.router_bias
|
| 131 |
+
|
| 132 |
+
self.classifier = nn.Linear(config.hidden_size, self.n_routed_experts, bias=self.router_bias)
|
| 133 |
+
self.register_buffer("e_score_correction_bias", torch.zeros((self.n_routed_experts)))
|
| 134 |
+
|
| 135 |
+
@torch.no_grad()
|
| 136 |
+
def get_topk_indices(self, scores):
|
| 137 |
+
scores_for_choice = scores.view(-1, self.n_routed_experts) + self.e_score_correction_bias.unsqueeze(0)
|
| 138 |
+
topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
| 139 |
+
return topk_indices
|
| 140 |
+
|
| 141 |
+
def forward(self, hidden_states):
|
| 142 |
+
hidden_states = hidden_states.view(
|
| 143 |
+
-1, self.config.hidden_size
|
| 144 |
+
) # hidden_states: [batchsize*seq_len, hidden_size]
|
| 145 |
+
router_logits = F.linear(hidden_states.type(torch.float32), self.classifier.weight.type(torch.float32))
|
| 146 |
+
scores = router_logits.softmax(dim=-1)
|
| 147 |
+
topk_indices = self.get_topk_indices(scores)
|
| 148 |
+
topk_weights = scores.gather(1, topk_indices)
|
| 149 |
+
if self.norm_topk_prob:
|
| 150 |
+
denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
|
| 151 |
+
topk_weights /= denominator
|
| 152 |
+
topk_weights = topk_weights * self.routed_scaling_factor
|
| 153 |
+
return topk_indices, topk_weights
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class LongcatMoE(nn.Module):
|
| 157 |
+
"""
|
| 158 |
+
A mixture of expert module.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
def __init__(self, config):
|
| 162 |
+
super().__init__()
|
| 163 |
+
self.config = config
|
| 164 |
+
self.experts = nn.ModuleList(
|
| 165 |
+
[
|
| 166 |
+
LongcatMLP(config, intermediate_size=config.expert_ffn_hidden_size)
|
| 167 |
+
for _ in range(config.n_routed_experts)
|
| 168 |
+
]
|
| 169 |
+
)
|
| 170 |
+
self.router = LongcatTopkRouter(config)
|
| 171 |
+
self.zero_expert_num = config.zero_expert_num
|
| 172 |
+
self.zero_expert_type = config.zero_expert_type
|
| 173 |
+
|
| 174 |
+
def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
|
| 175 |
+
r"""
|
| 176 |
+
CALL FOR CONTRIBUTION! I don't have time to optimise this right now, but expert weights need to be fused
|
| 177 |
+
to not have to do a loop here (deepseek has 256 experts soooo yeah).
|
| 178 |
+
"""
|
| 179 |
+
final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
|
| 180 |
+
total_experts = len(self.experts) if self.zero_expert_num is None else len(self.experts) + self.zero_expert_num
|
| 181 |
+
|
| 182 |
+
expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=total_experts) # (T, K, E)
|
| 183 |
+
expert_mask = expert_mask.permute(2, 0, 1) # (E, T, K)
|
| 184 |
+
|
| 185 |
+
for expert_idx in range(total_experts):
|
| 186 |
+
expert = self.experts[expert_idx] if expert_idx<len(self.experts) else None
|
| 187 |
+
mask = expert_mask[expert_idx] # (T, K)
|
| 188 |
+
token_indices, weight_indices = torch.where(mask) # 哪些token选择了这些专家 shape (N, )
|
| 189 |
+
|
| 190 |
+
if token_indices.numel() > 0:
|
| 191 |
+
expert_weights = topk_weights[token_indices, weight_indices]
|
| 192 |
+
expert_input = hidden_states[token_indices] # (T, H) --> (N, H)
|
| 193 |
+
|
| 194 |
+
if self.zero_expert_num is None or expert_idx<len(self.experts):
|
| 195 |
+
expert_output = expert(expert_input)
|
| 196 |
+
elif self.zero_expert_type=='drop':
|
| 197 |
+
expert_output = 0*expert_input
|
| 198 |
+
elif self.zero_expert_type=='identity':
|
| 199 |
+
expert_output = expert_input
|
| 200 |
+
else:
|
| 201 |
+
raise ValueError("Unknown condition")
|
| 202 |
+
|
| 203 |
+
weighted_output = expert_output * expert_weights.unsqueeze(-1)
|
| 204 |
+
final_hidden_states.index_add_(0, token_indices, weighted_output)
|
| 205 |
+
|
| 206 |
+
# in original deepseek, the output of the experts are gathered once we leave this module
|
| 207 |
+
# thus the moe module is itelsf an IsolatedParallel module
|
| 208 |
+
# and all expert are "local" meaning we shard but we don't gather
|
| 209 |
+
return final_hidden_states.type(hidden_states.dtype)
|
| 210 |
+
|
| 211 |
+
def forward(self, hidden_states):
|
| 212 |
+
residuals = hidden_states
|
| 213 |
+
orig_shape = hidden_states.shape
|
| 214 |
+
topk_indices, topk_weights = self.router(hidden_states)
|
| 215 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
| 216 |
+
hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
|
| 217 |
+
return hidden_states
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def rotate_half(x):
|
| 221 |
+
"""Rotates half the hidden dims of the input."""
|
| 222 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 223 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 224 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 228 |
+
"""
|
| 229 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 230 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 231 |
+
"""
|
| 232 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 233 |
+
if n_rep == 1:
|
| 234 |
+
return hidden_states
|
| 235 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 236 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def eager_attention_forward(
|
| 240 |
+
module: nn.Module,
|
| 241 |
+
query: torch.Tensor,
|
| 242 |
+
key: torch.Tensor,
|
| 243 |
+
value: torch.Tensor,
|
| 244 |
+
attention_mask: Optional[torch.Tensor],
|
| 245 |
+
scaling: float,
|
| 246 |
+
dropout: float = 0.0,
|
| 247 |
+
**kwargs,
|
| 248 |
+
):
|
| 249 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 250 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 251 |
+
|
| 252 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 253 |
+
if attention_mask is not None:
|
| 254 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 255 |
+
attn_weights = attn_weights + causal_mask
|
| 256 |
+
|
| 257 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 258 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 259 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 260 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 261 |
+
|
| 262 |
+
return attn_output, attn_weights
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1, use_mla=False):
|
| 266 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
q (`torch.Tensor`): The query tensor.
|
| 270 |
+
k (`torch.Tensor`): The key tensor.
|
| 271 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 272 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 273 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 274 |
+
Deprecated and unused.
|
| 275 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 276 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 277 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 278 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 279 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 280 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 281 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 282 |
+
Returns:
|
| 283 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 284 |
+
"""
|
| 285 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 286 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 287 |
+
|
| 288 |
+
if use_mla:
|
| 289 |
+
b, h, s, d = q.shape
|
| 290 |
+
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
| 291 |
+
|
| 292 |
+
b, h, s, d = k.shape
|
| 293 |
+
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
| 294 |
+
|
| 295 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 296 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 297 |
+
return q_embed, k_embed
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
class LongcatGQA(nn.Module):
|
| 301 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 302 |
+
|
| 303 |
+
def __init__(self, config: LongcatConfig, layer_idx: int):
|
| 304 |
+
super().__init__()
|
| 305 |
+
self.config = config
|
| 306 |
+
self.layer_idx = layer_idx
|
| 307 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 308 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 309 |
+
self.scaling = self.head_dim**-0.5
|
| 310 |
+
self.attention_dropout = config.attention_dropout
|
| 311 |
+
self.is_causal = True
|
| 312 |
+
|
| 313 |
+
self.q_proj = nn.Linear(
|
| 314 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 315 |
+
)
|
| 316 |
+
self.k_proj = nn.Linear(
|
| 317 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 318 |
+
)
|
| 319 |
+
self.v_proj = nn.Linear(
|
| 320 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 321 |
+
)
|
| 322 |
+
self.o_proj = nn.Linear(
|
| 323 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
def forward(
|
| 327 |
+
self,
|
| 328 |
+
hidden_states: torch.Tensor,
|
| 329 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 330 |
+
attention_mask: Optional[torch.Tensor],
|
| 331 |
+
past_key_value: Optional[Cache] = None,
|
| 332 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 333 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 334 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 335 |
+
input_shape = hidden_states.shape[:-1]
|
| 336 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 337 |
+
|
| 338 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 339 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 340 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 341 |
+
|
| 342 |
+
cos, sin = position_embeddings
|
| 343 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 344 |
+
|
| 345 |
+
if past_key_value is not None:
|
| 346 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 347 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 348 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 349 |
+
|
| 350 |
+
attention_interface: Callable = eager_attention_forward
|
| 351 |
+
|
| 352 |
+
if self.config._attn_implementation != "eager":
|
| 353 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
| 354 |
+
logger.warning_once(
|
| 355 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
| 356 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 357 |
+
)
|
| 358 |
+
else:
|
| 359 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 360 |
+
|
| 361 |
+
attn_output, attn_weights = attention_interface(
|
| 362 |
+
self,
|
| 363 |
+
query_states,
|
| 364 |
+
key_states,
|
| 365 |
+
value_states,
|
| 366 |
+
attention_mask,
|
| 367 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 368 |
+
scaling=self.scaling,
|
| 369 |
+
**kwargs,
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 373 |
+
attn_output = self.o_proj(attn_output)
|
| 374 |
+
return attn_output, attn_weights
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class LongcatMLA(nn.Module):
|
| 378 |
+
"""Modified from Deepseek MLA"""
|
| 379 |
+
|
| 380 |
+
def __init__(self, config: LongcatConfig, layer_idx: int):
|
| 381 |
+
super().__init__()
|
| 382 |
+
self.config = config
|
| 383 |
+
self.layer_idx = layer_idx
|
| 384 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 385 |
+
self.attention_dropout = config.attention_dropout
|
| 386 |
+
self.num_heads = config.num_attention_heads
|
| 387 |
+
self.rope_theta = config.rope_theta
|
| 388 |
+
self.q_lora_rank = config.q_lora_rank
|
| 389 |
+
self.qk_rope_head_dim = config.qk_rope_head_dim
|
| 390 |
+
self.kv_lora_rank = config.kv_lora_rank
|
| 391 |
+
self.v_head_dim = config.v_head_dim
|
| 392 |
+
self.qk_nope_head_dim = config.qk_nope_head_dim
|
| 393 |
+
self.qk_head_dim = config.qk_head_dim
|
| 394 |
+
|
| 395 |
+
self.is_causal = True
|
| 396 |
+
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
|
| 397 |
+
self.q_a_layernorm = LongcatRMSNorm(config.q_lora_rank)
|
| 398 |
+
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
|
| 399 |
+
|
| 400 |
+
self.kv_a_proj_with_mqa = nn.Linear(
|
| 401 |
+
config.hidden_size,
|
| 402 |
+
self.kv_lora_rank + self.qk_rope_head_dim,
|
| 403 |
+
bias=config.attention_bias,
|
| 404 |
+
)
|
| 405 |
+
self.kv_a_layernorm = LongcatRMSNorm(self.kv_lora_rank)
|
| 406 |
+
self.kv_b_proj = nn.Linear(
|
| 407 |
+
self.kv_lora_rank,
|
| 408 |
+
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
|
| 409 |
+
bias=False,
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
self.o_proj = nn.Linear(
|
| 413 |
+
self.num_heads * self.v_head_dim,
|
| 414 |
+
config.hidden_size,
|
| 415 |
+
bias=config.attention_bias,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
if config.mla_scale_q_lora:
|
| 419 |
+
self.mla_scale_q_lora = (config.hidden_size / self.q_lora_rank) ** 0.5
|
| 420 |
+
if config.mla_scale_kv_lora:
|
| 421 |
+
self.mla_scale_kv_lora = (config.hidden_size / self.kv_lora_rank) ** 0.5
|
| 422 |
+
self.scaling = self.qk_head_dim ** (-0.5)
|
| 423 |
+
|
| 424 |
+
def forward(
|
| 425 |
+
self,
|
| 426 |
+
hidden_states: torch.Tensor,
|
| 427 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 428 |
+
attention_mask: Optional[torch.Tensor],
|
| 429 |
+
past_key_value: Optional[Cache] = None,
|
| 430 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 431 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 432 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 433 |
+
batch_size, seq_length = hidden_states.shape[:-1]
|
| 434 |
+
query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
|
| 435 |
+
key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
|
| 436 |
+
|
| 437 |
+
q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))).view(query_shape).transpose(1, 2)
|
| 438 |
+
q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
| 439 |
+
|
| 440 |
+
# apply q_lora scaling
|
| 441 |
+
if self.mla_scale_q_lora is not None:
|
| 442 |
+
q_pass = q_pass * self.mla_scale_q_lora
|
| 443 |
+
q_rot = q_rot * self.mla_scale_q_lora
|
| 444 |
+
|
| 445 |
+
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
| 446 |
+
k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
| 447 |
+
k_pass = self.kv_a_layernorm(k_pass)
|
| 448 |
+
|
| 449 |
+
# apply kv_lora scaling
|
| 450 |
+
if self.mla_scale_kv_lora is not None:
|
| 451 |
+
k_pass = k_pass * self.mla_scale_kv_lora
|
| 452 |
+
|
| 453 |
+
k_pass = self.kv_b_proj(k_pass).view(key_shape).transpose(1, 2)
|
| 454 |
+
k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
| 455 |
+
|
| 456 |
+
k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
|
| 457 |
+
|
| 458 |
+
cos, sin = position_embeddings
|
| 459 |
+
q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin, use_mla=True)
|
| 460 |
+
k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
|
| 461 |
+
|
| 462 |
+
query_states = torch.cat((q_pass, q_rot), dim=-1)
|
| 463 |
+
key_states = torch.cat((k_pass, k_rot), dim=-1)
|
| 464 |
+
|
| 465 |
+
if past_key_value is not None:
|
| 466 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 467 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 468 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 469 |
+
|
| 470 |
+
if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
|
| 471 |
+
value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
|
| 472 |
+
|
| 473 |
+
attention_interface: Callable = eager_attention_forward
|
| 474 |
+
if self.config._attn_implementation != "eager":
|
| 475 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
| 476 |
+
logger.warning_once(
|
| 477 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
| 478 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 479 |
+
)
|
| 480 |
+
else:
|
| 481 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 482 |
+
|
| 483 |
+
attn_output, attn_weights = attention_interface(
|
| 484 |
+
self,
|
| 485 |
+
query_states,
|
| 486 |
+
key_states,
|
| 487 |
+
value_states,
|
| 488 |
+
attention_mask,
|
| 489 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 490 |
+
scaling=self.scaling,
|
| 491 |
+
**kwargs,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
|
| 495 |
+
attn_output = attn_output[:, :, :, : self.v_head_dim]
|
| 496 |
+
|
| 497 |
+
attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
|
| 498 |
+
attn_output = self.o_proj(attn_output)
|
| 499 |
+
return attn_output, attn_weights
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def create_attention_block(class_name, *args, **kwargs):
|
| 503 |
+
# 字典将输入参数映射到类及其参数列表
|
| 504 |
+
attention_mapping = {"MLA": LongcatMLA, "GQA": LongcatGQA}
|
| 505 |
+
|
| 506 |
+
chosen_class = attention_mapping.get(class_name)
|
| 507 |
+
if not chosen_class:
|
| 508 |
+
raise ValueError(f"No class found for name: {class_name}")
|
| 509 |
+
|
| 510 |
+
# 实例化并传递参数
|
| 511 |
+
return chosen_class(*args, **kwargs)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
class LongcatDecoderLayer(nn.Module):
|
| 515 |
+
def __init__(self, config: LongcatConfig, layer_idx: int):
|
| 516 |
+
super().__init__()
|
| 517 |
+
self.layer_idx = layer_idx
|
| 518 |
+
self.hidden_size = config.hidden_size
|
| 519 |
+
self.mlp = LongcatMoE(config)
|
| 520 |
+
|
| 521 |
+
self_attn = []
|
| 522 |
+
mlps = []
|
| 523 |
+
input_layernorm = []
|
| 524 |
+
post_attention_layernorm = []
|
| 525 |
+
for i in range(2):
|
| 526 |
+
self_attn.append(
|
| 527 |
+
create_attention_block(config.attention_method, config=config, layer_idx=layer_idx * 2 + i)
|
| 528 |
+
)
|
| 529 |
+
mlps.append(LongcatMLP(config))
|
| 530 |
+
input_layernorm.append(LongcatRMSNorm(config.hidden_size, eps=config.rms_norm_eps))
|
| 531 |
+
post_attention_layernorm.append(LongcatRMSNorm(config.hidden_size, eps=config.rms_norm_eps))
|
| 532 |
+
|
| 533 |
+
self.self_attn = nn.ModuleList(self_attn)
|
| 534 |
+
self.mlps = nn.ModuleList(mlps)
|
| 535 |
+
self.input_layernorm = nn.ModuleList(input_layernorm)
|
| 536 |
+
self.post_attention_layernorm = nn.ModuleList(post_attention_layernorm)
|
| 537 |
+
|
| 538 |
+
def forward(
|
| 539 |
+
self,
|
| 540 |
+
hidden_states: torch.Tensor,
|
| 541 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 542 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 543 |
+
past_key_value: Optional[Cache] = None,
|
| 544 |
+
output_attentions: Optional[bool] = False,
|
| 545 |
+
use_cache: Optional[bool] = False,
|
| 546 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 547 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 548 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 549 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 550 |
+
for i in range(2):
|
| 551 |
+
residual = hidden_states
|
| 552 |
+
|
| 553 |
+
hidden_states = self.input_layernorm[i](hidden_states)
|
| 554 |
+
|
| 555 |
+
# Self Attention
|
| 556 |
+
hidden_states, self_attn_weights = self.self_attn[i](
|
| 557 |
+
hidden_states=hidden_states,
|
| 558 |
+
attention_mask=attention_mask,
|
| 559 |
+
position_ids=position_ids,
|
| 560 |
+
past_key_value=past_key_value,
|
| 561 |
+
output_attentions=output_attentions,
|
| 562 |
+
use_cache=use_cache,
|
| 563 |
+
cache_position=cache_position,
|
| 564 |
+
position_embeddings=position_embeddings,
|
| 565 |
+
**kwargs,
|
| 566 |
+
)
|
| 567 |
+
hidden_states = residual + hidden_states
|
| 568 |
+
|
| 569 |
+
# Fully Connected
|
| 570 |
+
residual = hidden_states
|
| 571 |
+
hidden_states = self.post_attention_layernorm[i](hidden_states)
|
| 572 |
+
|
| 573 |
+
if i == 0:
|
| 574 |
+
shortcut_mlp_output = self.mlp(hidden_states) # shortcut output (MoE output)
|
| 575 |
+
|
| 576 |
+
hidden_states = self.mlps[i](hidden_states)
|
| 577 |
+
hidden_states = residual + hidden_states
|
| 578 |
+
if i == 1:
|
| 579 |
+
hidden_states = hidden_states + shortcut_mlp_output
|
| 580 |
+
|
| 581 |
+
outputs = (hidden_states,)
|
| 582 |
+
if output_attentions:
|
| 583 |
+
outputs += (self_attn_weights,)
|
| 584 |
+
|
| 585 |
+
return outputs
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
LONGCAT_START_DOCSTRING = r"""
|
| 589 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 590 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 591 |
+
etc.)
|
| 592 |
+
|
| 593 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 594 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 595 |
+
and behavior.
|
| 596 |
+
|
| 597 |
+
Parameters:
|
| 598 |
+
config ([`LongcatConfig`]):
|
| 599 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 600 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 601 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 602 |
+
"""
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
@add_start_docstrings(
|
| 606 |
+
"The bare Longcat Model outputting raw hidden-states without any specific head on top.",
|
| 607 |
+
LONGCAT_START_DOCSTRING,
|
| 608 |
+
)
|
| 609 |
+
class LongcatPreTrainedModel(PreTrainedModel):
|
| 610 |
+
config_class = LongcatConfig
|
| 611 |
+
base_model_prefix = "model"
|
| 612 |
+
supports_gradient_checkpointing = True
|
| 613 |
+
_no_split_modules = ["LongcatDecoderLayer"]
|
| 614 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 615 |
+
_supports_flash_attn_2 = True
|
| 616 |
+
_supports_sdpa = True
|
| 617 |
+
_supports_flex_attn = True
|
| 618 |
+
_supports_cache_class = True
|
| 619 |
+
_supports_quantized_cache = True
|
| 620 |
+
_supports_static_cache = True
|
| 621 |
+
_supports_attention_backend = True
|
| 622 |
+
|
| 623 |
+
def _init_weights(self, module):
|
| 624 |
+
std = self.config.initializer_range
|
| 625 |
+
if isinstance(module, nn.Linear):
|
| 626 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 627 |
+
if module.bias is not None:
|
| 628 |
+
module.bias.data.zero_()
|
| 629 |
+
elif isinstance(module, nn.Embedding):
|
| 630 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 631 |
+
if module.padding_idx is not None:
|
| 632 |
+
module.weight.data[module.padding_idx].zero_()
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
LONGCAT_INPUTS_DOCSTRING = r"""
|
| 636 |
+
Args:
|
| 637 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 638 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 639 |
+
it.
|
| 640 |
+
|
| 641 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 642 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 643 |
+
|
| 644 |
+
[What are input IDs?](../glossary#input-ids)
|
| 645 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 646 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 647 |
+
|
| 648 |
+
- 1 for tokens that are **not masked**,
|
| 649 |
+
- 0 for tokens that are **masked**.
|
| 650 |
+
|
| 651 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 652 |
+
|
| 653 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 654 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 655 |
+
|
| 656 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
| 657 |
+
`past_key_values`).
|
| 658 |
+
|
| 659 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 660 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 661 |
+
information on the default strategy.
|
| 662 |
+
|
| 663 |
+
- 1 indicates the head is **not masked**,
|
| 664 |
+
- 0 indicates the head is **masked**.
|
| 665 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 666 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 667 |
+
config.n_positions - 1]`.
|
| 668 |
+
|
| 669 |
+
[What are position IDs?](../glossary#position-ids)
|
| 670 |
+
past_key_values (`Cache`, *optional*):
|
| 671 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 672 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
| 673 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
| 674 |
+
|
| 675 |
+
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
|
| 676 |
+
|
| 677 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
| 678 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
| 679 |
+
of shape `(batch_size, sequence_length)`.
|
| 680 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 681 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 682 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 683 |
+
model's internal embedding lookup matrix.
|
| 684 |
+
use_cache (`bool`, *optional*):
|
| 685 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 686 |
+
`past_key_values`).
|
| 687 |
+
output_attentions (`bool`, *optional*):
|
| 688 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 689 |
+
tensors for more detail.
|
| 690 |
+
output_hidden_states (`bool`, *optional*):
|
| 691 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 692 |
+
more detail.
|
| 693 |
+
return_dict (`bool`, *optional*):
|
| 694 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 695 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 696 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
| 697 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
| 698 |
+
the complete sequence length.
|
| 699 |
+
"""
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
@add_start_docstrings(
|
| 703 |
+
"The bare Longcat Model outputting raw hidden-states without any specific head on top.",
|
| 704 |
+
LONGCAT_START_DOCSTRING,
|
| 705 |
+
)
|
| 706 |
+
class LongcatModel(LongcatPreTrainedModel):
|
| 707 |
+
"""
|
| 708 |
+
Transformer decoder consisting of *config.num_layers* layers. Each layer is a [`LongcatDecoderLayer`]
|
| 709 |
+
|
| 710 |
+
Args:
|
| 711 |
+
config: LongcatConfig
|
| 712 |
+
"""
|
| 713 |
+
|
| 714 |
+
# _keys_to_ignore_on_load_unexpected = [r"model\.layers\.61.*"]
|
| 715 |
+
_keys_to_ignore_on_load_unexpected = None
|
| 716 |
+
|
| 717 |
+
def __init__(self, config: LongcatConfig):
|
| 718 |
+
super().__init__(config)
|
| 719 |
+
self.padding_idx = config.pad_token_id
|
| 720 |
+
self.vocab_size = config.vocab_size
|
| 721 |
+
|
| 722 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 723 |
+
self.layers = nn.ModuleList([LongcatDecoderLayer(config, layer_idx) for layer_idx in range(config.num_layers)])
|
| 724 |
+
self.norm = LongcatRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 725 |
+
self.rotary_emb = LongcatRotaryEmbedding(config=config)
|
| 726 |
+
self.gradient_checkpointing = False
|
| 727 |
+
|
| 728 |
+
# Initialize weights and apply final processing
|
| 729 |
+
self.post_init()
|
| 730 |
+
|
| 731 |
+
def get_input_embeddings(self):
|
| 732 |
+
return self.embed_tokens
|
| 733 |
+
|
| 734 |
+
def set_input_embeddings(self, value):
|
| 735 |
+
self.embed_tokens = value
|
| 736 |
+
|
| 737 |
+
@can_return_tuple
|
| 738 |
+
@add_start_docstrings_to_model_forward(LONGCAT_INPUTS_DOCSTRING)
|
| 739 |
+
def forward(
|
| 740 |
+
self,
|
| 741 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 742 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 743 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 744 |
+
past_key_values: Optional[Cache] = None,
|
| 745 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 746 |
+
use_cache: Optional[bool] = None,
|
| 747 |
+
output_attentions: Optional[bool] = None,
|
| 748 |
+
output_hidden_states: Optional[bool] = None,
|
| 749 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 750 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
| 751 |
+
) -> BaseModelOutputWithPast:
|
| 752 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 753 |
+
output_hidden_states = (
|
| 754 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 755 |
+
)
|
| 756 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 757 |
+
|
| 758 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 759 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 760 |
+
|
| 761 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 762 |
+
logger.warning_once(
|
| 763 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
| 764 |
+
)
|
| 765 |
+
use_cache = False
|
| 766 |
+
|
| 767 |
+
# TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
|
| 768 |
+
if not isinstance(past_key_values, (type(None), Cache)):
|
| 769 |
+
raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
|
| 770 |
+
|
| 771 |
+
if inputs_embeds is None:
|
| 772 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 773 |
+
|
| 774 |
+
if use_cache and past_key_values is None:
|
| 775 |
+
past_key_values = DynamicCache()
|
| 776 |
+
|
| 777 |
+
if cache_position is None:
|
| 778 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 779 |
+
cache_position = torch.arange(
|
| 780 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
if position_ids is None:
|
| 784 |
+
position_ids = cache_position.unsqueeze(0)
|
| 785 |
+
|
| 786 |
+
causal_mask = self._update_causal_mask(
|
| 787 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
hidden_states = inputs_embeds
|
| 791 |
+
|
| 792 |
+
# create position embeddings to be shared across the decoder layers
|
| 793 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 794 |
+
|
| 795 |
+
# decoder layers
|
| 796 |
+
all_hidden_states = () if output_hidden_states else None
|
| 797 |
+
all_self_attns = () if output_attentions else None
|
| 798 |
+
|
| 799 |
+
for decoder_layer in self.layers[: self.config.num_layers]:
|
| 800 |
+
if output_hidden_states:
|
| 801 |
+
all_hidden_states += (hidden_states,)
|
| 802 |
+
|
| 803 |
+
if self.gradient_checkpointing and self.training:
|
| 804 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 805 |
+
partial(decoder_layer.__call__, **flash_attn_kwargs),
|
| 806 |
+
hidden_states,
|
| 807 |
+
causal_mask,
|
| 808 |
+
position_ids,
|
| 809 |
+
past_key_values,
|
| 810 |
+
output_attentions,
|
| 811 |
+
use_cache,
|
| 812 |
+
cache_position,
|
| 813 |
+
position_embeddings,
|
| 814 |
+
)
|
| 815 |
+
else:
|
| 816 |
+
layer_outputs = decoder_layer(
|
| 817 |
+
hidden_states,
|
| 818 |
+
attention_mask=causal_mask,
|
| 819 |
+
position_ids=position_ids,
|
| 820 |
+
past_key_value=past_key_values,
|
| 821 |
+
output_attentions=output_attentions,
|
| 822 |
+
use_cache=use_cache,
|
| 823 |
+
cache_position=cache_position,
|
| 824 |
+
position_embeddings=position_embeddings,
|
| 825 |
+
**flash_attn_kwargs,
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
hidden_states = layer_outputs[0]
|
| 829 |
+
|
| 830 |
+
if output_attentions:
|
| 831 |
+
all_self_attns += (layer_outputs[1],)
|
| 832 |
+
|
| 833 |
+
hidden_states = self.norm(hidden_states)
|
| 834 |
+
|
| 835 |
+
# add hidden states from the last decoder layer
|
| 836 |
+
if output_hidden_states:
|
| 837 |
+
all_hidden_states += (hidden_states,)
|
| 838 |
+
|
| 839 |
+
return BaseModelOutputWithPast(
|
| 840 |
+
last_hidden_state=hidden_states,
|
| 841 |
+
past_key_values=past_key_values if use_cache else None,
|
| 842 |
+
hidden_states=all_hidden_states,
|
| 843 |
+
attentions=all_self_attns,
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
def _update_causal_mask(
|
| 847 |
+
self,
|
| 848 |
+
attention_mask: torch.Tensor,
|
| 849 |
+
input_tensor: torch.Tensor,
|
| 850 |
+
cache_position: torch.Tensor,
|
| 851 |
+
past_key_values: Cache,
|
| 852 |
+
output_attentions: bool = False,
|
| 853 |
+
):
|
| 854 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 855 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
| 856 |
+
return attention_mask
|
| 857 |
+
return None
|
| 858 |
+
if self.config._attn_implementation == "flex_attention":
|
| 859 |
+
if isinstance(attention_mask, torch.Tensor):
|
| 860 |
+
attention_mask = make_flex_block_causal_mask(attention_mask)
|
| 861 |
+
if isinstance(attention_mask, BlockMask):
|
| 862 |
+
return attention_mask
|
| 863 |
+
|
| 864 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
| 865 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
| 866 |
+
# to infer the attention mask.
|
| 867 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 868 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
| 869 |
+
|
| 870 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
| 871 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
| 872 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
| 873 |
+
attention_mask,
|
| 874 |
+
inputs_embeds=input_tensor,
|
| 875 |
+
past_key_values_length=past_seen_tokens,
|
| 876 |
+
is_training=self.training,
|
| 877 |
+
):
|
| 878 |
+
return None
|
| 879 |
+
|
| 880 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
| 881 |
+
sequence_length = input_tensor.shape[1]
|
| 882 |
+
if using_static_cache:
|
| 883 |
+
target_length = past_key_values.get_max_cache_shape()
|
| 884 |
+
else:
|
| 885 |
+
target_length = (
|
| 886 |
+
attention_mask.shape[-1]
|
| 887 |
+
if isinstance(attention_mask, torch.Tensor)
|
| 888 |
+
else past_seen_tokens + sequence_length + 1
|
| 889 |
+
)
|
| 890 |
+
|
| 891 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
| 892 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
| 893 |
+
attention_mask,
|
| 894 |
+
sequence_length=sequence_length,
|
| 895 |
+
target_length=target_length,
|
| 896 |
+
dtype=dtype,
|
| 897 |
+
device=device,
|
| 898 |
+
cache_position=cache_position,
|
| 899 |
+
batch_size=input_tensor.shape[0],
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
if (
|
| 903 |
+
self.config._attn_implementation == "sdpa"
|
| 904 |
+
and attention_mask is not None
|
| 905 |
+
and attention_mask.device.type in ["cuda", "xpu", "npu"]
|
| 906 |
+
and not output_attentions
|
| 907 |
+
):
|
| 908 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
| 909 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
| 910 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
| 911 |
+
min_dtype = torch.finfo(dtype).min
|
| 912 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
| 913 |
+
|
| 914 |
+
return causal_mask
|
| 915 |
+
|
| 916 |
+
@staticmethod
|
| 917 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
| 918 |
+
attention_mask: torch.Tensor,
|
| 919 |
+
sequence_length: int,
|
| 920 |
+
target_length: int,
|
| 921 |
+
dtype: torch.dtype,
|
| 922 |
+
device: torch.device,
|
| 923 |
+
cache_position: torch.Tensor,
|
| 924 |
+
batch_size: int,
|
| 925 |
+
**kwargs,
|
| 926 |
+
):
|
| 927 |
+
"""
|
| 928 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
| 929 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
| 930 |
+
|
| 931 |
+
Args:
|
| 932 |
+
attention_mask (`torch.Tensor`):
|
| 933 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
| 934 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
| 935 |
+
sequence_length (`int`):
|
| 936 |
+
The sequence length being processed.
|
| 937 |
+
target_length (`int`):
|
| 938 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
| 939 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
| 940 |
+
dtype (`torch.dtype`):
|
| 941 |
+
The dtype to use for the 4D attention mask.
|
| 942 |
+
device (`torch.device`):
|
| 943 |
+
The device to place the 4D attention mask on.
|
| 944 |
+
cache_position (`torch.Tensor`):
|
| 945 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 946 |
+
batch_size (`torch.Tensor`):
|
| 947 |
+
Batch size.
|
| 948 |
+
"""
|
| 949 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
| 950 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
| 951 |
+
causal_mask = attention_mask
|
| 952 |
+
else:
|
| 953 |
+
min_dtype = torch.finfo(dtype).min
|
| 954 |
+
causal_mask = torch.full(
|
| 955 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
| 956 |
+
)
|
| 957 |
+
if sequence_length != 1:
|
| 958 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
| 959 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
| 960 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
| 961 |
+
if attention_mask is not None:
|
| 962 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
| 963 |
+
mask_length = attention_mask.shape[-1]
|
| 964 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
|
| 965 |
+
causal_mask.device
|
| 966 |
+
)
|
| 967 |
+
padding_mask = padding_mask == 0
|
| 968 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
| 969 |
+
padding_mask, min_dtype
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
return causal_mask
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
| 976 |
+
|
| 977 |
+
|
| 978 |
+
class LongcatForCausalLM(LongcatPreTrainedModel, GenerationMixin):
|
| 979 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 980 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 981 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 982 |
+
|
| 983 |
+
def __init__(self, config):
|
| 984 |
+
super().__init__(config)
|
| 985 |
+
self.model = LongcatModel(config)
|
| 986 |
+
self.vocab_size = config.vocab_size
|
| 987 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 988 |
+
|
| 989 |
+
# Initialize weights and apply final processing
|
| 990 |
+
self.post_init()
|
| 991 |
+
|
| 992 |
+
def get_input_embeddings(self):
|
| 993 |
+
return self.model.embed_tokens
|
| 994 |
+
|
| 995 |
+
def set_input_embeddings(self, value):
|
| 996 |
+
self.model.embed_tokens = value
|
| 997 |
+
|
| 998 |
+
def get_output_embeddings(self):
|
| 999 |
+
return self.lm_head
|
| 1000 |
+
|
| 1001 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1002 |
+
self.lm_head = new_embeddings
|
| 1003 |
+
|
| 1004 |
+
def set_decoder(self, decoder):
|
| 1005 |
+
self.model = decoder
|
| 1006 |
+
|
| 1007 |
+
def get_decoder(self):
|
| 1008 |
+
return self.model
|
| 1009 |
+
|
| 1010 |
+
@can_return_tuple
|
| 1011 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
| 1012 |
+
@add_start_docstrings_to_model_forward(LONGCAT_INPUTS_DOCSTRING)
|
| 1013 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 1014 |
+
def forward(
|
| 1015 |
+
self,
|
| 1016 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1017 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1018 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1019 |
+
past_key_values: Optional[Cache] = None,
|
| 1020 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1021 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1022 |
+
use_cache: Optional[bool] = None,
|
| 1023 |
+
output_attentions: Optional[bool] = None,
|
| 1024 |
+
output_hidden_states: Optional[bool] = None,
|
| 1025 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1026 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 1027 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
| 1028 |
+
) -> CausalLMOutputWithPast:
|
| 1029 |
+
r"""
|
| 1030 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1031 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1032 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1033 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1034 |
+
|
| 1035 |
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
| 1036 |
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
| 1037 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
| 1038 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
| 1039 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
| 1040 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
| 1041 |
+
|
| 1042 |
+
Returns:
|
| 1043 |
+
|
| 1044 |
+
Example:
|
| 1045 |
+
|
| 1046 |
+
```python
|
| 1047 |
+
>>> from transformers import AutoTokenizer, LongcatForCausalLM
|
| 1048 |
+
|
| 1049 |
+
>>> model = LongcatForCausalLM.from_pretrained("meta-longcat/Longcat-2-7b-hf")
|
| 1050 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-longcat/Longcat-2-7b-hf")
|
| 1051 |
+
|
| 1052 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 1053 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 1054 |
+
|
| 1055 |
+
>>> # Generate
|
| 1056 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1057 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1058 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 1059 |
+
```"""
|
| 1060 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1061 |
+
output_hidden_states = (
|
| 1062 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1063 |
+
)
|
| 1064 |
+
|
| 1065 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1066 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 1067 |
+
input_ids=input_ids,
|
| 1068 |
+
attention_mask=attention_mask,
|
| 1069 |
+
position_ids=position_ids,
|
| 1070 |
+
past_key_values=past_key_values,
|
| 1071 |
+
inputs_embeds=inputs_embeds,
|
| 1072 |
+
use_cache=use_cache,
|
| 1073 |
+
output_attentions=output_attentions,
|
| 1074 |
+
output_hidden_states=output_hidden_states,
|
| 1075 |
+
cache_position=cache_position,
|
| 1076 |
+
**kwargs,
|
| 1077 |
+
)
|
| 1078 |
+
|
| 1079 |
+
hidden_states = outputs.last_hidden_state
|
| 1080 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1081 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1082 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 1083 |
+
|
| 1084 |
+
loss = None
|
| 1085 |
+
if labels is not None:
|
| 1086 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 1087 |
+
|
| 1088 |
+
return CausalLMOutputWithPast(
|
| 1089 |
+
loss=loss,
|
| 1090 |
+
logits=logits,
|
| 1091 |
+
past_key_values=outputs.past_key_values,
|
| 1092 |
+
hidden_states=outputs.hidden_states,
|
| 1093 |
+
attentions=outputs.attentions,
|
| 1094 |
+
)
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
__all__ = ["LongcatPreTrainedModel", "LongcatModel", "LongcatForCausalLM"]
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": {
|
| 3 |
+
"content": "<longcat_s>",
|
| 4 |
+
"lstrip": false,
|
| 5 |
+
"normalized": false,
|
| 6 |
+
"rstrip": false,
|
| 7 |
+
"single_word": false
|
| 8 |
+
},
|
| 9 |
+
"eos_token": {
|
| 10 |
+
"content": "</longcat_s>",
|
| 11 |
+
"lstrip": false,
|
| 12 |
+
"normalized": false,
|
| 13 |
+
"rstrip": false,
|
| 14 |
+
"single_word": false
|
| 15 |
+
},
|
| 16 |
+
"pad_token": {
|
| 17 |
+
"content": "<longcat_pad>",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": false,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
},
|
| 23 |
+
"unk_token": {
|
| 24 |
+
"content": "<longcat_unk>",
|
| 25 |
+
"lstrip": false,
|
| 26 |
+
"normalized": false,
|
| 27 |
+
"rstrip": false,
|
| 28 |
+
"single_word": false
|
| 29 |
+
}
|
| 30 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_eos_token": true,
|
| 4 |
+
"add_prefix_space": false,
|
| 5 |
+
"bos_token": {
|
| 6 |
+
"__type": "AddedToken",
|
| 7 |
+
"content": "<longcat_s>",
|
| 8 |
+
"lstrip": false,
|
| 9 |
+
"normalized": true,
|
| 10 |
+
"rstrip": false,
|
| 11 |
+
"single_word": false
|
| 12 |
+
},
|
| 13 |
+
"clean_up_tokenization_spaces": false,
|
| 14 |
+
"eos_token": {
|
| 15 |
+
"__type": "AddedToken",
|
| 16 |
+
"content": "</longcat_s>",
|
| 17 |
+
"lstrip": false,
|
| 18 |
+
"normalized": true,
|
| 19 |
+
"rstrip": false,
|
| 20 |
+
"single_word": false
|
| 21 |
+
},
|
| 22 |
+
"model_max_length": 131072,
|
| 23 |
+
"pad_token": {
|
| 24 |
+
"__type": "AddedToken",
|
| 25 |
+
"content": "<longcat_pad>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": true,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
},
|
| 31 |
+
"sp_model_kwargs": {},
|
| 32 |
+
"tokenizer_class": "BloomTokenizer",
|
| 33 |
+
"unk_token": {
|
| 34 |
+
"__type": "AddedToken",
|
| 35 |
+
"content": "<longcat_unk>",
|
| 36 |
+
"lstrip": false,
|
| 37 |
+
"normalized": true,
|
| 38 |
+
"rstrip": false,
|
| 39 |
+
"single_word": false
|
| 40 |
+
},
|
| 41 |
+
"chat_template": "{%- set tool_choice = tool_choice | default('auto') %}\n{%- set ns = namespace(rounds = 0, tool_types = [], last_query_index = -1) %}\n\n{%- if tools and tool_choice != 'none' %}\n {{- \"# Tools\n\" }}\n {{- \"You have access to the following tools: \n\n\" }}\n {%- for tool in tools %}\n {%- if tool.type in ['code_interpreter', 'function'] %}\n {%- if tool.type not in ns.tool_types %}\n {%- set ns.tool_types = ns.tool_types + [tool.type] %}\n {{- \"## Tool namespace: \" ~ tool.type ~ \"\n\n\" }}\n {%- endif %}\n {%- if tool.type == 'code_interpreter' %}\n {%- set tool = {\"type\":\"code_interpreter\",\"function\":{\"name\":\"code_interpreter_preview\",\"description\":\"The code will be executed in a stateful Jupyter notebook sandbox environment, only supports local computation, data processing, and file operations. \nCode sandbox environment (network isolated) Any external network requests or online API calls are prohibited. \nIf online functionality is needed, please use other permitted tools. \nCode will respond with the output of the execution or time out after 60.0 seconds. \",\"parameters\":{\"type\":\"object\",\"properties\":{\"language\":{\"type\":\"string\",\"description\":\"The programming language of the code to be executed. Available values: python (Default), java, go, js, ts, c, c++.\"},\"code\":{\"type\":\"string\",\"description\":\"Python code to be executed must not include the following:\n- Importing network libraries such as requests, httplib, etc.\n- Any form of HTTP requests.\n- External API calls.\n- Network port operations. Example: ```python\nimport pandas as pd\npd.DataFrame({'A':[1,2]})\n```\"},\"timeout\":{\"type\":\"number\",\"description\":\"The maximum execution time of the code, in seconds. Default is 60.0.\"}}},\"required\":[\"code\"]}} %}\n {%- endif %}\n {{- \"### Tool name: \" + tool.function.name + \"\n\n\" }}\n {{- \"Description: \" + tool.function.description + \"\n\n\" }}\n {{- \"InputSchema: \n\" + tool.function.parameters | tojson(indent=2) + \"\n\n\" }}\n {%- endif %}\n {%- endfor %}\n {{- '**Note**: For each function call, return a json object with function name and arguments within <longcat_tool_call></longcat_tool_call> XML tags as follows:\n<longcat_tool_call>\n{\"name\": <function-name>, \"arguments\": <args-dict>}\n</longcat_tool_call>\n' }}\n {{- 'When multiple functions need to be called simultaneously, each function call should be wrapped in its own <longcat_tool_call> tag and placed consecutively. For example:\n<longcat_tool_call>\n{\"name\": <function-name>, \"arguments\": <args-dict>}\n</longcat_tool_call><longcat_tool_call>\n{\"name\": <function-name>, \"arguments\": <args-dict>}\n</longcat_tool_call>\n\n' }}\n {{- \"# Messages\n\" }}\n\n {%- for idx in range(messages|length - 1) %}\n {%- set msg = messages[idx] %}\n {%- if msg.role == 'assistant' and not msg.tool_calls %}\n {%- set ns.last_query_index = idx %}\n {%- endif %}\n {%- endfor%}\n{%- endif %}\n\n{%- for msg in messages %}\n {%- if msg.role == \"system\" %}\n {{- \"SYSTEM:\" + msg.content }} \n {%- elif msg.role == \"user\" %}\n {%- if loop.first %}\n {{- \"[Round \" ~ (ns.rounds) ~ \"] USER:\" }}\n {%- else %}\n {{- \" [Round \" ~ (ns.rounds) ~ \"] USER:\"}}\n {%- endif %}\n {%- set ns.rounds = ns.rounds + 1 %}\n {%- if msg[\"files\"] %}\n {{- '<longcat_files>\n' ~ msg.files | tojson(indent=2) ~ '\n</longcat_files>' }}\n {%- endif %}\n {{- msg.content }}\n {%- elif msg.role == \"assistant\" %}\n {{- \" ASSISTANT:\" }}\n {%- if enable_thinking == true and msg.reasoning_content and ns.tool_types != [] and loop.index0 > ns.last_query_index %}\n {{- \"\n<longcat_think>\n\" ~ msg.reasoning_content ~ \"\n</longcat_think>\n\" }}\n {%- endif %}\n {%- if msg.content%}\n {{- msg.content }}\n {%- endif %}\n {%- if msg.tool_calls %}\n {%- for tool_call in msg.tool_calls -%}\n {{- \"<longcat_tool_call>\n\" -}}\n {\"name\": \"{{ tool_call.function.name }}\", \"arguments\": {{ tool_call.function.arguments }}}\n {{- \"\n</longcat_tool_call>\" }}\n {%- endfor %}\n {%- endif %}\n {%- elif msg.role == \"tool\" %}\n {{- \" TOOL:\" -}}\n {\"name\": {{msg.name | tojson}}, \"content\": {{msg.content | tojson}}}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %} \n {%- if enable_thinking == true %}\n {{- \" /think_on\" }}\n {%- if thinking_budget %}\n {%- if thinking_budget < 1024 %}\n {%- set thinking_budget = 1024 %}\n {%- endif%}\n {{- \"\nthinking_budget: < \" ~ thinking_budget ~ \".\"}}\n {%- endif %}\n {{- \" ASSISTANT:<longcat_think>\n\"}}\n {%- elif enable_thinking == false %}\n {{- \" /think_off ASSISTANT:<longcat_think>\n\n</longcat_think>\n\" }}\n {%- else %}\n {{- \" ASSISTANT:\" }}\n {%- endif %}\n{%- endif %}"
|
| 42 |
+
}
|