Leotsia commited on
Commit
f836ab9
·
verified ·
1 Parent(s): 2f0bc96

Upload DRPO checkpoint-450 (MATH-500 64.4)

Browse files
README.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: transformers
4
+ base_model: JetLM/SDAR-1.7B-Chat
5
+ pipeline_tag: text-generation
6
+ tags:
7
+ - diffusion-language-model
8
+ - reinforcement-learning
9
+ - math
10
+ - drpo
11
+ model-index:
12
+ - name: DRPO
13
+ results:
14
+ - task:
15
+ type: text-generation
16
+ name: Text Generation
17
+ dataset:
18
+ type: HuggingFaceH4/MATH-500
19
+ name: MATH-500
20
+ split: test
21
+ metrics:
22
+ - type: accuracy
23
+ name: Accuracy
24
+ value: 64.4
25
+ ---
26
+
27
+ # DRPO
28
+
29
+ DRPO is a full-weight math reasoning checkpoint derived from
30
+ [`JetLM/SDAR-1.7B-Chat`](https://huggingface.co/JetLM/SDAR-1.7B-Chat).
31
+ It equips the SDAR block-diffusion language model with a learned remasking head
32
+ and optimizes the remasking policy with same-state relative rollouts.
33
+
34
+ This repository contains the inference checkpoint saved after 450 optimizer
35
+ updates. Training-state files such as optimizer, scheduler, and RNG states are
36
+ intentionally excluded.
37
+
38
+ ## Evaluation
39
+
40
+ | Benchmark | Split | Metric | Score |
41
+ | --- | --- | --- | ---: |
42
+ | MATH-500 | test (500 examples) | Accuracy | **64.4** |
43
+
44
+ The score corresponds to 322 correct answers out of 500 and was produced with
45
+ the project's OpenCompass-based evaluator on 2026-06-15.
46
+
47
+ The decoding configuration used for this result was:
48
+
49
+ | Setting | Value |
50
+ | --- | ---: |
51
+ | Block length | 4 |
52
+ | Maximum new tokens | 1536 |
53
+ | Sampling temperature | 0.0 |
54
+ | Confidence threshold | 0.95 |
55
+ | Remask policy | learned gap head |
56
+ | Remask threshold | 0.50 |
57
+ | Remask interval | 2 blocks |
58
+ | Remask window | 3 blocks |
59
+ | Remask start | 192 generated tokens |
60
+ | Prefix guard | 192 generated tokens |
61
+ | Tail guard | 1 block |
62
+
63
+ The reported result depends on the custom remasking decoder and these settings;
64
+ it should not be interpreted as the result of the default Transformers text
65
+ generation pipeline.
66
+
67
+ ## Loading the checkpoint
68
+
69
+ The model contains custom SDAR code, so `trust_remote_code=True` is required.
70
+
71
+ ```python
72
+ from transformers import AutoModelForCausalLM, AutoTokenizer
73
+
74
+ model_id = "Leotsia/DRPO"
75
+
76
+ tokenizer = AutoTokenizer.from_pretrained(
77
+ model_id,
78
+ trust_remote_code=True,
79
+ )
80
+ model = AutoModelForCausalLM.from_pretrained(
81
+ model_id,
82
+ trust_remote_code=True,
83
+ torch_dtype="auto",
84
+ device_map="auto",
85
+ )
86
+ ```
87
+
88
+ The training and evaluation environment used Transformers 4.52.4. Reproducing
89
+ the reported MATH-500 score requires the project-specific remasking evaluation
90
+ adapter in addition to the checkpoint.
91
+
92
+ ## Training summary
93
+
94
+ - Backbone: `JetLM/SDAR-1.7B-Chat`
95
+ - Training data: 7,490 competition-math training examples
96
+ - Fine-tuning: full parameters
97
+ - Objective: learned remasking policy with same-state relative rollouts
98
+ - Sampled revision branches per example: 8
99
+ - Checkpoint: step 450
100
+
101
+ ## Limitations
102
+
103
+ This is a research checkpoint focused on mathematical reasoning. It has not
104
+ been comprehensively evaluated for general knowledge, factual reliability,
105
+ safety, bias, or multilingual use. Generated reasoning may be incorrect even
106
+ when it is fluent. Applications should validate outputs independently.
107
+
108
+ Because loading executes repository-provided Python code, review the files and
109
+ pin a repository revision in security-sensitive deployments.
110
+
111
+ ## License and attribution
112
+
113
+ The checkpoint is released under Apache-2.0, following the license metadata of
114
+ the SDAR-1.7B-Chat base model. Please also cite and follow the attribution
115
+ guidance of the [SDAR project](https://github.com/JetAstra/SDAR).
added_tokens.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|MASK|>": 151669,
9
+ "<|box_end|>": 151649,
10
+ "<|box_start|>": 151648,
11
+ "<|endoftext|>": 151643,
12
+ "<|file_sep|>": 151664,
13
+ "<|fim_middle|>": 151660,
14
+ "<|fim_pad|>": 151662,
15
+ "<|fim_prefix|>": 151659,
16
+ "<|fim_suffix|>": 151661,
17
+ "<|im_end|>": 151645,
18
+ "<|im_start|>": 151644,
19
+ "<|image_pad|>": 151655,
20
+ "<|object_ref_end|>": 151647,
21
+ "<|object_ref_start|>": 151646,
22
+ "<|quad_end|>": 151651,
23
+ "<|quad_start|>": 151650,
24
+ "<|repo_name|>": 151663,
25
+ "<|video_pad|>": 151656,
26
+ "<|vision_end|>": 151653,
27
+ "<|vision_pad|>": 151654,
28
+ "<|vision_start|>": 151652
29
+ }
chat_template.jinja ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
27
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
28
+ {%- elif message.role == "assistant" %}
29
+ {%- set content = message.content %}
30
+ {%- set reasoning_content = '' %}
31
+ {%- if message.reasoning_content is defined and message.reasoning_content is not none %}
32
+ {%- set reasoning_content = message.reasoning_content %}
33
+ {%- else %}
34
+ {%- if '</think>' in message.content %}
35
+ {%- set content = message.content.split('</think>')[-1].lstrip('\n') %}
36
+ {%- set reasoning_content = message.content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
37
+ {%- endif %}
38
+ {%- endif %}
39
+ {%- if loop.index0 > ns.last_query_index %}
40
+ {%- if loop.last or (not loop.last and reasoning_content) %}
41
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
42
+ {%- else %}
43
+ {{- '<|im_start|>' + message.role + '\n' + content }}
44
+ {%- endif %}
45
+ {%- else %}
46
+ {{- '<|im_start|>' + message.role + '\n' + content }}
47
+ {%- endif %}
48
+ {%- if message.tool_calls %}
49
+ {%- for tool_call in message.tool_calls %}
50
+ {%- if (loop.first and content) or (not loop.first) %}
51
+ {{- '\n' }}
52
+ {%- endif %}
53
+ {%- if tool_call.function %}
54
+ {%- set tool_call = tool_call.function %}
55
+ {%- endif %}
56
+ {{- '<tool_call>\n{"name": "' }}
57
+ {{- tool_call.name }}
58
+ {{- '", "arguments": ' }}
59
+ {%- if tool_call.arguments is string %}
60
+ {{- tool_call.arguments }}
61
+ {%- else %}
62
+ {{- tool_call.arguments | tojson }}
63
+ {%- endif %}
64
+ {{- '}\n</tool_call>' }}
65
+ {%- endfor %}
66
+ {%- endif %}
67
+ {{- '<|im_end|>\n' }}
68
+ {%- elif message.role == "tool" %}
69
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
70
+ {{- '<|im_start|>user' }}
71
+ {%- endif %}
72
+ {{- '\n<tool_response>\n' }}
73
+ {{- message.content }}
74
+ {{- '\n</tool_response>' }}
75
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
76
+ {{- '<|im_end|>\n' }}
77
+ {%- endif %}
78
+ {%- endif %}
79
+ {%- endfor %}
80
+ {%- if add_generation_prompt %}
81
+ {{- '<|im_start|>assistant\n' }}
82
+ {%- if enable_thinking is defined and enable_thinking is false %}
83
+ {{- '<think>\n\n</think>\n\n' }}
84
+ {%- endif %}
85
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "SDARForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_sdar.SDARConfig",
9
+ "AutoModel": "modeling_sdar.SDARForCausalLM",
10
+ "AutoModelForCausalLM": "modeling_sdar.SDARForCausalLM"
11
+ },
12
+ "block_size": 4,
13
+ "bos_token_id": 151643,
14
+ "debug": false,
15
+ "eos_token_id": 151643,
16
+ "ep_size": 1,
17
+ "fuse_cross_entropy": true,
18
+ "gap_curriculum_enable": true,
19
+ "gap_curriculum_min_coupling": 0.25,
20
+ "gap_curriculum_warmup_ratio": 0.15,
21
+ "gap_diffusion_loss_weight": 0.0,
22
+ "gap_enable": true,
23
+ "gap_global_loss_weight": 0.0,
24
+ "gap_grpo_action_granularity": "threshold",
25
+ "gap_grpo_advantage_eps": 0.0001,
26
+ "gap_grpo_anchor_bias_power": 2.0,
27
+ "gap_grpo_branch_debug_interval": 5,
28
+ "gap_grpo_branch_debug_max_branches": 0,
29
+ "gap_grpo_branch_debug_max_chars": 600,
30
+ "gap_grpo_branch_debug_max_examples": 1,
31
+ "gap_grpo_branch_debug_once": false,
32
+ "gap_grpo_candidate_window_blocks": 4,
33
+ "gap_grpo_clip_eps": 0.15,
34
+ "gap_grpo_correct_threshold": 0.5,
35
+ "gap_grpo_dense_reward_weight": 0.2,
36
+ "gap_grpo_diverse_rollbacks": false,
37
+ "gap_grpo_entropy_coef": 0.05,
38
+ "gap_grpo_fixed_visible_blocks": true,
39
+ "gap_grpo_format_reward_weight": 0.0,
40
+ "gap_grpo_initial_rollout_temperature": 0.9,
41
+ "gap_grpo_kl_coef": 0.02,
42
+ "gap_grpo_loss_weight": 0.35,
43
+ "gap_grpo_max_correct_count": -1,
44
+ "gap_grpo_min_correct_count": 1,
45
+ "gap_grpo_min_visible_blocks": 3,
46
+ "gap_grpo_mixed_terminal_filter": false,
47
+ "gap_grpo_num_parents": 1,
48
+ "gap_grpo_num_samples": 8,
49
+ "gap_grpo_ref_model_path": "/work/leotsia0416/projects/SDAR/training/model/SDAR-1.7B-Chat",
50
+ "gap_grpo_remask_penalty": 0.0,
51
+ "gap_grpo_rollout_temperature": 0.9,
52
+ "gap_grpo_rollout_top_k": 128,
53
+ "gap_grpo_rollout_top_p": 0.98,
54
+ "gap_grpo_sample_prob_eps": 0.0001,
55
+ "gap_grpo_sft_ce_weight": 0.0,
56
+ "gap_grpo_terminal_reward_weight": 2.0,
57
+ "gap_grpo_terminal_rollout_scope": "all",
58
+ "gap_grpo_terminal_rollout_strategy": "low_confidence_dynamic",
59
+ "gap_grpo_use_baseline_branch": false,
60
+ "gap_grpo_value_baseline_weight": 0.0,
61
+ "gap_grpo_value_loss_weight": 0.0,
62
+ "gap_loss_scope": "all",
63
+ "gap_min_reveal_tokens": 1,
64
+ "gap_noisy_context_loss_weight": 0.05,
65
+ "gap_projected_aux_loss_weight": 0.0,
66
+ "gap_remask_adv_max_candidates": 1,
67
+ "gap_remask_adv_warmup_ratio": 0.1,
68
+ "gap_remask_default_p_mask": 1.0,
69
+ "gap_remask_loss_weight": 0.0,
70
+ "gap_remask_stage_mode": "two_stage",
71
+ "gap_remask_supervision": "adv_bce",
72
+ "gap_remask_threshold": 0.45,
73
+ "gap_reveal_ratio": 0.25,
74
+ "gap_rollout_confidence_threshold": 0.92,
75
+ "gap_rollout_scope": "frontier_block",
76
+ "gap_rollout_steps": 3,
77
+ "gap_rollout_strategy": "sequential",
78
+ "gap_training_mode": "remask",
79
+ "head_dim": 128,
80
+ "hidden_act": "silu",
81
+ "hidden_size": 2048,
82
+ "initializer_range": 0.02,
83
+ "intermediate_size": 6144,
84
+ "mask_token_id": 151669,
85
+ "max_position_embeddings": 32768,
86
+ "max_window_layers": 28,
87
+ "micro_forward": false,
88
+ "model_type": "sdar",
89
+ "num_attention_heads": 16,
90
+ "num_hidden_layers": 28,
91
+ "num_key_value_heads": 8,
92
+ "rms_norm_eps": 1e-06,
93
+ "rope_scaling": null,
94
+ "rope_theta": 1000000,
95
+ "skip_checkpoint": false,
96
+ "sliding_window": null,
97
+ "tie_word_embeddings": false,
98
+ "torch_dtype": "float32",
99
+ "transformers_version": "4.52.4",
100
+ "use_cache": false,
101
+ "use_deepep": false,
102
+ "use_sliding_window": false,
103
+ "vocab_size": 151936
104
+ }
configuration_sdar.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """SDAR model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.modeling_rope_utils import rope_config_validation
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class SDARConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`SDARModel`]. It is used to instantiate a
28
+ SDAR model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of
30
+ SDAR-1.7B [DiffuOpen/SDAR-1.7B-Chat](https://huggingface.co/DiffuOpen/SDAR-1.7B-Chat/).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 151936):
38
+ Vocabulary size of the SDAR model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`SDARModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 22016):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 32):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
55
+ head_dim (`int`, *optional*, defaults to 128):
56
+ The attention head dimension.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ rope_scaling (`Dict`, *optional*):
73
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
74
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
75
+ accordingly.
76
+ Expected contents:
77
+ `rope_type` (`str`):
78
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
79
+ 'llama3'], with 'default' being the original RoPE implementation.
80
+ `factor` (`float`, *optional*):
81
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
82
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
83
+ original maximum pre-trained length.
84
+ `original_max_position_embeddings` (`int`, *optional*):
85
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
86
+ pretraining.
87
+ `attention_factor` (`float`, *optional*):
88
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
89
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
90
+ `factor` field to infer the suggested value.
91
+ `beta_fast` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 32.
94
+ `beta_slow` (`float`, *optional*):
95
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
96
+ ramp function. If unspecified, it defaults to 1.
97
+ `short_factor` (`List[float]`, *optional*):
98
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
99
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
100
+ size divided by the number of attention heads divided by 2
101
+ `long_factor` (`List[float]`, *optional*):
102
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
103
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
104
+ size divided by the number of attention heads divided by 2
105
+ `low_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
107
+ `high_freq_factor` (`float`, *optional*):
108
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
109
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
110
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
111
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
112
+ Whether to use sliding window attention.
113
+ sliding_window (`int`, *optional*, defaults to 4096):
114
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
115
+ max_window_layers (`int`, *optional*, defaults to 28):
116
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
117
+ attention_dropout (`float`, *optional*, defaults to 0.0):
118
+ The dropout ratio for the attention probabilities.
119
+
120
+ ```python
121
+ >>> from transformers import SDARModel, SDARConfig
122
+
123
+ >>> # Initializing a SDAR style configuration
124
+ >>> configuration = SDARConfig()
125
+
126
+ >>> # Initializing a model from the SDAR-8B style configuration
127
+ >>> model = SDARModel(configuration)
128
+
129
+ >>> # Accessing the model configuration
130
+ >>> configuration = model.config
131
+ ```"""
132
+
133
+ model_type = "sdar"
134
+ keys_to_ignore_at_inference = ["past_key_values"]
135
+
136
+ # Default tensor parallel plan for base model `SDAR`
137
+ base_model_tp_plan = {
138
+ "layers.*.self_attn.q_proj": "colwise",
139
+ "layers.*.self_attn.k_proj": "colwise",
140
+ "layers.*.self_attn.v_proj": "colwise",
141
+ "layers.*.self_attn.o_proj": "rowwise",
142
+ "layers.*.mlp.gate_proj": "colwise",
143
+ "layers.*.mlp.up_proj": "colwise",
144
+ "layers.*.mlp.down_proj": "rowwise",
145
+ }
146
+ base_model_pp_plan = {
147
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
148
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
149
+ "norm": (["hidden_states"], ["hidden_states"]),
150
+ }
151
+
152
+ def __init__(
153
+ self,
154
+ vocab_size=151936,
155
+ hidden_size=4096,
156
+ intermediate_size=22016,
157
+ num_hidden_layers=32,
158
+ num_attention_heads=32,
159
+ num_key_value_heads=32,
160
+ head_dim=128,
161
+ hidden_act="silu",
162
+ max_position_embeddings=32768,
163
+ initializer_range=0.02,
164
+ rms_norm_eps=1e-6,
165
+ use_cache=True,
166
+ tie_word_embeddings=False,
167
+ rope_theta=10000.0,
168
+ rope_scaling=None,
169
+ attention_bias=False,
170
+ use_sliding_window=False,
171
+ sliding_window=4096,
172
+ max_window_layers=28,
173
+ attention_dropout=0.0,
174
+ **kwargs,
175
+ ):
176
+ self.vocab_size = vocab_size
177
+ self.max_position_embeddings = max_position_embeddings
178
+ self.hidden_size = hidden_size
179
+ self.intermediate_size = intermediate_size
180
+ self.num_hidden_layers = num_hidden_layers
181
+ self.num_attention_heads = num_attention_heads
182
+ self.use_sliding_window = use_sliding_window
183
+ self.sliding_window = sliding_window # we check `use_sliding_window` in the modeling code
184
+ self.max_window_layers = max_window_layers
185
+
186
+ # for backward compatibility
187
+ if num_key_value_heads is None:
188
+ num_key_value_heads = num_attention_heads
189
+
190
+ self.num_key_value_heads = num_key_value_heads
191
+ self.head_dim = head_dim
192
+ self.hidden_act = hidden_act
193
+ self.initializer_range = initializer_range
194
+ self.rms_norm_eps = rms_norm_eps
195
+ self.use_cache = use_cache
196
+ self.rope_theta = rope_theta
197
+ self.rope_scaling = rope_scaling
198
+ self.attention_bias = attention_bias
199
+ self.attention_dropout = attention_dropout
200
+ # Validate the correctness of rotary position embeddings parameters
201
+ # BC: if there is a 'type' field, move it to 'rope_type'.
202
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
203
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
204
+ rope_config_validation(self)
205
+
206
+ super().__init__(
207
+ tie_word_embeddings=tie_word_embeddings,
208
+ **kwargs,
209
+ )
210
+
211
+
212
+ __all__ = ["SDARConfig"]
fused_linear_diffusion_cross_entropy.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Code adapted from
4
+ # https://github.com/fla-org/flash-linear-attention/blob/main/fla/modules/fused_linear_cross_entropy.py
5
+ # Implementation of element-wise division of cross entropy loss
6
+
7
+
8
+ # Code adapted from
9
+ # https://github.com/linkedin/Liger-Kernel/blob/main/src/liger_kernel/ops/fused_linear_cross_entropy.py
10
+
11
+ from functools import partial
12
+ from typing import Optional, Tuple
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import triton
18
+ import triton.language as tl
19
+ from torch.distributed import DeviceMesh
20
+ from torch.distributed.tensor import DTensor, Replicate, Shard, distribute_module
21
+ from torch.distributed.tensor.parallel import ParallelStyle
22
+
23
+ # The hard limit of TRITON_MAX_TENSOR_NUMEL is 1048576
24
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/language/core.py#L19
25
+ # However, setting limit as 65536 as in LayerNorm tutorial is faster because of less register spilling
26
+ # The optimal maximum block size depends on your hardware, your kernel, and your dtype
27
+ MAX_FUSED_SIZE = 65536 // 2
28
+
29
+
30
+ @triton.heuristics({
31
+ 'HAS_SCALE': lambda args: args['scale'] is not None
32
+ })
33
+ @triton.autotune(
34
+ configs=[
35
+ triton.Config({}, num_warps=num_warps)
36
+ for num_warps in [1, 2, 4, 8, 16, 32]
37
+ ],
38
+ key=['D']
39
+ )
40
+ @triton.jit
41
+ def logsumexp_fwd_kernel(
42
+ x,
43
+ z,
44
+ scale,
45
+ D: tl.constexpr,
46
+ B: tl.constexpr,
47
+ HAS_SCALE: tl.constexpr
48
+ ):
49
+ i_n, i_d = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64)
50
+ o_d = i_d * B + tl.arange(0, B)
51
+ m_d = o_d < D
52
+
53
+ b_x = tl.load(x + i_n * D + o_d, mask=m_d, other=-float('inf'))
54
+ if HAS_SCALE:
55
+ b_x = b_x * scale
56
+ b_m = tl.max(b_x, 0)
57
+ b_z = tl.log(tl.sum(tl.exp(b_x - b_m), 0)) + b_m
58
+ tl.store(z + i_n * tl.cdiv(D, B) + i_d, b_z)
59
+
60
+
61
+ def logsumexp_fwd(
62
+ x,
63
+ scale: Optional[float] = None,
64
+ dtype: Optional[torch.dtype] = None
65
+ ):
66
+ r"""
67
+ Compute the logsumexp of the input tensor over the last dimension.
68
+
69
+ Args:
70
+ x (Tensor):
71
+ The input tensor of any shape.
72
+ scale (Optional[float]):
73
+ The scale applied to the input tensor. Default: `None`.
74
+ dtype (Optional[torch.dtype]):
75
+ The data type of the output tensor. Default: `None`.
76
+ Returns:
77
+ Tensor: The logsumexp of the input tensor.
78
+ """
79
+
80
+ shape = x.shape
81
+ x = x.view(-1, shape[-1])
82
+ N, D = x.shape
83
+ B = min(triton.next_power_of_2(D), 64 * 1024)
84
+ ND = triton.cdiv(D, B)
85
+
86
+ z = x.new_empty(N, ND, dtype=torch.float)
87
+ logsumexp_fwd_kernel[(N, ND)](
88
+ x=x,
89
+ z=z,
90
+ scale=scale,
91
+ D=D,
92
+ B=B
93
+ )
94
+ z = z.logsumexp(-1).view(*shape[:-1])
95
+ if dtype is not None and dtype != torch.float:
96
+ z = z.to(dtype)
97
+ return z
98
+
99
+ @triton.jit
100
+ def cross_entropy_kernel(
101
+ logits,
102
+ lse,
103
+ target,
104
+ p_mask,
105
+ loss,
106
+ total,
107
+ ignore_index,
108
+ label_smoothing: tl.constexpr,
109
+ logit_scale: tl.constexpr,
110
+ reduction: tl.constexpr,
111
+ V: tl.constexpr,
112
+ BV: tl.constexpr
113
+ ):
114
+ """
115
+ This kernel computes both cross entropy loss and the gradient of the input.
116
+ We only consider hard label + mean reduction for now.
117
+ Please refer to https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html for the math.
118
+
119
+ Args:
120
+ logits:
121
+ Pointer to logits tensor.
122
+ lse:
123
+ Pointer to logsumexp tensor.
124
+ target: Pointer to target tensor.
125
+ loss:
126
+ Pointer to tensor to store the loss.
127
+ V (int):
128
+ The number of columns in the input tensor.
129
+ total (int):
130
+ The number of non-ignored classes.
131
+ ignore_index (int):
132
+ The index to ignore in the target.
133
+ label_smoothing (float):
134
+ The amount of smoothing when computing the loss, where 0.0 means no smoothing.
135
+ reduction (str):
136
+ The string for the reduction to apply
137
+ BV (int):
138
+ The block size for vocab.
139
+ """
140
+
141
+ # https://github.com/triton-lang/triton/issues/1058
142
+ # If B*T*V is too large, i_n * stride will overflow out of int32, so we convert to int64
143
+ i_n = tl.program_id(0).to(tl.int64)
144
+ NV = tl.cdiv(V, BV)
145
+
146
+ # 1. Load target first because if the target is ignore_index, we can return right away
147
+ b_y = tl.load(target + i_n)
148
+ # load p_mask
149
+ b_p_mask = tl.load(p_mask + i_n)
150
+
151
+ # 2. locate the start index
152
+ logits += i_n * V
153
+
154
+ if b_y == ignore_index:
155
+ # set all x as 0
156
+ for i in range(0, V, BV):
157
+ o_v = i + tl.arange(0, BV)
158
+ tl.store(logits + o_v, 0.0, mask=o_v < V)
159
+ return
160
+
161
+ # Online softmax: 2 loads + 1 store (compared with 3 loads + 1 store for the safe softmax)
162
+ # Refer to Algorithm 3 in the paper: https://arxiv.org/pdf/1805.02867
163
+
164
+ # 3. [Online softmax] first pass: compute logsumexp
165
+ # we did this in anouter kernel
166
+ b_l = tl.load(logits + b_y) * logit_scale
167
+ b_lse = tl.load(lse + i_n)
168
+
169
+ # 4. Calculate the loss
170
+ # loss = lse - logits_l
171
+ # celoss = -log(q_y) = -log(softmax(x_y))
172
+ b_loss = (b_lse - b_l) / b_p_mask # Diffusion Scaled '1/t'
173
+
174
+ # Label smoothing is a general case of normal cross entropy
175
+ # See the full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issue-2503665310
176
+ b_z = 0.0
177
+ eps = label_smoothing / V
178
+
179
+ # We need tl.debug_barrier() as mentioned in
180
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/ops/cross_entropy.py#L34
181
+ tl.debug_barrier()
182
+
183
+ # 5. [Online Softmax] Second pass: compute gradients
184
+ # For 'mean' reduction, gradients are normalized by number of non-ignored elements
185
+ # dx_y = (softmax(x_y) - 1) / N
186
+ # dx_i = softmax(x_i) / N, i != y
187
+ # For label smoothing:
188
+ # dx_i = (softmax(x_y) - label_smoothing / V) / N, i != y
189
+ # dx_y = (softmax(x_y) - label_smoothing / V - (1 - label_smoothing)) / N
190
+ # = dx_i - (1 - label_smoothing) / N
191
+ for iv in range(0, NV):
192
+ o_v = iv * BV + tl.arange(0, BV)
193
+ b_logits = tl.load(logits + o_v, mask=o_v < V, other=float('-inf')) * logit_scale
194
+ if label_smoothing > 0:
195
+ # scale X beforehand to avoid overflow
196
+ b_z += tl.sum(tl.where(o_v < V, -eps * b_logits, 0.0))
197
+ b_p = (tl.exp(b_logits - b_lse) - eps) * logit_scale
198
+ b_p /= b_p_mask # 修改
199
+ if reduction == "mean":
200
+ b_p = b_p / total
201
+ tl.store(logits + o_v, b_p, mask=o_v < V)
202
+
203
+ tl.debug_barrier()
204
+
205
+ # Orginal loss = H(q, p), with label smoothing regularization = H(q', p) and (label_smoothing / V) = eps
206
+ # H(q', p) = (1 - label_smoothing) * H(q, p) + label_smoothing * H(u, p)
207
+ # = (1 - label_smoothing) * H(q, p) + eps * sum(logsoftmax(x_i))
208
+ # By using m (global max of xi) and d (sum of e^(xi-m)), we can simplify as:
209
+ # = (1 - label_smoothing) * H(q, p) + (-sum(x_i * eps) + label_smoothing * (m + logd))
210
+ # Refer to H(q', p) in section 7 of the paper:
211
+ # https://arxiv.org/pdf/1512.00567
212
+ # pytorch:
213
+ # https://github.com/pytorch/pytorch/blob/2981534f54d49fa3a9755c9b0855e7929c2527f0/aten/src/ATen/native/LossNLL.cpp#L516
214
+ # See full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issuecomment-2333753087
215
+ if label_smoothing > 0:
216
+ b_loss = b_loss * (1 - label_smoothing) + (b_z + label_smoothing * b_lse)
217
+
218
+ # 6. Specially handle the i==y case where `dx_y = (softmax(x_y) - (1 - label_smoothing) / N`
219
+ b_l = tl.load(logits + b_y)
220
+
221
+ # Normalize the loss by the number of non-ignored elements if reduction is "mean"
222
+ if reduction == 'mean':
223
+ b_loss = b_loss / total
224
+ # b_l += (label_smoothing - 1) / total * logit_scale
225
+ # b_l has already been divided by b_p_mask and total
226
+ b_l += (label_smoothing - 1) / b_p_mask / total * logit_scale
227
+ else:
228
+ # b_l += (label_smoothing - 1) * logit_scale
229
+ b_l += (label_smoothing - 1) / b_p_mask * logit_scale
230
+
231
+ tl.store(loss + i_n, b_loss)
232
+ tl.store(logits + b_y, b_l)
233
+
234
+
235
+ @triton.jit
236
+ def elementwise_mul_kernel(
237
+ x,
238
+ g,
239
+ N: tl.constexpr,
240
+ B: tl.constexpr
241
+ ):
242
+ """
243
+ This function multiplies each element of the tensor pointed by x with the value pointed by g.
244
+ The multiplication is performed in-place on the tensor pointed by x.
245
+
246
+ Parameters:
247
+ x:
248
+ Pointer to the input tensor.
249
+ g:
250
+ Pointer to the gradient output value.
251
+ N (int):
252
+ The number of columns in the input tensor.
253
+ B (int):
254
+ The block size for Triton operations.
255
+ """
256
+
257
+ # Get the program ID and convert it to int64 to avoid overflow
258
+ i_x = tl.program_id(0).to(tl.int64)
259
+ o_x = i_x * B + tl.arange(0, B)
260
+
261
+ # Load the gradient output value
262
+ b_g = tl.load(g)
263
+ b_x = tl.load(x + o_x, mask=o_x < N)
264
+ tl.store(x + o_x, b_x * b_g, mask=o_x < N)
265
+
266
+
267
+ def fused_linear_cross_entropy_forward(
268
+ x: torch.Tensor,
269
+ target: torch.LongTensor,
270
+ weight: torch.Tensor,
271
+ bias: torch.Tensor = None,
272
+ p_mask: torch.Tensor = None,
273
+ ignore_index: int = -100,
274
+ label_smoothing: float = 0.0,
275
+ logit_scale: float = 1.0,
276
+ num_chunks: int = 8,
277
+ reduction: str = "mean"
278
+ ):
279
+ device = x.device
280
+ # inputs have shape: [N, H]
281
+ # materialized activations will have shape: [N, V]
282
+ # the increase in memory = [N, V]
283
+ # reduction can be achieved by partitioning the number of tokens N into smaller chunks.
284
+
285
+ # ideally, we would like to achieve the same memory consumption as [N, H],
286
+ # so the expected chunk size should be:
287
+ # NC = ceil(V / H)
288
+ # C = ceil(N / NC)
289
+ # for ex: N = 4096*4, V = 32000, H = 4096 ==> NC = 8, C = ceil(N / NC) = 2048
290
+ N, H, V = *x.shape, weight.shape[0]
291
+ BV = min(MAX_FUSED_SIZE, triton.next_power_of_2(V))
292
+ # TODO: in real cases, we may need to limit the number of chunks NC to
293
+ # ensure the precisions of accumulated gradients
294
+ NC = min(num_chunks, triton.cdiv(V, H))
295
+ C = triton.next_power_of_2(triton.cdiv(N, NC))
296
+ NC = triton.cdiv(N, C)
297
+
298
+ # [N, H]
299
+ dx = torch.zeros_like(x, device=device)
300
+ # [V, H]
301
+ dw = torch.zeros_like(weight, device=device, dtype=torch.float) if weight is not None else None
302
+ # [V]
303
+ db = torch.zeros_like(bias, device=device, dtype=torch.float) if bias is not None else None
304
+ # [N]
305
+ loss = torch.zeros(N, device=device, dtype=torch.float)
306
+
307
+ total = target.ne(ignore_index).sum().item()
308
+
309
+ for ic in range(NC):
310
+ start, end = ic * C, min((ic + 1) * C, N)
311
+ # [C, N]
312
+ c_x = x[start:end]
313
+ # when doing matmul, use the original precision
314
+ # [C, V]
315
+ c_logits = F.linear(c_x, weight, bias)
316
+ c_target = target[start:end]
317
+ c_p_mask = p_mask[start:end]
318
+ # [C]
319
+ # keep lse in fp32 to maintain precision
320
+ c_lse = logsumexp_fwd(c_logits, scale=logit_scale, dtype=torch.float)
321
+
322
+ # unreduced loss
323
+ c_loss = loss[start:end]
324
+
325
+ # Here we calculate the gradient of c_logits in place so we can save memory.
326
+ cross_entropy_kernel[(c_logits.shape[0],)](
327
+ logits=c_logits,
328
+ lse=c_lse,
329
+ target=c_target,
330
+ p_mask=c_p_mask,
331
+ loss=c_loss,
332
+ total=total,
333
+ ignore_index=ignore_index,
334
+ label_smoothing=label_smoothing,
335
+ logit_scale=logit_scale,
336
+ reduction=reduction,
337
+ V=V,
338
+ BV=BV,
339
+ num_warps=32
340
+ )
341
+
342
+ # gradient of logits is computed in-place by the above triton kernel and is of shape: C x V
343
+ # thus dx should be of shape: C x H
344
+ dx[start:end] = torch.mm(c_logits, weight)
345
+
346
+ # keep dw in fp32 to maintain precision
347
+ if weight is not None:
348
+ dw += c_logits.t() @ c_x
349
+
350
+ if bias is not None:
351
+ torch.add(input=db, other=c_logits.sum(0), out=db)
352
+
353
+ loss = loss.sum()
354
+ if dw is not None:
355
+ dw = dw.to(weight)
356
+ if db is not None:
357
+ db = db.to(bias)
358
+ return loss, dx, dw, db
359
+
360
+
361
+ def fused_linear_cross_entropy_backward(
362
+ do: torch.Tensor,
363
+ dx: torch.Tensor,
364
+ dw: torch.Tensor,
365
+ db: torch.Tensor
366
+ ):
367
+ # If cross entropy is the last layer, do is 1.0. Skip the mul to save time
368
+ if torch.ne(do, torch.tensor(1.0, device=do.device)):
369
+ # We use a Triton kernel instead of a PyTorch operation because modifying inputs in-place
370
+ # for gradient storage and backward multiple times causes anomalies with PyTorch but not with Triton.
371
+ N, H = dx.shape
372
+ B = min(MAX_FUSED_SIZE, triton.next_power_of_2(H))
373
+
374
+ elementwise_mul_kernel[(triton.cdiv(N * H, B),)](
375
+ x=dx,
376
+ g=do,
377
+ N=N*H,
378
+ B=B,
379
+ num_warps=32,
380
+ )
381
+
382
+ # handle dw
383
+ if dw is not None:
384
+ V, H = dw.shape
385
+ elementwise_mul_kernel[(triton.cdiv(V * H, B),)](
386
+ x=dw,
387
+ g=do,
388
+ N=V*H,
389
+ B=B,
390
+ num_warps=32,
391
+ )
392
+
393
+ if db is not None:
394
+ V = db.shape[0]
395
+ elementwise_mul_kernel[(triton.cdiv(V, B),)](
396
+ x=db,
397
+ g=do,
398
+ N=V,
399
+ B=B,
400
+ num_warps=32,
401
+ )
402
+ return dx, dw, db
403
+
404
+
405
+ class FusedLinearCrossEntropyFunction(torch.autograd.Function):
406
+
407
+ @staticmethod
408
+ def forward(
409
+ ctx,
410
+ x: torch.Tensor,
411
+ target: torch.LongTensor,
412
+ weight: torch.Tensor,
413
+ bias: torch.Tensor = None,
414
+ p_mask: torch.Tensor = None,
415
+ ignore_index: int = -100,
416
+ label_smoothing: float = 0.0,
417
+ logit_scale: float = 1.0,
418
+ num_chunks: int = 8,
419
+ reduction: str = "mean"
420
+ ):
421
+ """
422
+ Fusing the last linear layer with cross-entropy loss
423
+ Reference: https://github.com/mgmalek/efficient_cross_entropy
424
+
425
+ Handle the forward and backward pass of the final linear layer via cross-entropy loss by avoiding
426
+ the materialization of the large logits tensor. Since Cross Entropy Loss is the last layer, we can
427
+ compute the gradient at the forward pass. By doing so, we don't have to store the x and target
428
+ for the backward pass.
429
+
430
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
431
+ target (torch.LongTensor): [batch_size * seq_len]
432
+ where each value is in [0, vocab_size).
433
+ weight (torch.Tensor): [vocab_size, hidden_size]
434
+ where `vocab_size` is the number of classes.
435
+ bias (Optional[torch.Tensor]): [vocab_size]
436
+ where `vocab_size` is the number of classes.
437
+ p_mask(torch.Tensor): [batch_size * seq_len]
438
+ Its shape should be same as target.
439
+ ignore_index:
440
+ the index to ignore in the target.
441
+ label_smoothing:
442
+ the amount of smoothing when computing the loss, where 0.0 means no smoothing.
443
+ logit_scale: float = 1.0,
444
+ A scaling factor applied to the logits. Default: 1.0
445
+ num_chunks: int
446
+ The number of chunks to split the input tensor into for processing.
447
+ This can help optimize memory usage and computation speed.
448
+ Default: 8
449
+ reduction:
450
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
451
+ 'mean': the weighted mean of the output is taken,
452
+ 'sum': the output will be summed.
453
+ Default: 'mean'.
454
+ """
455
+ loss, dx, dw, db = fused_linear_cross_entropy_forward(
456
+ x,
457
+ target,
458
+ weight,
459
+ bias,
460
+ p_mask,
461
+ ignore_index,
462
+ label_smoothing,
463
+ logit_scale,
464
+ num_chunks,
465
+ reduction
466
+ )
467
+ # downcast to dtype and store for backward
468
+ ctx.save_for_backward(
469
+ dx.detach(),
470
+ dw.detach() if weight is not None else None,
471
+ db.detach() if bias is not None else None,
472
+ )
473
+ return loss
474
+
475
+ @staticmethod
476
+ def backward(ctx, do):
477
+ dx, dw, db = ctx.saved_tensors
478
+ dx, dw, db = fused_linear_cross_entropy_backward(do, dx, dw, db)
479
+ # 10 gradients should be returned, with `p_mask` having no grads
480
+ # Check the number of arguments in the `forward` method
481
+ return dx, None, dw, db, None, None, None, None, None, None
482
+
483
+
484
+ def fused_linear_cross_entropy_loss(
485
+ x: torch.Tensor,
486
+ target: torch.LongTensor,
487
+ weight: torch.Tensor,
488
+ bias: torch.Tensor = None,
489
+ p_mask: torch.Tensor = None,
490
+ ignore_index: int = -100,
491
+ label_smoothing: float = 0.0,
492
+ logit_scale: float = 1.0,
493
+ num_chunks: int = 8,
494
+ reduction: str = "mean"
495
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
496
+ """
497
+ Args:
498
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
499
+ target (torch.LongTensor): [batch_size * seq_len]
500
+ where each value is in [0, vocab_size).
501
+ weight (torch.Tensor): [vocab_size, hidden_size]
502
+ where `vocab_size` is the number of classes.
503
+ bias (Optional[torch.Tensor]): [vocab_size]
504
+ where `vocab_size` is the number of classes.
505
+ p_mask(torch.Tensor): [batch_size * seq_len]
506
+ Its shape should be same as target.
507
+ ignore_index: int.
508
+ If target == ignore_index, the loss is set to 0.0.
509
+ label_smoothing: float
510
+ logit_scale: float
511
+ A scaling factor applied to the logits. Default: 1.0
512
+ num_chunks: int
513
+ The number of chunks to split the input tensor into for processing.
514
+ This can help optimize memory usage and computation speed.
515
+ Default: 8
516
+ reduction:
517
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
518
+ 'mean': the weighted mean of the output is taken,
519
+ 'sum': the output will be summed.
520
+ Default: 'mean'.
521
+ Returns:
522
+ losses: [batch,], float
523
+ """
524
+ return FusedLinearCrossEntropyFunction.apply(
525
+ x,
526
+ target,
527
+ weight,
528
+ bias,
529
+ p_mask,
530
+ ignore_index,
531
+ label_smoothing,
532
+ logit_scale,
533
+ num_chunks,
534
+ reduction
535
+ )
536
+
537
+
538
+ class FusedLinearDiffusionCrossEntropyLoss(nn.Module):
539
+
540
+ def __init__(
541
+ self,
542
+ ignore_index: int = -100,
543
+ label_smoothing: float = 0.0,
544
+ logit_scale: float = 1.0,
545
+ num_chunks: int = 8,
546
+ reduction: str = "mean"
547
+ ):
548
+ """
549
+ Args:
550
+ ignore_index: int.
551
+ If target == ignore_index, the loss is set to 0.0.
552
+ label_smoothing: float
553
+ logit_scale: float
554
+ A scaling factor applied to the logits. Default: 1.0
555
+ num_chunks: int
556
+ The number of chunks to split the input tensor into for processing.
557
+ This can help optimize memory usage and computation speed.
558
+ Default: 8
559
+ reduction:
560
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
561
+ 'mean': the weighted mean of the output is taken,
562
+ 'sum': the output will be summed.
563
+ Default: 'mean'.
564
+ """
565
+ super().__init__()
566
+
567
+ assert reduction in ["mean", "sum"], f"reduction: {reduction} is not supported"
568
+
569
+ self.ignore_index = ignore_index
570
+ self.label_smoothing = label_smoothing
571
+ self.logit_scale = logit_scale
572
+ self.num_chunks = num_chunks
573
+ self.reduction = reduction
574
+
575
+ @torch.compiler.disable
576
+ def forward(
577
+ self,
578
+ x: torch.Tensor,
579
+ target: torch.LongTensor,
580
+ weight: torch.Tensor,
581
+ bias: Optional[torch.Tensor] = None,
582
+ p_mask: torch.Tensor = None
583
+ ):
584
+ """
585
+ Args:
586
+ x (torch.Tensor): [batch_size, seq_len, hidden_size]
587
+ target (torch.LongTensor): [batch_size, seq_len]
588
+ where each value is in [0, V).
589
+ weight (torch.Tensor): [vocab_size, hidden_size]
590
+ where `vocab_size` is the number of classes.
591
+ bias (Optional[torch.Tensor]): [vocab_size]
592
+ where `vocab_size` is the number of classes.
593
+ p_mask(torch.Tensor): [batch_size, seq_len]
594
+ Its shape is same as target.
595
+ Shape: (1, packed_length) when varlen attn is used.
596
+ Returns:
597
+ loss
598
+
599
+ TODO:
600
+ follow https://github.com/ML-GSAI/LLaDA/blob/main/GUIDELINES.md#pre-training
601
+ ```py
602
+ unreduced_loss /= p_mask
603
+ ```
604
+ Scale the values of `unreduced_loss at different positions
605
+ """
606
+ if p_mask is None:
607
+ p_mask = torch.ones_like(target, dtype=torch.float, device=x.device)
608
+
609
+ x = x.contiguous().view(-1, x.shape[-1])
610
+ target = target.contiguous().view(-1)
611
+ weight = weight.contiguous()
612
+ bias = bias.contiguous() if bias else None
613
+ p_mask = p_mask.contiguous().view(-1)
614
+ l, d = x.shape
615
+ assert l == target.shape[0] == p_mask.shape[0], f"{x.shape=}, {target.shape=}, {p_mask.shape=}"
616
+
617
+ loss = fused_linear_cross_entropy_loss(
618
+ x,
619
+ target,
620
+ weight=weight,
621
+ bias=bias,
622
+ p_mask=p_mask,
623
+ ignore_index=self.ignore_index,
624
+ label_smoothing=self.label_smoothing,
625
+ logit_scale=self.logit_scale,
626
+ num_chunks=self.num_chunks,
627
+ reduction=self.reduction
628
+ )
629
+ return loss
630
+
631
+
632
+ class LinearLossParallel(ParallelStyle):
633
+ def __init__(
634
+ self,
635
+ *,
636
+ sequence_dim: int = 1,
637
+ use_local_output: bool = False,
638
+ ):
639
+ super().__init__()
640
+
641
+ self.sequence_sharding = (Shard(sequence_dim),)
642
+ self.use_local_output = use_local_output
643
+
644
+ @staticmethod
645
+ def _prepare_input_fn(sequence_sharding, mod, inputs, device_mesh):
646
+ x, target, weight, bias = inputs
647
+
648
+ if not isinstance(x, DTensor):
649
+ # assume the input passed in already sharded on the sequence dim and create the DTensor
650
+ x = DTensor.from_local(x, device_mesh, sequence_sharding)
651
+ if x.placements != sequence_sharding:
652
+ x = x.redistribute(placements=sequence_sharding, async_op=True)
653
+ if not isinstance(target, DTensor):
654
+ target = DTensor.from_local(target, device_mesh, [Replicate()])
655
+ if target.placements != sequence_sharding:
656
+ target = target.redistribute(placements=sequence_sharding, async_op=True)
657
+
658
+ if not isinstance(weight, DTensor):
659
+ weight = DTensor.from_local(weight, device_mesh, [Replicate()])
660
+ if weight.placements != [Replicate()]:
661
+ # we replicate the weight/bias in FLCE
662
+ weight = weight.redistribute(placements=[Replicate()], async_op=True)
663
+
664
+ if bias is not None and not isinstance(bias, DTensor):
665
+ bias = DTensor.from_local(bias, device_mesh, [Replicate()])
666
+ if bias is not None and bias.placements != [Replicate()]:
667
+ bias = bias.redistribute(placements=[Replicate()], async_op=True)
668
+
669
+ return x.to_local(), target.to_local(), weight.to_local(), bias.to_local() if bias is not None else bias
670
+
671
+ @staticmethod
672
+ def _prepare_output_fn(use_local_output, mod, outputs, device_mesh):
673
+ return outputs.to_local() if use_local_output else outputs
674
+
675
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
676
+ return distribute_module(
677
+ module,
678
+ device_mesh,
679
+ partition_fn=None,
680
+ input_fn=partial(self._prepare_input_fn, self.sequence_sharding),
681
+ output_fn=partial(self._prepare_output_fn, self.use_local_output)
682
+ )
gap_sdar_training.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict, Optional, Sequence, Union
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+
7
+
8
+ @dataclass
9
+ class GapRemaskOutputs:
10
+ full_candidate_mask: torch.BoolTensor
11
+ remask_target_flat: torch.BoolTensor
12
+ remask_pred_full: torch.BoolTensor
13
+ z_accept: torch.LongTensor
14
+ z_proj: torch.LongTensor
15
+ projected_mask: torch.BoolTensor
16
+ projected_p_mask: torch.FloatTensor
17
+ remask_loss: torch.Tensor
18
+ metrics: Dict[str, float]
19
+
20
+
21
+ def _scatter_flat_mask(base_mask: torch.BoolTensor, selected_flat_mask: torch.BoolTensor) -> torch.BoolTensor:
22
+ full_mask = torch.zeros_like(base_mask)
23
+ full_mask[base_mask] = selected_flat_mask
24
+ return full_mask
25
+
26
+
27
+ def build_p_mask_full(
28
+ masked_indices: torch.BoolTensor,
29
+ p_mask: torch.FloatTensor,
30
+ shape: torch.Size,
31
+ default_p_mask: float,
32
+ ) -> torch.FloatTensor:
33
+ p_mask_full = torch.full(shape, default_p_mask, dtype=torch.float32, device=masked_indices.device)
34
+ p_mask_full[masked_indices] = p_mask.float()
35
+ return p_mask_full
36
+
37
+
38
+ def get_num_transfer_tokens(block_length: int, steps: int) -> torch.LongTensor:
39
+ if steps <= 0:
40
+ raise ValueError(f"steps must be positive, got {steps}")
41
+
42
+ base = block_length // steps
43
+ remainder = block_length % steps
44
+ num_transfer_tokens = torch.full((steps,), base, dtype=torch.long)
45
+ num_transfer_tokens[:remainder] += 1
46
+ return num_transfer_tokens
47
+
48
+
49
+ def _select_block_positions(
50
+ block_scores: torch.FloatTensor,
51
+ masked_local_indices: torch.LongTensor,
52
+ num_transfer_tokens: int,
53
+ strategy: str,
54
+ confidence_threshold: float,
55
+ ) -> torch.LongTensor:
56
+ k = min(num_transfer_tokens, int(masked_local_indices.numel()))
57
+ if k <= 0:
58
+ return masked_local_indices[:0]
59
+
60
+ if strategy == "low_confidence_dynamic":
61
+ high_conf_mask = block_scores > confidence_threshold
62
+ if int(high_conf_mask.sum().item()) >= num_transfer_tokens:
63
+ return masked_local_indices[high_conf_mask]
64
+
65
+ topk = torch.topk(block_scores, k=k, sorted=False).indices
66
+ return masked_local_indices[topk]
67
+ if strategy == "low_confidence_static":
68
+ topk = torch.topk(block_scores, k=k, sorted=False).indices
69
+ return masked_local_indices[topk]
70
+ if strategy == "sequential":
71
+ return masked_local_indices[:k]
72
+
73
+ raise ValueError(f"Unsupported rollout strategy: {strategy}")
74
+
75
+
76
+ def _resolve_num_transfer_tokens(
77
+ num_transfer_tokens: Union[int, torch.Tensor, Sequence[int]],
78
+ batch_idx: int,
79
+ ) -> int:
80
+ if torch.is_tensor(num_transfer_tokens):
81
+ if num_transfer_tokens.numel() == 1:
82
+ return int(num_transfer_tokens.item())
83
+ return int(num_transfer_tokens[batch_idx].item())
84
+
85
+ if isinstance(num_transfer_tokens, Sequence) and not isinstance(num_transfer_tokens, (str, bytes)):
86
+ if len(num_transfer_tokens) == 1:
87
+ return int(num_transfer_tokens[0])
88
+ return int(num_transfer_tokens[batch_idx])
89
+
90
+ return int(num_transfer_tokens)
91
+
92
+
93
+ def select_policy_transfer_tokens(
94
+ masked_indices: torch.BoolTensor,
95
+ proposal_scores_full: torch.FloatTensor,
96
+ num_tokens,
97
+ block_size: int,
98
+ num_transfer_tokens: Union[int, torch.Tensor, Sequence[int]],
99
+ strategy: str = "low_confidence_dynamic",
100
+ confidence_threshold: float = 0.95,
101
+ scope: str = "all",
102
+ ) -> torch.BoolTensor:
103
+ if scope not in {"all", "frontier_block"}:
104
+ raise ValueError(f"Unsupported rollout scope: {scope}")
105
+
106
+ reveal_mask = torch.zeros_like(masked_indices)
107
+ if torch.is_tensor(num_transfer_tokens):
108
+ if int(num_transfer_tokens.max().item()) <= 0:
109
+ return reveal_mask
110
+ elif isinstance(num_transfer_tokens, Sequence) and not isinstance(num_transfer_tokens, (str, bytes)):
111
+ if max(int(x) for x in num_transfer_tokens) <= 0:
112
+ return reveal_mask
113
+ elif int(num_transfer_tokens) <= 0:
114
+ return reveal_mask
115
+
116
+ for batch_idx, packed_lengths in enumerate(num_tokens):
117
+ current_num_transfer_tokens = _resolve_num_transfer_tokens(num_transfer_tokens, batch_idx)
118
+ cursor = 0
119
+ for sample_len_tensor in packed_lengths:
120
+ sample_len = int(sample_len_tensor.item())
121
+ sample_end = cursor + sample_len
122
+
123
+ for block_start in range(cursor, sample_end, block_size):
124
+ block_end = min(block_start + block_size, sample_end)
125
+ block_mask = masked_indices[batch_idx, block_start:block_end]
126
+ if not block_mask.any():
127
+ continue
128
+
129
+ masked_local_indices = torch.nonzero(block_mask, as_tuple=False).flatten()
130
+ block_scores = proposal_scores_full[batch_idx, block_start:block_end][masked_local_indices]
131
+ chosen = _select_block_positions(
132
+ block_scores=block_scores,
133
+ masked_local_indices=masked_local_indices,
134
+ num_transfer_tokens=current_num_transfer_tokens,
135
+ strategy=strategy,
136
+ confidence_threshold=confidence_threshold,
137
+ )
138
+ reveal_mask[batch_idx, block_start:block_end][chosen] = True
139
+
140
+ if scope == "frontier_block":
141
+ break
142
+
143
+ cursor = sample_end
144
+
145
+ return reveal_mask
146
+
147
+
148
+ def select_teacher_forced_rollout_tokens(
149
+ masked_indices: torch.BoolTensor,
150
+ proposal_scores_full: torch.FloatTensor,
151
+ num_tokens,
152
+ block_size: int,
153
+ num_transfer_tokens: Union[int, torch.Tensor, Sequence[int]],
154
+ strategy: str = "low_confidence_dynamic",
155
+ confidence_threshold: float = 0.95,
156
+ scope: str = "all",
157
+ ) -> torch.BoolTensor:
158
+ return select_policy_transfer_tokens(
159
+ masked_indices=masked_indices,
160
+ proposal_scores_full=proposal_scores_full,
161
+ num_tokens=num_tokens,
162
+ block_size=block_size,
163
+ num_transfer_tokens=num_transfer_tokens,
164
+ strategy=strategy,
165
+ confidence_threshold=confidence_threshold,
166
+ scope=scope,
167
+ )
168
+
169
+
170
+ def build_rollout_scope_mask(
171
+ masked_indices: torch.BoolTensor,
172
+ reference_mask: torch.BoolTensor,
173
+ num_tokens,
174
+ block_size: int,
175
+ scope: str = "all",
176
+ ) -> torch.BoolTensor:
177
+ if scope not in {"all", "frontier_block"}:
178
+ raise ValueError(f"Unsupported rollout scope: {scope}")
179
+
180
+ if scope == "all":
181
+ return reference_mask.clone()
182
+
183
+ scope_mask = torch.zeros_like(reference_mask)
184
+ for batch_idx, packed_lengths in enumerate(num_tokens):
185
+ cursor = 0
186
+ for sample_len_tensor in packed_lengths:
187
+ sample_len = int(sample_len_tensor.item())
188
+ sample_end = cursor + sample_len
189
+
190
+ for block_start in range(cursor, sample_end, block_size):
191
+ block_end = min(block_start + block_size, sample_end)
192
+ if not masked_indices[batch_idx, block_start:block_end].any():
193
+ continue
194
+
195
+ scope_mask[batch_idx, block_start:block_end] = reference_mask[batch_idx, block_start:block_end]
196
+ break
197
+
198
+ cursor = sample_end
199
+
200
+ return scope_mask
201
+
202
+
203
+ def build_rollout_p_mask(
204
+ masked_indices: torch.BoolTensor,
205
+ labels: torch.LongTensor,
206
+ num_tokens,
207
+ target_scope_mask: Optional[torch.BoolTensor] = None,
208
+ per_block: bool = False,
209
+ block_size: Optional[int] = None,
210
+ eps: float = 1e-3,
211
+ ) -> torch.FloatTensor:
212
+ p_mask_full = torch.full(masked_indices.shape, eps, dtype=torch.float32, device=masked_indices.device)
213
+
214
+ for batch_idx, packed_lengths in enumerate(num_tokens):
215
+ cursor = 0
216
+ for sample_len_tensor in packed_lengths:
217
+ sample_len = int(sample_len_tensor.item())
218
+ sample_end = cursor + sample_len
219
+ if per_block:
220
+ if block_size is None:
221
+ raise ValueError("block_size must be provided when per_block=True")
222
+ for block_start in range(cursor, sample_end, block_size):
223
+ block_end = min(block_start + block_size, sample_end)
224
+ block_target_mask = labels[batch_idx, block_start:block_end].ne(-100)
225
+ if target_scope_mask is not None:
226
+ block_target_mask = block_target_mask & target_scope_mask[batch_idx, block_start:block_end]
227
+ target_count = int(block_target_mask.sum().item())
228
+ if target_count == 0:
229
+ continue
230
+ block_masked = masked_indices[batch_idx, block_start:block_end] & block_target_mask
231
+ block_p_mask = max(block_masked.sum().item() / target_count, eps)
232
+ p_mask_full[batch_idx, block_start:block_end][block_masked] = block_p_mask
233
+ else:
234
+ sample_target_mask = labels[batch_idx, cursor:sample_end].ne(-100)
235
+ if target_scope_mask is not None:
236
+ sample_target_mask = sample_target_mask & target_scope_mask[batch_idx, cursor:sample_end]
237
+ target_count = int(sample_target_mask.sum().item())
238
+ if target_count > 0:
239
+ sample_masked = masked_indices[batch_idx, cursor:sample_end] & sample_target_mask
240
+ sample_p_mask = max(sample_masked.sum().item() / target_count, eps)
241
+ p_mask_full[batch_idx, cursor:sample_end][sample_masked] = sample_p_mask
242
+ cursor = sample_end
243
+
244
+ return p_mask_full[masked_indices]
245
+
246
+
247
+ def _expand_positive_blocks(
248
+ positive_mask: torch.BoolTensor,
249
+ candidate_mask: torch.BoolTensor,
250
+ block_size: int,
251
+ ) -> torch.BoolTensor:
252
+ expanded = positive_mask.clone()
253
+ _, seq_len = positive_mask.shape
254
+ for block_start in range(0, seq_len, block_size):
255
+ block_end = min(block_start + block_size, seq_len)
256
+ block_positive = positive_mask[:, block_start:block_end].any(dim=1, keepdim=True)
257
+ if not bool(block_positive.any().item()):
258
+ continue
259
+ expanded[:, block_start:block_end] |= candidate_mask[:, block_start:block_end] & block_positive
260
+ return expanded
261
+
262
+
263
+ def _build_remask_targets(
264
+ masked_indices: torch.BoolTensor,
265
+ proposal_ids: torch.LongTensor,
266
+ clean_targets_flat: torch.LongTensor,
267
+ full_candidate_mask: torch.BoolTensor,
268
+ block_size: int,
269
+ supervision: Optional[str],
270
+ ) -> torch.BoolTensor:
271
+ supervision = (supervision or "adv_bce").strip().lower()
272
+ wrong_flat_all = proposal_ids.ne(clean_targets_flat)
273
+ wrong_mask = _scatter_flat_mask(masked_indices, wrong_flat_all) & full_candidate_mask
274
+ if supervision in {"gt_mismatch_block_bce", "block_mismatch_bce", "gt_block_bce"}:
275
+ return _expand_positive_blocks(wrong_mask, full_candidate_mask, block_size)
276
+ return wrong_mask
277
+
278
+
279
+ def apply_gap_remask(
280
+ noisy_input_ids: torch.LongTensor,
281
+ clean_input_ids: torch.LongTensor,
282
+ labels: torch.LongTensor,
283
+ masked_indices: torch.BoolTensor,
284
+ p_mask: torch.FloatTensor,
285
+ proposal_ids: torch.LongTensor,
286
+ remask_logits: torch.FloatTensor,
287
+ candidate_mask_full: torch.BoolTensor,
288
+ mask_token_id: int,
289
+ remask_threshold: float,
290
+ remask_loss_weight: float,
291
+ remask_default_p_mask: float,
292
+ block_size: int,
293
+ supervision: Optional[str] = None,
294
+ target_scope_mask: Optional[torch.BoolTensor] = None,
295
+ ignore_index: int = -100,
296
+ ) -> GapRemaskOutputs:
297
+ full_candidate_mask = candidate_mask_full & masked_indices
298
+ candidate_mask_flat = full_candidate_mask[masked_indices]
299
+
300
+ clean_targets_flat = clean_input_ids[masked_indices]
301
+ remask_target_full = _build_remask_targets(
302
+ masked_indices=masked_indices,
303
+ proposal_ids=proposal_ids,
304
+ clean_targets_flat=clean_targets_flat,
305
+ full_candidate_mask=full_candidate_mask,
306
+ block_size=block_size,
307
+ supervision=supervision,
308
+ )
309
+ remask_target_flat = remask_target_full[masked_indices]
310
+
311
+ z_accept = noisy_input_ids.clone()
312
+ if candidate_mask_flat.any():
313
+ z_accept[full_candidate_mask] = clean_input_ids[full_candidate_mask]
314
+
315
+ candidate_logits = remask_logits[candidate_mask_flat]
316
+ candidate_targets = remask_target_flat[candidate_mask_flat].float()
317
+ remask_pred_flat = torch.zeros_like(candidate_mask_flat)
318
+ pos_weight_value = 1.0
319
+ if candidate_logits.numel() > 0:
320
+ positive_count = float(candidate_targets.sum().item())
321
+ negative_count = float(candidate_targets.numel() - positive_count)
322
+ pos_weight = None
323
+ if positive_count > 0.0 and negative_count > 0.0:
324
+ pos_weight_value = max(1.0, min(8.0, negative_count / positive_count))
325
+ pos_weight = candidate_logits.new_tensor(pos_weight_value)
326
+ remask_loss = F.binary_cross_entropy_with_logits(
327
+ candidate_logits,
328
+ candidate_targets,
329
+ pos_weight=pos_weight,
330
+ )
331
+ remask_pred_flat[candidate_mask_flat] = torch.sigmoid(candidate_logits) >= remask_threshold
332
+ else:
333
+ remask_loss = remask_logits.sum() * 0.0
334
+
335
+ remask_pred_full = _scatter_flat_mask(masked_indices, remask_pred_flat)
336
+ z_proj = z_accept.clone()
337
+ z_proj[remask_pred_full] = mask_token_id
338
+
339
+ if target_scope_mask is None:
340
+ target_scope_mask = labels.ne(ignore_index)
341
+ else:
342
+ target_scope_mask = target_scope_mask & labels.ne(ignore_index)
343
+
344
+ projected_mask = z_proj.eq(mask_token_id) & target_scope_mask
345
+ if not projected_mask.any():
346
+ fallback_mask = full_candidate_mask & target_scope_mask
347
+ if not fallback_mask.any():
348
+ fallback_mask = masked_indices & target_scope_mask
349
+ if not fallback_mask.any():
350
+ fallback_mask = target_scope_mask
351
+ fallback_indices = torch.nonzero(fallback_mask, as_tuple=False)
352
+ if fallback_indices.numel() > 0:
353
+ row, col = fallback_indices[0].tolist()
354
+ z_proj[row, col] = mask_token_id
355
+ projected_mask[row, col] = True
356
+
357
+ p_mask_full = build_p_mask_full(
358
+ masked_indices=masked_indices,
359
+ p_mask=p_mask,
360
+ shape=noisy_input_ids.shape,
361
+ default_p_mask=remask_default_p_mask,
362
+ )
363
+ projected_p_mask = p_mask_full[projected_mask]
364
+
365
+ candidate_total = max(int(candidate_mask_flat.sum().item()), 1)
366
+ remask_positive = int(remask_target_flat.sum().item())
367
+ remask_predicted = int(remask_pred_full.sum().item())
368
+ remask_true_positive = int((remask_pred_full & remask_target_full).sum().item())
369
+ precision = remask_true_positive / max(remask_predicted, 1)
370
+ recall = remask_true_positive / max(remask_positive, 1)
371
+ metrics = {
372
+ "candidate_tokens": float(candidate_mask_flat.sum().item()),
373
+ "remask_positive_rate": remask_positive / candidate_total,
374
+ "remask_pred_rate": remask_predicted / candidate_total,
375
+ "remask_precision": precision,
376
+ "remask_recall": recall,
377
+ "remask_pos_weight": pos_weight_value,
378
+ "projected_mask_tokens": float(projected_mask.sum().item()),
379
+ "remask_loss": float((remask_loss.detach() * remask_loss_weight).item()),
380
+ }
381
+
382
+ return GapRemaskOutputs(
383
+ full_candidate_mask=full_candidate_mask,
384
+ remask_target_flat=remask_target_flat,
385
+ remask_pred_full=remask_pred_full,
386
+ z_accept=z_accept,
387
+ z_proj=z_proj,
388
+ projected_mask=projected_mask,
389
+ projected_p_mask=projected_p_mask,
390
+ remask_loss=remask_loss * remask_loss_weight,
391
+ metrics=metrics,
392
+ )
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.52.4"
13
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:caa92001f2b4b62433db1b8b16702ba35726b07b1442cf814bdfd4b1951fee0f
3
+ size 4969539560
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5a3575ce8b1481d7ba949c841c37edc7c13f70262b69b29164c85d37a33441e
3
+ size 3174299204
model.safetensors.index.json ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 8143802380
4
+ },
5
+ "weight_map": {
6
+ "gap_remask_head.base_scale": "model-00002-of-00002.safetensors",
7
+ "gap_remask_head.conf_proj.bias": "model-00002-of-00002.safetensors",
8
+ "gap_remask_head.conf_proj.weight": "model-00002-of-00002.safetensors",
9
+ "gap_remask_head.down_proj.bias": "model-00002-of-00002.safetensors",
10
+ "gap_remask_head.down_proj.weight": "model-00002-of-00002.safetensors",
11
+ "gap_remask_head.residual_scale": "model-00002-of-00002.safetensors",
12
+ "gap_remask_head.up_proj.bias": "model-00002-of-00002.safetensors",
13
+ "gap_remask_head.up_proj.weight": "model-00002-of-00002.safetensors",
14
+ "gap_value_head.weight": "model-00002-of-00002.safetensors",
15
+ "lm_head.weight": "model-00002-of-00002.safetensors",
16
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.0.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.0.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.1.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.1.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.10.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.10.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.11.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.11.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.12.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.12.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.13.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.13.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
88
+ "model.layers.14.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
90
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.14.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
93
+ "model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
94
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
95
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
96
+ "model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
98
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
99
+ "model.layers.15.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
100
+ "model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
101
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
102
+ "model.layers.15.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
103
+ "model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
104
+ "model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
105
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
106
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
107
+ "model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
108
+ "model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
109
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
110
+ "model.layers.16.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
111
+ "model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
112
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
113
+ "model.layers.16.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
114
+ "model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
115
+ "model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
116
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
117
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
118
+ "model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
119
+ "model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
120
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
121
+ "model.layers.17.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
122
+ "model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
123
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
124
+ "model.layers.17.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
125
+ "model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
126
+ "model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
127
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00002.safetensors",
128
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
129
+ "model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
130
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
131
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
132
+ "model.layers.18.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
133
+ "model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
134
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
135
+ "model.layers.18.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
136
+ "model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
137
+ "model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
138
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00002.safetensors",
139
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
140
+ "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
141
+ "model.layers.19.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
142
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
143
+ "model.layers.19.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
144
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
145
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
146
+ "model.layers.19.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
147
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
148
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
149
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
153
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
154
+ "model.layers.2.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
155
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
156
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
157
+ "model.layers.2.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
158
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
159
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
160
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00002.safetensors",
161
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
162
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
163
+ "model.layers.20.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
164
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
165
+ "model.layers.20.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
166
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
167
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
168
+ "model.layers.20.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
169
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
170
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
171
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
172
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
173
+ "model.layers.21.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
174
+ "model.layers.21.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
175
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
176
+ "model.layers.21.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
177
+ "model.layers.21.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
178
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
179
+ "model.layers.21.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
180
+ "model.layers.21.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
181
+ "model.layers.21.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
182
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
183
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
184
+ "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
185
+ "model.layers.22.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
186
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
187
+ "model.layers.22.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
188
+ "model.layers.22.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
189
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
190
+ "model.layers.22.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
191
+ "model.layers.22.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
192
+ "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
193
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
194
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
195
+ "model.layers.23.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
196
+ "model.layers.23.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
197
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
198
+ "model.layers.23.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
199
+ "model.layers.23.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
200
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
201
+ "model.layers.23.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
202
+ "model.layers.23.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
203
+ "model.layers.23.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
204
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
205
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
206
+ "model.layers.24.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
207
+ "model.layers.24.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
208
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
209
+ "model.layers.24.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
210
+ "model.layers.24.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
211
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
212
+ "model.layers.24.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
213
+ "model.layers.24.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
214
+ "model.layers.24.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
215
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
216
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
217
+ "model.layers.25.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
218
+ "model.layers.25.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
219
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
220
+ "model.layers.25.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
221
+ "model.layers.25.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
222
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
223
+ "model.layers.25.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
224
+ "model.layers.25.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
225
+ "model.layers.25.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
226
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
227
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
228
+ "model.layers.26.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
229
+ "model.layers.26.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
230
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
231
+ "model.layers.26.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
232
+ "model.layers.26.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
233
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
234
+ "model.layers.26.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
235
+ "model.layers.26.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
236
+ "model.layers.26.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
237
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
238
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
239
+ "model.layers.27.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
240
+ "model.layers.27.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
241
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
242
+ "model.layers.27.self_attn.k_norm.weight": "model-00002-of-00002.safetensors",
243
+ "model.layers.27.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
244
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
245
+ "model.layers.27.self_attn.q_norm.weight": "model-00002-of-00002.safetensors",
246
+ "model.layers.27.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
247
+ "model.layers.27.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
248
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
249
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
250
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
251
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
252
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
253
+ "model.layers.3.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
254
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
255
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
256
+ "model.layers.3.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
257
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
258
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
259
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
260
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
261
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
262
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
263
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
264
+ "model.layers.4.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
265
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
266
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
267
+ "model.layers.4.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
268
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
269
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
270
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
271
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
272
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
273
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
274
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
275
+ "model.layers.5.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
276
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
277
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
278
+ "model.layers.5.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
279
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
280
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
281
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
282
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
283
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
284
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
285
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
286
+ "model.layers.6.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
287
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
288
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
289
+ "model.layers.6.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
290
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
291
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
292
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
293
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
294
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
295
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
296
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
297
+ "model.layers.7.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
298
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
299
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
300
+ "model.layers.7.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
301
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
302
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
303
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
304
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
305
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
306
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
307
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
308
+ "model.layers.8.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
309
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
310
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
311
+ "model.layers.8.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
312
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
313
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
314
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
315
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
316
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
317
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
318
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
319
+ "model.layers.9.self_attn.k_norm.weight": "model-00001-of-00002.safetensors",
320
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
321
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
322
+ "model.layers.9.self_attn.q_norm.weight": "model-00001-of-00002.safetensors",
323
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
324
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
325
+ "model.norm.weight": "model-00002-of-00002.safetensors"
326
+ }
327
+ }
modeling_sdar.py ADDED
The diff for this file is too large to render. See raw diff
 
special_tokens_map.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "<|MASK|>"
17
+ ],
18
+ "eos_token": {
19
+ "content": "<|im_end|>",
20
+ "lstrip": false,
21
+ "normalized": false,
22
+ "rstrip": false,
23
+ "single_word": false
24
+ },
25
+ "mask_token": {
26
+ "content": "<|MASK|>",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false
31
+ },
32
+ "pad_token": {
33
+ "content": "<|endoftext|>",
34
+ "lstrip": false,
35
+ "normalized": false,
36
+ "rstrip": false,
37
+ "single_word": false
38
+ }
39
+ }
tokenization_qwen2.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Qwen2."""
16
+
17
+ import json
18
+ import os
19
+ import unicodedata
20
+ from functools import lru_cache
21
+ from typing import Optional, Tuple
22
+
23
+ import regex as re
24
+
25
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
26
+ from transformers.utils import logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {
32
+ "vocab_file": "vocab.json",
33
+ "merges_file": "merges.txt",
34
+ }
35
+
36
+
37
+ MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
38
+
39
+ PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
40
+
41
+
42
+ @lru_cache()
43
+ # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
44
+ def bytes_to_unicode():
45
+ """
46
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
47
+ characters the bpe code barfs on.
48
+
49
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
50
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
51
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
52
+ tables between utf-8 bytes and unicode strings.
53
+ """
54
+ bs = (
55
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
56
+ )
57
+ cs = bs[:]
58
+ n = 0
59
+ for b in range(2**8):
60
+ if b not in bs:
61
+ bs.append(b)
62
+ cs.append(2**8 + n)
63
+ n += 1
64
+ cs = [chr(n) for n in cs]
65
+ return dict(zip(bs, cs))
66
+
67
+
68
+ # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
69
+ def get_pairs(word):
70
+ """
71
+ Return set of symbol pairs in a word.
72
+
73
+ Word is represented as tuple of symbols (symbols being variable-length strings).
74
+ """
75
+ pairs = set()
76
+ prev_char = word[0]
77
+ for char in word[1:]:
78
+ pairs.add((prev_char, char))
79
+ prev_char = char
80
+ return pairs
81
+
82
+
83
+ class Qwen2Tokenizer(PreTrainedTokenizer):
84
+ """
85
+ Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
86
+
87
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
88
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
89
+
90
+ ```python
91
+ >>> from transformers import Qwen2Tokenizer
92
+
93
+ >>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
94
+ >>> tokenizer("Hello world")["input_ids"]
95
+ [9707, 1879]
96
+
97
+ >>> tokenizer(" Hello world")["input_ids"]
98
+ [21927, 1879]
99
+ ```
100
+ This is expected.
101
+
102
+ You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
103
+
104
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
105
+ this superclass for more information regarding those methods.
106
+
107
+ Args:
108
+ vocab_file (`str`):
109
+ Path to the vocabulary file.
110
+ merges_file (`str`):
111
+ Path to the merges file.
112
+ errors (`str`, *optional*, defaults to `"replace"`):
113
+ Paradigm to follow when decoding bytes to UTF-8. See
114
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
115
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
116
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
117
+ token instead.
118
+ bos_token (`str`, *optional*):
119
+ The beginning of sequence token. Not applicable for this tokenizer.
120
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
121
+ The end of sequence token.
122
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
123
+ The token used for padding, for example when batching sequences of different lengths.
124
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
125
+ Whether or not the model should cleanup the spaces that were added when splitting the input text during the
126
+ tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
127
+ split_special_tokens (`bool`, *optional*, defaults to `False`):
128
+ Whether or not the special tokens should be split during the tokenization process. The default behavior is
129
+ to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
130
+ ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
131
+ '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
132
+ """
133
+
134
+ vocab_files_names = VOCAB_FILES_NAMES
135
+ model_input_names = ["input_ids", "attention_mask"]
136
+
137
+ def __init__(
138
+ self,
139
+ vocab_file,
140
+ merges_file,
141
+ errors="replace",
142
+ unk_token="<|endoftext|>",
143
+ bos_token=None,
144
+ eos_token="<|endoftext|>",
145
+ pad_token="<|endoftext|>",
146
+ clean_up_tokenization_spaces=False,
147
+ split_special_tokens=False,
148
+ **kwargs,
149
+ ):
150
+ # Qwen vocab does not contain control tokens; added tokens need to be special
151
+ bos_token = (
152
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
153
+ if isinstance(bos_token, str)
154
+ else bos_token
155
+ )
156
+ eos_token = (
157
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
158
+ if isinstance(eos_token, str)
159
+ else eos_token
160
+ )
161
+ unk_token = (
162
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
163
+ if isinstance(unk_token, str)
164
+ else unk_token
165
+ )
166
+ pad_token = (
167
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
168
+ if isinstance(pad_token, str)
169
+ else pad_token
170
+ )
171
+
172
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
173
+ self.encoder = json.load(vocab_handle)
174
+ self.decoder = {v: k for k, v in self.encoder.items()}
175
+ self.errors = errors # how to handle errors in decoding
176
+ self.byte_encoder = bytes_to_unicode()
177
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
178
+ bpe_merges = []
179
+ with open(merges_file, encoding="utf-8") as merges_handle:
180
+ for i, line in enumerate(merges_handle):
181
+ line = line.strip()
182
+ if (i == 0 and line.startswith("#version:")) or not line:
183
+ continue
184
+ bpe_merges.append(tuple(line.split()))
185
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
186
+ # NOTE: the cache can grow without bound and will get really large for long running processes
187
+ # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
188
+ # not a memory leak but appears as one.
189
+ # GPT2Tokenizer has the same problem, so let's be consistent.
190
+ self.cache = {}
191
+
192
+ self.pat = re.compile(PRETOKENIZE_REGEX)
193
+
194
+ if kwargs.get("add_prefix_space", False):
195
+ logger.warning_once(
196
+ f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
197
+ )
198
+
199
+ super().__init__(
200
+ errors=errors,
201
+ bos_token=bos_token,
202
+ eos_token=eos_token,
203
+ pad_token=pad_token,
204
+ unk_token=unk_token,
205
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
206
+ split_special_tokens=split_special_tokens,
207
+ **kwargs,
208
+ )
209
+
210
+ @property
211
+ def vocab_size(self) -> int:
212
+ return len(self.encoder)
213
+
214
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
215
+ def get_vocab(self):
216
+ return dict(self.encoder, **self.added_tokens_encoder)
217
+
218
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
219
+ def bpe(self, token):
220
+ if token in self.cache:
221
+ return self.cache[token]
222
+ word = tuple(token)
223
+ pairs = get_pairs(word)
224
+
225
+ if not pairs:
226
+ return token
227
+
228
+ while True:
229
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
230
+ if bigram not in self.bpe_ranks:
231
+ break
232
+ first, second = bigram
233
+ new_word = []
234
+ i = 0
235
+ while i < len(word):
236
+ try:
237
+ j = word.index(first, i)
238
+ except ValueError:
239
+ new_word.extend(word[i:])
240
+ break
241
+ else:
242
+ new_word.extend(word[i:j])
243
+ i = j
244
+
245
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
246
+ new_word.append(first + second)
247
+ i += 2
248
+ else:
249
+ new_word.append(word[i])
250
+ i += 1
251
+ new_word = tuple(new_word)
252
+ word = new_word
253
+ if len(word) == 1:
254
+ break
255
+ else:
256
+ pairs = get_pairs(word)
257
+ word = " ".join(word)
258
+ self.cache[token] = word
259
+ return word
260
+
261
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
262
+ def _tokenize(self, text):
263
+ """Tokenize a string."""
264
+ bpe_tokens = []
265
+ for token in re.findall(self.pat, text):
266
+ token = "".join(
267
+ self.byte_encoder[b] for b in token.encode("utf-8")
268
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
269
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
270
+ return bpe_tokens
271
+
272
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
273
+ def _convert_token_to_id(self, token):
274
+ """Converts a token (str) in an id using the vocab."""
275
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
276
+
277
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
278
+ def _convert_id_to_token(self, index):
279
+ """Converts an index (integer) in a token (str) using the vocab."""
280
+ return self.decoder.get(index)
281
+
282
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
283
+ def convert_tokens_to_string(self, tokens):
284
+ """Converts a sequence of tokens (string) in a single string."""
285
+ text = "".join(tokens)
286
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
287
+ return text
288
+
289
+ def decode(
290
+ self,
291
+ token_ids,
292
+ skip_special_tokens: bool = False,
293
+ clean_up_tokenization_spaces: Optional[bool] = False,
294
+ spaces_between_special_tokens: bool = False,
295
+ **kwargs,
296
+ ) -> str:
297
+ # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
298
+ # and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
299
+ return super().decode(
300
+ token_ids,
301
+ skip_special_tokens=skip_special_tokens,
302
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
303
+ spaces_between_special_tokens=spaces_between_special_tokens,
304
+ **kwargs,
305
+ )
306
+
307
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
308
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
309
+ if not os.path.isdir(save_directory):
310
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
311
+ return
312
+ vocab_file = os.path.join(
313
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
314
+ )
315
+ merge_file = os.path.join(
316
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
317
+ )
318
+
319
+ with open(vocab_file, "w", encoding="utf-8") as f:
320
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
321
+
322
+ index = 0
323
+ with open(merge_file, "w", encoding="utf-8") as writer:
324
+ writer.write("#version: 0.2\n")
325
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
326
+ if index != token_index:
327
+ logger.warning(
328
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
329
+ " Please check that the tokenizer is not corrupted!"
330
+ )
331
+ index = token_index
332
+ writer.write(" ".join(bpe_tokens) + "\n")
333
+ index += 1
334
+
335
+ return vocab_file, merge_file
336
+
337
+ def prepare_for_tokenization(self, text, **kwargs):
338
+ text = unicodedata.normalize("NFC", text)
339
+ return (text, kwargs)
340
+
341
+
342
+ __all__ = ["Qwen2Tokenizer"]
tokenizer_config.json ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "151669": {
214
+ "content": "<|MASK|>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": true
220
+ }
221
+ },
222
+ "additional_special_tokens": [
223
+ "<|im_start|>",
224
+ "<|im_end|>",
225
+ "<|object_ref_start|>",
226
+ "<|object_ref_end|>",
227
+ "<|box_start|>",
228
+ "<|box_end|>",
229
+ "<|quad_start|>",
230
+ "<|quad_end|>",
231
+ "<|vision_start|>",
232
+ "<|vision_end|>",
233
+ "<|vision_pad|>",
234
+ "<|image_pad|>",
235
+ "<|video_pad|>",
236
+ "<|MASK|>"
237
+ ],
238
+ "auto_map": {
239
+ "AutoTokenizer": [
240
+ "tokenization_qwen2.Qwen2Tokenizer",
241
+ null
242
+ ]
243
+ },
244
+ "bos_token": null,
245
+ "clean_up_tokenization_spaces": false,
246
+ "eos_token": "<|im_end|>",
247
+ "errors": "replace",
248
+ "extra_special_tokens": {},
249
+ "mask_token": "<|MASK|>",
250
+ "model_max_length": 131072,
251
+ "pad_token": "<|endoftext|>",
252
+ "padding_side": "right",
253
+ "split_special_tokens": false,
254
+ "tokenizer_class": "Qwen2Tokenizer",
255
+ "unk_token": null
256
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff