返回 F5-TTS
dit.py
根目录 / src / f5_tts / model / backbones / dit.py
1 """
2 ein notation:
3 b - batch
4 n - sequence
5 nt - text sequence
6 nw - raw wave length
7 d - dimension
8 """
9 # ruff: noqa: F722 F821
10
11 from __future__ import annotations
12
13 import threading
14
15 import torch
16 import torch.nn.functional as F
17 from torch import nn
18
19 from f5_tts.model.modules import (
20 AdaLayerNorm_Final,
21 ConvNeXtV2Block,
22 ConvPositionEmbedding,
23 DiTBlock,
24 RotaryEmbedding,
25 TimestepEmbedding,
26 precompute_freqs_cis,
27 )
28
29
30 # Text embedding
31
32
33 class TextEmbedding(nn.Module):
34 def __init__(
35 self, text_num_embeds, text_dim, mask_padding=True, average_upsampling=False, conv_layers=0, conv_mult=2
36 ):
37 super().__init__()
38 self.text_embed = nn.Embedding(text_num_embeds + 1, text_dim) # use 0 as filler token
39
40 self.mask_padding = mask_padding # mask filler and batch padding tokens or not
41 self.average_upsampling = average_upsampling # zipvoice-style text late average upsampling (after text encoder)
42 if average_upsampling:
43 assert mask_padding, "text_embedding_average_upsampling requires text_mask_padding to be True"
44
45 if conv_layers > 0:
46 self.extra_modeling = True
47 self.precompute_max_pos = 8192 # 8192 is ~87.38s of 24khz audio; 4096 is ~43.69s of 24khz audio
48 self.register_buffer("freqs_cis", precompute_freqs_cis(text_dim, self.precompute_max_pos), persistent=False)
49 self.text_blocks = nn.Sequential(
50 *[ConvNeXtV2Block(text_dim, text_dim * conv_mult) for _ in range(conv_layers)]
51 )
52 else:
53 self.extra_modeling = False
54
55 def average_upsample_text_by_mask(self, text, text_mask, target_lens):
56 batch, max_seq_len, text_dim = text.shape
57 text_lens = text_mask.sum(dim=1) # [batch]
58
59 upsampled_text = torch.zeros_like(text)
60
61 for i in range(batch):
62 text_len = int(text_lens[i].item())
63 audio_len = int(target_lens[i].item())
64
65 if text_len == 0 or audio_len <= 0:
66 continue
67
68 valid_ind = torch.where(text_mask[i])[0]
69 valid_data = text[i, valid_ind, :] # [text_len, text_dim]
70
71 base_repeat = audio_len // text_len
72 remainder = audio_len % text_len
73
74 indices = []
75 for j in range(text_len):
76 repeat_count = base_repeat + (1 if j >= text_len - remainder else 0)
77 indices.extend([j] * repeat_count)
78
79 indices = torch.tensor(indices[:audio_len], device=text.device, dtype=torch.long)
80 upsampled = valid_data[indices] # [audio_len, text_dim]
81
82 upsampled_text[i, :audio_len, :] = upsampled
83
84 return upsampled_text
85
86 def forward(self, text: int["b nt"], seq_len, drop_text=False):
87 text = text + 1 # use 0 as filler token. preprocess of batch pad -1, see list_str_to_idx()
88 valid_pos_mask = None
89 if torch.is_tensor(seq_len):
90 seq_len = seq_len.to(device=text.device, dtype=torch.long)
91 max_seq_len = int(seq_len.max().item())
92 else:
93 max_seq_len = int(seq_len)
94
95 text = text[:, :max_seq_len] # curtail if character tokens are more than the mel spec tokens
96 text = F.pad(text, (0, max_seq_len - text.shape[1]), value=0)
97
98 if torch.is_tensor(seq_len):
99 seq_pos = torch.arange(max_seq_len, device=text.device).unsqueeze(0)
100 valid_pos_mask = seq_pos < seq_len.unsqueeze(1)
101 text = text.masked_fill(~valid_pos_mask, 0)
102
103 if self.mask_padding:
104 text_mask = text == 0
105
106 if drop_text: # cfg for text
107 text = torch.zeros_like(text)
108
109 text = self.text_embed(text) # b n -> b n d
110 if valid_pos_mask is not None:
111 # Keep short-sample tail strictly zero (equivalent to per-sample pad_sequence(..., 0)).
112 text = text.masked_fill(~valid_pos_mask.unsqueeze(-1), 0.0)
113
114 # possible extra modeling
115 if self.extra_modeling:
116 # sinus pos emb; for variable seq lengths, only add positions within each sample's valid range.
117 freqs = self.freqs_cis[:max_seq_len, :]
118 if max_seq_len > freqs.size(0):
119 extra_freqs = precompute_freqs_cis(text.size(-1), max_seq_len, start=freqs.size(0), device=freqs.device)
120 freqs = torch.cat((freqs, extra_freqs.to(freqs.dtype)), dim=0)
121 if valid_pos_mask is not None:
122 freqs = freqs.unsqueeze(0) * valid_pos_mask.unsqueeze(-1).to(freqs.dtype)
123 text = text + freqs
124
125 # convnextv2 blocks
126 if self.mask_padding:
127 text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
128 for block in self.text_blocks:
129 text = block(text)
130 text = text.masked_fill(text_mask.unsqueeze(-1).expand(-1, -1, text.size(-1)), 0.0)
131 else:
132 text = self.text_blocks(text)
133
134 if self.average_upsampling:
135 if torch.is_tensor(seq_len):
136 target_lens = seq_len.to(device=text.device, dtype=torch.long)
137 else:
138 target_lens = torch.full((text.shape[0],), int(seq_len), device=text.device, dtype=torch.long)
139
140 text = self.average_upsample_text_by_mask(text, ~text_mask, target_lens)
141
142 return text
143
144
145 # noised input audio and context mixing embedding
146
147
148 class InputEmbedding(nn.Module):
149 def __init__(self, mel_dim, text_dim, out_dim):
150 super().__init__()
151 self.proj = nn.Linear(mel_dim * 2 + text_dim, out_dim)
152 self.conv_pos_embed = ConvPositionEmbedding(dim=out_dim)
153
154 def forward(
155 self,
156 x: float["b n d"],
157 cond: float["b n d"],
158 text_embed: float["b n d"],
159 drop_audio_cond=False,
160 audio_mask: bool["b n"] | None = None,
161 ):
162 if drop_audio_cond: # cfg for cond audio
163 cond = torch.zeros_like(cond)
164
165 x = self.proj(torch.cat((x, cond, text_embed), dim=-1))
166 x = self.conv_pos_embed(x, mask=audio_mask) + x
167 return x
168
169
170 # Transformer backbone using DiT blocks
171
172
173 class DiT(nn.Module):
174 def __init__(
175 self,
176 *,
177 dim,
178 depth=8,
179 heads=8,
180 dim_head=64,
181 dropout=0.1,
182 ff_mult=4,
183 mel_dim=100,
184 text_num_embeds=256,
185 text_dim=None,
186 text_mask_padding=True,
187 text_embedding_average_upsampling=False,
188 qk_norm=None,
189 conv_layers=0,
190 pe_attn_head=None,
191 attn_backend="torch", # "torch" | "flash_attn"
192 attn_mask_enabled=False,
193 long_skip_connection=False,
194 checkpoint_activations=False,
195 ):
196 super().__init__()
197
198 self.time_embed = TimestepEmbedding(dim)
199 if text_dim is None:
200 text_dim = mel_dim
201 self.text_embed = TextEmbedding(
202 text_num_embeds,
203 text_dim,
204 mask_padding=text_mask_padding,
205 average_upsampling=text_embedding_average_upsampling,
206 conv_layers=conv_layers,
207 )
208 self.input_embed = InputEmbedding(mel_dim, text_dim, dim)
209
210 self.rotary_embed = RotaryEmbedding(dim_head)
211
212 self.dim = dim
213 self.depth = depth
214
215 self.transformer_blocks = nn.ModuleList(
216 [
217 DiTBlock(
218 dim=dim,
219 heads=heads,
220 dim_head=dim_head,
221 ff_mult=ff_mult,
222 dropout=dropout,
223 qk_norm=qk_norm,
224 pe_attn_head=pe_attn_head,
225 attn_backend=attn_backend,
226 attn_mask_enabled=attn_mask_enabled,
227 )
228 for _ in range(depth)
229 ]
230 )
231 self.long_skip_connection = nn.Linear(dim * 2, dim, bias=False) if long_skip_connection else None
232
233 self.norm_out = AdaLayerNorm_Final(dim) # final modulation
234 self.proj_out = nn.Linear(dim, mel_dim)
235
236 self.checkpoint_activations = checkpoint_activations
237
238 self.initialize_weights()
239
240 # `_cache_local` is lazily initialized on first inference-time cache write so that
241 # training models (which never touch the cache) stay deepcopy-friendly for EMA.
242 def _get_cache_local(self):
243 cache = self.__dict__.get("_cache_local")
244 if cache is None:
245 cache = threading.local()
246 self.__dict__["_cache_local"] = cache
247 return cache
248
249 @property
250 def text_cond(self):
251 cache = self.__dict__.get("_cache_local")
252 return getattr(cache, "text_cond", None) if cache is not None else None
253
254 @text_cond.setter
255 def text_cond(self, value):
256 self._get_cache_local().text_cond = value
257
258 @property
259 def text_uncond(self):
260 cache = self.__dict__.get("_cache_local")
261 return getattr(cache, "text_uncond", None) if cache is not None else None
262
263 @text_uncond.setter
264 def text_uncond(self, value):
265 self._get_cache_local().text_uncond = value
266
267 def initialize_weights(self):
268 # Zero-out AdaLN layers in DiT blocks:
269 for block in self.transformer_blocks:
270 nn.init.constant_(block.attn_norm.linear.weight, 0)
271 nn.init.constant_(block.attn_norm.linear.bias, 0)
272
273 # Zero-out output layers:
274 nn.init.constant_(self.norm_out.linear.weight, 0)
275 nn.init.constant_(self.norm_out.linear.bias, 0)
276 nn.init.constant_(self.proj_out.weight, 0)
277 nn.init.constant_(self.proj_out.bias, 0)
278
279 def ckpt_wrapper(self, module):
280 # https://github.com/chuanyangjin/fast-DiT/blob/main/models.py
281 def ckpt_forward(*inputs):
282 outputs = module(*inputs)
283 return outputs
284
285 return ckpt_forward
286
287 def get_input_embed(
288 self,
289 x, # b n d
290 cond, # b n d
291 text, # b nt
292 drop_audio_cond: bool = False,
293 drop_text: bool = False,
294 cache: bool = True,
295 audio_mask: bool["b n"] | None = None,
296 ):
297 if self.text_uncond is None or self.text_cond is None or not cache:
298 if audio_mask is None:
299 seq_len = x.shape[1]
300 else:
301 seq_len = audio_mask.sum(dim=1) # per-sample valid speech length
302 text_embed = self.text_embed(text, seq_len=seq_len, drop_text=drop_text)
303 if cache:
304 if drop_text:
305 self.text_uncond = text_embed
306 else:
307 self.text_cond = text_embed
308
309 if cache:
310 if drop_text:
311 text_embed = self.text_uncond
312 else:
313 text_embed = self.text_cond
314
315 x = self.input_embed(x, cond, text_embed, drop_audio_cond=drop_audio_cond, audio_mask=audio_mask)
316
317 return x
318
319 def clear_cache(self):
320 self.text_cond, self.text_uncond = None, None
321
322 def forward(
323 self,
324 x: float["b n d"], # nosied input audio
325 cond: float["b n d"], # masked cond audio
326 text: int["b nt"], # text
327 time: float["b"] | float[""], # time step
328 mask: bool["b n"] | None = None,
329 drop_audio_cond: bool = False, # cfg for cond audio
330 drop_text: bool = False, # cfg for text
331 cfg_infer: bool = False, # cfg inference, pack cond & uncond forward
332 cache: bool = False,
333 ):
334 batch, seq_len = x.shape[0], x.shape[1]
335 if time.ndim == 0:
336 time = time.repeat(batch)
337
338 # t: conditioning time, text: text, x: noised audio + cond audio + text
339 t = self.time_embed(time)
340 if cfg_infer: # pack cond & uncond forward: b n d -> 2b n d
341 x_cond = self.get_input_embed(
342 x, cond, text, drop_audio_cond=False, drop_text=False, cache=cache, audio_mask=mask
343 )
344 x_uncond = self.get_input_embed(
345 x, cond, text, drop_audio_cond=True, drop_text=True, cache=cache, audio_mask=mask
346 )
347 x = torch.cat((x_cond, x_uncond), dim=0)
348 t = torch.cat((t, t), dim=0)
349 mask = torch.cat((mask, mask), dim=0) if mask is not None else None
350 else:
351 x = self.get_input_embed(
352 x, cond, text, drop_audio_cond=drop_audio_cond, drop_text=drop_text, cache=cache, audio_mask=mask
353 )
354
355 rope = self.rotary_embed.forward_from_seq_len(seq_len)
356
357 if self.long_skip_connection is not None:
358 residual = x
359
360 for block in self.transformer_blocks:
361 if self.checkpoint_activations:
362 # https://pytorch.org/docs/stable/checkpoint.html#torch.utils.checkpoint.checkpoint
363 x = torch.utils.checkpoint.checkpoint(self.ckpt_wrapper(block), x, t, mask, rope, use_reentrant=False)
364 else:
365 x = block(x, t, mask=mask, rope=rope)
366
367 if self.long_skip_connection is not None:
368 x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
369
370 x = self.norm_out(x, t)
371 output = self.proj_out(x)
372
373 return output
374
374 lines PYTHON