ApacheOne deepgrove-team commited on
Commit
3fc8079
·
0 Parent(s):

Duplicate from deepgrove/maple-preview

Browse files

Co-authored-by: deepgrove <deepgrove-team@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/01-speed-frontier.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/05-benchmark-scores-table.png filter=lfs diff=lfs merge=lfs -text
38
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 deepgrove
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language: en
4
+ library_name: transformers
5
+ pipeline_tag: text-generation
6
+ tags:
7
+ - causal-lm
8
+ - mixture-of-experts
9
+ - reasoning
10
+ - ternary
11
+ - custom-code
12
+ ---
13
+
14
+ # Maple-Preview
15
+
16
+ **DeepGrove · 2026**
17
+
18
+ Today we introduce Maple-Preview, an open-source 20B-A1B ternary-weight reasoning LLM. Maple-Preview has SOTA reasoning for its weight class and is even competitive with larger models. It solves IMO-level problems and runs at 200+ tokens/sec on a Mac mini M4, 5–16× faster than efficient models like Gemma 4, Qwen3.5, and gpt-oss.
19
+
20
+ - 20B-A1B Model
21
+ - 218 tok/s M4 Mac mini
22
+ - 5.31 GB Checkpoint
23
+ - 131,072 Token context
24
+
25
+ ![Maple-Preview speed and performance frontier](assets/01-speed-frontier.png)
26
+
27
+ > [!NOTE]
28
+ > The included Transformers implementation depends on Triton and FlashAttention
29
+ > and is intended for a compatible CUDA environment. The reported Apple Silicon
30
+ > result uses a separate on-device runtime.
31
+
32
+ ## Architecture
33
+
34
+ Maple-Preview is a 20B-A1B reasoning model designed from the start for efficient on-device inference. It utilizes a 24-layer, 256-expert (8 active) configuration with 3:1 SWA-512:GA attention.
35
+
36
+ ## Evaluation
37
+
38
+ On benchmarks, Maple-Preview sets a new point on the Pareto frontier for both memory-to-performance and speed-to-performance, demonstrating its strong reasoning capabilities. However, we note that this preview is focused primarily on raw reasoning and, as such, may underperform on agentic benchmarks. We intend to continue improving general performance through extended training before Maple's full release.
39
+
40
+ ![Benchmark score comparison](assets/05-benchmark-scores-table.png)
41
+
42
+ Capability comparison using the dense output head across LCBv6, AIME 2026, HMMT 2026, and GPQA-D.
43
+
44
+ ## Limitations
45
+
46
+ This preview received minimal post-training for agentic tasks and only
47
+ small-scale general reinforcement learning.
48
+
49
+ ## License
50
+
51
+ Maple-Preview is released under the [MIT License](LICENSE).
added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
assets/01-speed-frontier.png ADDED

Git LFS Details

  • SHA256: b067ed02ca3331a61c6e8718f68cda1bda5533c37179e6db03fefc5c6e144688
  • Pointer size: 131 Bytes
  • Size of remote file: 153 kB
assets/05-benchmark-scores-table.png ADDED

Git LFS Details

  • SHA256: 36db8e78642c5231c0f25d1d9b690351165097e327fae42a1d877b5918035651
  • Pointer size: 131 Bytes
  • Size of remote file: 245 kB
