Sayoyo commited on
Commit
353e85b
·
verified ·
1 Parent(s): fe9706d

Upload folder using huggingface_hub

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