Sayoyo commited on
Commit
1d10ffd
·
verified ·
1 Parent(s): c049207

Upload folder using huggingface_hub

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