chat_template.jinja ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- '# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>' }}
7
+ {%- for tool in tools %}
8
+ {{- '\n' }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- '\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n' }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+
18
+
19
+ {%- for message in messages %}
20
+ {%- if message.content is string %}
21
+ {%- set content = message.content %}
22
+ {%- else %}
23
+ {%- set content = '' %}
24
+ {%- endif %}
25
+
26
+ {%- if message.role == 'user' or (message.role == 'system' and not loop.first) %}
27
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>\n' }}
28
+
29
+ {%- elif message.role == 'assistant' %}
30
+ {%- set reasoning_content = '' %}
31
+
32
+ {%- if message.reasoning_content is string %}
33
+ {%- set reasoning_content = message.reasoning_content %}
34
+ {%- elif '</think>' in content %}
35
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
36
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
37
+ {%- endif %}
38
+
39
+ {%- if reasoning_content %}
40
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
41
+ {%- else %}
42
+ {{- '<|im_start|>' + message.role + '\n' + content }}
43
+ {%- endif %}
44
+
45
+ {%- if message.tool_calls %}
46
+ {%- for tool_call in message.tool_calls %}
47
+ {%- if (loop.first and content) or not loop.first %}
48
+ {{- '\n' }}
49
+ {%- endif %}
50
+
51
+ {%- if tool_call.function %}
52
+ {%- set tool_call = tool_call.function %}
53
+ {%- endif %}
54
+
55
+ {{- '<tool_call>\n{\"name\": \"' }}
56
+ {{- tool_call.name }}
57
+ {{- '\", \"arguments\": ' }}
58
+
59
+ {%- if tool_call.arguments is string %}
60
+ {{- tool_call.arguments }}
61
+ {%- else %}
62
+ {{- tool_call.arguments | tojson }}
63
+ {%- endif %}
64
+
65
+ {{- '}\n</tool_call>' }}
66
+ {%- endfor %}
67
+ {%- endif %}
68
+
69
+ {{- '<|im_end|>\n' }}
70
+
71
+ {%- elif message.role == 'tool' %}
72
+ {%- if loop.first or messages[loop.index0 - 1].role != 'tool' %}
73
+ {{- '<|im_start|>user' }}
74
+ {%- endif %}
75
+
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+
80
+ {%- if loop.last or messages[loop.index0 + 1].role != 'tool' %}
81
+ {{- '<|im_end|>\n' }}
82
+ {%- endif %}
83
+ {%- endif %}
84
+ {%- endfor %}
85
+
86
+ {%- if add_generation_prompt %}
87
+ {{- '<|im_start|>assistant\n<think>\n' }}
88
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MapleForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_maple.MapleConfig",
8
+ "AutoModel": "modeling_maple.MapleModel",
9
+ "AutoModelForCausalLM": "modeling_maple.MapleForCausalLM"
10
+ },
11
+ "bos_token_id": 151643,
12
+ "dtype": "bfloat16",
13
+ "embedding_dropout": 0.0,
14
+ "eos_token_id": 151645,
15
+ "head_dim": 128,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 4096,
20
+ "layer_types": [
21
+ "sliding_attention",
22
+ "sliding_attention",
23
+ "sliding_attention",
24
+ "full_attention",
25
+ "sliding_attention",
26
+ "sliding_attention",
27
+ "sliding_attention",
28
+ "full_attention",
29
+ "sliding_attention",
30
+ "sliding_attention",
31
+ "sliding_attention",
32
+ "full_attention",
33
+ "sliding_attention",
34
+ "sliding_attention",
35
+ "sliding_attention",
36
+ "full_attention",
37
+ "sliding_attention",
38
+ "sliding_attention",
39
+ "sliding_attention",
40
+ "full_attention",
41
+ "sliding_attention",
42
+ "sliding_attention",
43
+ "sliding_attention",
44
+ "full_attention"
45
+ ],
46
+ "max_position_embeddings": 131072,
47
+ "max_window_layers": 24,
48
+ "moe_intermediate_size": 512,
49
+ "moe_router_enable_expert_bias": false,
50
+ "nope_on_global_attention": true,
51
+ "norm_topk_prob": true,
52
+ "num_attention_heads": 16,
53
+ "num_experts": 256,
54
+ "num_experts_per_tok": 8,
55
+ "num_hidden_layers": 24,
56
+ "num_key_value_heads": 4,
57
+ "num_shared_experts": 0,
58
+ "output_dropout": 0.0,
59
+ "output_router_logits": false,
60
+ "pad_token_id": null,
61
+ "partial_rotary_factor": 0.5,
62
+ "preaffine": false,
63
+ "quantize": true,
64
+ "rms_norm_eps": 1e-06,
65
+ "rope_scaling": null,
66
+ "rope_theta": 10000,
67
+ "router_dtype": "fp32",
68
+ "sliding_window": 512,
69
+ "tie_word_embeddings": false,
70
+ "transformers_version": "4.57.1",
71
+ "use_cache": true,
72
+ "use_qk_norm": true,
73
+ "use_rmsnorm": true,
74
+ "vocab_size": 151936
75
+ }
configuration_maple.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration for Maple models."""
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+
5
+
6
+ class MapleConfig(PretrainedConfig):
7
+ """Configuration for the Maple mixture-of-experts causal language model."""
8
+
9
+ model_type = "maple"
10
+
11
+ def __init__(
12
+ self,
13
+ vocab_size=151936,
14
+ hidden_size=2048,
15
+ num_hidden_layers=20,
16
+ num_attention_heads=16,
17
+ num_key_value_heads=4,
18
+ hidden_act="silu",
19
+ use_bias=False,
20
+ rms_norm_eps=1e-6,
21
+ tie_word_embeddings=False,
22
+ attention_dropout=0.0,
23
+ initializer_range=0.02,
24
+ max_position_embeddings=32768,
25
+ rope_theta=10000.0,
26
+ use_cache=True,
27
+ rope_scaling=None,
28
+ partial_rotary_factor=0.5,
29
+ pad_token_id=None,
30
+ eos_token_id=None,
31
+ num_experts=256,
32
+ num_experts_per_tok=8,
33
+ moe_intermediate_size=512,
34
+ head_dim=128,
35
+ output_router_logits=False,
36
+ **kwargs,
37
+ ):
38
+ self.num_hidden_layers = num_hidden_layers
39
+ self.vocab_size = vocab_size
40
+ self.hidden_size = hidden_size
41
+ self.num_attention_heads = num_attention_heads
42
+ self.num_key_value_heads = num_key_value_heads
43
+ self.hidden_act = hidden_act
44
+ self.use_bias = use_bias
45
+ self.rms_norm_eps = rms_norm_eps
46
+ self.attention_dropout = attention_dropout
47
+ self.initializer_range = initializer_range
48
+ self.max_position_embeddings = max_position_embeddings
49
+ self.rope_theta = rope_theta
50
+ self.use_cache = use_cache
51
+ self.head_dim = head_dim or self.hidden_size // self.num_attention_heads
52
+ self.rope_scaling = rope_scaling
53
+ self.partial_rotary_factor = partial_rotary_factor
54
+
55
+ self.num_experts = num_experts
56
+ self.num_experts_per_tok = num_experts_per_tok
57
+ self.moe_intermediate_size = moe_intermediate_size
58
+ self.output_router_logits = output_router_logits
59
+
60
+ super().__init__(
61
+ pad_token_id=pad_token_id,
62
+ eos_token_id=eos_token_id,
63
+ tie_word_embeddings=tie_word_embeddings,
64
+ **kwargs,
65
+ )
fa3.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import os
3
+ from typing import Optional, Tuple, TypedDict
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+
9
+ try:
10
+ from flash_attn_interface import flash_attn_func, flash_attn_varlen_func
11
+ except:
12
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
13
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
14
+
15
+
16
+ # Detect supported kwargs in FA3
17
+ _sig = inspect.signature(flash_attn_func)
18
+ _flash_supports_window_size = "window_size" in _sig.parameters
19
+ _flash_accepts_deterministic = "deterministic" in _sig.parameters
20
+ _flash_accepts_softcap = "softcap" in _sig.parameters
21
+
22
+
23
+ def _get_unpad_data(attention_mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, int]:
24
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
25
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
26
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
27
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
28
+ return indices, cu_seqlens, max_seqlen_in_batch
29
+
30
+
31
+ def _upad_input(
32
+ query_layer: torch.Tensor,
33
+ key_layer: torch.Tensor,
34
+ value_layer: torch.Tensor,
35
+ attention_mask: torch.Tensor,
36
+ query_length: int,
37
+ ):
38
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
39
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
40
+
41
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k)
42
+ value_layer = index_first_axis(
43
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
44
+ )
45
+
46
+ if query_length == kv_seq_len:
47
+ query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, -1, head_dim), indices_k)
48
+ cu_seqlens_q = cu_seqlens_k
49
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
50
+ indices_q = indices_k
51
+ elif query_length == 1:
52
+ max_seqlen_in_batch_q = 1
53
+ cu_seqlens_q = torch.arange(batch_size + 1, dtype=torch.int32, device=query_layer.device)
54
+ indices_q = cu_seqlens_q[:-1]
55
+ query_layer = query_layer.squeeze(1)
56
+ else:
57
+ attention_mask = attention_mask[:, -query_length:]
58
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q, *_ = unpad_input(query_layer, attention_mask)
59
+
60
+ return (
61
+ query_layer,
62
+ key_layer,
63
+ value_layer,
64
+ indices_q,
65
+ (cu_seqlens_q, cu_seqlens_k),
66
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
67
+ )
68
+
69
+
70
+ def prepare_fa3_from_position_ids(query, key, value, position_ids):
71
+ query = query.view(-1, query.size(-2), query.size(-1))
72
+ key = key.contiguous().view(-1, key.size(-2), key.size(-1))
73
+ value = value.contiguous().view(-1, value.size(-2), value.size(-1))
74
+ position_ids = position_ids.flatten()
75
+ indices_q = torch.arange(position_ids.size(0), device=position_ids.device, dtype=torch.int32)
76
+
77
+ cu_seq_lens = torch.cat(
78
+ (
79
+ indices_q[position_ids == 0],
80
+ torch.tensor(position_ids.size(), device=position_ids.device, dtype=torch.int32),
81
+ )
82
+ )
83
+
84
+ max_length = position_ids.max() + 1
85
+ return query, key, value, indices_q, (cu_seq_lens, cu_seq_lens), (max_length, max_length)
86
+
87
+
88
+ def fa_peft_integration_check(
89
+ query: torch.Tensor,
90
+ key: torch.Tensor,
91
+ value: torch.Tensor,
92
+ target_dtype: Optional[torch.dtype] = None,
93
+ ):
94
+ if target_dtype is None:
95
+ return query, key, value
96
+ if query.dtype == torch.float32:
97
+ query = query.to(target_dtype)
98
+ key = key.to(target_dtype)
99
+ value = value.to(target_dtype)
100
+ return query, key, value
101
+
102
+
103
+ deterministic_g = os.environ.get("FLASH_ATTENTION_DETERMINISTIC", "0") == "1"
104
+
105
+
106
+ def _flash_attention_forward(
107
+ query_states: torch.Tensor,
108
+ key_states: torch.Tensor,
109
+ value_states: torch.Tensor,
110
+ attention_mask: Optional[torch.Tensor],
111
+ query_length: int,
112
+ is_causal: bool,
113
+ dropout: float = 0.0,
114
+ position_ids: Optional[torch.Tensor] = None,
115
+ softmax_scale: Optional[float] = None,
116
+ sliding_window: Optional[int] = None,
117
+ use_top_left_mask: bool = False,
118
+ softcap: Optional[float] = None,
119
+ deterministic: Optional[bool] = None,
120
+ cu_seq_lens_q: Optional[torch.LongTensor] = None,
121
+ cu_seq_lens_k: Optional[torch.LongTensor] = None,
122
+ max_length_q: Optional[int] = None,
123
+ max_length_k: Optional[int] = None,
124
+ target_dtype: Optional[torch.dtype] = None,
125
+ **kwargs,
126
+ ):
127
+ causal = is_causal if not use_top_left_mask else (is_causal and query_length != 1)
128
+
129
+ flash_kwargs = {}
130
+ if _flash_supports_window_size and sliding_window is not None and key_states.shape[1] > sliding_window:
131
+ flash_kwargs["window_size"] = (sliding_window, 0)
132
+ if _flash_accepts_deterministic:
133
+ if deterministic is None:
134
+ deterministic = deterministic_g
135
+ flash_kwargs["deterministic"] = deterministic
136
+
137
+ if attention_mask is not None:
138
+ batch_size = query_states.shape[0]
139
+ q_unpad, k_unpad, v_unpad, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_q, max_k) = _upad_input(
140
+ query_states, key_states, value_states, attention_mask, query_length
141
+ )
142
+ attn_output_unpad = flash_attn_varlen_func(
143
+ q_unpad,
144
+ k_unpad,
145
+ v_unpad,
146
+ cu_seqlens_q=cu_seqlens_q,
147
+ cu_seqlens_k=cu_seqlens_k,
148
+ max_seqlen_q=max_q,
149
+ max_seqlen_k=max_k,
150
+ # dropout_p=dropout,
151
+ softmax_scale=softmax_scale,
152
+ causal=causal,
153
+ **flash_kwargs,
154
+ )
155
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
156
+
157
+ elif position_ids is not None and (
158
+ max_length_q is not None
159
+ # This fucks up compile
160
+ # or (query_length != 1 and not (torch.diff(position_ids, dim=-1) >= 0).all())
161
+ ):
162
+ batch_size = query_states.size(0)
163
+ if cu_seq_lens_q is None or cu_seq_lens_k is None:
164
+ q_unpad, k_unpad, v_unpad, indices_q, (cu_seq_lens_q, cu_seq_lens_k), (max_length_q, max_length_k) = (
165
+ prepare_fa3_from_position_ids(query_states, key_states, value_states, position_ids)
166
+ )
167
+ else:
168
+ q_unpad = query_states.reshape(-1, query_states.size(-2), query_states.size(-1))
169
+ k_unpad = key_states.reshape(-1, key_states.size(-2), key_states.size(-1))
170
+ v_unpad = value_states.reshape(-1, value_states.size(-2), value_states.size(-1))
171
+
172
+ attn_output = flash_attn_varlen_func(
173
+ q_unpad,
174
+ k_unpad,
175
+ v_unpad,
176
+ cu_seqlens_q=cu_seq_lens_q,
177
+ cu_seqlens_k=cu_seq_lens_k,
178
+ max_seqlen_q=max_length_q,
179
+ max_seqlen_k=max_length_k,
180
+ # dropout_p=dropout,
181
+ softmax_scale=softmax_scale,
182
+ causal=causal,
183
+ **flash_kwargs,
184
+ )
185
+ attn_output = attn_output.view(batch_size, -1, attn_output.size(-2), attn_output.size(-1))
186
+
187
+ else:
188
+ # print(f"scale {softmax_scale}")
189
+ attn_output = flash_attn_func(
190
+ query_states,
191
+ key_states,
192
+ value_states,
193
+ # dropout,
194
+ softmax_scale=softmax_scale,
195
+ causal=causal,
196
+ **flash_kwargs,
197
+ )
198
+
199
+ return attn_output
200
+
201
+
202
+ class FlashAttentionKwargs(TypedDict, total=False):
203
+ cu_seq_lens_q: Optional[torch.LongTensor]
204
+ cu_seq_lens_k: Optional[torch.LongTensor]
205
+ max_length_q: Optional[int]
206
+ max_length_k: Optional[int]
207
+
208
+
209
+ # _use_top_left_mask = flash_attn_supports_top_left_mask()
210
+
211
+ _use_top_left_mask = False
212
+
213
+
214
+ def flash_attention_forward(
215
+ module: torch.nn.Module,
216
+ query: torch.Tensor,
217
+ key: torch.Tensor,
218
+ value: torch.Tensor,
219
+ attention_mask: Optional[torch.Tensor],
220
+ dropout: float = 0.0,
221
+ scaling: Optional[float] = None,
222
+ sliding_window: Optional[int] = None,
223
+ softcap: Optional[float] = None,
224
+ **kwargs,
225
+ ) -> Tuple[torch.Tensor, None]:
226
+ # This is before the transpose
227
+ seq_len = query.shape[1]
228
+
229
+ # FA2 uses non-transposed inputs
230
+ query = query.transpose(1, 2)
231
+ key = key.transpose(1, 2)
232
+ value = value.transpose(1, 2)
233
+
234
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
235
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
236
+ # cast them back in the correct dtype just to be sure everything works as expected.
237
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
238
+ # in fp32. (usually our RMSNorm modules handle it correctly)
239
+ target_dtype = None
240
+ if query.dtype == torch.float32:
241
+ if torch.is_autocast_enabled():
242
+ target_dtype = torch.get_autocast_gpu_dtype()
243
+ # Handle the case where the model is quantized
244
+ elif hasattr(module.config, "_pre_quantization_dtype"):
245
+ target_dtype = module.config._pre_quantization_dtype
246
+ else:
247
+ target_dtype = next(layer for layer in module.modules() if isinstance(layer, torch.nn.Linear)).weight.dtype
248
+
249
+ # FA2 always relies on the value set in the module, so remove it if present in kwargs to avoid passing it twice
250
+ kwargs.pop("is_causal", None)
251
+
252
+ attn_output = _flash_attention_forward(
253
+ query,
254
+ key,
255
+ value,
256
+ attention_mask,
257
+ query_length=seq_len,
258
+ is_causal=module.is_causal,
259
+ dropout=dropout,
260
+ softmax_scale=scaling,
261
+ sliding_window=sliding_window,
262
+ softcap=softcap,
263
+ use_top_left_mask=_use_top_left_mask,
264
+ target_dtype=target_dtype,
265
+ **kwargs,
266
+ )
267
+
268
+ return attn_output, None
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0e75504d43e41c5aa1796abac3266e8626706742f2c6da8a67a48d31d9a4f77
3
+ size 4998990664
model-00002-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:166113ab0c8f485d5d8a6060c4f1714ed4a7103ba703fd5c51316fb70c5abdd6
3
+ size 4999904624
model-00003-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82c08761b18236f95e06b04ebb24ef55e2a54d0abda95afe6ee8ad963ce712dd
3
+ size 4999904624
model-00004-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dda74a69c9ac24dfaf135b0d459b47307e134dc5dc2cd7c4171f249a6c267fa0
3
+ size 4999905768
model-00005-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73b5a1edfcc317374305ea29c79b0ddb184f8f069163f9083bffe0b0181a00ec
3
+ size 4999907000
model-00006-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8533087e0a88695d8bb43fa82d2be16e396e8fbc1e32357d8cfa99af6860446
3
+ size 4999907000
model-00007-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:efcb94993cb5d9062c879c4d132489f58687b5e21ff20d2913b011d6504127dd
3
+ size 4999906992
model-00008-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79be22027606cf7efde7d6f409a6cf369380132d1baf625bcc90f4280a7baab0
3
+ size 4999907000
model-00009-of-00009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4761e38c77d93f4807181eb972557f44649336c0d261064578a9d3c1587cbebb
3
+ size 432038704
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_maple.py ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Optional, Tuple, Union
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+ from transformers.activations import ACT2FN
9
+ from transformers.cache_utils import Cache, DynamicCache
10
+ from transformers.generation.utils import GenerationMixin
11
+ from transformers.modeling_outputs import MoeModelOutputWithPast
12
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
13
+ from transformers.modeling_utils import PreTrainedModel
14
+ from transformers.utils import ModelOutput, add_start_docstrings
15
+ from transformers.utils import logging as hf_logging
16
+
17
+ from .configuration_maple import MapleConfig
18
+ from .fa3 import flash_attention_forward
19
+
20
+ logger = hf_logging.get_logger(__name__)
21
+
22
+ @dataclass
23
+ class MapleOutputWithPast(ModelOutput):
24
+ loss: Optional[torch.FloatTensor] = None
25
+ logits: Optional[torch.FloatTensor] = None
26
+ past_key_values: Optional[Cache] = None
27
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
28
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
29
+ aux_loss: Optional[torch.FloatTensor] = None
30
+ router_logits: Optional[tuple[torch.FloatTensor, ...]] = None
31
+
32
+
33
+ class MapleModelOutputWithPast(MoeModelOutputWithPast):
34
+ """Maple base-model output with an auxiliary router loss."""
35
+
36
+ def __init__(self, aux_loss=0.0, **kwargs):
37
+ super().__init__(**kwargs)
38
+ self.aux_loss = aux_loss
39
+
40
+
41
+ class MapleRotaryEmbedding(nn.Module):
42
+ def __init__(self, config: MapleConfig, device=None):
43
+ super().__init__()
44
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
45
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
46
+ else:
47
+ self.rope_type = "default"
48
+ self.max_seq_len_cached = config.max_position_embeddings
49
+ self.original_max_seq_len = config.max_position_embeddings
50
+
51
+ self.config = config
52
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
53
+
54
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
55
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
56
+ self.original_inv_freq = self.inv_freq
57
+
58
+ @torch.no_grad()
59
+ @dynamic_rope_update
60
+ def forward(self, x, position_ids):
61
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
62
+ position_ids_expanded = position_ids[:, None, :].float()
63
+
64
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
65
+ with torch.autocast(device_type=device_type, enabled=False):
66
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
67
+ emb = torch.cat((freqs, freqs), dim=-1)
68
+ cos = emb.cos() * self.attention_scaling
69
+ sin = emb.sin() * self.attention_scaling
70
+ freqs = torch.cat([freqs, freqs], dim=-1)
71
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype), freqs.float()
72
+
73
+
74
+ def rotate_half(x):
75
+ x1 = x[..., : x.shape[-1] // 2]
76
+ x2 = x[..., x.shape[-1] // 2 :]
77
+ return torch.cat((-x2, x1), dim=-1)
78
+
79
+
80
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
81
+ cos = cos.unsqueeze(unsqueeze_dim)
82
+ sin = sin.unsqueeze(unsqueeze_dim)
83
+
84
+ rotary_dim = cos.shape[-1]
85
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
86
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
87
+
88
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
89
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
90
+
91
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
92
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
93
+ return q_embed, k_embed
94
+
95
+
96
+ class MapleMLP(nn.Module):
97
+ def __init__(self, config: MapleConfig, intermediate_size: int):
98
+ super().__init__()
99
+ self.hidden_size = config.hidden_size
100
+ self.intermediate_size = intermediate_size
101
+
102
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
103
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
104
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
105
+ self.act_fn = ACT2FN[config.hidden_act]
106
+
107
+ def forward(self, x):
108
+ gate_weight, up_weight, down_weight = self.gate_proj.weight, self.up_proj.weight, self.down_proj.weight
109
+ return torch.nn.functional.linear(
110
+ self.act_fn(torch.clamp(torch.nn.functional.linear(x, gate_weight), max=7.0)) * torch.clamp(torch.nn.functional.linear(x, up_weight), min=-7.0, max=7.0),
111
+ down_weight,
112
+ )
113
+
114
+
115
+ class MapleRMSNorm(nn.Module):
116
+ def __init__(self, hidden_size, eps=1e-6):
117
+ super().__init__()
118
+ self.weight = nn.Parameter(torch.ones(hidden_size))
119
+ self.variance_epsilon = eps
120
+
121
+ def forward(self, hidden_states):
122
+ input_dtype = hidden_states.dtype
123
+ hidden_states = hidden_states.to(torch.float32)
124
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
125
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
126
+ return self.weight * hidden_states.to(input_dtype)
127
+
128
+
129
+ try:
130
+ from liger_kernel.transformers.rms_norm import LigerRMSNorm
131
+
132
+ MapleRMSNorm = LigerRMSNorm
133
+ except ImportError:
134
+ pass
135
+
136
+
137
+ class MapleGate(nn.Module):
138
+ def __init__(self, config: MapleConfig):
139
+ super().__init__()
140
+ self.top_k = config.num_experts_per_tok
141
+ self.num_experts = config.num_experts
142
+ self.gating_dim = config.hidden_size
143
+ self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim)))
144
+ self.reset_parameters()
145
+
146
+ def reset_parameters(self) -> None:
147
+ import torch.nn.init as init
148
+
149
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
150
+
151
+ def forward(self, hidden_states: torch.Tensor):
152
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
153
+ logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
154
+ routing_weights = F.softmax(logits, dim=1, dtype=torch.float)
155
+ scores, topk_idx = torch.topk(routing_weights, self.top_k, dim=-1)
156
+ scores = scores.type_as(logits)
157
+ topk_weight = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
158
+ return topk_idx, topk_weight, logits
159
+
160
+
161
+ class MapleSparseMoeBlock(nn.Module):
162
+ """Unfused Maple mixture-of-experts block."""
163
+
164
+ def __init__(self, config) -> None:
165
+ super().__init__()
166
+ self.config = config
167
+ self.num_experts_per_tok = config.num_experts_per_tok
168
+ self._setup_experts()
169
+ self.gate = MapleGate(config)
170
+
171
+ def _setup_experts(self):
172
+ self.experts = nn.ModuleList(
173
+ [
174
+ MapleMLP(
175
+ config=self.config,
176
+ intermediate_size=self.config.moe_intermediate_size,
177
+ )
178
+ for _ in range(self.config.num_experts)
179
+ ]
180
+ )
181
+
182
+ def forward(
183
+ self, hidden_states: torch.Tensor
184
+ ) -> tuple[torch.Tensor, torch.Tensor]:
185
+ bsz, seq_len, h = hidden_states.shape
186
+ topk_idx, topk_weight, router_logits = self.gate(hidden_states)
187
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
188
+ flat_topk_idx = topk_idx.view(-1)
189
+
190
+ if self.training:
191
+ hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
192
+ y = torch.empty_like(hidden_states)
193
+ for i, expert in enumerate(self.experts):
194
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
195
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
196
+ y = y.to(hidden_states.dtype).view(bsz, seq_len, h)
197
+ else:
198
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(bsz, seq_len, h)
199
+
200
+ return y, router_logits
201
+
202
+ @torch.no_grad()
203
+ def moe_infer(self, x, topk_ids, topk_weight):
204
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
205
+ cnts.scatter_(1, topk_ids, 1)
206
+ tokens_per_expert = cnts.sum(dim=0)
207
+ idxs = topk_ids.view(-1).argsort()
208
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
209
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
210
+ outputs = []
211
+ start_idx = 0
212
+ for i, num_tokens in enumerate(tokens_per_expert):
213
+ end_idx = start_idx + num_tokens
214
+ if num_tokens == 0:
215
+ continue
216
+ expert = self.experts[i]
217
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
218
+ expert_out = expert(tokens_for_this_expert)
219
+ outputs.append(expert_out.to(x.device))
220
+ start_idx = end_idx
221
+
222
+ outs = torch.cat(outputs, dim=0) if outputs else sorted_tokens.new_empty(0)
223
+ new_x = torch.empty_like(outs)
224
+ new_x[idxs] = outs
225
+ final_out = (
226
+ new_x.view(*topk_ids.shape, -1)
227
+ .type(topk_weight.dtype)
228
+ .mul_(topk_weight.unsqueeze(dim=-1))
229
+ .sum(dim=1)
230
+ .type(new_x.dtype)
231
+ )
232
+ return final_out
233
+
234
+
235
+ class MapleAttention(nn.Module):
236
+ """Maple grouped-query attention implemented with FlashAttention."""
237
+
238
+ def __init__(self, config: MapleConfig, layer_idx: Optional[int] = None):
239
+ super().__init__()
240
+ self.config = config
241
+ self.layer_idx = layer_idx
242
+ if layer_idx is None:
243
+ logger.warning_once(
244
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
245
+ "lead to errors during the forward call if caching is used. Please pass `layer_idx`."
246
+ )
247
+
248
+ self.attention_dropout = config.attention_dropout
249
+ self.hidden_size = config.hidden_size
250
+ self.num_heads = config.num_attention_heads
251
+ self.head_dim = config.head_dim or self.hidden_size // self.num_heads
252
+ self.scaling = self.head_dim**-0.5
253
+
254
+ self.num_key_value_heads = config.num_key_value_heads
255
+ self.is_causal = True
256
+
257
+ layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
258
+ self.sliding_window = config.sliding_window if layer_type == "sliding_attention" else None
259
+
260
+ self.q_proj = nn.Linear(
261
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=False
262
+ )
263
+ self.k_proj = nn.Linear(
264
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False
265
+ )
266
+ self.v_proj = nn.Linear(
267
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False
268
+ )
269
+
270
+ self.q_norm = MapleRMSNorm(self.head_dim, eps=config.rms_norm_eps)
271
+ self.k_norm = MapleRMSNorm(self.head_dim, eps=config.rms_norm_eps)
272
+
273
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.use_bias)
274
+
275
+ def forward(
276
+ self,
277
+ hidden_states: torch.Tensor,
278
+ attention_mask: Optional[torch.Tensor] = None,
279
+ position_ids: Optional[torch.LongTensor] = None,
280
+ past_key_value: Optional[Cache] = None,
281
+ output_attentions: bool = False,
282
+ use_cache: bool = False,
283
+ cache_position: Optional[torch.LongTensor] = None,
284
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = None,
285
+ **kwargs,
286
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
287
+ bsz, q_len, _ = hidden_states.size()
288
+ qkv_weight = torch.cat([self.q_proj.weight, self.k_proj.weight, self.v_proj.weight], dim=0)
289
+ out_qkv = torch.nn.functional.linear(hidden_states, qkv_weight)
290
+ cos, sin, _freqs = position_embeddings
291
+ qkv = out_qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
292
+
293
+ query_states, key_states, value_states = qkv.split(
294
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
295
+ )
296
+ query_states = query_states.transpose(1, 2)
297
+ key_states = key_states.transpose(1, 2)
298
+ value_states = value_states.transpose(1, 2)
299
+
300
+ query_states = self.q_norm(query_states)
301
+ key_states = self.k_norm(key_states)
302
+ if self.sliding_window is not None:
303
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
304
+
305
+ if use_cache and past_key_value is not None:
306
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
307
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
308
+
309
+ attn_output, attn_weights = flash_attention_forward(
310
+ self,
311
+ query_states,
312
+ key_states,
313
+ value_states,
314
+ attention_mask,
315
+ dropout=self.attention_dropout if self.training else 0.0,
316
+ position_ids=position_ids,
317
+ scaling=self.scaling,
318
+ sliding_window=self.sliding_window,
319
+ **kwargs,
320
+ )
321
+
322
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
323
+ attn_output = torch.nn.functional.linear(attn_output, self.o_proj.weight)
324
+
325
+ if not output_attentions:
326
+ attn_weights = None
327
+
328
+ return attn_output, attn_weights, past_key_value
329
+
330
+
331
+ class MapleDecoderLayer(nn.Module):
332
+ def __init__(self, config: MapleConfig, layer_idx: int):
333
+ super().__init__()
334
+ self.self_attn = MapleAttention(config=config, layer_idx=layer_idx)
335
+
336
+ self.mlp = MapleSparseMoeBlock(config)
337
+
338
+ self.input_layernorm = MapleRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
339
+ self.post_attention_layernorm = MapleRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
340
+
341
+ def forward(
342
+ self,
343
+ hidden_states: torch.Tensor,
344
+ attention_mask: Optional[torch.Tensor] = None,
345
+ position_ids: Optional[torch.LongTensor] = None,
346
+ past_key_value: Optional[Cache] = None,
347
+ output_attentions: Optional[bool] = False,
348
+ output_router_logits: Optional[bool] = False,
349
+ use_cache: Optional[bool] = False,
350
+ cache_position: Optional[torch.LongTensor] = None,
351
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = None,
352
+ **kwargs,
353
+ ) -> Tuple[
354
+ torch.Tensor,
355
+ Optional[torch.Tensor],
356
+ Optional[Cache],
357
+ torch.Tensor,
358
+ Optional[torch.Tensor],
359
+ ]:
360
+ residual = hidden_states
361
+ hidden_states = self.input_layernorm(hidden_states)
362
+
363
+ attn_out, self_attn_weights, present_key_value = self.self_attn(
364
+ hidden_states=hidden_states,
365
+ attention_mask=attention_mask,
366
+ position_ids=position_ids,
367
+ past_key_value=past_key_value,
368
+ output_attentions=bool(output_attentions),
369
+ use_cache=bool(use_cache),
370
+ cache_position=cache_position,
371
+ position_embeddings=position_embeddings,
372
+ **kwargs,
373
+ )
374
+ hidden_states = residual + attn_out
375
+
376
+ residual = hidden_states
377
+ hidden_states = self.post_attention_layernorm(hidden_states)
378
+
379
+ hidden_states, router_logits = self.mlp(hidden_states)
380
+ aux_loss = 0.0
381
+
382
+ hidden_states = residual + hidden_states.to(residual.device)
383
+
384
+ return (
385
+ hidden_states,
386
+ self_attn_weights,
387
+ present_key_value,
388
+ aux_loss,
389
+ router_logits,
390
+ )
391
+
392
+
393
+ @add_start_docstrings(
394
+ "The bare Maple model, which outputs raw hidden states without a task-specific head.",
395
+ )
396
+ class MaplePreTrainedModel(PreTrainedModel):
397
+ config_class = MapleConfig
398
+ base_model_prefix = "model"
399
+ supports_gradient_checkpointing = True
400
+ _no_split_modules = ["MapleDecoderLayer"]
401
+ _skip_keys_device_placement = "past_key_values"
402
+ _supports_attention_backend = True
403
+ _supports_flash_attn_2 = True
404
+ _supports_sdpa = True
405
+ _supports_cache_class = True
406
+
407
+ def _init_weights(self, module):
408
+ std = self.config.initializer_range
409
+ if isinstance(module, nn.Linear):
410
+ module.weight.data.normal_(mean=0.0, std=std)
411
+ if module.bias is not None:
412
+ module.bias.data.zero_()
413
+ elif isinstance(module, nn.Embedding):
414
+ module.weight.data.normal_(mean=0.0, std=std)
415
+ if module.padding_idx is not None:
416
+ module.weight.data[module.padding_idx].zero_()
417
+
418
+
419
+ @add_start_docstrings(
420
+ "The bare Maple model, which outputs raw hidden states without a task-specific head.",
421
+ )
422
+ class MapleModel(MaplePreTrainedModel):
423
+ def __init__(self, config: MapleConfig):
424
+ super().__init__(config)
425
+ self.padding_idx = config.pad_token_id
426
+ self.vocab_size = config.vocab_size
427
+
428
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
429
+
430
+ layers = []
431
+ for layer_idx in range(config.num_hidden_layers):
432
+ layers.append(MapleDecoderLayer(config, layer_idx))
433
+ self.layers = nn.ModuleList(layers)
434
+ self.config = config
435
+
436
+ self.norm = MapleRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
437
+ self.rotary_emb = MapleRotaryEmbedding(config=config)
438
+ self.gradient_checkpointing = False
439
+ self.post_init()
440
+
441
+ def get_input_embeddings(self):
442
+ return self.word_embeddings
443
+
444
+ def set_input_embeddings(self, value):
445
+ self.word_embeddings = value
446
+
447
+ def prepare_fa2_from_position_ids(self, position_ids: torch.Tensor):
448
+ position_ids = position_ids.flatten()
449
+ total_tokens = position_ids.numel()
450
+ indices_q = torch.arange(total_tokens, device=position_ids.device, dtype=torch.int32)
451
+
452
+ starts = indices_q[position_ids == 0]
453
+
454
+ # If no segment-start markers exist (common in decoding where pos ids are offset),
455
+ # treat as a single sequence.
456
+ if starts.numel() == 0:
457
+ cu_seq_lens = torch.tensor([0, total_tokens], device=position_ids.device, dtype=torch.int32)
458
+ else:
459
+ if starts[0].item() != 0:
460
+ starts = torch.cat([starts.new_zeros(1), starts], dim=0)
461
+ if starts[-1].item() != total_tokens:
462
+ starts = torch.cat([starts, starts.new_tensor([total_tokens])], dim=0)
463
+ cu_seq_lens = starts
464
+
465
+ max_length = (cu_seq_lens[1:] - cu_seq_lens[:-1]).max().item()
466
+ return (indices_q, (cu_seq_lens, cu_seq_lens), (max_length, max_length))
467
+
468
+ def forward(
469
+ self,
470
+ input_ids: torch.LongTensor = None,
471
+ attention_mask: Optional[torch.Tensor] = None,
472
+ position_ids: Optional[torch.LongTensor] = None,
473
+ past_key_values: Optional[Cache] = None,
474
+ inputs_embeds: Optional[torch.FloatTensor] = None,
475
+ use_cache: Optional[bool] = None,
476
+ output_attentions: Optional[bool] = None,
477
+ output_hidden_states: Optional[bool] = None,
478
+ output_router_logits: Optional[bool] = None,
479
+ return_dict: Optional[bool] = None,
480
+ cache_position: Optional[torch.LongTensor] = None,
481
+ **kwargs,
482
+ ) -> Union[Tuple, MapleModelOutputWithPast]:
483
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
484
+ output_router_logits = (
485
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
486
+ )
487
+ output_hidden_states = (
488
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
489
+ )
490
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
491
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
492
+
493
+ if (input_ids is None) == (inputs_embeds is None):
494
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
495
+
496
+ if self.gradient_checkpointing and self.training and use_cache:
497
+ logger.warning_once(
498
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
499
+ )
500
+ use_cache = False
501
+
502
+ if use_cache and past_key_values is None:
503
+ past_key_values = DynamicCache()
504
+
505
+ if inputs_embeds is None:
506
+ inputs_embeds = self.word_embeddings(input_ids)
507
+
508
+ forward_batch = kwargs.get("forward_batch", None)
509
+ is_decode_step = False
510
+ forward_mode = getattr(forward_batch, "forward_mode", None) if forward_batch is not None else None
511
+ if forward_mode is not None:
512
+ for mode_name in (
513
+ "is_decode",
514
+ "is_decode_or_idle",
515
+ "is_target_verify",
516
+ "is_draft_decode",
517
+ ):
518
+ mode_fn = getattr(forward_mode, mode_name, None)
519
+ if callable(mode_fn) and bool(mode_fn()):
520
+ is_decode_step = True
521
+ break
522
+
523
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
524
+
525
+ if cache_position is None:
526
+ cache_position = torch.arange(
527
+ past_seen_tokens,
528
+ past_seen_tokens + inputs_embeds.shape[1],
529
+ device=inputs_embeds.device,
530
+ )
531
+
532
+ if position_ids is not None:
533
+ # Expand shared position IDs before preparing packed-sequence metadata.
534
+ batch_size = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
535
+ if position_ids.shape[0] != batch_size:
536
+ position_ids = position_ids.expand(batch_size, -1)
537
+
538
+ # Decode does not need cu_seq_lens/max_length metadata and creating
539
+ # them every step hurts CUDA graph capture stability.
540
+ if (not is_decode_step) and inputs_embeds.shape[1] > 1:
541
+ _, (cu_seq_lens_q, cu_seq_lens_k), (max_length_q, max_length_k) = self.prepare_fa2_from_position_ids(
542
+ position_ids
543
+ )
544
+ kwargs["cu_seq_lens_q"] = cu_seq_lens_q
545
+ kwargs["cu_seq_lens_k"] = cu_seq_lens_k
546
+ kwargs["max_length_q"] = max_length_q
547
+ kwargs["max_length_k"] = max_length_k
548
+
549
+ if position_ids is None:
550
+ position_ids = cache_position.unsqueeze(0)
551
+
552
+ causal_mask = attention_mask
553
+
554
+ hidden_states = inputs_embeds
555
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
556
+
557
+ all_hidden_states = () if output_hidden_states else None
558
+ all_self_attns = () if output_attentions else None
559
+ all_router_logits = () if output_router_logits else None
560
+
561
+ aux_loss_sum = 0.0
562
+
563
+ for decoder_layer in self.layers:
564
+ if output_hidden_states:
565
+ all_hidden_states += (hidden_states,)
566
+
567
+ if self.gradient_checkpointing and self.training:
568
+ layer_outputs = self._gradient_checkpointing_func(
569
+ decoder_layer.__call__,
570
+ hidden_states,
571
+ causal_mask,
572
+ position_ids,
573
+ past_key_values,
574
+ output_attentions,
575
+ output_router_logits,
576
+ use_cache,
577
+ cache_position,
578
+ position_embeddings,
579
+ **kwargs,
580
+ )
581
+ else:
582
+ layer_outputs = decoder_layer(
583
+ hidden_states,
584
+ attention_mask=causal_mask,
585
+ position_ids=position_ids,
586
+ past_key_value=past_key_values,
587
+ output_attentions=output_attentions,
588
+ output_router_logits=output_router_logits,
589
+ use_cache=use_cache,
590
+ cache_position=cache_position,
591
+ position_embeddings=position_embeddings,
592
+ **kwargs,
593
+ )
594
+
595
+ hidden_states = layer_outputs[0]
596
+
597
+ if output_attentions:
598
+ all_self_attns += (layer_outputs[1],)
599
+
600
+ aux_loss_sum = aux_loss_sum + layer_outputs[3]
601
+
602
+ if output_router_logits:
603
+ all_router_logits += (layer_outputs[4],)
604
+
605
+ hidden_states = self.norm(hidden_states)
606
+
607
+ if output_hidden_states:
608
+ all_hidden_states += (hidden_states,)
609
+ moe_layer_count = max(len(self.layers), 1)
610
+ out = MapleModelOutputWithPast(
611
+ last_hidden_state=hidden_states,
612
+ past_key_values=past_key_values if use_cache else None,
613
+ hidden_states=all_hidden_states,
614
+ attentions=all_self_attns,
615
+ router_logits=all_router_logits,
616
+ aux_loss=aux_loss_sum / moe_layer_count,
617
+ )
618
+ return (
619
+ out
620
+ if return_dict
621
+ else (
622
+ out.last_hidden_state,
623
+ out.past_key_values,
624
+ out.hidden_states,
625
+ out.attentions,
626
+ )
627
+ )
628
+
629
+
630
+ class MapleForCausalLM(MaplePreTrainedModel, GenerationMixin):
631
+ _tied_weights_keys = ["lm_head.weight"]
632
+
633
+ def __init__(self, config: MapleConfig):
634
+ super().__init__(config)
635
+ self.model = MapleModel(config)
636
+ self.vocab_size = config.vocab_size
637
+
638
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
639
+ self.post_init()
640
+
641
+ def get_input_embeddings(self):
642
+ return self.model.word_embeddings
643
+
644
+ def set_input_embeddings(self, value):
645
+ self.model.word_embeddings = value
646
+
647
+ def get_output_embeddings(self):
648
+ return self.lm_head
649
+
650
+ def set_output_embeddings(self, new_embeddings):
651
+ self.lm_head = new_embeddings
652
+
653
+ def set_decoder(self, decoder):
654
+ self.model = decoder
655
+
656
+ def get_decoder(self):
657
+ return self.model
658
+
659
+ def forward(
660
+ self,
661
+ input_ids: torch.LongTensor = None,
662
+ attention_mask: Optional[torch.Tensor] = None,
663
+ position_ids: Optional[torch.LongTensor] = None,
664
+ past_key_values: Optional[Cache] = None,
665
+ inputs_embeds: Optional[torch.FloatTensor] = None,
666
+ labels: Optional[torch.Tensor] = None,
667
+ use_cache: Optional[bool] = None,
668
+ output_attentions: Optional[bool] = None,
669
+ output_hidden_states: Optional[bool] = None,
670
+ output_router_logits: Optional[bool] = None,
671
+ return_dict: Optional[bool] = None,
672
+ logits_to_keep: Union[int, torch.Tensor] = 0,
673
+ **kwargs,
674
+ ) -> Union[Tuple, MapleOutputWithPast]:
675
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
676
+ output_hidden_states = (
677
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
678
+ )
679
+ output_router_logits = (
680
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
681
+ )
682
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
683
+
684
+ outputs = self.model(
685
+ input_ids=input_ids,
686
+ attention_mask=attention_mask,
687
+ position_ids=position_ids,
688
+ past_key_values=past_key_values,
689
+ inputs_embeds=inputs_embeds,
690
+ use_cache=use_cache,
691
+ output_attentions=output_attentions,
692
+ output_hidden_states=output_hidden_states,
693
+ output_router_logits=output_router_logits,
694
+ return_dict=True,
695
+ **kwargs,
696
+ )
697
+
698
+ hidden_states = outputs.last_hidden_state
699
+ assert isinstance(hidden_states, torch.Tensor)
700
+
701
+ loss = None
702
+ logits = None
703
+ if labels is not None:
704
+ loss, logits = self.loss_function(hidden_states, self.lm_head.weight, labels)
705
+ else:
706
+ slice_indices = (
707
+ slice(-logits_to_keep, None)
708
+ if isinstance(logits_to_keep, int)
709
+ else logits_to_keep
710
+ )
711
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
712
+ out = MapleOutputWithPast(
713
+ loss=loss,
714
+ aux_loss=getattr(outputs, "aux_loss", 0.0),
715
+ logits=logits,
716
+ past_key_values=outputs.past_key_values if hasattr(outputs, "past_key_values") else None,
717
+ hidden_states=outputs.hidden_states if hasattr(outputs, "hidden_states") else None,
718
+ attentions=outputs.attentions if hasattr(outputs, "attentions") else None,
719
+ router_logits=outputs.router_logits if hasattr(outputs, "router_logits") else None,
720
+ )
721
+ return out if return_dict else out.to_tuple()
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654
tokenizer_config.json ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "clean_up_tokenization_spaces": false,
231
+ "eos_token": "<|im_end|>",
232
+ "errors": "replace",
233
+ "extra_special_tokens": {},
234
+ "model_max_length": 1010000,
235
+ "pad_token": "<|endoftext|>",
236
+ "padding_side": "right",
237
+ "split_special_tokens": false,
238
+ "tokenizer_class": "Qwen2Tokenizer",
239
+ "unk_token": null
240
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff