Sayoyo commited on
Commit
571cee8
·
verified ·
1 Parent(s): 9e1ac67

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ acestep-5Hz-lm-1.7B/tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ acestep-5Hz-lm-1.7B/tokenizer_config.json filter=lfs diff=lfs merge=lfs -text
38
+ Qwen3-Embedding-0.6B/tokenizer.json filter=lfs diff=lfs merge=lfs -text
Qwen3-Embedding-0.6B/added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
Qwen3-Embedding-0.6B/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 %}
Qwen3-Embedding-0.6B/config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3Model"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "dtype": "bfloat16",
9
+ "eos_token_id": 151643,
10
+ "head_dim": 128,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 1024,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 3072,
15
+ "layer_types": [
16
+ "full_attention",
17
+ "full_attention",
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention",
43
+ "full_attention"
44
+ ],
45
+ "max_position_embeddings": 32768,
46
+ "max_window_layers": 28,
47
+ "model_type": "qwen3",
48
+ "num_attention_heads": 16,
49
+ "num_hidden_layers": 28,
50
+ "num_key_value_heads": 8,
51
+ "rms_norm_eps": 1e-06,
52
+ "rope_scaling": null,
53
+ "rope_theta": 1000000,
54
+ "sliding_window": null,
55
+ "tie_word_embeddings": true,
56
+ "transformers_version": "4.57.0.dev0",
57
+ "use_cache": true,
58
+ "use_sliding_window": false,
59
+ "vocab_size": 151669
60
+ }
Qwen3-Embedding-0.6B/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
Qwen3-Embedding-0.6B/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0437e45c94563b09e13cb7a64478fc406947a93cb34a7e05870fc8dcd48e23fd
3
+ size 1191586416
Qwen3-Embedding-0.6B/special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
Qwen3-Embedding-0.6B/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:def76fb086971c7867b829c23a26261e38d9d74e02139253b38aeb9df8b4b50a
3
+ size 11423705
Qwen3-Embedding-0.6B/tokenizer_config.json ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "clean_up_tokenization_spaces": false,
231
+ "eos_token": "<|im_end|>",
232
+ "errors": "replace",
233
+ "extra_special_tokens": {},
234
+ "model_max_length": 131072,
235
+ "pad_token": "<|endoftext|>",
236
+ "split_special_tokens": false,
237
+ "tokenizer_class": "Qwen2Tokenizer",
238
+ "unk_token": null
239
+ }
Qwen3-Embedding-0.6B/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
acestep-5Hz-lm-1.7B/added_tokens.json ADDED
The diff for this file is too large to render. See raw diff
 
acestep-5Hz-lm-1.7B/chat_template.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 message.content is string 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.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
acestep-5Hz-lm-1.7B/config.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3Model"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "dtype": "bfloat16",
9
+ "eos_token_id": 151645,
10
+ "head_dim": 128,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 2048,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 6144,
15
+ "layer_types": [
16
+ "full_attention",
17
+ "full_attention",
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention",
43
+ "full_attention"
44
+ ],
45
+ "max_position_embeddings": 40960,
46
+ "max_window_layers": 28,
47
+ "model_type": "qwen3",
48
+ "num_attention_heads": 16,
49
+ "num_hidden_layers": 28,
50
+ "num_key_value_heads": 8,
51
+ "pad_token_id": 151643,
52
+ "rms_norm_eps": 1e-06,
53
+ "rope_scaling": null,
54
+ "rope_theta": 1000000,
55
+ "sliding_window": null,
56
+ "tie_word_embeddings": true,
57
+ "transformers_version": "4.57.0.dev0",
58
+ "use_cache": true,
59
+ "use_sliding_window": false,
60
+ "vocab_size": 217204
61
+ }
acestep-5Hz-lm-1.7B/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
acestep-5Hz-lm-1.7B/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f161689da73e5ecefa28ff780d51c2d92a00f056d021d7933c779ed5c6cd7db8
3
+ size 3708521528
acestep-5Hz-lm-1.7B/special_tokens_map.json ADDED
The diff for this file is too large to render. See raw diff
 
