diichen commited on
Commit
94c4ee4
·
verified ·
1 Parent(s): 7db05e6

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. audio/config.json +85 -0
  2. audio/global_cmvn +0 -0
  3. audio/preprocessor_config.json +26 -0
  4. audio_codec/config.yaml +11 -0
  5. config.json +0 -0
  6. configuration_longcat_flash.py +216 -0
  7. generation_config.json +7 -0
  8. language_model_embedding.pt +3 -0
  9. model.safetensors.index.json +0 -0
  10. model_00001-of-00080.safetensors +3 -0
  11. model_00006-of-00080.safetensors +3 -0
  12. model_00007-of-00080.safetensors +3 -0
  13. model_00008-of-00080.safetensors +3 -0
  14. model_00009-of-00080.safetensors +3 -0
  15. model_00010-of-00080.safetensors +3 -0
  16. model_00011-of-00080.safetensors +3 -0
  17. model_00012-of-00080.safetensors +3 -0
  18. model_00013-of-00080.safetensors +3 -0
  19. model_00014-of-00080.safetensors +3 -0
  20. model_00015-of-00080.safetensors +3 -0
  21. model_00016-of-00080.safetensors +3 -0
  22. model_00017-of-00080.safetensors +3 -0
  23. model_00018-of-00080.safetensors +3 -0
  24. model_00019-of-00080.safetensors +3 -0
  25. model_00020-of-00080.safetensors +3 -0
  26. model_00021-of-00080.safetensors +3 -0
  27. model_00022-of-00080.safetensors +3 -0
  28. model_00023-of-00080.safetensors +3 -0
  29. model_00024-of-00080.safetensors +3 -0
  30. model_00025-of-00080.safetensors +3 -0
  31. model_00066-of-00080.safetensors +3 -0
  32. model_00067-of-00080.safetensors +3 -0
  33. model_00068-of-00080.safetensors +3 -0
  34. model_00069-of-00080.safetensors +3 -0
  35. model_00070-of-00080.safetensors +3 -0
  36. model_00071-of-00080.safetensors +3 -0
  37. model_00072-of-00080.safetensors +3 -0
  38. model_00073-of-00080.safetensors +3 -0
  39. model_00074-of-00080.safetensors +3 -0
  40. model_00075-of-00080.safetensors +3 -0
  41. model_00076-of-00080.safetensors +3 -0
  42. model_00077-of-00080.safetensors +3 -0
  43. model_00078-of-00080.safetensors +3 -0
  44. model_00079-of-00080.safetensors +3 -0
  45. model_00080-of-00080.safetensors +3 -0
  46. modeling_longcat_flash.py +643 -0
  47. special_tokens_map.json +30 -0
  48. tokenizer.json +0 -0
  49. tokenizer_config.json +42 -0
  50. vision/config.json +39 -0
audio/config.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "",
3
+ "activation": "relu6",
4
+ "add_cross_attention": false,
5
+ "architectures": [
6
+ "LongCatAudioEncoder"
7
+ ],
8
+ "bad_words_ids": null,
9
+ "begin_suppress_tokens": null,
10
+ "bos_token_id": null,
11
+ "chunk_size_feed_forward": 0,
12
+ "cross_attention_hidden_size": null,
13
+ "decoder_start_token_id": null,
14
+ "diversity_penalty": 0.0,
15
+ "do_sample": false,
16
+ "dropout": 0.0,
17
+ "early_stopping": false,
18
+ "encoder_no_repeat_ngram_size": 0,
19
+ "eos_token_id": null,
20
+ "exponential_decay_length_penalty": null,
21
+ "finetuning_task": null,
22
+ "forced_bos_token_id": null,
23
+ "forced_eos_token_id": null,
24
+ "gradient_checkpointing": false,
25
+ "hidden_size": 6144,
26
+ "id2label": {
27
+ "0": "LABEL_0",
28
+ "1": "LABEL_1"
29
+ },
30
+ "input_size": 1200,
31
+ "is_decoder": false,
32
+ "is_encoder_decoder": false,
33
+ "label2id": {
34
+ "LABEL_0": 0,
35
+ "LABEL_1": 1
36
+ },
37
+ "layer_drop": 0.0,
38
+ "left_context": 7,
39
+ "left_order": 10,
40
+ "left_stride": 1,
41
+ "length_penalty": 1.0,
42
+ "max_length": 20,
43
+ "min_length": 0,
44
+ "model_type": "",
45
+ "ndnn": 2,
46
+ "nlayer": 22,
47
+ "no_repeat_ngram_size": 0,
48
+ "normalize": "LayerNorm",
49
+ "num_beam_groups": 1,
50
+ "num_beams": 1,
51
+ "num_return_sequences": 1,
52
+ "num_right_layers": 6,
53
+ "output_attentions": false,
54
+ "output_hidden_states": false,
55
+ "output_scores": false,
56
+ "pad_token_id": null,
57
+ "prefix": null,
58
+ "problem_type": null,
59
+ "proj_size": 1536,
60
+ "pruned_heads": {},
61
+ "remove_invalid_values": false,
62
+ "repetition_penalty": 1.0,
63
+ "return_dict": true,
64
+ "return_dict_in_generate": false,
65
+ "right_context": 7,
66
+ "right_order": 1,
67
+ "right_stride": 1,
68
+ "sep_token_id": null,
69
+ "stride": 8,
70
+ "suppress_tokens": null,
71
+ "task_specific_params": null,
72
+ "temperature": 1.0,
73
+ "tf_legacy_loss": false,
74
+ "tie_encoder_decoder": false,
75
+ "tie_word_embeddings": false,
76
+ "tokenizer_class": null,
77
+ "top_k": 50,
78
+ "top_p": 1.0,
79
+ "torch_dtype": "float32",
80
+ "torchscript": false,
81
+ "transformers_version": "4.39.3",
82
+ "typical_p": 1.0,
83
+ "use_bfloat16": false,
84
+ "vocab_size": 5252
85
+ }
audio/global_cmvn ADDED
Binary file (663 Bytes). View file
 
audio/preprocessor_config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fbank": {
3
+ "dither": 0.0,
4
+ "frame_length": 25,
5
+ "frame_shift": 10,
6
+ "preemphasis": 0.97,
7
+ "freq": 16000,
8
+ "high_freq": -200,
9
+ "low_freq": 40,
10
+ "num_mel_bins": 80
11
+ },
12
+ "delta": {
13
+ "delta_order": 0,
14
+ "window_size": 2
15
+ },
16
+ "cmvn": {
17
+ "global_cmvn": "/path/to/audio/global_cmvn"
18
+ },
19
+ "splice": {
20
+ "left": 7,
21
+ "right": 7,
22
+ "stride": 8,
23
+ "random_start": false,
24
+ "seed": 0
25
+ }
26
+ }
audio_codec/config.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ codec_config:
2
+ codec_dimension: 1024
3
+ codec_dec_ratios: [8,6,6,5]
4
+ decoder_dim: 1536
5
+ semantic_dim: 1280
6
+ decoder_type: '24k'
7
+ ckpt_path: '/path/to/audio_codec/LongCatAudioCodec_decoder_24k_4codebooks_aug_sft.pt'
8
+ codec_codebook_size: 90
9
+ codec_codebook_search_dim: 8
10
+ codec_codebooks: 3
11
+ semantic_token_nums: 8192
config.json ADDED
The diff for this file is too large to render. See raw diff
 
configuration_longcat_flash.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """LongcatFlash model configuration"""
3
+
4
+ from transformers.configuration_utils import PretrainedConfig
5
+ from transformers.modeling_rope_utils import rope_config_validation
6
+
7
+
8
+ LONGCAT_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
9
+
10
+
11
+ class LongcatFlashConfig(PretrainedConfig):
12
+ r"""
13
+ This is the configuration class to store the configuration of a [`LongcatFlashModel`]. It is used to instantiate an LongcatFlash
14
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
15
+ defaults will yield a similar configuration to that of the LongcatFlash.
16
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
17
+ documentation from [`PretrainedConfig`] for more information.
18
+
19
+
20
+ Args:
21
+ vocab_size (`int`, *optional*, defaults to 131072):
22
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
23
+ `inputs_ids` passed when calling [`LongcatFlashModel`]
24
+ hidden_size (`int`, *optional*, defaults to 7168):
25
+ Dimension of the hidden representations.
26
+ ffn_hidden_size (`int`, *optional*, defaults to 18432):
27
+ Dimension of the MLP representations.
28
+ expert_ffn_hidden_size (`int`, *optional*, defaults to 2048):
29
+ Dimension of the MoE representations.
30
+ num_layers (`int`, *optional*, defaults to 61):
31
+ Number of hidden layers in the Transformer decoder.
32
+ num_attention_heads (`int`, *optional*, defaults to 128):
33
+ Number of attention heads for each attention layer in the Transformer decoder.
34
+ num_key_value_heads (`int`, *optional*, defaults to 128):
35
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
36
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
37
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
38
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
39
+ by meanpooling all the original heads within that group. For more details checkout [this
40
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
41
+ `num_attention_heads`.
42
+ n_routed_experts (`int`, *optional*, defaults to 256):
43
+ Number of routed experts.
44
+ routed_scaling_factor (`float`, *optional*, defaults to 2.5):
45
+ Scaling factor or routed experts.
46
+ kv_lora_rank (`int`, *optional*, defaults to 512):
47
+ Rank of the LoRA matrices for key and value projections.
48
+ q_lora_rank (`int`, *optional*, defaults to 1536):
49
+ Rank of the LoRA matrices for query projections.
50
+ qk_rope_head_dim (`int`, *optional*, defaults to 64):
51
+ Dimension of the query/key heads that use rotary position embeddings.
52
+ v_head_dim (`int`, *optional*, defaults to 128):
53
+ Dimension of the value heads.
54
+ qk_nope_head_dim (`int`, *optional*, defaults to 128):
55
+ Dimension of the query/key heads that don't use rotary position embeddings.
56
+ norm_topk_prob (`bool`, *optional*, defaults to `True`):
57
+ Whether to normalize the weights of the routed experts.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
61
+ The maximum sequence length that this model might ever be used with.
62
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
63
+ The epsilon used by the rms normalization layers.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
66
+ relevant if `config.is_decoder=True`.
67
+ pad_token_id (`int`, *optional*):
68
+ Padding token id.
69
+ bos_token_id (`int`, *optional*, defaults to 0):
70
+ Beginning of stream token id.
71
+ eos_token_id (`int`, *optional*, defaults to 1):
72
+ End of stream token id.
73
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
74
+ Whether to tie weight embeddings
75
+ rope_theta (`float`, *optional*, defaults to 10000.0):
76
+ The base period of the RoPE embeddings.
77
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
78
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
79
+ attention_dropout (`float`, *optional*, defaults to 0.0):
80
+ The dropout ratio for the attention probabilities.
81
+ attention_method (`str`, *optional*, defaults to `"MLA"`):
82
+ The attention method to use.
83
+ initializer_range (`float`, *optional*, defaults to 0.006):
84
+ The initializer range for the model.
85
+ router_bias (`bool`, *optional*, defaults to `False`):
86
+ Whether to use a bias in the router.
87
+ zero_expert_num (`int`, *optional*, defaults to `None`):
88
+ The number of zero experts to use.
89
+ zero_expert_type (`str`, *optional*, defaults to `None`):
90
+ The type of zero expert to use.
91
+
92
+ ```python
93
+ >>> from transformers import LongcatFlashModel, LongcatFlashConfig
94
+
95
+ >>> # Initializing a LongcatFlash style configuration
96
+ >>> configuration = LongcatFlashConfig()
97
+
98
+ >>> # Accessing the model configuration
99
+ >>> configuration = model.config
100
+ ```"""
101
+
102
+ model_type = "longcat_flash"
103
+ keys_to_ignore_at_inference = ["past_key_values"]
104
+ base_model_tp_plan = {
105
+ "layers.*.self_attn.k_proj": "colwise",
106
+ "layers.*.self_attn.v_proj": "colwise",
107
+ "layers.*.self_attn.o_proj": "rowwise",
108
+ "layers.*.mlp.experts.*.gate_proj": "local_colwise",
109
+ "layers.*.mlp.experts.*.up_proj": "local_colwise",
110
+ "layers.*.mlp.experts.*.down_proj": "local_rowwise",
111
+ "layers.*.mlps.*.gate_proj": "local_colwise",
112
+ "layers.*.mlps.*.up_proj": "local_colwise",
113
+ "layers.*.mlps.*.down_proj": "local_rowwise",
114
+ }
115
+ base_model_pp_plan = {
116
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
117
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
118
+ "norm": (["hidden_states"], ["hidden_states"]),
119
+ }
120
+
121
+ def __init__(
122
+ self,
123
+ vocab_size=131072,
124
+ hidden_size=7168,
125
+ ffn_hidden_size=18432,
126
+ expert_ffn_hidden_size=2048,
127
+ num_layers=61,
128
+ num_attention_heads=128,
129
+ num_key_value_heads=None,
130
+ n_routed_experts=256,
131
+ routed_scaling_factor=1,
132
+ kv_lora_rank=512,
133
+ q_lora_rank=1536,
134
+ qk_rope_head_dim=64,
135
+ v_head_dim=128,
136
+ qk_nope_head_dim=128,
137
+ mla_scale_q_lora=True,
138
+ mla_scale_kv_lora=True,
139
+ moe_topk=8,
140
+ norm_topk_prob=False,
141
+ hidden_act="silu",
142
+ max_position_embeddings=4096,
143
+ rms_norm_eps=1e-6,
144
+ use_cache=True,
145
+ pad_token_id=None,
146
+ bos_token_id=0,
147
+ eos_token_id=1,
148
+ tie_word_embeddings=False,
149
+ rope_theta=10000.0,
150
+ attention_bias=False,
151
+ attention_dropout=0.0,
152
+ attention_method='MLA',
153
+ initializer_range=0.006,
154
+ router_bias=False,
155
+ zero_expert_num=None,
156
+ zero_expert_type=None,
157
+ **kwargs,
158
+ ):
159
+ self.vocab_size = vocab_size
160
+ self.max_position_embeddings = max_position_embeddings
161
+ self.hidden_size = hidden_size
162
+ self.ffn_hidden_size = ffn_hidden_size
163
+ self.expert_ffn_hidden_size = expert_ffn_hidden_size
164
+ self.num_layers = num_layers
165
+ self.num_attention_heads = num_attention_heads
166
+ self.n_routed_experts = n_routed_experts
167
+ self.routed_scaling_factor = routed_scaling_factor
168
+ self.kv_lora_rank = kv_lora_rank
169
+ self.q_lora_rank = q_lora_rank
170
+ self.qk_rope_head_dim = qk_rope_head_dim
171
+ self.v_head_dim = v_head_dim
172
+ self.qk_nope_head_dim = qk_nope_head_dim
173
+ self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
174
+ self.moe_topk = moe_topk
175
+ self.norm_topk_prob = norm_topk_prob
176
+ self.mla_scale_q_lora = mla_scale_q_lora
177
+ self.mla_scale_kv_lora = mla_scale_kv_lora
178
+ self.attention_method = attention_method
179
+ self.initializer_range = initializer_range
180
+ self.router_bias = router_bias
181
+ self.zero_expert_num = zero_expert_num
182
+ self.zero_expert_type = zero_expert_type
183
+
184
+ if self.attention_method == "MLA":
185
+ self.head_dim = qk_rope_head_dim
186
+ else:
187
+ ValueError('attention_method should be one of ["MLA"]')
188
+
189
+
190
+ if num_key_value_heads is None:
191
+ num_key_value_heads = num_attention_heads
192
+
193
+ self.num_key_value_heads = num_key_value_heads
194
+ self.hidden_act = hidden_act
195
+ self.rms_norm_eps = rms_norm_eps
196
+ self.use_cache = use_cache
197
+ self.rope_theta = rope_theta
198
+ self.attention_bias = attention_bias
199
+ self.attention_dropout = attention_dropout
200
+
201
+ rope_config_validation(self)
202
+
203
+ super().__init__(
204
+ pad_token_id=pad_token_id,
205
+ bos_token_id=bos_token_id,
206
+ eos_token_id=eos_token_id,
207
+ tie_word_embeddings=tie_word_embeddings,
208
+ **kwargs,
209
+ )
210
+
211
+ @property
212
+ def num_hidden_layers(self):
213
+ return self.num_layers
214
+
215
+
216
+ __all__ = ["LongcatFlashConfig"]
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": 3,
6
+ "transformers_version": "4.51.3"
7
+ }
language_model_embedding.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f18abb8d0e4cc2fa99c4a5fa30f887a3a12a1a41c0732b79f8b2bd133202a76d
3
+ size 1610614129
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
model_00001-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5051b7a8ed68e285afda8253d256850cf7c0924792731581568a3420a396a5f5
3
+ size 1610612848
model_00006-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04bac356fa4191b2a9c64e370116efd483dec19ff449efebba8843d254ca371b
3
+ size 8079016496
model_00007-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:203c2b9b775b5b63069f960badff015d38b29df2d711f8bd5075d9841d81ea1b
3
+ size 8043386792
model_00008-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b6a7cd15df782f01d7a1bda9381ce6f76842549a827e22940f43254fadfd105
3
+ size 7965008920
model_00009-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ecb9b58b879a2f3fe138a8c685a1702e4c8cf48541477deb0ea4ed334c70276e
3
+ size 8148238536
model_00010-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c67f30b0a4d29b0b019a4d810f1f9d2f29879f866eff97e5be215fba095a951d
3
+ size 8097897392
model_00011-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:614319af0b910be0fdcbf8e32057d64c7df85c0dd0f53b185bccdd62e7fc8f78
3
+ size 8079016496
model_00012-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4516ca8356d3d0b1864816fe47ee9f9c8917f4445ca9b49a0151adaf815a1d88
3
+ size 8043386792
model_00013-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b289ee403ed57a2e71b3cabd8c104791641c3ad0590487efc4b3613122488d1a
3
+ size 7965008920
model_00014-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2498f21177668e3444e3ba03cfa38b271e8564edbe061b41c44d0eb87a25c42f
3
+ size 8148238536
model_00015-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84fc76be6a3ca246908a3e960692ed1fdaf4c510b7951425af1cc639a433f710
3
+ size 8097897392
model_00016-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4573f67d5a28aab26e00593af7564839fba377352a4c7e07ab27a74eacd91b3
3
+ size 8079016496
model_00017-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:884ae42fbe382ca70e5ece33f7c9c50e02d0c698b6970cc308efd0f0dc8331e4
3
+ size 8043386792
model_00018-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddb6f0ec13f6b7615dce6272e3da3534ef24e7fd7319c38a7c161a7e8ce917de
3
+ size 7965008920
model_00019-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d900aa34e19e4f3789620e353d9e92ca2bc906a7bb29267d42c54609ed74f7cc
3
+ size 8148238536
model_00020-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:026f85b7c6215b95296c55b09d6a2b4d4eaa1a6968794a676482f42d9de8824d
3
+ size 8097897392
model_00021-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f24f223ce1b4d9176624fcf2be35a05fe8ff2ba49ce2c99b3415cf0bb295cd6
3
+ size 8079016496
model_00022-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4fd28ed592241b95ac6eb028612f978478666629d6adcbdbe37ab2a60d9075ae
3
+ size 8043386792
model_00023-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99d8463bb0ef58a53d4d013b3ded1d710df6749cb175f9bb4a32f29b9f6ada31
3
+ size 7965008920
model_00024-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbcf100d05860da59046c5dfda3a3e26692ef28948065b6958a33f04830bf8d4
3
+ size 8148238536
model_00025-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f9341adb3303284a2d860c9acba8545a2ae4ea067f34829fc5f3cd644311d7ac
3
+ size 8097897392
model_00066-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1777683df7fb30691083214bcab5652ab5967aabe63dc9ab411aaa4219dde025
3
+ size 15953919272
model_00067-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8753f4f717087f893676e0fd17d1d5e31560bff210368a2020790cb963635953
3
+ size 15918290208
model_00068-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:701ab05b9469c37af8546e01954cf07548b4305d918c847e0c3ec01fb4244eda
3
+ size 15852492080
model_00069-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ea6306d4e3173d6311f42284e1f52804308343d10b93e99c6019a398c040f2d
3
+ size 16111200592
model_00070-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55a569a2bcd3d9debf0ae93524b3da66bf355d5eadf3d12665af6e1664763808
3
+ size 16048279720
model_00071-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26cb023d2a3b1791ff81340efe0eaaee69138cd83f9226604055eb6983c072af
3
+ size 8041318848
model_00072-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aca02c23961e3daa297a5b63289074eb3c9bce50f53f980c398119d05caa61bf
3
+ size 7902136760
model_00073-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec0e5a14726baf28f9341b0c4590528f8e16fd7fe3e68b040bc889a084bd92be
3
+ size 7950354768
model_00074-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebf5715346982222e6d1bfe97337263db7639a44db354f178269af3ac3a14cae
3
+ size 8135679312
model_00075-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:11bc0f12fb9bd612048c4c1cf38d65a3c7d46c356339484b5b9ad286ee905e89
3
+ size 7912599872
model_00076-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:252e1dd3ecfb12691592ddcb6349a5fb3ffc793ee41174761819c0e52efa0a1b
3
+ size 8041318848
model_00077-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47ebce51fd76fb18ada40af67f8930b5f77c43c4559b22fc7273437b43b122b1
3
+ size 7876983192
model_00078-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08125b6783a5106b37837f90f707a6355f90d1d0b19a4eb7ea6172b4898f9c9d
3
+ size 9560967680
model_00079-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0dba97ecafabb29bfc5bcf7e2ea383596e7523505aee361682c1cc7506c055e
3
+ size 8160845264
model_00080-of-00080.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d897416ae1e3db51c5c99cbed91ef4201311ab5fdc0362003e8a49a02928edc2
3
+ size 7912599872
modeling_longcat_flash.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2025 Meituan
3
+ # This code is licensed under the MIT License, for details, see the ./LICENSE file.
4
+
5
+ from typing import Callable, Optional, Union
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from torch import nn
10
+
11
+ from transformers.activations import ACT2FN
12
+ from transformers.cache_utils import Cache, DynamicCache
13
+ from transformers.generation import GenerationMixin
14
+ from transformers.integrations import use_kernel_forward_from_hub
15
+ from transformers.masking_utils import create_causal_mask
16
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
17
+ from transformers.modeling_layers import GradientCheckpointingLayer
18
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
19
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
20
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
21
+ from transformers.processing_utils import Unpack
22
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
23
+ from transformers.utils.generic import check_model_inputs
24
+ from .configuration_longcat_flash import LongcatFlashConfig
25
+
26
+
27
+ @use_kernel_forward_from_hub("RMSNorm")
28
+ class LongcatFlashRMSNorm(nn.Module):
29
+ def __init__(self, hidden_size, eps=1e-6):
30
+ """
31
+ LongcatFlashRMSNorm is equivalent to T5LayerNorm
32
+ """
33
+ super().__init__()
34
+ self.weight = nn.Parameter(torch.ones(hidden_size))
35
+ self.variance_epsilon = eps
36
+
37
+ def forward(self, hidden_states):
38
+ input_dtype = hidden_states.dtype
39
+ hidden_states = hidden_states.to(torch.float32)
40
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
41
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
42
+ return self.weight * hidden_states.to(input_dtype)
43
+
44
+ def extra_repr(self):
45
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
46
+
47
+
48
+ class LongcatFlashRotaryEmbedding(nn.Module):
49
+ def __init__(self, config: LongcatFlashConfig, device=None):
50
+ super().__init__()
51
+ # BC: "rope_type" was originally "type"
52
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
53
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
54
+ else:
55
+ self.rope_type = "default"
56
+ self.max_seq_len_cached = config.max_position_embeddings
57
+ self.original_max_seq_len = config.max_position_embeddings
58
+
59
+ self.config = config
60
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
61
+
62
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
63
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
64
+ self.original_inv_freq = self.inv_freq
65
+
66
+ @torch.no_grad()
67
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
68
+ def forward(self, x, position_ids):
69
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
70
+ position_ids_expanded = position_ids[:, None, :].float()
71
+
72
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
73
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
74
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
75
+ emb = torch.cat((freqs, freqs), dim=-1)
76
+ cos = emb.cos() * self.attention_scaling
77
+ sin = emb.sin() * self.attention_scaling
78
+
79
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
80
+
81
+
82
+ class LongcatFlashMLP(nn.Module):
83
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
84
+ super().__init__()
85
+ self.config = config
86
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
87
+ self.intermediate_size = config.ffn_hidden_size if intermediate_size is None else intermediate_size
88
+
89
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
90
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
91
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
92
+ self.act_fn = ACT2FN[config.hidden_act]
93
+
94
+ def forward(self, x):
95
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
96
+ return down_proj
97
+
98
+
99
+ class LongcatFlashTopkRouter(nn.Module):
100
+ def __init__(self, config):
101
+ super().__init__()
102
+ self.config = config
103
+ self.top_k = config.moe_topk
104
+ self.n_routed_experts = (
105
+ config.n_routed_experts
106
+ if config.zero_expert_num is None
107
+ else config.n_routed_experts + config.zero_expert_num
108
+ )
109
+ self.routed_scaling_factor = config.routed_scaling_factor
110
+ self.norm_topk_prob = config.norm_topk_prob
111
+ self.router_bias = config.router_bias
112
+
113
+ self.classifier = nn.Linear(config.hidden_size, self.n_routed_experts, bias=self.router_bias)
114
+ self.register_buffer("e_score_correction_bias", torch.zeros((self.n_routed_experts)))
115
+
116
+ @torch.no_grad()
117
+ def get_topk_indices(self, scores):
118
+ scores_for_choice = scores.view(-1, self.n_routed_experts) + self.e_score_correction_bias.unsqueeze(0)
119
+ topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
120
+ return topk_indices
121
+
122
+ def forward(self, hidden_states):
123
+ hidden_states = hidden_states.view(-1, self.config.hidden_size)
124
+ router_logits = F.linear(hidden_states.type(torch.float32), self.classifier.weight.type(torch.float32))
125
+ scores = router_logits.softmax(dim=-1)
126
+ topk_indices = self.get_topk_indices(scores)
127
+ topk_weights = scores.gather(1, topk_indices)
128
+ if self.norm_topk_prob:
129
+ denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
130
+ topk_weights /= denominator
131
+ topk_weights = topk_weights * self.routed_scaling_factor
132
+ return topk_indices, topk_weights
133
+
134
+
135
+ class LongcatFlashMoE(nn.Module):
136
+ """
137
+ moe module.
138
+ """
139
+
140
+ def __init__(self, config):
141
+ super().__init__()
142
+ self.config = config
143
+ self.experts = nn.ModuleList(
144
+ [
145
+ LongcatFlashMLP(config, intermediate_size=config.expert_ffn_hidden_size)
146
+ for _ in range(config.n_routed_experts)
147
+ ]
148
+ )
149
+ self.router = LongcatFlashTopkRouter(config)
150
+ self.zero_expert_num = config.zero_expert_num
151
+ self.zero_expert_type = config.zero_expert_type
152
+
153
+ def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
154
+ final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
155
+ total_experts = len(self.experts) if self.zero_expert_num is None else len(self.experts) + self.zero_expert_num
156
+
157
+ expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=total_experts)
158
+ expert_mask = expert_mask.permute(2, 0, 1)
159
+
160
+ for expert_idx in range(total_experts):
161
+ expert = self.experts[expert_idx] if expert_idx < len(self.experts) else None
162
+ mask = expert_mask[expert_idx]
163
+ token_indices, weight_indices = torch.where(mask)
164
+
165
+ if token_indices.numel() > 0:
166
+ expert_weights = topk_weights[token_indices, weight_indices]
167
+ expert_input = hidden_states[token_indices]
168
+
169
+ if self.zero_expert_num is None or expert_idx < len(self.experts):
170
+ expert_output = expert(expert_input)
171
+ elif self.zero_expert_type == "identity":
172
+ expert_output = expert_input
173
+ else:
174
+ raise ValueError("Unknown condition")
175
+
176
+ weighted_output = expert_output * expert_weights.unsqueeze(-1)
177
+ final_hidden_states.index_add_(0, token_indices, weighted_output)
178
+
179
+ return final_hidden_states.type(hidden_states.dtype)
180
+
181
+ def forward(self, hidden_states):
182
+ orig_shape = hidden_states.shape
183
+ topk_indices, topk_weights = self.router(hidden_states)
184
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
185
+ hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
186
+ return hidden_states
187
+
188
+
189
+ def rotate_half(x):
190
+ """Rotates half the hidden dims of the input."""
191
+ x1 = x[..., : x.shape[-1] // 2]
192
+ x2 = x[..., x.shape[-1] // 2 :]
193
+ return torch.cat((-x2, x1), dim=-1)
194
+
195
+
196
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
197
+ """
198
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
199
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
200
+ """
201
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
202
+ if n_rep == 1:
203
+ return hidden_states
204
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
205
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
206
+
207
+
208
+ def eager_attention_forward(
209
+ module: nn.Module,
210
+ query: torch.Tensor,
211
+ key: torch.Tensor,
212
+ value: torch.Tensor,
213
+ attention_mask: Optional[torch.Tensor],
214
+ scaling: float,
215
+ dropout: float = 0.0,
216
+ **kwargs: Unpack[TransformersKwargs],
217
+ ):
218
+ key_states = repeat_kv(key, module.num_key_value_groups)
219
+ value_states = repeat_kv(value, module.num_key_value_groups)
220
+
221
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
222
+ if attention_mask is not None:
223
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
224
+ attn_weights = attn_weights + causal_mask
225
+
226
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
227
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
228
+ attn_output = torch.matmul(attn_weights, value_states)
229
+ attn_output = attn_output.transpose(1, 2).contiguous()
230
+
231
+ return attn_output, attn_weights
232
+
233
+
234
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1, use_mla=False):
235
+ """Applies Rotary Position Embedding to the query and key tensors.
236
+ Args:
237
+ q (`torch.Tensor`): The query tensor.
238
+ k (`torch.Tensor`): The key tensor.
239
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
240
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
241
+ position_ids (`torch.Tensor`, *optional*):
242
+ Deprecated and unused.
243
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
244
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
245
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
246
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
247
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
248
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
249
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
250
+ Returns:
251
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
252
+ """
253
+ cos = cos.unsqueeze(unsqueeze_dim)
254
+ sin = sin.unsqueeze(unsqueeze_dim)
255
+
256
+ if use_mla:
257
+ b, h, s, d = q.shape
258
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
259
+
260
+ b, h, s, d = k.shape
261
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
262
+
263
+ q_embed = (q * cos) + (rotate_half(q) * sin)
264
+ k_embed = (k * cos) + (rotate_half(k) * sin)
265
+ return q_embed, k_embed
266
+
267
+
268
+ class LongcatFlashMLA(nn.Module):
269
+ """Modified from Deepseek MLA"""
270
+
271
+ def __init__(self, config: LongcatFlashConfig, layer_idx: int):
272
+ super().__init__()
273
+ self.config = config
274
+ self.layer_idx = layer_idx
275
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
276
+ self.attention_dropout = config.attention_dropout
277
+ self.num_heads = config.num_attention_heads
278
+ self.rope_theta = config.rope_theta
279
+ self.q_lora_rank = config.q_lora_rank
280
+ self.qk_rope_head_dim = config.qk_rope_head_dim
281
+ self.kv_lora_rank = config.kv_lora_rank
282
+ self.v_head_dim = config.v_head_dim
283
+ self.qk_nope_head_dim = config.qk_nope_head_dim
284
+ self.qk_head_dim = config.qk_head_dim
285
+
286
+ self.is_causal = True
287
+ if self.q_lora_rank is None:
288
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
289
+ else:
290
+ self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
291
+ self.q_a_layernorm = LongcatFlashRMSNorm(config.q_lora_rank)
292
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
293
+
294
+ self.kv_a_proj_with_mqa = nn.Linear(
295
+ config.hidden_size,
296
+ self.kv_lora_rank + self.qk_rope_head_dim,
297
+ bias=config.attention_bias,
298
+ )
299
+ self.kv_a_layernorm = LongcatFlashRMSNorm(self.kv_lora_rank)
300
+ self.kv_b_proj = nn.Linear(
301
+ self.kv_lora_rank,
302
+ self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
303
+ bias=False,
304
+ )
305
+
306
+ self.o_proj = nn.Linear(
307
+ self.num_heads * self.v_head_dim,
308
+ config.hidden_size,
309
+ bias=config.attention_bias,
310
+ )
311
+
312
+ if config.mla_scale_q_lora:
313
+ self.mla_scale_q_lora = (config.hidden_size / self.q_lora_rank) ** 0.5
314
+ if config.mla_scale_kv_lora:
315
+ self.mla_scale_kv_lora = (config.hidden_size / self.kv_lora_rank) ** 0.5
316
+ self.scaling = self.qk_head_dim ** (-0.5)
317
+
318
+ def forward(
319
+ self,
320
+ hidden_states: torch.Tensor,
321
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
322
+ attention_mask: Optional[torch.Tensor],
323
+ past_key_value: Optional[Cache] = None,
324
+ cache_position: Optional[torch.LongTensor] = None,
325
+ **kwargs: Unpack[FlashAttentionKwargs],
326
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
327
+ batch_size, seq_length = hidden_states.shape[:-1]
328
+ query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
329
+ key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
330
+
331
+ q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))).view(query_shape).transpose(1, 2)
332
+ q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
333
+
334
+ # apply q_lora scaling
335
+ if self.mla_scale_q_lora is not None:
336
+ q_pass = q_pass * self.mla_scale_q_lora
337
+ q_rot = q_rot * self.mla_scale_q_lora
338
+
339
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
340
+ k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
341
+ k_pass = self.kv_a_layernorm(k_pass)
342
+
343
+ # apply kv_lora scaling
344
+ if self.mla_scale_kv_lora is not None:
345
+ k_pass = k_pass * self.mla_scale_kv_lora
346
+
347
+ k_pass = self.kv_b_proj(k_pass).view(key_shape).transpose(1, 2)
348
+ k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
349
+
350
+ k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
351
+
352
+ cos, sin = position_embeddings
353
+ q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin, use_mla=True)
354
+ k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
355
+
356
+ query_states = torch.cat((q_pass, q_rot), dim=-1)
357
+ key_states = torch.cat((k_pass, k_rot), dim=-1)
358
+
359
+ if past_key_value is not None:
360
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
361
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
362
+
363
+ if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
364
+ value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
365
+
366
+ attention_interface: Callable = eager_attention_forward
367
+ if self.config._attn_implementation != "eager":
368
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
369
+
370
+ attn_output, attn_weights = attention_interface(
371
+ self,
372
+ query_states,
373
+ key_states,
374
+ value_states,
375
+ attention_mask,
376
+ dropout=0.0 if not self.training else self.attention_dropout,
377
+ scaling=self.scaling,
378
+ **kwargs,
379
+ )
380
+
381
+ if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
382
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
383
+
384
+ attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
385
+ attn_output = self.o_proj(attn_output)
386
+ return attn_output, attn_weights
387
+
388
+
389
+ def create_attention_block(class_name, *args, **kwargs):
390
+ attention_mapping = {"MLA": LongcatFlashMLA}
391
+
392
+ chosen_class = attention_mapping.get(class_name)
393
+ if not chosen_class:
394
+ raise ValueError(f"No class found for name: {class_name}")
395
+
396
+ return chosen_class(*args, **kwargs)
397
+
398
+
399
+ class LongcatFlashDecoderLayer(GradientCheckpointingLayer):
400
+ def __init__(self, config: LongcatFlashConfig, layer_idx: int):
401
+ super().__init__()
402
+ self.layer_idx = layer_idx
403
+ self.hidden_size = config.hidden_size
404
+ self.mlp = LongcatFlashMoE(config)
405
+
406
+ self_attn = []
407
+ mlps = []
408
+ input_layernorm = []
409
+ post_attention_layernorm = []
410
+ for i in range(2):
411
+ self_attn.append(
412
+ create_attention_block(config.attention_method, config=config, layer_idx=layer_idx * 2 + i)
413
+ )
414
+ mlps.append(LongcatFlashMLP(config))
415
+ input_layernorm.append(LongcatFlashRMSNorm(config.hidden_size, eps=config.rms_norm_eps))
416
+ post_attention_layernorm.append(LongcatFlashRMSNorm(config.hidden_size, eps=config.rms_norm_eps))
417
+
418
+ self.self_attn = nn.ModuleList(self_attn)
419
+ self.mlps = nn.ModuleList(mlps)
420
+ self.input_layernorm = nn.ModuleList(input_layernorm)
421
+ self.post_attention_layernorm = nn.ModuleList(post_attention_layernorm)
422
+
423
+ def forward(
424
+ self,
425
+ hidden_states: torch.Tensor,
426
+ attention_mask: Optional[torch.Tensor] = None,
427
+ position_ids: Optional[torch.LongTensor] = None,
428
+ past_key_value: Optional[Cache] = None,
429
+ use_cache: Optional[bool] = False,
430
+ cache_position: Optional[torch.LongTensor] = None,
431
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
432
+ **kwargs: Unpack[FlashAttentionKwargs],
433
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
434
+ for i in range(2):
435
+ residual = hidden_states
436
+
437
+ hidden_states = self.input_layernorm[i](hidden_states)
438
+
439
+ hidden_states, _ = self.self_attn[i](
440
+ hidden_states=hidden_states,
441
+ attention_mask=attention_mask,
442
+ position_ids=position_ids,
443
+ past_key_value=past_key_value,
444
+ use_cache=use_cache,
445
+ cache_position=cache_position,
446
+ position_embeddings=position_embeddings,
447
+ **kwargs,
448
+ )
449
+ hidden_states = residual + hidden_states
450
+
451
+ residual = hidden_states
452
+ hidden_states = self.post_attention_layernorm[i](hidden_states)
453
+
454
+ if i == 0:
455
+ shortcut_mlp_output = self.mlp(hidden_states) # shortcut output (MoE output)
456
+
457
+ hidden_states = self.mlps[i](hidden_states)
458
+ hidden_states = residual + hidden_states
459
+ if i == 1:
460
+ hidden_states = hidden_states + shortcut_mlp_output
461
+
462
+ return hidden_states
463
+
464
+
465
+ @auto_docstring
466
+ class LongcatFlashPreTrainedModel(PreTrainedModel):
467
+ config: LongcatFlashConfig
468
+ base_model_prefix = "model"
469
+ supports_gradient_checkpointing = True
470
+ _no_split_modules = ["LongcatFlashDecoderLayer"]
471
+ _skip_keys_device_placement = ["past_key_values"]
472
+ _supports_flash_attn = True
473
+ _supports_sdpa = True
474
+ _supports_flex_attn = True
475
+ _can_compile_fullgraph = True
476
+ _supports_attention_backend = True
477
+ _can_record_outputs = {
478
+ "hidden_states": LongcatFlashDecoderLayer,
479
+ "attentions": LongcatFlashMLA,
480
+ }
481
+
482
+
483
+ @auto_docstring
484
+ class LongcatFlashModel(LongcatFlashPreTrainedModel):
485
+ _keys_to_ignore_on_load_unexpected = [r"model\.mtp.*"]
486
+
487
+ def __init__(self, config: LongcatFlashConfig):
488
+ super().__init__(config)
489
+ self.padding_idx = config.pad_token_id
490
+ self.vocab_size = config.vocab_size
491
+
492
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
493
+ self.layers = nn.ModuleList(
494
+ [LongcatFlashDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
495
+ )
496
+ self.norm = LongcatFlashRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
497
+ self.rotary_emb = LongcatFlashRotaryEmbedding(config=config)
498
+ self.gradient_checkpointing = False
499
+
500
+ # Initialize weights and apply final processing
501
+ self.post_init()
502
+
503
+ @check_model_inputs
504
+ @auto_docstring
505
+ def forward(
506
+ self,
507
+ input_ids: Optional[torch.LongTensor] = None,
508
+ attention_mask: Optional[torch.Tensor] = None,
509
+ position_ids: Optional[torch.LongTensor] = None,
510
+ past_key_values: Optional[Cache] = None,
511
+ inputs_embeds: Optional[torch.FloatTensor] = None,
512
+ cache_position: Optional[torch.LongTensor] = None,
513
+ use_cache: Optional[bool] = None,
514
+ **kwargs: Unpack[TransformersKwargs],
515
+ ) -> BaseModelOutputWithPast:
516
+ if (input_ids is None) ^ (inputs_embeds is not None):
517
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
518
+
519
+ if inputs_embeds is None:
520
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
521
+
522
+ if use_cache and past_key_values is None:
523
+ past_key_values = DynamicCache()
524
+
525
+ if cache_position is None:
526
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
527
+ cache_position: torch.Tensor = torch.arange(
528
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
529
+ )
530
+
531
+ if position_ids is None:
532
+ position_ids = cache_position.unsqueeze(0)
533
+
534
+ causal_mask = create_causal_mask(
535
+ config=self.config,
536
+ input_embeds=inputs_embeds,
537
+ attention_mask=attention_mask,
538
+ cache_position=cache_position,
539
+ past_key_values=past_key_values,
540
+ position_ids=position_ids,
541
+ )
542
+
543
+ hidden_states = inputs_embeds
544
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
545
+
546
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
547
+ hidden_states = decoder_layer(
548
+ hidden_states,
549
+ attention_mask=causal_mask,
550
+ position_ids=position_ids,
551
+ past_key_value=past_key_values,
552
+ cache_position=cache_position,
553
+ position_embeddings=position_embeddings,
554
+ **kwargs,
555
+ )
556
+
557
+ hidden_states = self.norm(hidden_states)
558
+ return BaseModelOutputWithPast(
559
+ last_hidden_state=hidden_states,
560
+ past_key_values=past_key_values,
561
+ )
562
+
563
+
564
+ @auto_docstring
565
+ class LongcatFlashForCausalLM(LongcatFlashPreTrainedModel, GenerationMixin):
566
+ _tied_weights_keys = ["lm_head.weight"]
567
+ _tp_plan = {"lm_head": "colwise_rep"}
568
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
569
+ _keys_to_ignore_on_load_unexpected = [r"model\.mtp.*"]
570
+
571
+ def __init__(self, config):
572
+ super().__init__(config)
573
+ self.model = LongcatFlashModel(config)
574
+ self.vocab_size = config.vocab_size
575
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
576
+
577
+ # Initialize weights and apply final processing
578
+ self.post_init()
579
+
580
+ def set_decoder(self, decoder):
581
+ self.model = decoder
582
+
583
+ def get_decoder(self):
584
+ return self.model
585
+
586
+ @can_return_tuple
587
+ @auto_docstring
588
+ def forward(
589
+ self,
590
+ input_ids: Optional[torch.LongTensor] = None,
591
+ attention_mask: Optional[torch.Tensor] = None,
592
+ position_ids: Optional[torch.LongTensor] = None,
593
+ past_key_values: Optional[Cache] = None,
594
+ inputs_embeds: Optional[torch.FloatTensor] = None,
595
+ labels: Optional[torch.LongTensor] = None,
596
+ use_cache: Optional[bool] = None,
597
+ cache_position: Optional[torch.LongTensor] = None,
598
+ logits_to_keep: Union[int, torch.Tensor] = 0,
599
+ **kwargs: Unpack[TransformersKwargs],
600
+ ) -> CausalLMOutputWithPast:
601
+ r"""
602
+ Example:
603
+ ```python
604
+ >>> from transformers import AutoTokenizer, LongcatFlashForCausalLM
605
+ >>> model = LongcatFlashForCausalLM.from_pretrained("meta-longcat_flash/LongcatFlash-2-7b-hf")
606
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-longcat_flash/LongcatFlash-2-7b-hf")
607
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
608
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
609
+ >>> # Generate
610
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
611
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
612
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
613
+ ```"""
614
+ outputs: BaseModelOutputWithPast = self.model(
615
+ input_ids=input_ids,
616
+ attention_mask=attention_mask,
617
+ position_ids=position_ids,
618
+ past_key_values=past_key_values,
619
+ inputs_embeds=inputs_embeds,
620
+ use_cache=use_cache,
621
+ cache_position=cache_position,
622
+ **kwargs,
623
+ )
624
+
625
+ hidden_states = outputs.last_hidden_state
626
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
627
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
628
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
629
+
630
+ loss = None
631
+ if labels is not None:
632
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
633
+
634
+ return CausalLMOutputWithPast(
635
+ loss=loss,
636
+ logits=logits,
637
+ past_key_values=outputs.past_key_values,
638
+ hidden_states=outputs.hidden_states,
639
+ attentions=outputs.attentions,
640
+ )
641
+
642
+
643
+ __all__ = ["LongcatFlashPreTrainedModel", "LongcatFlashModel", "LongcatFlashForCausalLM"]
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 {%- if tool_call.function.arguments is string -%}\n {\"name\": \"{{ tool_call.function.name}}\", \"arguments\": {{tool_call.function.arguments}}}\n {%- else -%}\n {\"name\": \"{{ tool_call.function.name}}\", \"arguments\": {{tool_call.function.arguments | tojson}}}\n {%- endif -%}\n {{- \"\n</longcat_tool_call>\" }}\n {%- endfor %}\n {%- endif %}\n {{- \"</longcat_s>\" -}}\n {%- elif msg.role == \"tool\" %}\n {{- \" TOOL:\" -}}\n {%- if msg.name -%}\n {\"name\": {{msg.name | tojson}}, \"content\": {{msg.content | tojson}}}\n {%- else -%}\n {\"content\": {{msg.content | tojson}}}\n {%- endif -%}\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
+ }
vision/config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "resolution_mode": "native",
3
+ "init_method": "xavier",
4
+ "pe_type": "rope2d",
5
+ "rope_theta": 10000,
6
+ "patch_size": 14,
7
+ "temporal_patch_size": 2,
8
+ "spatial_merge_size": 1,
9
+ "num_hidden_layers": 32,
10
+ "num_attention_heads": 16,
11
+ "hidden_size": 1280,
12
+ "intermediate_size": 5184,
13
+ "patch_embedding_bias": true,
14
+ "qk_normalization": true,
15
+ "qkv_bias": false,
16
+ "use_pre_norm": false,
17
+ "use_flash_attn": true,
18
+ "norm_type": "RMSNorm",
19
+ "layer_norm_eps": 1e-06,
20
+ "hidden_act": "SwiGLU",
21
+ "patch_dropout": 0.5,
22
+ "attention_dropout": 0.0,
23
+ "drop_path_rate": 0.0,
24
+ "initializer_range": 1e-10,
25
+ "initializer_factor": 0.1,
26
+ "image_size": 1792,
27
+ "min_tokens": 576,
28
+ "max_tokens": 5832,
29
+ "min_tokens_video": 512,
30
+ "max_tokens_video": 28672,
31
+ "min_tokens_video_vit": 576,
32
+ "max_tokens_video_vit": 156800,
33
+ "max_frames": 128,
34
+ "image_mean": [0.485, 0.456, 0.406],
35
+ "image_std": [0.229, 0.224, 0.225],
36
+ "resize_factor": 8,
37
+ "relarge_ratio": 1.0,
38
+ "adaptor_dim": 7168
39
+ }