acestep-5Hz-lm-1.7B/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35af56c3f5cb3ea2cc578aa28a8937770981d504f183ac5c8c38baf4bbd4af4d
3
+ size 24321939
acestep-5Hz-lm-1.7B/tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6cd70cdd89425971794f5235562edcc608b0629a6c4686ae51a8b8c8b8ba5e95
3
+ size 14072925
acestep-5Hz-lm-1.7B/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
acestep-v15-turbo/config.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "AceStepConditionGenerationModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "audio_acoustic_hidden_dim": 64,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_acestep_v15.AceStepConfig",
10
+ "AutoModel": "modeling_acestep_v15_turbo.AceStepConditionGenerationModel"
11
+ },
12
+ "data_proportion": 0.5,
13
+ "dtype": "bfloat16",
14
+ "fsq_dim": 2048,
15
+ "fsq_input_levels": [
16
+ 8,
17
+ 8,
18
+ 8,
19
+ 5,
20
+ 5,
21
+ 5
22
+ ],
23
+ "fsq_input_num_quantizers": 1,
24
+ "head_dim": 128,
25
+ "hidden_act": "silu",
26
+ "hidden_size": 2048,
27
+ "in_channels": 192,
28
+ "initializer_range": 0.02,
29
+ "intermediate_size": 6144,
30
+ "is_turbo": true,
31
+ "layer_types": [
32
+ "sliding_attention",
33
+ "full_attention",
34
+ "sliding_attention",
35
+ "full_attention",
36
+ "sliding_attention",
37
+ "full_attention",
38
+ "sliding_attention",
39
+ "full_attention",
40
+ "sliding_attention",
41
+ "full_attention",
42
+ "sliding_attention",
43
+ "full_attention",
44
+ "sliding_attention",
45
+ "full_attention",
46
+ "sliding_attention",
47
+ "full_attention",
48
+ "sliding_attention",
49
+ "full_attention",
50
+ "sliding_attention",
51
+ "full_attention",
52
+ "sliding_attention",
53
+ "full_attention",
54
+ "sliding_attention",
55
+ "full_attention"
56
+ ],
57
+ "max_position_embeddings": 32768,
58
+ "model_type": "acestep",
59
+ "model_version": "turbo",
60
+ "num_attention_heads": 16,
61
+ "num_attention_pooler_hidden_layers": 2,
62
+ "num_audio_decoder_hidden_layers": 24,
63
+ "num_hidden_layers": 24,
64
+ "num_key_value_heads": 8,
65
+ "num_lyric_encoder_hidden_layers": 8,
66
+ "num_timbre_encoder_hidden_layers": 4,
67
+ "patch_size": 2,
68
+ "pool_window_size": 5,
69
+ "rms_norm_eps": 1e-06,
70
+ "rope_scaling": null,
71
+ "rope_theta": 1000000,
72
+ "sliding_window": 128,
73
+ "text_hidden_dim": 1024,
74
+ "timbre_fix_frame": 750,
75
+ "timbre_hidden_dim": 64,
76
+ "timestep_mu": -0.4,
77
+ "timestep_sigma": 1.0,
78
+ "transformers_version": "4.57.0.dev0",
79
+ "use_cache": true,
80
+ "use_sliding_window": true,
81
+ "vocab_size": 64003
82
+ }
acestep-v15-turbo/configuration_acestep_v15.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """AceStep model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig, layer_type_validation
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 AceStepConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`AceStepModel`]. It is used to instantiate an
28
+ AceStep model according to the specified arguments, defining the model architecture.
29
+
30
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PretrainedConfig`] for more information.
32
+
33
+ Args:
34
+ vocab_size (`int`, *optional*, defaults to 64003):
35
+ Vocabulary size of the AceStep model. Defines the number of different tokens that can be represented by the
36
+ `inputs_ids` passed when calling the model.
37
+ hidden_size (`int`, *optional*, defaults to 4096):
38
+ Dimension of the hidden representations.
39
+ intermediate_size (`int`, *optional*, defaults to 22016):
40
+ Dimension of the MLP representations.
41
+ num_hidden_layers (`int`, *optional*, defaults to 32):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 32):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ num_key_value_heads (`int`, *optional*, defaults to 32):
46
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
47
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
48
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
49
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
50
+ by meanpooling all the original heads within that group. For more details, check out [this
51
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
52
+ head_dim (`int`, *optional*, defaults to 128):
53
+ The attention head dimension.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether the model's input and output word embeddings should be tied.
67
+ rope_theta (`float`, *optional*, defaults to 10000.0):
68
+ The base period of the RoPE embeddings.
69
+ rope_scaling (`Dict`, *optional*):
70
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
71
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
72
+ accordingly.
73
+ Expected contents:
74
+ `rope_type` (`str`):
75
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
76
+ 'llama3'], with 'default' being the original RoPE implementation.
77
+ `factor` (`float`, *optional*):
78
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
79
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
80
+ original maximum pre-trained length.
81
+ `original_max_position_embeddings` (`int`, *optional*):
82
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
83
+ pretraining.
84
+ `attention_factor` (`float`, *optional*):
85
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
86
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
87
+ `factor` field to infer the suggested value.
88
+ `beta_fast` (`float`, *optional*):
89
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
90
+ ramp function. If unspecified, it defaults to 32.
91
+ `beta_slow` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 1.
94
+ `short_factor` (`list[float]`, *optional*):
95
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
96
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
97
+ size divided by the number of attention heads divided by 2
98
+ `long_factor` (`list[float]`, *optional*):
99
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
100
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
101
+ size divided by the number of attention heads divided by 2
102
+ `low_freq_factor` (`float`, *optional*):
103
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
104
+ `high_freq_factor` (`float`, *optional*):
105
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
106
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
107
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
108
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
109
+ Whether to use sliding window attention.
110
+ sliding_window (`int`, *optional*, defaults to 4096):
111
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
112
+ layer_types (`list`, *optional*):
113
+ Attention pattern for each layer.
114
+ attention_dropout (`float`, *optional*, defaults to 0.0):
115
+ The dropout ratio for the attention probabilities.
116
+
117
+ ```python
118
+ >>> from acestep.models import AceStepConfig
119
+
120
+ >>> # Initializing an AceStep configuration
121
+ >>> configuration = AceStepConfig()
122
+
123
+ >>> # Initializing a model from the configuration
124
+ >>> model = AceStepConditionGenerationModel(configuration)
125
+
126
+ >>> # Accessing the model configuration
127
+ >>> configuration = model.config
128
+ ```"""
129
+
130
+ model_type = "acestep"
131
+ keys_to_ignore_at_inference = ["past_key_values"]
132
+
133
+ # Default tensor parallel plan for the base model
134
+ base_model_tp_plan = {
135
+ "layers.*.self_attn.q_proj": "colwise",
136
+ "layers.*.self_attn.k_proj": "colwise",
137
+ "layers.*.self_attn.v_proj": "colwise",
138
+ "layers.*.self_attn.o_proj": "rowwise",
139
+ "layers.*.mlp.gate_proj": "colwise",
140
+ "layers.*.mlp.up_proj": "colwise",
141
+ "layers.*.mlp.down_proj": "rowwise",
142
+ }
143
+ base_model_pp_plan = {
144
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
145
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
146
+ "norm": (["hidden_states"], ["hidden_states"]),
147
+ }
148
+ def __init__(
149
+ self,
150
+ vocab_size=64003,
151
+ fsq_dim=2048,
152
+ fsq_input_levels=[8, 8, 8, 5, 5, 5],
153
+ fsq_input_num_quantizers=1,
154
+ hidden_size=2048,
155
+ intermediate_size=6144,
156
+ num_hidden_layers=24,
157
+ num_attention_heads=16,
158
+ num_key_value_heads=8,
159
+ head_dim=128,
160
+ hidden_act="silu",
161
+ max_position_embeddings=32768,
162
+ initializer_range=0.02,
163
+ rms_norm_eps=1e-6,
164
+ use_cache=True,
165
+ tie_word_embeddings=True,
166
+ rope_theta=1000000,
167
+ rope_scaling=None,
168
+ attention_bias=False,
169
+ use_sliding_window=True,
170
+ sliding_window=128,
171
+ layer_types=None,
172
+ attention_dropout=0.0,
173
+ num_lyric_encoder_hidden_layers=8,
174
+ audio_acoustic_hidden_dim=64,
175
+ pool_window_size=5,
176
+ text_hidden_dim=1024,
177
+ in_channels=192,
178
+ data_proportion=0.5,
179
+ timestep_mu=-0.4,
180
+ timestep_sigma=1.0,
181
+ timbre_hidden_dim=64,
182
+ num_timbre_encoder_hidden_layers=4,
183
+ timbre_fix_frame=750,
184
+ patch_size=2,
185
+ num_attention_pooler_hidden_layers=2,
186
+ num_audio_decoder_hidden_layers=24,
187
+ model_version="turbo",
188
+ **kwargs,
189
+ ):
190
+ self.max_position_embeddings = max_position_embeddings
191
+ self.hidden_size = hidden_size
192
+ self.intermediate_size = intermediate_size
193
+ self.num_hidden_layers = num_hidden_layers
194
+ self.num_attention_heads = num_attention_heads
195
+ self.use_sliding_window = use_sliding_window
196
+ self.sliding_window = sliding_window if self.use_sliding_window else None
197
+
198
+ # Text encoder configuration
199
+ self.text_hidden_dim = text_hidden_dim
200
+
201
+ # Lyric encoder configuration
202
+ self.num_lyric_encoder_hidden_layers = num_lyric_encoder_hidden_layers
203
+ self.patch_size = patch_size
204
+
205
+ # Audio semantic token generation configuration
206
+ self.audio_acoustic_hidden_dim = audio_acoustic_hidden_dim
207
+ self.pool_window_size = pool_window_size
208
+ self.in_channels = in_channels
209
+ self.data_proportion = data_proportion
210
+ self.timestep_mu = timestep_mu
211
+ self.timestep_sigma = timestep_sigma
212
+
213
+ # FSQ (Finite Scalar Quantization) configuration
214
+ self.fsq_dim = fsq_dim
215
+ self.fsq_input_levels = fsq_input_levels
216
+ self.fsq_input_num_quantizers = fsq_input_num_quantizers
217
+
218
+ # Timbre encoder configuration
219
+ self.timbre_hidden_dim = timbre_hidden_dim
220
+ self.num_timbre_encoder_hidden_layers = num_timbre_encoder_hidden_layers
221
+ self.timbre_fix_frame = timbre_fix_frame
222
+ self.num_attention_pooler_hidden_layers = num_attention_pooler_hidden_layers
223
+ self.num_audio_decoder_hidden_layers = num_audio_decoder_hidden_layers
224
+ self.vocab_size = vocab_size
225
+
226
+ # Backward compatibility: ensure num_key_value_heads is set
227
+ if num_key_value_heads is None:
228
+ num_key_value_heads = num_attention_heads
229
+
230
+ self.num_key_value_heads = num_key_value_heads
231
+ self.head_dim = head_dim
232
+ self.hidden_act = hidden_act
233
+ self.initializer_range = initializer_range
234
+ self.rms_norm_eps = rms_norm_eps
235
+ self.use_cache = use_cache
236
+ self.rope_theta = rope_theta
237
+ self.rope_scaling = rope_scaling
238
+ self.attention_bias = attention_bias
239
+ self.attention_dropout = attention_dropout
240
+ self.model_version = model_version
241
+
242
+ # Validate rotary position embeddings parameters
243
+ # Backward compatibility: if there is a 'type' field, move it to 'rope_type'
244
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
245
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
246
+ rope_config_validation(self)
247
+
248
+ self.layer_types = layer_types
249
+
250
+ # Set default layer types if not specified
251
+ if self.layer_types is None:
252
+ self.layer_types = [
253
+ "sliding_attention" if bool((i + 1) % 2) else "full_attention" for i in range(self.num_hidden_layers)
254
+ ]
255
+ layer_type_validation(self.layer_types)
256
+
257
+ super().__init__(
258
+ tie_word_embeddings=tie_word_embeddings,
259
+ **kwargs,
260
+ )
261
+
262
+
263
+ __all__ = ["AceStepConfig"]
acestep-v15-turbo/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f6e0797fad420a39bd33979eb6e840e30989e34a3794e843d23b60ec6e422d7
3
+ size 4787825604
acestep-v15-turbo/modeling_acestep_v15_turbo.py ADDED
@@ -0,0 +1,2136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The ACESTEO Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+ import time
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch import nn
21
+
22
+ from einops import rearrange
23
+
24
+ # Transformers imports (sorted by submodule, then alphabetically)
25
+ from transformers.cache_utils import Cache, DynamicCache, EncoderDecoderCache
26
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
27
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
28
+ from transformers.modeling_layers import GradientCheckpointingLayer
29
+ from transformers.modeling_outputs import BaseModelOutput
30
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
31
+ from transformers.processing_utils import Unpack
32
+ from transformers.utils import auto_docstring, can_return_tuple, logging
33
+ from transformers.models.qwen3.modeling_qwen3 import (
34
+ Qwen3MLP,
35
+ Qwen3RMSNorm,
36
+ Qwen3RotaryEmbedding,
37
+ apply_rotary_pos_emb,
38
+ eager_attention_forward,
39
+ )
40
+
41
+ from vector_quantize_pytorch import ResidualFSQ
42
+
43
+ # Local config import with fallback
44
+ try:
45
+ from .configuration_acestep_v15 import AceStepConfig
46
+ except ImportError:
47
+ from configuration_acestep_v15 import AceStepConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+
53
+ def create_4d_mask(
54
+ seq_len: int,
55
+ dtype: torch.dtype,
56
+ device: torch.device,
57
+ attention_mask: Optional[torch.Tensor] = None, # [Batch, Seq_Len]
58
+ sliding_window: Optional[int] = None,
59
+ is_sliding_window: bool = False,
60
+ is_causal: bool = True,
61
+ ) -> torch.Tensor:
62
+ """
63
+ General 4D Attention Mask generator compatible with CPU/Mac/SDPA and Eager mode.
64
+ Supports use cases:
65
+ 1. Causal Full: is_causal=True, is_sliding_window=False (standard GPT)
66
+ 2. Causal Sliding: is_causal=True, is_sliding_window=True (Mistral/Qwen local window)
67
+ 3. Bidirectional Full: is_causal=False, is_sliding_window=False (BERT/Encoder)
68
+ 4. Bidirectional Sliding: is_causal=False, is_sliding_window=True (Longformer local)
69
+
70
+ Returns:
71
+ [Batch, 1, Seq_Len, Seq_Len] additive mask (0.0 for keep, -inf for mask)
72
+ """
73
+ # ------------------------------------------------------
74
+ # 1. Construct basic geometry mask [Seq_Len, Seq_Len]
75
+ # ------------------------------------------------------
76
+
77
+ # Build index matrices
78
+ # i (Query): [0, 1, ..., L-1]
79
+ # j (Key): [0, 1, ..., L-1]
80
+ indices = torch.arange(seq_len, device=device)
81
+ # diff = i - j
82
+ diff = indices.unsqueeze(1) - indices.unsqueeze(0)
83
+
84
+ # Initialize all True (all positions visible)
85
+ valid_mask = torch.ones((seq_len, seq_len), device=device, dtype=torch.bool)
86
+
87
+ # (A) Handle causality (Causal)
88
+ if is_causal:
89
+ # i >= j => diff >= 0
90
+ valid_mask = valid_mask & (diff >= 0)
91
+
92
+ # (B) Handle sliding window
93
+ if is_sliding_window and sliding_window is not None:
94
+ if is_causal:
95
+ # Causal sliding: only attend to past window steps
96
+ # i - j <= window => diff <= window
97
+ # (diff >= 0 already handled above)
98
+ valid_mask = valid_mask & (diff <= sliding_window)
99
+ else:
100
+ # Bidirectional sliding: attend past and future window steps
101
+ # |i - j| <= window => abs(diff) <= sliding_window
102
+ valid_mask = valid_mask & (torch.abs(diff) <= sliding_window)
103
+
104
+ # Expand dimensions to [1, 1, Seq_Len, Seq_Len] for broadcasting
105
+ valid_mask = valid_mask.unsqueeze(0).unsqueeze(0)
106
+
107
+ # ------------------------------------------------------
108
+ # 2. Apply padding mask (Key Masking)
109
+ # ------------------------------------------------------
110
+ if attention_mask is not None:
111
+ # attention_mask shape: [Batch, Seq_Len] (1=valid, 0=padding)
112
+ # We want to mask out invalid keys (columns)
113
+ # Expand shape: [Batch, 1, 1, Seq_Len]
114
+ padding_mask_4d = attention_mask.view(attention_mask.shape[0], 1, 1, seq_len).to(torch.bool)
115
+
116
+ # Broadcasting: Geometry Mask [1, 1, L, L] & Padding Mask [B, 1, 1, L]
117
+ # Result shape: [B, 1, L, L]
118
+ valid_mask = valid_mask & padding_mask_4d
119
+
120
+ # ------------------------------------------------------
121
+ # 3. Convert to additive mask
122
+ # ------------------------------------------------------
123
+ # Get the minimal value for current dtype
124
+ min_dtype = torch.finfo(dtype).min
125
+
126
+ # Create result tensor filled with -inf by default
127
+ mask_tensor = torch.full(valid_mask.shape, min_dtype, dtype=dtype, device=device)
128
+
129
+ # Set valid positions to 0.0
130
+ mask_tensor.masked_fill_(valid_mask, 0.0)
131
+
132
+ return mask_tensor
133
+
134
+
135
+ def pack_sequences(hidden1: torch.Tensor, hidden2: torch.Tensor, mask1: torch.Tensor, mask2: torch.Tensor):
136
+ """
137
+ Pack two sequences by concatenating and sorting them based on mask values.
138
+
139
+ Args:
140
+ hidden1: First hidden states tensor of shape [B, L1, D]
141
+ hidden2: Second hidden states tensor of shape [B, L2, D]
142
+ mask1: First mask tensor of shape [B, L1]
143
+ mask2: Second mask tensor of shape [B, L2]
144
+
145
+ Returns:
146
+ Tuple of (packed_hidden_states, new_mask) where:
147
+ - packed_hidden_states: Packed hidden states with valid tokens (mask=1) first, shape [B, L1+L2, D]
148
+ - new_mask: New mask tensor indicating valid positions, shape [B, L1+L2]
149
+ """
150
+ # Step 1: Concatenate hidden states and masks along sequence dimension
151
+ hidden_cat = torch.cat([hidden1, hidden2], dim=1) # [B, L, D]
152
+ mask_cat = torch.cat([mask1, mask2], dim=1) # [B, L]
153
+
154
+ B, L, D = hidden_cat.shape
155
+
156
+ # Step 2: Sort indices so that mask values of 1 come before 0
157
+ sort_idx = mask_cat.argsort(dim=1, descending=True, stable=True) # [B, L]
158
+
159
+ # Step 3: Reorder hidden states using sorted indices
160
+ hidden_left = torch.gather(hidden_cat, 1, sort_idx.unsqueeze(-1).expand(B, L, D))
161
+
162
+ # Step 4: Create new mask based on valid sequence lengths
163
+ lengths = mask_cat.sum(dim=1) # [B]
164
+ new_mask = (torch.arange(L, dtype=torch.long, device=hidden_cat.device).unsqueeze(0) < lengths.unsqueeze(1))
165
+
166
+ return hidden_left, new_mask
167
+
168
+
169
+ def sample_t_r(batch_size, device, dtype, data_proportion=0.0, timestep_mu=-0.4, timestep_sigma=1.0, use_meanflow=True):
170
+ """
171
+ Sample timestep t and r for flow matching training.
172
+
173
+ Args:
174
+ batch_size: Batch size
175
+ device: Device to create tensors on
176
+ dtype: Data type for tensors
177
+ data_proportion: Proportion of data samples (0.0 to 1.0)
178
+ timestep_mu: Mean for timestep sampling
179
+ timestep_sigma: Standard deviation for timestep sampling
180
+ use_meanflow: Whether to use meanflow (if False, data_proportion is set to 1.0)
181
+
182
+ Returns:
183
+ Tuple of (t, r) tensors, each of shape [batch_size]
184
+ """
185
+ t = torch.sigmoid(torch.randn((batch_size,), device=device, dtype=dtype) * timestep_sigma + timestep_mu)
186
+ r = torch.sigmoid(torch.randn((batch_size,), device=device, dtype=dtype) * timestep_sigma + timestep_mu)
187
+ # Assign t = max, r = min, for each pair
188
+ t, r = torch.maximum(t, r), torch.minimum(t, r)
189
+ if not use_meanflow:
190
+ data_proportion = 1.0
191
+ data_size = int(batch_size * data_proportion)
192
+ zero_mask = torch.arange(batch_size, device=device) < data_size
193
+ r = torch.where(zero_mask, t, r)
194
+ return t, r
195
+
196
+
197
+ class TimestepEmbedding(nn.Module):
198
+ """
199
+ Timestep embedding module for diffusion models.
200
+
201
+ Converts timestep values into high-dimensional embeddings using sinusoidal
202
+ positional encoding, followed by MLP layers. Used for conditioning diffusion
203
+ models on timestep information.
204
+ """
205
+ def __init__(
206
+ self,
207
+ in_channels: int,
208
+ time_embed_dim: int,
209
+ scale: float = 1000,
210
+ ):
211
+ super().__init__()
212
+
213
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim, bias=True)
214
+ self.act1 = nn.SiLU()
215
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim, bias=True)
216
+ self.in_channels = in_channels
217
+
218
+ self.act2 = nn.SiLU()
219
+ self.time_proj = nn.Linear(time_embed_dim, time_embed_dim * 6)
220
+ self.scale = scale
221
+
222
+ def timestep_embedding(self, t, dim, max_period=10000):
223
+ """
224
+ Create sinusoidal timestep embeddings.
225
+
226
+ Args:
227
+ t: A 1-D tensor of N indices, one per batch element. These may be fractional.
228
+ dim: The dimension of the output embeddings.
229
+ max_period: Controls the minimum frequency of the embeddings.
230
+
231
+ Returns:
232
+ An (N, D) tensor of positional embeddings.
233
+ """
234
+ t = t * self.scale
235
+ half = dim // 2
236
+ freqs = torch.exp(
237
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
238
+ ).to(device=t.device)
239
+ args = t[:, None].float() * freqs[None]
240
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
241
+ if dim % 2:
242
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
243
+ return embedding
244
+
245
+ def forward(self, t):
246
+ t_freq = self.timestep_embedding(t, self.in_channels)
247
+ temb = self.linear_1(t_freq.to(t.dtype))
248
+ temb = self.act1(temb)
249
+ temb = self.linear_2(temb)
250
+ timestep_proj = self.time_proj(self.act2(temb)).unflatten(1, (6, -1))
251
+ return temb, timestep_proj
252
+
253
+ class AceStepAttention(nn.Module):
254
+ """
255
+ Multi-headed attention module for AceStep model.
256
+
257
+ Implements the attention mechanism from 'Attention Is All You Need' paper,
258
+ with support for both self-attention and cross-attention modes. Uses RMSNorm
259
+ for query and key normalization, and supports sliding window attention for
260
+ efficient long-sequence processing.
261
+ """
262
+
263
+ def __init__(self, config: AceStepConfig, layer_idx: int, is_cross_attention: bool = False, is_causal: bool = False):
264
+ super().__init__()
265
+ self.config = config
266
+ self.layer_idx = layer_idx
267
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
268
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
269
+ self.scaling = self.head_dim**-0.5
270
+ self.attention_dropout = config.attention_dropout
271
+ if is_cross_attention:
272
+ is_causal = False
273
+ self.is_causal = is_causal
274
+ self.is_cross_attention = is_cross_attention
275
+
276
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias)
277
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)
278
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)
279
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
280
+ # Apply RMS normalization only on the head dimension (unlike OLMo)
281
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
282
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
283
+ self.attention_type = config.layer_types[layer_idx]
284
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
285
+
286
+ def forward(
287
+ self,
288
+ hidden_states: torch.Tensor,
289
+ attention_mask: Optional[torch.Tensor],
290
+ past_key_value: Optional[Cache] = None,
291
+ cache_position: Optional[torch.LongTensor] = None,
292
+ encoder_hidden_states: Optional[torch.Tensor] = None,
293
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] = None,
294
+ output_attentions: Optional[bool] = False,
295
+ **kwargs: Unpack[FlashAttentionKwargs],
296
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
297
+ input_shape = hidden_states.shape[:-1]
298
+ hidden_shape = (*input_shape, -1, self.head_dim)
299
+
300
+ # Project and normalize query states
301
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
302
+
303
+ # Determine if this is cross-attention (requires encoder_hidden_states)
304
+ is_cross_attention = self.is_cross_attention and encoder_hidden_states is not None
305
+
306
+ # Cross-attention path: attend to encoder hidden states
307
+ if is_cross_attention:
308
+ encoder_hidden_shape = (*encoder_hidden_states.shape[:-1], -1, self.head_dim)
309
+ if past_key_value is not None:
310
+ is_updated = past_key_value.is_updated.get(self.layer_idx)
311
+ # After the first generated token, we can reuse all key/value states from cache
312
+ curr_past_key_value = past_key_value.cross_attention_cache
313
+
314
+ # Conditions for calculating key and value states
315
+ if not is_updated:
316
+ # Compute and cache K/V for the first time
317
+ key_states = self.k_norm(self.k_proj(encoder_hidden_states).view(encoder_hidden_shape)).transpose(1, 2)
318
+ value_states = self.v_proj(encoder_hidden_states).view(encoder_hidden_shape).transpose(1, 2)
319
+ # Update cache: save all key/value states to cache for fast auto-regressive generation
320
+ key_states, value_states = curr_past_key_value.update(key_states, value_states, self.layer_idx)
321
+ # Set flag that this layer's cross-attention cache is updated
322
+ past_key_value.is_updated[self.layer_idx] = True
323
+ else:
324
+ # Reuse cached key/value states for subsequent tokens
325
+ key_states = curr_past_key_value.layers[self.layer_idx].keys
326
+ value_states = curr_past_key_value.layers[self.layer_idx].values
327
+ else:
328
+ # No cache used, compute K/V directly
329
+ key_states = self.k_norm(self.k_proj(encoder_hidden_states).view(encoder_hidden_shape)).transpose(1, 2)
330
+ value_states = self.v_proj(encoder_hidden_states).view(encoder_hidden_shape).transpose(1, 2)
331
+
332
+ # Self-attention path: attend to the same sequence
333
+ else:
334
+ # Project and normalize key/value states for self-attention
335
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
336
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
337
+ # Apply rotary position embeddings (RoPE) if provided
338
+ if position_embeddings is not None:
339
+ cos, sin = position_embeddings
340
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
341
+
342
+ # Update cache for auto-regressive generation
343
+ if past_key_value is not None:
344
+ # Sin and cos are specific to RoPE models; cache_position needed for the static cache
345
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
346
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
347
+
348
+ attention_interface: Callable = eager_attention_forward
349
+ if is_cross_attention and output_attentions:
350
+ attention_interface: Callable = eager_attention_forward
351
+ elif self.config._attn_implementation != "eager":
352
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
353
+
354
+ attn_output, attn_weights = attention_interface(
355
+ self,
356
+ query_states,
357
+ key_states,
358
+ value_states,
359
+ attention_mask,
360
+ dropout=self.attention_dropout if self.training else 0.0,
361
+ scaling=self.scaling,
362
+ sliding_window=self.sliding_window if not self.is_cross_attention else None,
363
+ **kwargs,
364
+ )
365
+
366
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
367
+ attn_output = self.o_proj(attn_output)
368
+ return attn_output, attn_weights
369
+
370
+
371
+ class AceStepEncoderLayer(GradientCheckpointingLayer):
372
+ """
373
+ Encoder layer for AceStep model.
374
+
375
+ Consists of self-attention and MLP (feed-forward) sub-layers with residual connections.
376
+ """
377
+
378
+ def __init__(self, config, layer_idx: int):
379
+ super().__init__()
380
+ self.hidden_size = config.hidden_size
381
+ self.config = config
382
+ self.layer_idx = layer_idx
383
+
384
+ # Self-attention sub-layer
385
+ self.self_attn = AceStepAttention(
386
+ config=config,
387
+ layer_idx=layer_idx,
388
+ is_cross_attention=False,
389
+ is_causal=False,
390
+ )
391
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
392
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
393
+
394
+ # MLP (feed-forward) sub-layer
395
+ self.mlp = Qwen3MLP(config)
396
+ self.attention_type = config.layer_types[layer_idx]
397
+
398
+ def forward(
399
+ self,
400
+ hidden_states: torch.Tensor,
401
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
402
+ attention_mask: Optional[torch.Tensor] = None,
403
+ position_ids: Optional[torch.LongTensor] = None,
404
+ output_attentions: Optional[bool] = False,
405
+ **kwargs,
406
+ ) -> tuple[
407
+ torch.FloatTensor,
408
+ Optional[tuple[torch.FloatTensor, torch.FloatTensor]],
409
+ ]:
410
+ # Self-attention with residual connection
411
+ residual = hidden_states
412
+ hidden_states = self.input_layernorm(hidden_states)
413
+ hidden_states, self_attn_weights = self.self_attn(
414
+ hidden_states=hidden_states,
415
+ position_embeddings=position_embeddings,
416
+ attention_mask=attention_mask,
417
+ position_ids=position_ids,
418
+ output_attentions=output_attentions,
419
+ # Encoders don't use cache
420
+ use_cache=False,
421
+ past_key_value=None,
422
+ **kwargs,
423
+ )
424
+ hidden_states = residual + hidden_states
425
+
426
+ # MLP with residual connection
427
+ residual = hidden_states
428
+ hidden_states = self.post_attention_layernorm(hidden_states)
429
+ hidden_states = self.mlp(hidden_states)
430
+ hidden_states = residual + hidden_states
431
+
432
+ outputs = (hidden_states,)
433
+
434
+ if output_attentions:
435
+ outputs += (self_attn_weights,)
436
+
437
+ return outputs
438
+
439
+
440
+ class AceStepDiTLayer(GradientCheckpointingLayer):
441
+ """
442
+ DiT (Diffusion Transformer) layer for AceStep model.
443
+
444
+ Implements a transformer layer with three main components:
445
+ 1. Self-attention with adaptive layer norm (AdaLN)
446
+ 2. Cross-attention (optional) for conditioning on encoder outputs
447
+ 3. Feed-forward MLP with adaptive layer norm
448
+
449
+ Uses scale-shift modulation from timestep embeddings for adaptive normalization.
450
+ """
451
+ def __init__(self, config: AceStepConfig, layer_idx: int, use_cross_attention: bool = True):
452
+ super().__init__()
453
+
454
+ # 1. Self-attention sub-layer with adaptive normalization
455
+ self.self_attn_norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
456
+ self.self_attn = AceStepAttention(config=config, layer_idx=layer_idx)
457
+
458
+ # 2. Cross-attention sub-layer (optional, for encoder conditioning)
459
+ self.use_cross_attention = use_cross_attention
460
+ if self.use_cross_attention:
461
+ self.cross_attn_norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
462
+ self.cross_attn = AceStepAttention(config=config, layer_idx=layer_idx, is_cross_attention=True)
463
+
464
+ # 3. Feed-forward MLP sub-layer with adaptive normalization
465
+ self.mlp_norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
466
+ self.mlp = Qwen3MLP(config)
467
+
468
+ # Scale-shift table for adaptive layer norm modulation (6 values: 3 for self-attn, 3 for MLP)
469
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, config.hidden_size) / config.hidden_size**0.5)
470
+ self.attention_type = config.layer_types[layer_idx]
471
+
472
+ def forward(
473
+ self,
474
+ hidden_states: torch.Tensor,
475
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
476
+ temb: torch.Tensor,
477
+ attention_mask: Optional[torch.Tensor] = None,
478
+ position_ids: Optional[torch.LongTensor] = None,
479
+ past_key_value: Optional[EncoderDecoderCache] = None,
480
+ output_attentions: Optional[bool] = False,
481
+ use_cache: Optional[bool] = False,
482
+ cache_position: Optional[torch.LongTensor] = None,
483
+ encoder_hidden_states: Optional[torch.Tensor] = None,
484
+ encoder_attention_mask: Optional[torch.Tensor] = None,
485
+ **kwargs,
486
+ ) -> torch.Tensor:
487
+
488
+ # Extract scale-shift parameters for adaptive layer norm from timestep embeddings
489
+ # 6 values: (shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa)
490
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
491
+ self.scale_shift_table + temb
492
+ ).chunk(6, dim=1)
493
+
494
+ # Step 1: Self-attention with adaptive layer norm (AdaLN)
495
+ # Apply adaptive normalization: norm(x) * (1 + scale) + shift
496
+ norm_hidden_states = (self.self_attn_norm(hidden_states) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
497
+ attn_output, self_attn_weights = self.self_attn(
498
+ hidden_states=norm_hidden_states,
499
+ position_embeddings=position_embeddings,
500
+ attention_mask=attention_mask,
501
+ position_ids=position_ids,
502
+ output_attentions=output_attentions,
503
+ use_cache=False,
504
+ past_key_value=None,
505
+ **kwargs,
506
+ )
507
+ # Apply gated residual connection: x = x + attn_output * gate
508
+ hidden_states = (hidden_states + attn_output * gate_msa).type_as(hidden_states)
509
+
510
+ # Step 2: Cross-attention (if enabled) for conditioning on encoder outputs
511
+ if self.use_cross_attention:
512
+ norm_hidden_states = self.cross_attn_norm(hidden_states).type_as(hidden_states)
513
+ attn_output, cross_attn_weights = self.cross_attn(
514
+ hidden_states=norm_hidden_states,
515
+ encoder_hidden_states=encoder_hidden_states,
516
+ attention_mask=encoder_attention_mask,
517
+ past_key_value=past_key_value,
518
+ output_attentions=output_attentions,
519
+ use_cache=use_cache,
520
+ **kwargs,
521
+ )
522
+ # Standard residual connection for cross-attention
523
+ hidden_states = hidden_states + attn_output
524
+
525
+ # Step 3: Feed-forward (MLP) with adaptive layer norm
526
+ # Apply adaptive normalization for MLP: norm(x) * (1 + scale) + shift
527
+ norm_hidden_states = (self.mlp_norm(hidden_states) * (1 + c_scale_msa) + c_shift_msa).type_as(hidden_states)
528
+ ff_output = self.mlp(norm_hidden_states)
529
+ # Apply gated residual connection: x = x + mlp_output * gate
530
+ hidden_states = (hidden_states + ff_output * c_gate_msa).type_as(hidden_states)
531
+
532
+ outputs = (hidden_states,)
533
+ if output_attentions:
534
+ outputs += (self_attn_weights, cross_attn_weights)
535
+
536
+ return outputs
537
+
538
+
539
+ @auto_docstring
540
+ class AceStepPreTrainedModel(PreTrainedModel):
541
+ config_class = AceStepConfig
542
+ base_model_prefix = "model"
543
+ supports_gradient_checkpointing = True
544
+ _no_split_modules = ["AceStepEncoderLayer", "AceStepDiTLayer"]
545
+ _skip_keys_device_placement = ["past_key_values"]
546
+ _supports_flash_attn_3 = True
547
+ _supports_flash_attn_2 = True
548
+ _supports_sdpa = True
549
+ _supports_flex_attn = True
550
+ _supports_cache_class = True
551
+ _supports_quantized_cache = True
552
+ _supports_static_cache = True
553
+ _supports_attention_backend = True
554
+
555
+ def _init_weights(self, module):
556
+ """
557
+ Initialize weights for different module types.
558
+
559
+ TODO: Support separate initialization for encoders and decoders.
560
+ """
561
+ std = self.config.initializer_range
562
+ if isinstance(module, nn.Linear):
563
+ module.weight.data.normal_(mean=0.0, std=std)
564
+ if module.bias is not None:
565
+ module.bias.data.zero_()
566
+ elif isinstance(module, nn.Embedding):
567
+ module.weight.data.normal_(mean=0.0, std=std)
568
+ if module.padding_idx is not None:
569
+ module.weight.data[module.padding_idx].zero_()
570
+ elif isinstance(module, Qwen3RMSNorm):
571
+ module.weight.data.fill_(1.0)
572
+
573
+
574
+ class AceStepLyricEncoder(AceStepPreTrainedModel):
575
+ """
576
+ Encoder for processing lyric text embeddings.
577
+
578
+ Encodes lyric text hidden states using a transformer encoder architecture
579
+ with bidirectional attention. Projects text embeddings to model hidden size
580
+ and processes them through multiple encoder layers.
581
+ """
582
+ def __init__(self, config):
583
+ super().__init__(config)
584
+
585
+ # Project text embeddings to model hidden size
586
+ self.embed_tokens = nn.Linear(config.text_hidden_dim, config.hidden_size)
587
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
588
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
589
+ self.gradient_checkpointing = False
590
+
591
+ # Stack of encoder layers
592
+ self.layers = nn.ModuleList(
593
+ [AceStepEncoderLayer(config, layer_idx) for layer_idx in range(config.num_lyric_encoder_hidden_layers)]
594
+ )
595
+
596
+ # Initialize weights and apply final processing
597
+ self.post_init()
598
+
599
+ @can_return_tuple
600
+ def forward(
601
+ self,
602
+ input_ids: Optional[torch.LongTensor] = None,
603
+ attention_mask: Optional[torch.Tensor] = None,
604
+ position_ids: Optional[torch.LongTensor] = None,
605
+ inputs_embeds: Optional[torch.FloatTensor] = None,
606
+ output_attentions: Optional[bool] = None,
607
+ output_hidden_states: Optional[bool] = None,
608
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
609
+ ) -> BaseModelOutput:
610
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
611
+ output_hidden_states = (
612
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
613
+ )
614
+
615
+ assert input_ids is None, "Only `input_ids` is supported for the lyric encoder."
616
+ assert attention_mask is not None, "Attention mask must be provided for the lyric encoder."
617
+ assert inputs_embeds is not None, "Inputs embeddings must be provided for the lyric encoder."
618
+
619
+ # Project input embeddings: N x T x text_hidden_dim -> N x T x hidden_size
620
+ inputs_embeds = self.embed_tokens(inputs_embeds)
621
+ # Cache position: only used for mask construction (not for actual caching)
622
+ cache_position = torch.arange(0, inputs_embeds.shape[1], device=inputs_embeds.device)
623
+
624
+ # Positional IDs
625
+ if position_ids is None:
626
+ position_ids = cache_position.unsqueeze(0)
627
+
628
+ # Attention masks
629
+ seq_len = inputs_embeds.shape[1]
630
+ dtype = inputs_embeds.dtype
631
+ device = inputs_embeds.device
632
+
633
+ # 判断是否使用 Flash Attention 2
634
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
635
+
636
+ # 初始化 Mask 变量
637
+ full_attn_mask = None
638
+ sliding_attn_mask = None
639
+
640
+ if is_flash_attn:
641
+ # -------------------------------------------------------
642
+ # 场景 A: Flash Attention 模式
643
+ # -------------------------------------------------------
644
+ # FA 不需要 4D Mask。
645
+ # 如果有 padding mask (attention_mask [B, L]),直接传给它即可。
646
+ # 如果没有 padding mask,传 None。
647
+ # 滑动窗口逻辑由 Layer 内部传给 FA kernel 的 sliding_window 参数控制。
648
+ full_attn_mask = attention_mask
649
+
650
+ # 这里的逻辑是:如果配置启用了滑动窗口,FA 模式下我们也只需要传基础的 padding mask
651
+ # Layer 会自己决定是否调用带 sliding window 的 kernel
652
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
653
+
654
+ else:
655
+ # -------------------------------------------------------
656
+ # 场景 B: CPU / Mac / SDPA (Eager 模式)
657
+ # -------------------------------------------------------
658
+ # 必须手动生成 4D Mask [B, 1, L, L]
659
+
660
+ # 1. Full Attention (Bidirectional, Global)
661
+ # 对应原来的 create_causal_mask + bidirectional
662
+ full_attn_mask = create_4d_mask(
663
+ seq_len=seq_len,
664
+ dtype=dtype,
665
+ device=device,
666
+ attention_mask=attention_mask, # [B, L]
667
+ sliding_window=None,
668
+ is_sliding_window=False,
669
+ is_causal=False # <--- 关键:双向注意力
670
+ )
671
+
672
+ # 2. Sliding Attention (Bidirectional, Local)
673
+ # 对应原来的 create_sliding_window... + bidirectional
674
+ if self.config.use_sliding_window:
675
+ sliding_attn_mask = create_4d_mask(
676
+ seq_len=seq_len,
677
+ dtype=dtype,
678
+ device=device,
679
+ attention_mask=attention_mask, # [B, L]
680
+ sliding_window=self.config.sliding_window,
681
+ is_sliding_window=True, # <--- 开启滑动窗口
682
+ is_causal=False # <--- 关键:双向注意力
683
+ )
684
+
685
+ # 构建 Mapping
686
+ self_attn_mask_mapping = {
687
+ "full_attention": full_attn_mask,
688
+ "sliding_attention": sliding_attn_mask,
689
+ }
690
+
691
+ # Initialize hidden states with input embeddings
692
+ hidden_states = inputs_embeds
693
+
694
+ # Create position embeddings to be shared across all layers
695
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
696
+
697
+ # Pass through transformer layers
698
+ all_hidden_states = () if output_hidden_states else None
699
+ all_self_attns = () if output_attentions else None
700
+
701
+ for layer_module in self.layers[: self.config.num_hidden_layers]:
702
+ if output_hidden_states:
703
+ all_hidden_states += (hidden_states,)
704
+
705
+ layer_outputs = layer_module(
706
+ hidden_states,
707
+ position_embeddings,
708
+ self_attn_mask_mapping[layer_module.attention_type],
709
+ position_ids,
710
+ output_attentions,
711
+ **flash_attn_kwargs,
712
+ )
713
+
714
+ hidden_states = layer_outputs[0]
715
+
716
+ if output_attentions:
717
+ all_self_attns += (layer_outputs[1],)
718
+
719
+ hidden_states = self.norm(hidden_states)
720
+
721
+ if output_hidden_states:
722
+ all_hidden_states += (hidden_states,)
723
+
724
+ return BaseModelOutput(
725
+ last_hidden_state=hidden_states,
726
+ hidden_states=all_hidden_states,
727
+ attentions=all_self_attns,
728
+ )
729
+
730
+
731
+ class AttentionPooler(AceStepPreTrainedModel):
732
+ """
733
+ Attention-based pooling module.
734
+
735
+ Pools sequences of patches using a special token and attention mechanism.
736
+ The special token attends to all patches and its output is used as the
737
+ pooled representation. Used for aggregating patch-level features into
738
+ sequence-level representations.
739
+ """
740
+ def __init__(self, config):
741
+ super().__init__(config)
742
+ self.config = config
743
+ self.embed_tokens = nn.Linear(config.hidden_size, config.hidden_size)
744
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
745
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
746
+ self.gradient_checkpointing = False
747
+ # Special token used for pooling (CLS-like token)
748
+ self.special_token = nn.Parameter(torch.randn(1, 1, config.hidden_size) * 0.02)
749
+ self.layers = nn.ModuleList(
750
+ [AceStepEncoderLayer(config, layer_idx) for layer_idx in range(config.num_attention_pooler_hidden_layers)]
751
+ )
752
+
753
+ # Initialize weights and apply final processing
754
+ self.post_init()
755
+
756
+ @can_return_tuple
757
+ def forward(self,
758
+ x,
759
+ attention_mask: Optional[torch.Tensor] = None,
760
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
761
+ ) -> BaseModelOutput:
762
+ B, T, P, D = x.shape
763
+ x = self.embed_tokens(x)
764
+ special_tokens = self.special_token.expand(B, T, 1, -1)
765
+ x = torch.cat([special_tokens, x], dim=2)
766
+ x = rearrange(x, "b t p c -> (b t) p c")
767
+
768
+ # Cache position: only used for mask construction.
769
+ cache_position = torch.arange(0, x.shape[1], device=x.device)
770
+ # Postional ids.
771
+ position_ids = cache_position.unsqueeze(0)
772
+
773
+ # embed positions
774
+ hidden_states = x
775
+
776
+ # create position embeddings to be shared across the decoder layers
777
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
778
+
779
+ seq_len = x.shape[1]
780
+ dtype = x.dtype
781
+ device = x.device
782
+
783
+ # 判断是否使用 Flash Attention 2
784
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
785
+
786
+ # 初始化 Mask 变量
787
+ full_attn_mask = None
788
+ sliding_attn_mask = None
789
+
790
+ if is_flash_attn:
791
+ # -------------------------------------------------------
792
+ # 场景 A: Flash Attention 模式
793
+ # -------------------------------------------------------
794
+ # FA 不需要 4D Mask。
795
+ # 如果有 padding mask (attention_mask [B, L]),直接传给它即可。
796
+ # 如果没有 padding mask,传 None。
797
+ # 滑动窗口逻辑由 Layer 内部传给 FA kernel 的 sliding_window 参数控制。
798
+ full_attn_mask = attention_mask
799
+
800
+ # 这里的逻辑是:如果配置启用了滑动窗口,FA 模式下我们也只需要传基础的 padding mask
801
+ # Layer 会自己决定是否调用带 sliding window 的 kernel
802
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
803
+
804
+ else:
805
+ # -------------------------------------------------------
806
+ # 场景 B: CPU / Mac / SDPA (Eager 模式)
807
+ # -------------------------------------------------------
808
+ # 必须手动生成 4D Mask [B, 1, L, L]
809
+
810
+ # 1. Full Attention (Bidirectional, Global)
811
+ # 对应原来的 create_causal_mask + bidirectional
812
+ full_attn_mask = create_4d_mask(
813
+ seq_len=seq_len,
814
+ dtype=dtype,
815
+ device=device,
816
+ attention_mask=attention_mask, # [B, L]
817
+ sliding_window=None,
818
+ is_sliding_window=False,
819
+ is_causal=False # <--- 关键:双向注意力
820
+ )
821
+
822
+ # 2. Sliding Attention (Bidirectional, Local)
823
+ # 对应原来的 create_sliding_window... + bidirectional
824
+ if self.config.use_sliding_window:
825
+ sliding_attn_mask = create_4d_mask(
826
+ seq_len=seq_len,
827
+ dtype=dtype,
828
+ device=device,
829
+ attention_mask=attention_mask, # [B, L]
830
+ sliding_window=self.config.sliding_window,
831
+ is_sliding_window=True, # <--- 开启滑动窗口
832
+ is_causal=False # <--- 关键:双向注意力
833
+ )
834
+
835
+ # 构建 Mapping
836
+ self_attn_mask_mapping = {
837
+ "full_attention": full_attn_mask,
838
+ "sliding_attention": sliding_attn_mask,
839
+ }
840
+
841
+ for layer_module in self.layers:
842
+ layer_outputs = layer_module(
843
+ hidden_states,
844
+ position_embeddings,
845
+ attention_mask=self_attn_mask_mapping[layer_module.attention_type],
846
+ **flash_attn_kwargs,
847
+ )
848
+
849
+ hidden_states = layer_outputs[0]
850
+
851
+ hidden_states = self.norm(hidden_states)
852
+
853
+ # Extract the special token output (first position) as pooled representation
854
+ cls_output = hidden_states[:, 0, :]
855
+ cls_output = rearrange(cls_output, "(b t) c -> b t c", b=B)
856
+ return cls_output
857
+
858
+
859
+ class AudioTokenDetokenizer(AceStepPreTrainedModel):
860
+ """
861
+ Audio token detokenizer module.
862
+
863
+ Converts quantized audio tokens back to continuous acoustic representations.
864
+ Expands each token into multiple patches using special tokens, processes them
865
+ through encoder layers, and projects to acoustic hidden dimension.
866
+ """
867
+ def __init__(self, config):
868
+ super().__init__(config)
869
+ self.config = config
870
+ self.embed_tokens = nn.Linear(config.hidden_size, config.hidden_size)
871
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
872
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
873
+ self.gradient_checkpointing = False
874
+ # Special tokens for expanding each quantized token into patches
875
+ self.special_tokens = nn.Parameter(torch.randn(1, config.pool_window_size, config.hidden_size) * 0.02)
876
+ self.layers = nn.ModuleList(
877
+ [AceStepEncoderLayer(config, layer_idx) for layer_idx in range(config.num_attention_pooler_hidden_layers)]
878
+ )
879
+ # Project back to acoustic hidden dimension
880
+ self.proj_out = nn.Linear(config.hidden_size, config.audio_acoustic_hidden_dim)
881
+
882
+ # Initialize weights and apply final processing
883
+ self.post_init()
884
+
885
+ @can_return_tuple
886
+ def forward(self,
887
+ x,
888
+ attention_mask: Optional[torch.Tensor] = None,
889
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
890
+ ) -> BaseModelOutput:
891
+ B, T, D = x.shape
892
+ x = self.embed_tokens(x)
893
+ # Expand and add special tokens: N x T x D -> N x T x P x D
894
+ # Each token is expanded into pool_window_size patches
895
+ x = x.unsqueeze(2) # N x T x 1 x D
896
+ x = x.repeat(1, 1, self.config.pool_window_size, 1) # N x T x P x D
897
+ # Add learnable special tokens to each patch
898
+ special_tokens = self.special_tokens.expand(B, T, -1, -1)
899
+ x = x + special_tokens
900
+ # Reshape for processing: (batch * time) x patches x hidden
901
+ x = rearrange(x, "b t p c -> (b t) p c")
902
+
903
+ # Cache position: only used for mask construction
904
+ cache_position = torch.arange(0, x.shape[1], device=x.device)
905
+ # Positional IDs
906
+ position_ids = cache_position.unsqueeze(0)
907
+
908
+ # Initialize hidden states
909
+ hidden_states = x
910
+
911
+ # Create position embeddings to be shared across all layers
912
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
913
+
914
+ seq_len = x.shape[1]
915
+ dtype = x.dtype
916
+ device = x.device
917
+
918
+ # 判断是否使用 Flash Attention 2
919
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
920
+
921
+ # 初始化 Mask 变量
922
+ full_attn_mask = None
923
+ sliding_attn_mask = None
924
+
925
+ if is_flash_attn:
926
+ # -------------------------------------------------------
927
+ # 场景 A: Flash Attention 模式
928
+ # -------------------------------------------------------
929
+ # FA 不需要 4D Mask。
930
+ # 如果有 padding mask (attention_mask [B, L]),直接传给它即可。
931
+ # 如果没有 padding mask,传 None。
932
+ # 滑动窗口逻辑由 Layer 内部传给 FA kernel 的 sliding_window 参数控制。
933
+ full_attn_mask = attention_mask
934
+
935
+ # 这里的逻辑是:如果配置启用了滑动窗口,FA 模式下我们也只需要传基础的 padding mask
936
+ # Layer 会自己决定是否调用带 sliding window 的 kernel
937
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
938
+
939
+ else:
940
+ # -------------------------------------------------------
941
+ # 场景 B: CPU / Mac / SDPA (Eager 模式)
942
+ # -------------------------------------------------------
943
+ # 必须手动生成 4D Mask [B, 1, L, L]
944
+
945
+ # 1. Full Attention (Bidirectional, Global)
946
+ # 对应原来的 create_causal_mask + bidirectional
947
+ full_attn_mask = create_4d_mask(
948
+ seq_len=seq_len,
949
+ dtype=dtype,
950
+ device=device,
951
+ attention_mask=attention_mask, # [B, L]
952
+ sliding_window=None,
953
+ is_sliding_window=False,
954
+ is_causal=False # <--- 关键:双向注意力
955
+ )
956
+
957
+ # 2. Sliding Attention (Bidirectional, Local)
958
+ # 对应原来的 create_sliding_window... + bidirectional
959
+ if self.config.use_sliding_window:
960
+ sliding_attn_mask = create_4d_mask(
961
+ seq_len=seq_len,
962
+ dtype=dtype,
963
+ device=device,
964
+ attention_mask=attention_mask, # [B, L]
965
+ sliding_window=self.config.sliding_window,
966
+ is_sliding_window=True, # <--- 开启滑动窗口
967
+ is_causal=False # <--- 关键:双向注意力
968
+ )
969
+
970
+ # 构建 Mapping
971
+ self_attn_mask_mapping = {
972
+ "full_attention": full_attn_mask,
973
+ "sliding_attention": sliding_attn_mask,
974
+ }
975
+
976
+ for layer_module in self.layers:
977
+ layer_outputs = layer_module(
978
+ hidden_states,
979
+ position_embeddings,
980
+ attention_mask=self_attn_mask_mapping[layer_module.attention_type],
981
+ **flash_attn_kwargs,
982
+ )
983
+
984
+ hidden_states = layer_outputs[0]
985
+
986
+ hidden_states = self.norm(hidden_states)
987
+
988
+ hidden_states = self.proj_out(hidden_states)
989
+
990
+ hidden_states = rearrange(hidden_states, "(b t) p c -> b (t p) c", b=B, p=self.config.pool_window_size)
991
+ return hidden_states
992
+
993
+
994
+ class AceStepTimbreEncoder(AceStepPreTrainedModel):
995
+ """
996
+ Encoder for extracting timbre embeddings from reference audio.
997
+
998
+ Processes packed reference audio acoustic features to extract timbre
999
+ representations. Uses a special token (CLS-like) to aggregate information
1000
+ from the entire reference audio sequence. Outputs are unpacked back to
1001
+ batch format for use in conditioning.
1002
+ """
1003
+ def __init__(self, config):
1004
+ super().__init__(config)
1005
+
1006
+ # Project acoustic features to model hidden size
1007
+ self.embed_tokens = nn.Linear(config.timbre_hidden_dim, config.hidden_size)
1008
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1009
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
1010
+ self.gradient_checkpointing = False
1011
+ # Special token for aggregating timbre information (prepended to sequence)
1012
+ self.special_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
1013
+ self.layers = nn.ModuleList(
1014
+ [AceStepEncoderLayer(config, layer_idx) for layer_idx in range(config.num_timbre_encoder_hidden_layers)]
1015
+ )
1016
+
1017
+ # Initialize weights and apply final processing
1018
+ self.post_init()
1019
+
1020
+ def unpack_timbre_embeddings(self, timbre_embs_packed, refer_audio_order_mask):
1021
+ """
1022
+ Unpack packed timbre embeddings into batch format.
1023
+
1024
+ Args:
1025
+ timbre_embs_packed: Packed timbre embeddings of shape [N, d]
1026
+ refer_audio_order_mask: Order mask indicating batch assignment for each packed embedding
1027
+
1028
+ Returns:
1029
+ Tuple of (unpacked_embeddings, mask):
1030
+ - unpacked_embeddings: Unpacked embeddings of shape [B, max_count, d]
1031
+ - new_mask: Mask indicating valid positions, shape [B, max_count]
1032
+ """
1033
+ N, d = timbre_embs_packed.shape
1034
+ device = timbre_embs_packed.device
1035
+ dtype = timbre_embs_packed.dtype
1036
+
1037
+ # Get batch size
1038
+ B = int(refer_audio_order_mask.max().item() + 1)
1039
+
1040
+ # Calculate element count and positions for each batch
1041
+ counts = torch.bincount(refer_audio_order_mask, minlength=B)
1042
+ max_count = counts.max().item()
1043
+
1044
+ # Calculate positions within batch
1045
+ sorted_indices = torch.argsort(refer_audio_order_mask * N + torch.arange(N, device=device), stable=True)
1046
+ sorted_batch_ids = refer_audio_order_mask[sorted_indices]
1047
+
1048
+ positions = torch.arange(N, device=device)
1049
+ batch_starts = torch.cat([torch.tensor([0], device=device),
1050
+ torch.cumsum(counts, dim=0)[:-1]])
1051
+ positions_in_sorted = positions - batch_starts[sorted_batch_ids]
1052
+
1053
+ inverse_indices = torch.empty_like(sorted_indices)
1054
+ inverse_indices[sorted_indices] = torch.arange(N, device=device)
1055
+ positions_in_batch = positions_in_sorted[inverse_indices]
1056
+
1057
+ # Use one-hot encoding and matrix multiplication (gradient-friendly approach)
1058
+ # Create one-hot encoding
1059
+ indices_2d = refer_audio_order_mask * max_count + positions_in_batch # (N,)
1060
+ one_hot = F.one_hot(indices_2d, num_classes=B * max_count).to(dtype) # (N, B*max_count)
1061
+
1062
+ # Rearrange using matrix multiplication
1063
+ timbre_embs_flat = one_hot.t() @ timbre_embs_packed # (B*max_count, d)
1064
+ timbre_embs_unpack = timbre_embs_flat.reshape(B, max_count, d)
1065
+
1066
+ # Create mask indicating valid positions
1067
+ mask_flat = (one_hot.sum(dim=0) > 0).long() # (B*max_count,)
1068
+ new_mask = mask_flat.reshape(B, max_count)
1069
+
1070
+ return timbre_embs_unpack, new_mask
1071
+
1072
+ @can_return_tuple
1073
+ def forward(
1074
+ self,
1075
+ refer_audio_acoustic_hidden_states_packed: Optional[torch.FloatTensor] = None,
1076
+ refer_audio_order_mask: Optional[torch.LongTensor] = None,
1077
+ attention_mask: Optional[torch.Tensor] = None,
1078
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
1079
+ ) -> BaseModelOutput:
1080
+ inputs_embeds = refer_audio_acoustic_hidden_states_packed
1081
+ # Project embeddings: N x T x timbre_hidden_dim -> N x T x hidden_size
1082
+ inputs_embeds = self.embed_tokens(inputs_embeds)
1083
+ # Prepend special token for timbre aggregation (CLS-like token)
1084
+ # inputs_embeds = torch.cat([self.special_token.expand(inputs_embeds.shape[0], 1, -1), inputs_embeds], dim=1)
1085
+ # Cache position: only used for mask construction (not for actual caching)
1086
+ cache_position = torch.arange(0, inputs_embeds.shape[1], device=inputs_embeds.device)
1087
+ # Positional IDs
1088
+ position_ids = cache_position.unsqueeze(0)
1089
+
1090
+ seq_len = inputs_embeds.shape[1]
1091
+ dtype = inputs_embeds.dtype
1092
+ device = inputs_embeds.device
1093
+
1094
+ # 判断是否使用 Flash Attention 2
1095
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
1096
+
1097
+ # 初始化 Mask 变量
1098
+ full_attn_mask = None
1099
+ sliding_attn_mask = None
1100
+
1101
+ if is_flash_attn:
1102
+ # -------------------------------------------------------
1103
+ # 场景 A: Flash Attention 模式
1104
+ # -------------------------------------------------------
1105
+ # FA 不需要 4D Mask。
1106
+ # 如果有 padding mask (attention_mask [B, L]),直接传给它即可。
1107
+ # 如果没有 padding mask,传 None。
1108
+ # 滑动窗口逻辑由 Layer 内部传给 FA kernel 的 sliding_window 参数控制。
1109
+ full_attn_mask = attention_mask
1110
+
1111
+ # 这里的逻辑是:如果配置启用了滑动窗口,FA 模式下我们也只需要传基础的 padding mask
1112
+ # Layer 会自己决定是否调用带 sliding window 的 kernel
1113
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
1114
+
1115
+ else:
1116
+ # -------------------------------------------------------
1117
+ # 场景 B: CPU / Mac / SDPA (Eager 模式)
1118
+ # -------------------------------------------------------
1119
+ # 必须手动生成 4D Mask [B, 1, L, L]
1120
+
1121
+ # 1. Full Attention (Bidirectional, Global)
1122
+ # 对应原来的 create_causal_mask + bidirectional
1123
+ full_attn_mask = create_4d_mask(
1124
+ seq_len=seq_len,
1125
+ dtype=dtype,
1126
+ device=device,
1127
+ attention_mask=attention_mask, # [B, L]
1128
+ sliding_window=None,
1129
+ is_sliding_window=False,
1130
+ is_causal=False # <--- 关键:双向注意力
1131
+ )
1132
+
1133
+ # 2. Sliding Attention (Bidirectional, Local)
1134
+ # 对应原来的 create_sliding_window... + bidirectional
1135
+ if self.config.use_sliding_window:
1136
+ sliding_attn_mask = create_4d_mask(
1137
+ seq_len=seq_len,
1138
+ dtype=dtype,
1139
+ device=device,
1140
+ attention_mask=attention_mask, # [B, L]
1141
+ sliding_window=self.config.sliding_window,
1142
+ is_sliding_window=True, # <--- 开启滑动窗口
1143
+ is_causal=False # <--- 关键:双向注意力
1144
+ )
1145
+
1146
+ # 构建 Mapping
1147
+ self_attn_mask_mapping = {
1148
+ "full_attention": full_attn_mask,
1149
+ "sliding_attention": sliding_attn_mask,
1150
+ }
1151
+
1152
+ # Initialize hidden states
1153
+ hidden_states = inputs_embeds
1154
+
1155
+ # Create position embeddings to be shared across all layers
1156
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1157
+
1158
+ # Pass through transformer layers
1159
+ for layer_module in self.layers[: self.config.num_hidden_layers]:
1160
+ layer_outputs = layer_module(
1161
+ hidden_states,
1162
+ position_embeddings,
1163
+ self_attn_mask_mapping[layer_module.attention_type],
1164
+ position_ids,
1165
+ **flash_attn_kwargs,
1166
+ )
1167
+
1168
+ hidden_states = layer_outputs[0]
1169
+
1170
+ hidden_states = self.norm(hidden_states)
1171
+ # Extract special token output (first position) as timbre embedding: N x T x D -> N x D
1172
+ hidden_states = hidden_states[:, 0, :]
1173
+ # Unpack packed embeddings back to batch format
1174
+ timbre_embs_unpack, timbre_embs_mask = self.unpack_timbre_embeddings(hidden_states, refer_audio_order_mask)
1175
+ return timbre_embs_unpack, timbre_embs_mask
1176
+
1177
+
1178
+ class AceStepAudioTokenizer(AceStepPreTrainedModel):
1179
+ """
1180
+ Audio tokenizer module.
1181
+
1182
+ Converts continuous acoustic features into discrete quantized tokens.
1183
+ Process: project -> pool patches -> quantize. Used for converting audio
1184
+ representations into discrete tokens for processing by the diffusion model.
1185
+ """
1186
+ def __init__(self, config):
1187
+ super().__init__(config)
1188
+ # Project acoustic features to hidden size
1189
+ self.audio_acoustic_proj = nn.Linear(config.audio_acoustic_hidden_dim, config.hidden_size)
1190
+ # Pool patches into sequence-level representations
1191
+ self.attention_pooler = AttentionPooler(config)
1192
+ # Quantize continuous representations into discrete tokens
1193
+ self.quantizer = ResidualFSQ(
1194
+ dim=config.fsq_dim,
1195
+ levels=config.fsq_input_levels,
1196
+ num_quantizers=config.fsq_input_num_quantizers
1197
+ )
1198
+ self.pool_window_size = config.pool_window_size
1199
+ # Initialize weights and apply final processing
1200
+ self.post_init()
1201
+
1202
+ @can_return_tuple
1203
+ def forward(
1204
+ self,
1205
+ hidden_states: Optional[torch.FloatTensor] = None,
1206
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
1207
+ ) -> BaseModelOutput:
1208
+
1209
+ # Project acoustic features to hidden size
1210
+ hidden_states = self.audio_acoustic_proj(hidden_states)
1211
+ # Pool sequences: N x T//pool_window_size x pool_window_size x d -> N x T//pool_window_size x d
1212
+ hidden_states = self.attention_pooler(hidden_states)
1213
+ # Quantize continuous representations into discrete tokens: N x T//pool_window_size x d
1214
+ quantized, indices = self.quantizer(hidden_states)
1215
+ return quantized, indices
1216
+
1217
+ def tokenize(self, x):
1218
+ x = rearrange(x, 'n (t_patch p) d -> n t_patch p d', p=self.pool_window_size)
1219
+ quantized, indices = self.forward(x)
1220
+ return quantized, indices
1221
+
1222
+ class Lambda(nn.Module):
1223
+ """
1224
+ Wrapper module for arbitrary lambda functions.
1225
+
1226
+ Allows using lambda functions in nn.Sequential by wrapping them in a Module.
1227
+ Useful for simple transformations like transpose operations.
1228
+ """
1229
+ def __init__(self, func):
1230
+ super().__init__()
1231
+ self.func = func
1232
+
1233
+ def forward(self, x):
1234
+ return self.func(x)
1235
+
1236
+
1237
+ class AceStepDiTModel(AceStepPreTrainedModel):
1238
+ """
1239
+ DiT (Diffusion Transformer) model for AceStep.
1240
+
1241
+ Main diffusion model that generates audio latents conditioned on text, lyrics,
1242
+ and timbre. Uses patch-based processing with transformer layers, timestep
1243
+ conditioning, and cross-attention to encoder outputs.
1244
+ """
1245
+ def __init__(self, config: AceStepConfig):
1246
+ super().__init__(config)
1247
+ # Rotary position embeddings for transformer layers
1248
+ self.rotary_emb = Qwen3RotaryEmbedding(config)
1249
+ # Stack of DiT transformer layers
1250
+ self.layers = nn.ModuleList(
1251
+ [AceStepDiTLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1252
+ )
1253
+
1254
+ in_channels = config.in_channels
1255
+ inner_dim = config.hidden_size
1256
+ patch_size = config.patch_size
1257
+ self.patch_size = patch_size
1258
+
1259
+ # Input projection: patch embedding using 1D convolution
1260
+ # Converts sequence into patches for efficient processing
1261
+ self.proj_in = nn.Sequential(
1262
+ Lambda(lambda x: x.transpose(1, 2)), # [B, T, C] -> [B, C, T]
1263
+ nn.Conv1d(
1264
+ in_channels=in_channels,
1265
+ out_channels=inner_dim,
1266
+ kernel_size=patch_size,
1267
+ stride=patch_size,
1268
+ padding=0,
1269
+ ),
1270
+ Lambda(lambda x: x.transpose(1, 2)), # [B, C, T//patch_size] -> [B, T//patch_size, C]
1271
+ )
1272
+
1273
+ # Timestep embeddings for diffusion conditioning
1274
+ # Two embeddings: one for timestep t, one for timestep difference (t - r)
1275
+ self.time_embed = TimestepEmbedding(in_channels=256, time_embed_dim=inner_dim)
1276
+ self.time_embed_r = TimestepEmbedding(in_channels=256, time_embed_dim=inner_dim)
1277
+
1278
+ # Project encoder hidden states to model dimension
1279
+ self.condition_embedder = nn.Linear(inner_dim, inner_dim, bias=True)
1280
+
1281
+ # Output normalization and projection
1282
+ # Adaptive layer norm with scale-shift modulation, then de-patchify
1283
+ self.norm_out = Qwen3RMSNorm(inner_dim, eps=config.rms_norm_eps)
1284
+ self.proj_out = nn.Sequential(
1285
+ Lambda(lambda x: x.transpose(1, 2)), # [B, T//patch_size, inner_dim] -> [B, inner_dim, T//patch_size]
1286
+ nn.ConvTranspose1d(
1287
+ in_channels=inner_dim,
1288
+ out_channels=config.audio_acoustic_hidden_dim,
1289
+ kernel_size=patch_size,
1290
+ stride=patch_size,
1291
+ padding=0,
1292
+ ),
1293
+ Lambda(lambda x: x.transpose(1, 2)), # [B, out_channels, T] -> [B, T, out_channels]
1294
+ )
1295
+ # Scale-shift table for adaptive output normalization (2 values: shift, scale)
1296
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
1297
+
1298
+ self.gradient_checkpointing = False
1299
+
1300
+ def forward(
1301
+ self,
1302
+ hidden_states: torch.Tensor,
1303
+ timestep: torch.Tensor,
1304
+ timestep_r: torch.Tensor,
1305
+ attention_mask: torch.Tensor,
1306
+ encoder_hidden_states: torch.Tensor,
1307
+ encoder_attention_mask: torch.Tensor,
1308
+ context_latents: torch.Tensor,
1309
+ use_cache: Optional[bool] = None,
1310
+ past_key_values: Optional[EncoderDecoderCache] = None,
1311
+ cache_position: Optional[torch.LongTensor] = None,
1312
+ position_ids: Optional[torch.LongTensor] = None,
1313
+ output_attentions: Optional[bool] = False,
1314
+ return_hidden_states: int = None,
1315
+ custom_layers_config: Optional[dict] = None,
1316
+ enable_early_exit: bool = False,
1317
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
1318
+ ):
1319
+
1320
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1321
+
1322
+ # Disable cache during training or when gradient checkpointing is enabled
1323
+ if self.gradient_checkpointing and self.training and use_cache:
1324
+ logger.warning_once(
1325
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1326
+ )
1327
+ use_cache = False
1328
+ if self.training:
1329
+ use_cache = False
1330
+
1331
+ # Initialize cache if needed (only during inference for auto-regressive generation)
1332
+ if not self.training and use_cache and past_key_values is None:
1333
+ past_key_values = EncoderDecoderCache(DynamicCache(), DynamicCache())
1334
+
1335
+ # Compute timestep embeddings for diffusion conditioning
1336
+ # Two embeddings: one for timestep t, one for timestep difference (t - r)
1337
+ temb_t, timestep_proj_t = self.time_embed(timestep)
1338
+ temb_r, timestep_proj_r = self.time_embed_r(timestep - timestep_r)
1339
+ # Combine embeddings
1340
+ temb = temb_t + temb_r
1341
+ timestep_proj = timestep_proj_t + timestep_proj_r
1342
+
1343
+ # Concatenate context latents (source latents + chunk masks) with hidden states
1344
+ hidden_states = torch.cat([context_latents, hidden_states], dim=-1)
1345
+ # Record original sequence length for later restoration after padding
1346
+ original_seq_len = hidden_states.shape[1]
1347
+ # Apply padding if sequence length is not divisible by patch_size
1348
+ # This ensures proper patch extraction
1349
+ pad_length = 0
1350
+ if hidden_states.shape[1] % self.patch_size != 0:
1351
+ pad_length = self.patch_size - (hidden_states.shape[1] % self.patch_size)
1352
+ hidden_states = F.pad(hidden_states, (0, 0, 0, pad_length), mode='constant', value=0)
1353
+
1354
+ # Project input to patches and project encoder states
1355
+ hidden_states = self.proj_in(hidden_states)
1356
+ encoder_hidden_states = self.condition_embedder(encoder_hidden_states)
1357
+
1358
+ # Cache positions
1359
+ if cache_position is None:
1360
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1361
+ cache_position = torch.arange(
1362
+ past_seen_tokens, past_seen_tokens + hidden_states.shape[1], device=hidden_states.device
1363
+ )
1364
+
1365
+ # Position IDs
1366
+ if position_ids is None:
1367
+ position_ids = cache_position.unsqueeze(0)
1368
+
1369
+
1370
+ seq_len = hidden_states.shape[1]
1371
+ encoder_seq_len = encoder_hidden_states.shape[1]
1372
+ dtype = hidden_states.dtype
1373
+ device = hidden_states.device
1374
+
1375
+ # 判断是否使用 Flash Attention 2
1376
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
1377
+
1378
+ # 初始化 Mask 变量
1379
+ full_attn_mask = None
1380
+ sliding_attn_mask = None
1381
+ encoder_attention_mask = None
1382
+ attention_mask = None
1383
+ if is_flash_attn:
1384
+ # -------------------------------------------------------
1385
+ # 场景 A: Flash Attention 模式
1386
+ # -------------------------------------------------------
1387
+ # FA 不需要 4D Mask。
1388
+ # 如果有 padding mask (attention_mask [B, L]),直接传给它即可。
1389
+ # 如果没有 padding mask,传 None。
1390
+ # 滑动窗口逻辑由 Layer 内部传给 FA kernel 的 sliding_window 参数控制。
1391
+ full_attn_mask = attention_mask
1392
+
1393
+ # 这里的逻辑是:如果配置启用了滑动窗口,FA 模式下我们也只需要传基础的 padding mask
1394
+ # Layer 会自己决定是否调用带 sliding window 的 kernel
1395
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
1396
+
1397
+ else:
1398
+ # -------------------------------------------------------
1399
+ # 场景 B: CPU / Mac / SDPA (Eager 模式)
1400
+ # -------------------------------------------------------
1401
+ # 必须手动生成 4D Mask [B, 1, L, L]
1402
+
1403
+ # 1. Full Attention (Bidirectional, Global)
1404
+ # 对应原来的 create_causal_mask + bidirectional
1405
+ full_attn_mask = create_4d_mask(
1406
+ seq_len=seq_len,
1407
+ dtype=dtype,
1408
+ device=device,
1409
+ attention_mask=attention_mask, # [B, L]
1410
+ sliding_window=None,
1411
+ is_sliding_window=False,
1412
+ is_causal=False # <--- 关键:双向注意力
1413
+ )
1414
+ max_len = max(seq_len, encoder_seq_len)
1415
+
1416
+ encoder_attention_mask = create_4d_mask(
1417
+ seq_len=max_len,
1418
+ dtype=dtype,
1419
+ device=device,
1420
+ attention_mask=attention_mask, # [B, L]
1421
+ sliding_window=None,
1422
+ is_sliding_window=False,
1423
+ is_causal=False # <--- 关键:双向注意力
1424
+ )
1425
+ encoder_attention_mask = encoder_attention_mask[:, :, :seq_len, :encoder_seq_len]
1426
+ # 2. Sliding Attention (Bidirectional, Local)
1427
+ # 对应原来的 create_sliding_window... + bidirectional
1428
+ if self.config.use_sliding_window:
1429
+ sliding_attn_mask = create_4d_mask(
1430
+ seq_len=seq_len,
1431
+ dtype=dtype,
1432
+ device=device,
1433
+ attention_mask=attention_mask, # [B, L]
1434
+ sliding_window=self.config.sliding_window,
1435
+ is_sliding_window=True, # <--- 开启滑动窗口
1436
+ is_causal=False # <--- 关键:双向注意力
1437
+ )
1438
+
1439
+ # 构建 Mapping
1440
+ self_attn_mask_mapping = {
1441
+ "full_attention": full_attn_mask,
1442
+ "sliding_attention": sliding_attn_mask,
1443
+ "encoder_attention_mask": encoder_attention_mask,
1444
+ }
1445
+
1446
+ # Create position embeddings to be shared across all decoder layers
1447
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1448
+ all_cross_attentions = () if output_attentions else None
1449
+
1450
+ # Handle early exit for custom layer configurations
1451
+ max_needed_layer = float('inf')
1452
+ if custom_layers_config is not None and enable_early_exit:
1453
+ max_needed_layer = max(custom_layers_config.keys())
1454
+ # Force output_attentions to True when early exit is enabled for attention extraction
1455
+ output_attentions = True
1456
+ if all_cross_attentions is None:
1457
+ all_cross_attentions = ()
1458
+
1459
+ # Process through transformer layers
1460
+ for index_block, layer_module in enumerate(self.layers):
1461
+
1462
+ layer_outputs = layer_module(
1463
+ hidden_states,
1464
+ position_embeddings,
1465
+ timestep_proj,
1466
+ self_attn_mask_mapping[layer_module.attention_type],
1467
+ position_ids,
1468
+ past_key_values,
1469
+ output_attentions,
1470
+ use_cache,
1471
+ cache_position,
1472
+ encoder_hidden_states,
1473
+ self_attn_mask_mapping["encoder_attention_mask"],
1474
+ **flash_attn_kwargs,
1475
+ )
1476
+ hidden_states = layer_outputs[0]
1477
+
1478
+ if output_attentions and self.layers[index_block].use_cross_attention:
1479
+ # layer_outputs structure: (hidden_states, self_attn_weights, cross_attn_weights)
1480
+ # Extract the last element which is cross_attn_weights
1481
+ if len(layer_outputs) >= 3:
1482
+ all_cross_attentions += (layer_outputs[2],)
1483
+
1484
+ if return_hidden_states:
1485
+ return hidden_states
1486
+
1487
+ # Extract scale-shift parameters for adaptive output normalization
1488
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
1489
+ shift = shift.to(hidden_states.device)
1490
+ scale = scale.to(hidden_states.device)
1491
+
1492
+ # Apply adaptive layer norm: norm(x) * (1 + scale) + shift
1493
+ hidden_states = (self.norm_out(hidden_states) * (1 + scale) + shift).type_as(hidden_states)
1494
+ # Project output: de-patchify back to original sequence format
1495
+ hidden_states = self.proj_out(hidden_states)
1496
+
1497
+ # Crop back to original sequence length to ensure exact length match (remove padding)
1498
+ hidden_states = hidden_states[:, :original_seq_len, :]
1499
+
1500
+ outputs = (hidden_states, past_key_values)
1501
+
1502
+ if output_attentions:
1503
+ outputs += (all_cross_attentions,)
1504
+ return outputs
1505
+
1506
+ class AceStepConditionEncoder(AceStepPreTrainedModel):
1507
+ """
1508
+ Condition encoder for AceStep model.
1509
+
1510
+ Encodes multiple conditioning inputs (text, lyrics, timbre) and packs them
1511
+ into a single sequence for cross-attention in the diffusion model. Handles
1512
+ projection, encoding, and sequence packing.
1513
+ """
1514
+ def __init__(self, config: AceStepConfig):
1515
+ super().__init__(config)
1516
+ self.config = config
1517
+ # Project text embeddings to model hidden size
1518
+ self.text_projector = nn.Linear(config.text_hidden_dim, config.hidden_size, bias=False)
1519
+ # Encoder for lyric text
1520
+ self.lyric_encoder = AceStepLyricEncoder(config)
1521
+ # Encoder for timbre from reference audio
1522
+ self.timbre_encoder = AceStepTimbreEncoder(config)
1523
+
1524
+ def forward(
1525
+ self,
1526
+ # Text inputs
1527
+ text_hidden_states: Optional[torch.FloatTensor] = None,
1528
+ text_attention_mask: Optional[torch.Tensor] = None,
1529
+ # Lyric inputs
1530
+ lyric_hidden_states: Optional[torch.LongTensor] = None,
1531
+ lyric_attention_mask: Optional[torch.Tensor] = None,
1532
+ # Reference audio for timbre
1533
+ refer_audio_acoustic_hidden_states_packed: Optional[torch.Tensor] = None,
1534
+ refer_audio_order_mask: Optional[torch.LongTensor] = None,
1535
+ ):
1536
+ # Project and encode text
1537
+ text_hidden_states = self.text_projector(text_hidden_states)
1538
+ # Encode lyrics
1539
+ lyric_encoder_outputs = self.lyric_encoder(
1540
+ inputs_embeds=lyric_hidden_states,
1541
+ attention_mask=lyric_attention_mask,
1542
+ )
1543
+ lyric_hidden_states = lyric_encoder_outputs.last_hidden_state
1544
+ # Encode timbre from reference audio
1545
+ timbre_embs_unpack, timbre_embs_mask = self.timbre_encoder(refer_audio_acoustic_hidden_states_packed, refer_audio_order_mask)
1546
+
1547
+ # Pack sequences: combine lyrics and timbre, then add text
1548
+ # This creates a single sequence with all conditioning information
1549
+ encoder_hidden_states, encoder_attention_mask = pack_sequences(lyric_hidden_states, timbre_embs_unpack, lyric_attention_mask, timbre_embs_mask)
1550
+ encoder_hidden_states, encoder_attention_mask = pack_sequences(encoder_hidden_states, text_hidden_states, encoder_attention_mask, text_attention_mask)
1551
+ return encoder_hidden_states, encoder_attention_mask
1552
+
1553
+
1554
+ class AceStepConditionGenerationModel(AceStepPreTrainedModel):
1555
+ """
1556
+ Main conditional generation model for AceStep.
1557
+
1558
+ End-to-end model for generating audio conditioned on text, lyrics, and timbre.
1559
+ Combines encoder (for conditioning), decoder (diffusion model), tokenizer
1560
+ (for discrete tokenization), and detokenizer (for reconstruction).
1561
+ Supports flow matching training and inference with various sampling methods.
1562
+ """
1563
+ def __init__(self, config: AceStepConfig):
1564
+ super().__init__(config)
1565
+ self.config = config
1566
+ # Diffusion model components
1567
+ self.decoder = AceStepDiTModel(config) # Main diffusion transformer
1568
+ self.encoder = AceStepConditionEncoder(config) # Condition encoder
1569
+ self.tokenizer = AceStepAudioTokenizer(config) # Audio tokenizer
1570
+ self.detokenizer = AudioTokenDetokenizer(config) # Audio detokenizer
1571
+ # Null condition embedding for classifier-free guidance
1572
+ self.null_condition_emb = nn.Parameter(torch.randn(1, 1, config.hidden_size))
1573
+
1574
+ # Initialize weights and apply final processing
1575
+ self.post_init()
1576
+
1577
+ def tokenize(self, x, silence_latent, attention_mask):
1578
+ if x.shape[1] % self.config.pool_window_size != 0:
1579
+ pad_len = self.config.pool_window_size - (x.shape[1] % self.config.pool_window_size)
1580
+ x = torch.cat([x, silence_latent[:1,:pad_len].repeat(x.shape[0],1,1)], dim=1)
1581
+ attention_mask = F.pad(attention_mask, (0, pad_len), mode='constant', value=0)
1582
+ x = rearrange(x, 'n (t_patch p) d -> n t_patch p d', p=self.config.pool_window_size)
1583
+ seq_len = x.shape[1]
1584
+ chunk = math.ceil(attention_mask.shape[1] / seq_len)
1585
+ attention_mask = attention_mask.to(x.dtype)
1586
+ attention_mask = F.max_pool1d(attention_mask.unsqueeze(1), kernel_size=chunk, stride=chunk, ceil_mode=True).squeeze(1)
1587
+ quantized, indices = self.tokenizer(x)
1588
+ return quantized, indices, attention_mask
1589
+
1590
+ def detokenize(self, quantized):
1591
+ """
1592
+ Detokenize quantized audio tokens back to continuous representations.
1593
+
1594
+ Args:
1595
+ quantized: Quantized tokens of shape [N, T//pool_window_size, d]
1596
+
1597
+ Returns:
1598
+ Detokenized hidden states of shape [N, T, d]
1599
+ """
1600
+ hidden_states = self.detokenizer(quantized)
1601
+ return hidden_states
1602
+
1603
+ @torch.no_grad()
1604
+ def prepare_condition(
1605
+ self,
1606
+ text_hidden_states: torch.FloatTensor,
1607
+ text_attention_mask: torch.Tensor,
1608
+ lyric_hidden_states: torch.FloatTensor,
1609
+ lyric_attention_mask: torch.Tensor,
1610
+ refer_audio_acoustic_hidden_states_packed: torch.FloatTensor,
1611
+ refer_audio_order_mask: torch.Tensor,
1612
+ hidden_states: torch.FloatTensor,
1613
+ attention_mask: torch.Tensor,
1614
+ silence_latent: torch.FloatTensor,
1615
+ src_latents: torch.FloatTensor,
1616
+ chunk_masks: torch.Tensor,
1617
+ is_covers: torch.Tensor,
1618
+ precomputed_lm_hints_25Hz: Optional[torch.FloatTensor] = None,
1619
+ audio_codes: torch.FloatTensor = None,
1620
+ ):
1621
+
1622
+ dtype = hidden_states.dtype
1623
+ encoder_hidden_states, encoder_attention_mask = self.encoder(
1624
+ text_hidden_states=text_hidden_states,
1625
+ text_attention_mask=text_attention_mask,
1626
+ lyric_hidden_states=lyric_hidden_states,
1627
+ lyric_attention_mask=lyric_attention_mask,
1628
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
1629
+ refer_audio_order_mask=refer_audio_order_mask,
1630
+ )
1631
+
1632
+ # N x T x d -> N x T//pool_window_size x pool_window_size x d
1633
+ # tokenize and detokenize to get LM hints for cover songs (when is_covers=True)
1634
+ # Use precomputed hints if provided (e.g., from audio codes), otherwise tokenize hidden_states
1635
+ if precomputed_lm_hints_25Hz is not None:
1636
+ print("Using precomputed LM hints")
1637
+ lm_hints_25Hz = precomputed_lm_hints_25Hz[:, :src_latents.shape[1], :]
1638
+ else:
1639
+ if audio_codes is not None:
1640
+ lm_hints_5Hz = self.tokenize.quantizer.get_output_from_indices(audio_codes)
1641
+ else:
1642
+ lm_hints_5Hz, indices, llm_mask = self.tokenize(hidden_states, silence_latent, attention_mask)
1643
+ lm_hints_25Hz = self.detokenize(lm_hints_5Hz)
1644
+ # Crop lm_hints_25Hz to match src_latents length (tokenize may have added padding)
1645
+ lm_hints_25Hz = lm_hints_25Hz[:, :src_latents.shape[1], :]
1646
+ src_latents = torch.where(is_covers.unsqueeze(-1).unsqueeze(-1) > 0, lm_hints_25Hz, src_latents)
1647
+ # Concatenate source latents with chunk masks as context
1648
+ context_latents = torch.cat([src_latents, chunk_masks.to(dtype)], dim=-1)
1649
+ return encoder_hidden_states, encoder_attention_mask, context_latents
1650
+
1651
+ def forward(
1652
+ self,
1653
+ # Diffusion inputs
1654
+ hidden_states: torch.FloatTensor,
1655
+ attention_mask: torch.Tensor,
1656
+ # Encoder inputs
1657
+ # Text
1658
+ text_hidden_states: Optional[torch.FloatTensor] = None,
1659
+ text_attention_mask: Optional[torch.Tensor] = None,
1660
+ # Lyric
1661
+ lyric_hidden_states: Optional[torch.LongTensor] = None,
1662
+ lyric_attention_mask: Optional[torch.Tensor] = None,
1663
+ # Reference audio for timbre
1664
+ refer_audio_acoustic_hidden_states_packed: Optional[torch.Tensor] = None,
1665
+ refer_audio_order_mask: Optional[torch.LongTensor] = None,
1666
+ src_latents: torch.FloatTensor = None,
1667
+ chunk_masks: torch.FloatTensor = None,
1668
+ is_covers: torch.Tensor = None,
1669
+ silence_latent: torch.FloatTensor = None,
1670
+ cfg_ratio: float = 0.15,
1671
+ ):
1672
+ """
1673
+ Forward pass for training (computes training losses).
1674
+ """
1675
+ # Prepare conditioning inputs (encoder states, context latents)
1676
+ encoder_hidden_states, encoder_attention_mask, context_latents = self.prepare_condition(
1677
+ text_hidden_states=text_hidden_states,
1678
+ text_attention_mask=text_attention_mask,
1679
+ lyric_hidden_states=lyric_hidden_states,
1680
+ lyric_attention_mask=lyric_attention_mask,
1681
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
1682
+ refer_audio_order_mask=refer_audio_order_mask,
1683
+ hidden_states=src_latents,
1684
+ attention_mask=attention_mask,
1685
+ silence_latent=silence_latent,
1686
+ src_latents=src_latents,
1687
+ chunk_masks=chunk_masks,
1688
+ is_covers=is_covers,
1689
+ )
1690
+ bsz, device, dtype = hidden_states.shape[0], hidden_states.device, hidden_states.dtype
1691
+ # Classifier-free guidance: randomly drop conditions with probability cfg_ratio
1692
+ # This helps the model learn to work with and without conditions
1693
+ full_cfg_condition_mask = torch.where(
1694
+ (torch.rand(size=(bsz,), device=device, dtype=dtype) < cfg_ratio),
1695
+ torch.zeros(size=(bsz,), device=device, dtype=dtype),
1696
+ torch.ones(size=(bsz,), device=device, dtype=dtype)
1697
+ ).view(-1, 1, 1)
1698
+ # Replace dropped conditions with null condition embedding
1699
+ encoder_hidden_states = torch.where(full_cfg_condition_mask > 0, encoder_hidden_states, self.null_condition_emb.expand_as(encoder_hidden_states))
1700
+
1701
+ # Flow matching setup: sample noise x1 and interpolate with data x0
1702
+ x1 = torch.randn_like(hidden_states) # Noise
1703
+ x0 = hidden_states # Data
1704
+ # Sample timesteps t and r for flow matching
1705
+ t, r = sample_t_r(bsz, device, dtype, self.config.data_proportion, self.config.timestep_mu, self.config.timestep_sigma, use_meanflow=False)
1706
+ t_ = t.unsqueeze(-1).unsqueeze(-1)
1707
+ # Interpolate: x_t = t * x1 + (1 - t) * x0
1708
+ xt = t_ * x1 + (1.0 - t_) * x0
1709
+
1710
+ # Predict flow (velocity) from diffusion model
1711
+ decoder_outputs = self.decoder(
1712
+ hidden_states=xt,
1713
+ timestep=t,
1714
+ timestep_r=t,
1715
+ attention_mask=attention_mask,
1716
+ encoder_hidden_states=encoder_hidden_states,
1717
+ encoder_attention_mask=encoder_attention_mask,
1718
+ context_latents=context_latents,
1719
+ )
1720
+ # Flow matching loss: predict the flow field v = x1 - x0
1721
+ flow = x1 - x0
1722
+ diffusion_loss = F.mse_loss(decoder_outputs[0], flow)
1723
+ return {
1724
+ "diffusion_loss": diffusion_loss,
1725
+ }
1726
+
1727
+ def training_losses(self, **kwargs):
1728
+ return self.forward(**kwargs)
1729
+
1730
+ def prepare_noise(self, context_latents: torch.FloatTensor, seed: Union[int, List[int], None] = None):
1731
+ """
1732
+ Prepare noise tensor for generation with optional seeding.
1733
+
1734
+ Args:
1735
+ context_latents: Context latents to determine noise shape
1736
+ seed: Can be int, List[int], or None. If None, uses random noise.
1737
+
1738
+ Returns:
1739
+ Noise tensor of appropriate shape
1740
+ """
1741
+ bsz = context_latents.shape[0]
1742
+ device = context_latents.device
1743
+ dtype = context_latents.dtype
1744
+ # Handle seed: can be int, List[int], or None
1745
+ src_latents_shape = (context_latents.shape[0], context_latents.shape[1], context_latents.shape[-1] // 2)
1746
+ if seed is None:
1747
+ # No seed provided - use random
1748
+ noise = torch.randn(src_latents_shape, device=device, dtype=dtype)
1749
+ elif isinstance(seed, list):
1750
+ # List of seeds - generate noise for each sample separately
1751
+ noise_list = []
1752
+ for i, s in enumerate(seed):
1753
+ if s is None or s < 0:
1754
+ # Random seed for this sample
1755
+ noise_i = torch.randn(1, src_latents_shape[1], src_latents_shape[2], device=device, dtype=dtype)
1756
+ else:
1757
+ # Use specific seed for this sample
1758
+ generator = torch.Generator(device=device).manual_seed(int(s))
1759
+ noise_i = torch.randn(1, src_latents_shape[1], src_latents_shape[2], generator=generator, device=device, dtype=dtype)
1760
+ noise_list.append(noise_i)
1761
+ noise = torch.cat(noise_list, dim=0)
1762
+ else:
1763
+ # Single seed for all samples
1764
+ generator = torch.Generator(device=device).manual_seed(int(seed))
1765
+ noise = torch.randn(src_latents_shape, generator=generator, device=device, dtype=dtype)
1766
+
1767
+ return noise
1768
+
1769
+ def get_x0_from_noise(self, zt, vt, t):
1770
+ return zt - vt * t.unsqueeze(-1).unsqueeze(-1)
1771
+
1772
+ def renoise(self, x, t, noise=None):
1773
+ if noise is None:
1774
+ noise = torch.randn_like(x)
1775
+ if isinstance(t, torch.Tensor) and t.ndim != x.ndim:
1776
+ t = t.unsqueeze(-1).unsqueeze(-1)
1777
+ xt = t * noise + (1 - t) * x
1778
+ return xt
1779
+
1780
+ def generate_audio(
1781
+ self,
1782
+ text_hidden_states: torch.FloatTensor,
1783
+ text_attention_mask: torch.FloatTensor,
1784
+ lyric_hidden_states: torch.FloatTensor,
1785
+ lyric_attention_mask: torch.FloatTensor,
1786
+ refer_audio_acoustic_hidden_states_packed: torch.FloatTensor,
1787
+ refer_audio_order_mask: torch.LongTensor,
1788
+ src_latents: torch.FloatTensor,
1789
+ chunk_masks: torch.FloatTensor,
1790
+ is_covers: torch.Tensor,
1791
+ silence_latent: Optional[torch.FloatTensor] = None,
1792
+ attention_mask: torch.Tensor = None,
1793
+ seed: int = None,
1794
+ fix_nfe: int = 8,
1795
+ infer_method: str = "ode",
1796
+ use_cache: bool = True,
1797
+ audio_cover_strength: float = 1.0,
1798
+ non_cover_text_hidden_states: Optional[torch.FloatTensor] = None,
1799
+ non_cover_text_attention_mask: Optional[torch.FloatTensor] = None,
1800
+ precomputed_lm_hints_25Hz: Optional[torch.FloatTensor] = None,
1801
+ audio_codes: Optional[torch.FloatTensor] = None,
1802
+ shift: float = 3.0,
1803
+ timesteps: Optional[torch.Tensor] = None,
1804
+ **kwargs,
1805
+ ):
1806
+ # Valid shifts: only discrete values 1, 2, 3 are supported
1807
+ VALID_SHIFTS = [1.0, 2.0, 3.0]
1808
+
1809
+ # Valid timesteps: all unique timesteps from shift=1,2,3 with fix_nfe=8 (total 20 values)
1810
+ VALID_TIMESTEPS = [
1811
+ 1.0, 0.9545454545454546, 0.9333333333333333, 0.9, 0.875,
1812
+ 0.8571428571428571, 0.8333333333333334, 0.7692307692307693, 0.75,
1813
+ 0.6666666666666666, 0.6428571428571429, 0.625, 0.5454545454545454,
1814
+ 0.5, 0.4, 0.375, 0.3, 0.25, 0.2222222222222222, 0.125
1815
+ ]
1816
+
1817
+ # Pre-defined timestep schedules for each valid shift (fix_nfe=8, excluding final 0)
1818
+ SHIFT_TIMESTEPS = {
1819
+ 1.0: [1.0, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125],
1820
+ 2.0: [1.0, 0.9333333333333333, 0.8571428571428571, 0.7692307692307693, 0.6666666666666666, 0.5454545454545454, 0.4, 0.2222222222222222],
1821
+ 3.0: [1.0, 0.9545454545454546, 0.9, 0.8333333333333334, 0.75, 0.6428571428571429, 0.5, 0.3],
1822
+ }
1823
+
1824
+ # Determine the timestep schedule to use
1825
+ t_schedule_list = None
1826
+
1827
+ if timesteps is not None:
1828
+ # Process custom timesteps: map each value to nearest valid timestep
1829
+ timesteps_list = timesteps.tolist() if isinstance(timesteps, torch.Tensor) else list(timesteps)
1830
+
1831
+ # Remove trailing zeros
1832
+ while len(timesteps_list) > 0 and timesteps_list[-1] == 0:
1833
+ timesteps_list.pop()
1834
+
1835
+ # Validate length: 1-20
1836
+ if len(timesteps_list) < 1:
1837
+ logger.warning(f"timesteps length is too short after removing trailing zeros, using default shift={shift}")
1838
+ elif len(timesteps_list) > 20:
1839
+ logger.warning(f"timesteps length={len(timesteps_list)} exceeds maximum 20, truncating to 20")
1840
+ timesteps_list = timesteps_list[:20]
1841
+ t_schedule_list = timesteps_list
1842
+ else:
1843
+ t_schedule_list = timesteps_list
1844
+
1845
+ if t_schedule_list is not None:
1846
+ # Map each timestep to nearest valid timestep
1847
+ original_timesteps = t_schedule_list.copy()
1848
+ mapped_timesteps = []
1849
+ for t in t_schedule_list:
1850
+ nearest = min(VALID_TIMESTEPS, key=lambda x: abs(x - t))
1851
+ mapped_timesteps.append(nearest)
1852
+
1853
+ if original_timesteps != mapped_timesteps:
1854
+ logger.warning(f"timesteps mapped to nearest valid values: {original_timesteps} -> {mapped_timesteps}")
1855
+
1856
+ t_schedule_list = mapped_timesteps
1857
+
1858
+ if t_schedule_list is None:
1859
+ # Use shift-based schedule: round to nearest valid shift
1860
+ original_shift = shift
1861
+ shift = min(VALID_SHIFTS, key=lambda x: abs(x - shift))
1862
+ if original_shift != shift:
1863
+ logger.warning(f"shift={original_shift} not supported, rounded to nearest valid shift={shift}")
1864
+ t_schedule_list = SHIFT_TIMESTEPS[shift]
1865
+
1866
+ if attention_mask is None:
1867
+ latent_length = src_latents.shape[1]
1868
+ attention_mask = torch.ones(src_latents.shape[0], latent_length, device=src_latents.device, dtype=src_latents.dtype)
1869
+
1870
+ time_costs = {}
1871
+ start_time = time.time()
1872
+ total_start_time = start_time
1873
+ encoder_hidden_states, encoder_attention_mask, context_latents = self.prepare_condition(
1874
+ text_hidden_states=text_hidden_states,
1875
+ text_attention_mask=text_attention_mask,
1876
+ lyric_hidden_states=lyric_hidden_states,
1877
+ lyric_attention_mask=lyric_attention_mask,
1878
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
1879
+ refer_audio_order_mask=refer_audio_order_mask,
1880
+ hidden_states=src_latents,
1881
+ attention_mask=attention_mask,
1882
+ silence_latent=silence_latent,
1883
+ src_latents=src_latents,
1884
+ chunk_masks=chunk_masks,
1885
+ is_covers=is_covers,
1886
+ precomputed_lm_hints_25Hz=precomputed_lm_hints_25Hz,
1887
+ audio_codes=audio_codes,
1888
+ )
1889
+
1890
+ encoder_hidden_states_non_cover, encoder_attention_mask_non_cover, context_latents_non_cover = None, None, None
1891
+ if audio_cover_strength < 1.0:
1892
+ non_is_covers = torch.zeros_like(is_covers, device=is_covers.device, dtype=is_covers.dtype)
1893
+ # Use silence_latent for non-cover condition to simulate text2music mode (no reference audio)
1894
+ silence_latent_expanded = silence_latent[:, :src_latents.shape[1], :].expand(src_latents.shape[0], -1, -1)
1895
+ encoder_hidden_states_non_cover, encoder_attention_mask_non_cover, context_latents_non_cover = self.prepare_condition(
1896
+ text_hidden_states=non_cover_text_hidden_states,
1897
+ text_attention_mask=non_cover_text_attention_mask,
1898
+ lyric_hidden_states=lyric_hidden_states,
1899
+ lyric_attention_mask=lyric_attention_mask,
1900
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
1901
+ refer_audio_order_mask=refer_audio_order_mask,
1902
+ hidden_states=silence_latent_expanded,
1903
+ attention_mask=attention_mask,
1904
+ silence_latent=silence_latent,
1905
+ src_latents=silence_latent_expanded,
1906
+ chunk_masks=chunk_masks,
1907
+ is_covers=non_is_covers,
1908
+ precomputed_lm_hints_25Hz=None,
1909
+ audio_codes=None,
1910
+ )
1911
+
1912
+ end_time = time.time()
1913
+ time_costs["encoder_time_cost"] = end_time - start_time
1914
+ start_time = end_time
1915
+
1916
+ noise = self.prepare_noise(context_latents, seed)
1917
+ bsz, device, dtype = context_latents.shape[0], context_latents.device, context_latents.dtype
1918
+ past_key_values = EncoderDecoderCache(DynamicCache(), DynamicCache())
1919
+
1920
+ # Use pre-computed t_schedule_list (already validated and mapped to valid timesteps)
1921
+ t_schedule = torch.tensor(t_schedule_list, device=device, dtype=dtype)
1922
+ num_steps = len(t_schedule)
1923
+
1924
+ # Recalculate cover_steps based on actual num_steps
1925
+ cover_steps = int(num_steps * audio_cover_strength)
1926
+
1927
+ xt = noise
1928
+ for step_idx in range(num_steps):
1929
+ current_timestep = t_schedule[step_idx].item()
1930
+ t_curr_tensor = current_timestep * torch.ones((bsz,), device=device, dtype=dtype)
1931
+
1932
+ if step_idx >= cover_steps:
1933
+ encoder_hidden_states = encoder_hidden_states_non_cover
1934
+ encoder_attention_mask = encoder_attention_mask_non_cover
1935
+ context_latents = context_latents_non_cover
1936
+ past_key_values = EncoderDecoderCache(DynamicCache(), DynamicCache())
1937
+
1938
+ with torch.no_grad():
1939
+ decoder_outputs = self.decoder(
1940
+ hidden_states=xt,
1941
+ timestep=t_curr_tensor,
1942
+ timestep_r=t_curr_tensor,
1943
+ attention_mask=attention_mask,
1944
+ encoder_hidden_states=encoder_hidden_states,
1945
+ encoder_attention_mask=encoder_attention_mask,
1946
+ context_latents=context_latents,
1947
+ use_cache=True,
1948
+ past_key_values=past_key_values,
1949
+ )
1950
+
1951
+ vt = decoder_outputs[0]
1952
+ past_key_values = decoder_outputs[1]
1953
+
1954
+ # On final step, directly compute x0 from noise
1955
+ if step_idx == num_steps - 1:
1956
+ xt = self.get_x0_from_noise(xt, vt, t_curr_tensor)
1957
+ break
1958
+
1959
+ # Update x_t based on inference method
1960
+ if infer_method == "sde":
1961
+ # Stochastic Differential Equation: predict clean, then re-add noise
1962
+ pred_clean = self.get_x0_from_noise(xt, vt, t_curr_tensor)
1963
+ next_timestep = t_schedule[step_idx + 1].item()
1964
+ xt = self.renoise(pred_clean, next_timestep)
1965
+ elif infer_method == "ode":
1966
+ # Ordinary Differential Equation: Euler method
1967
+ # dx/dt = -v, so x_{t+1} = x_t - v_t * dt
1968
+ next_timestep = t_schedule[step_idx + 1].item()
1969
+ dt = current_timestep - next_timestep
1970
+ dt_tensor = dt * torch.ones((bsz,), device=device, dtype=dtype).unsqueeze(-1).unsqueeze(-1)
1971
+ xt = xt - vt * dt_tensor
1972
+
1973
+ x_gen = xt
1974
+ end_time = time.time()
1975
+ time_costs["diffusion_time_cost"] = end_time - start_time
1976
+ time_costs["diffusion_per_step_time_cost"] = time_costs["diffusion_time_cost"] / num_steps
1977
+ time_costs["total_time_cost"] = end_time - total_start_time
1978
+ return {
1979
+ "target_latents": x_gen,
1980
+ "time_costs": time_costs,
1981
+ }
1982
+
1983
+
1984
+ def test_forward(model, seed=42):
1985
+ # Fix random seed for reproducibility
1986
+ import random
1987
+ import numpy as np
1988
+ random.seed(seed)
1989
+ np.random.seed(seed)
1990
+ torch.manual_seed(seed)
1991
+ if torch.cuda.is_available():
1992
+ torch.cuda.manual_seed(seed)
1993
+ torch.cuda.manual_seed_all(seed)
1994
+ torch.backends.cudnn.deterministic = True
1995
+ torch.backends.cudnn.benchmark = False
1996
+
1997
+ # Get model dtype and device
1998
+ model_dtype = next(model.parameters()).dtype
1999
+ device = next(model.parameters()).device
2000
+
2001
+ print(f"Testing with dtype: {model_dtype}, device: {device}, seed: {seed}")
2002
+
2003
+ # Test data preparation with matching dtype
2004
+ text_hidden_states = torch.randn(2, 77, 1024, dtype=model_dtype, device=device)
2005
+ text_attention_mask = torch.ones(2, 77, dtype=model_dtype, device=device)
2006
+ lyric_hidden_states = torch.randn(2, 123, 1024, dtype=model_dtype, device=device)
2007
+ lyric_attention_mask = torch.ones(2, 123, dtype=model_dtype, device=device)
2008
+ refer_audio_acoustic_hidden_states_packed = torch.randn(3, 750, 64, dtype=model_dtype, device=device)
2009
+ refer_audio_order_mask = torch.LongTensor([0, 0, 1]).to(device)
2010
+
2011
+ # Base config: 25 Hz hidden states → 10 s = 250 frames (round to int)
2012
+ base_seconds = 10
2013
+ frames_per_second = 25
2014
+ base_seq_len = base_seconds * frames_per_second
2015
+
2016
+ hidden_states = torch.randn(2, base_seq_len, 64, dtype=model_dtype, device=device)
2017
+ attention_mask = torch.ones(2, base_seq_len, dtype=model_dtype, device=device)
2018
+ # Add some padding to test mask behavior
2019
+ pad_start = max(base_seq_len // 2, 1)
2020
+ attention_mask[0, pad_start:] = 0
2021
+ chunk_mask = torch.ones(2, base_seq_len, 64, dtype=model_dtype, device=device)
2022
+ chunk_mask[0, pad_start:] = 0
2023
+
2024
+ silence_latent = torch.randn(2, base_seq_len, 64, dtype=model_dtype, device=device)
2025
+ # New required parameters for updated training logic
2026
+ src_latents = torch.randn(2, base_seq_len, 64, dtype=model_dtype, device=device) # Source latents for context
2027
+ is_covers = torch.tensor([0, 1], dtype=torch.long, device=device) # Cover song indicators (0=original, 1=cover)
2028
+
2029
+ # Test 1: Flow matching training (using 10s sequence for sanity check by default)
2030
+ print(f"Testing flow matching training with {base_seconds}s sequence ({base_seq_len} frames @ {frames_per_second}Hz)...")
2031
+ outputs = model.training_losses(
2032
+ hidden_states=hidden_states,
2033
+ attention_mask=attention_mask,
2034
+ chunk_masks=chunk_mask,
2035
+ text_hidden_states=text_hidden_states,
2036
+ text_attention_mask=text_attention_mask,
2037
+ lyric_hidden_states=lyric_hidden_states,
2038
+ lyric_attention_mask=lyric_attention_mask,
2039
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
2040
+ refer_audio_order_mask=refer_audio_order_mask,
2041
+ silence_latent=silence_latent,
2042
+ src_latents=src_latents,
2043
+ is_covers=is_covers,
2044
+ cfg_ratio=0.15,
2045
+ )
2046
+ loss = outputs['diffusion_loss']
2047
+ print(f"Flow matching loss: {loss.item():.6f}")
2048
+ print(f" Loss stats - min: {loss.min().item():.6f}, max: {loss.max().item():.6f}, mean: {loss.mean().item():.6f}, std: {loss.std().item() if loss.numel() > 1 else 0:.6f}")
2049
+
2050
+ # Test 2: Generation with flow matching, testing throughput for different sequence lengths
2051
+ lengths_seconds = [10, 30, 60, 120, 180, 240]
2052
+ infer_steps = 2 # Can be increased as needed (e.g., 50/100) to better approximate real inference
2053
+
2054
+ print("\n===== Throughput benchmark (25Hz hidden states) =====")
2055
+ for seconds in lengths_seconds:
2056
+ seq_len = seconds * frames_per_second
2057
+
2058
+ # Reconstruct inputs for current sequence length
2059
+ cur_hidden_states = torch.randn(2, seq_len, 64, dtype=model_dtype, device=device)
2060
+ cur_attention_mask = torch.ones(2, seq_len, dtype=model_dtype, device=device)
2061
+ cur_chunk_mask = torch.ones(2, seq_len, 64, dtype=model_dtype, device=device)
2062
+ cur_silence_latent = torch.randn(2, seq_len, 64, dtype=model_dtype, device=device)
2063
+ cur_src_latents = torch.randn(2, seq_len, 64, dtype=model_dtype, device=device)
2064
+
2065
+ print(f"\n--- {seconds}s input ({seq_len} frames @ {frames_per_second}Hz) ---")
2066
+ outputs = model.generate_audio(
2067
+ text_hidden_states=text_hidden_states,
2068
+ text_attention_mask=text_attention_mask,
2069
+ lyric_hidden_states=lyric_hidden_states,
2070
+ lyric_attention_mask=lyric_attention_mask,
2071
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
2072
+ refer_audio_order_mask=refer_audio_order_mask,
2073
+ src_latents=cur_src_latents,
2074
+ chunk_masks=cur_chunk_mask,
2075
+ silence_latent=cur_silence_latent,
2076
+ infer_steps=infer_steps,
2077
+ is_covers=is_covers,
2078
+ seed=1234,
2079
+ )
2080
+
2081
+ target_latents = outputs["target_latents"]
2082
+ time_costs = outputs.get("time_costs", {})
2083
+
2084
+ total_time = time_costs.get("total_time_cost", None)
2085
+ diffusion_time = time_costs.get("diffusion_time_cost", None)
2086
+
2087
+ # Output shape and statistics
2088
+ print(f"Generated latents shape: {target_latents.shape}")
2089
+ print(
2090
+ f"Stats - min: {target_latents.min().item():.4f}, "
2091
+ f"max: {target_latents.max().item():.4f}, "
2092
+ f"mean: {target_latents.mean().item():.4f}, "
2093
+ f"std: {target_latents.std().item():.4f}"
2094
+ )
2095
+
2096
+ # Calculate throughput: statistics by frame count and audio seconds
2097
+ bsz, t_len = target_latents.shape[0], target_latents.shape[1]
2098
+ audio_seconds = t_len / frames_per_second
2099
+
2100
+ if total_time is not None:
2101
+ frames_throughput = (bsz * t_len) / total_time
2102
+ seconds_throughput = (bsz * audio_seconds) / total_time
2103
+ print(
2104
+ f"Time costs: total={total_time:.4f}s, diffusion={diffusion_time:.4f}s "
2105
+ f"({infer_steps} steps)"
2106
+ if diffusion_time is not None
2107
+ else f"Time costs: total={total_time:.4f}s"
2108
+ )
2109
+ print(
2110
+ f"Throughput (based on total_time): "
2111
+ f"{frames_throughput:.2f} frames/s, "
2112
+ f"{seconds_throughput:.2f} audio-seconds/s (batch={bsz})"
2113
+ )
2114
+ else:
2115
+ print("Time costs not available in outputs['time_costs']; only basic stats printed.")
2116
+
2117
+
2118
+ if __name__ == "__main__":
2119
+ from torch.profiler import profile, record_function, ProfilerActivity
2120
+ import os, torch
2121
+ import time
2122
+ from transformers import AutoModel
2123
+ config = AceStepConfig()
2124
+ start = time.time()
2125
+ import os
2126
+ model_dir = os.path.dirname(os.path.abspath(__file__))
2127
+ model = AceStepConditionGenerationModel.from_pretrained(model_dir)
2128
+ end = time.time()
2129
+ # model.config._attn_implementation = "sdpa"
2130
+ model.config._attn_implementation = "flash_attention_2"
2131
+ model.eval()
2132
+ # model = model.to("cpu")
2133
+ # model = model.float()
2134
+ model = model.to("cuda")
2135
+ model = model.bfloat16()
2136
+ test_forward(model)
acestep-v15-turbo/silence_latent.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a778e9dd942f5e8b2c09c55370782d318834432b03dabbcdf70e6ed49ad6358b
3
+ size 3841215
config.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "AceStepConditionGenerationModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "audio_acoustic_hidden_dim": 64,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_acestep_v15.AceStepConfig",
10
+ "AutoModel": "modeling_acestep_v15_turbo.AceStepConditionGenerationModel"
11
+ },
12
+ "data_proportion": 0.5,
13
+ "dtype": "bfloat16",
14
+ "fsq_dim": 2048,
15
+ "fsq_input_levels": [
16
+ 8,
17
+ 8,
18
+ 8,
19
+ 5,
20
+ 5,
21
+ 5
22
+ ],
23
+ "fsq_input_num_quantizers": 1,
24
+ "head_dim": 128,
25
+ "hidden_act": "silu",
26
+ "hidden_size": 2048,
27
+ "in_channels": 192,
28
+ "initializer_range": 0.02,
29
+ "intermediate_size": 6144,
30
+ "is_turbo": true,
31
+ "layer_types": [
32
+ "sliding_attention",
33
+ "full_attention",
34
+ "sliding_attention",
35
+ "full_attention",
36
+ "sliding_attention",
37
+ "full_attention",
38
+ "sliding_attention",
39
+ "full_attention",
40
+ "sliding_attention",
41
+ "full_attention",
42
+ "sliding_attention",
43
+ "full_attention",
44
+ "sliding_attention",
45
+ "full_attention",
46
+ "sliding_attention",
47
+ "full_attention",
48
+ "sliding_attention",
49
+ "full_attention",
50
+ "sliding_attention",
51
+ "full_attention",
52
+ "sliding_attention",
53
+ "full_attention",
54
+ "sliding_attention",
55
+ "full_attention"
56
+ ],
57
+ "max_position_embeddings": 32768,
58
+ "model_type": "acestep",
59
+ "model_version": "turbo",
60
+ "num_attention_heads": 16,
61
+ "num_attention_pooler_hidden_layers": 2,
62
+ "num_audio_decoder_hidden_layers": 24,
63
+ "num_hidden_layers": 24,
64
+ "num_key_value_heads": 8,
65
+ "num_lyric_encoder_hidden_layers": 8,
66
+ "num_timbre_encoder_hidden_layers": 4,
67
+ "patch_size": 2,
68
+ "pool_window_size": 5,
69
+ "rms_norm_eps": 1e-06,
70
+ "rope_scaling": null,
71
+ "rope_theta": 1000000,
72
+ "sliding_window": 128,
73
+ "text_hidden_dim": 1024,
74
+ "timbre_fix_frame": 750,
75
+ "timbre_hidden_dim": 64,
76
+ "timestep_mu": -0.4,
77
+ "timestep_sigma": 1.0,
78
+ "transformers_version": "4.57.0.dev0",
79
+ "use_cache": true,
80
+ "use_sliding_window": true,
81
+ "vocab_size": 64003
82
+ }
vae/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderOobleck",
3
+ "_diffusers_version": "0.34.0",
4
+ "_name_or_path": "/root/data/repo/gongjunmin/ACE-Step-1.5/checkpoints/vae/",
5
+ "audio_channels": 2,
6
+ "channel_multiples": [
7
+ 1,
8
+ 2,
9
+ 4,
10
+ 8,
11
+ 16
12
+ ],
13
+ "decoder_channels": 128,
14
+ "decoder_input_channels": 64,
15
+ "downsampling_ratios": [
16
+ 2,
17
+ 4,
18
+ 4,
19
+ 6,
20
+ 10
21
+ ],
22
+ "encoder_hidden_size": 128,
23
+ "sampling_rate": 48000
24
+ }
vae/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da17edb604c40deaf09e9b24974e590d1ca83a374070e5d0884cfa4bed9a99b0
3
+ size 337431388