gasmichel commited on
Commit
36c9929
·
verified ·
1 Parent(s): 16cd3ed

Upload Diffusion/DiT/dit.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. Diffusion/DiT/dit.py +1324 -0
Diffusion/DiT/dit.py ADDED
@@ -0,0 +1,1324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from huggingface_hub import PyTorchModelHubMixin
5
+ from torch import Tensor
6
+ from torch.nn import RMSNorm
7
+ import numpy as np
8
+ #from .config import DiaConfig
9
+ from state import DecoderInferenceState, EncoderInferenceState, KVCache
10
+ from transformers.modeling_outputs import CausalLMOutput,CausalLMOutputWithCrossAttentions
11
+ from safetensors.torch import load_file
12
+ from config import Config
13
+ import os
14
+ import math
15
+ from typing import Optional
16
+ from dataclasses import dataclass
17
+ from transformers.modeling_outputs import ModelOutput
18
+ from typing import Optional, Tuple
19
+ from transformers import T5EncoderModel
20
+ import math
21
+ from einops import rearrange
22
+ from convnext.convnext import ConvNeXtV2, IdentityConvNeXtV2
23
+ from text_encoder.model import T5Encoder
24
+ from scipy import stats
25
+ from diffloss import DiffLoss
26
+
27
+ @dataclass
28
+ class QuoteTTSOutput(ModelOutput):
29
+ """
30
+ Base class for masked language models outputs.
31
+
32
+ Args:
33
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
34
+ Masked language modeling (MLM) loss.
35
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
36
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
37
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
38
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
39
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
40
+
41
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
42
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
43
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
44
+ sequence_length)`.
45
+
46
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
47
+ heads.
48
+ """
49
+
50
+ loss: Optional[torch.FloatTensor] = None
51
+ mask_loss: Optional[torch.FloatTensor] = None
52
+ logits: Optional[torch.FloatTensor] = None
53
+ labels: Optional[torch.FloatTensor] = None
54
+ expressive_latents: Optional[torch.FloatTensor] = None
55
+ labels_latents: Optional[torch.FloatTensor] = None
56
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
57
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
58
+ cross_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
59
+ target_mask: Optional[Tuple[torch.FloatTensor, ...]] = None
60
+ mu: Optional[torch.FloatTensor] = None
61
+ logvar: Optional[torch.FloatTensor] = None
62
+
63
+
64
+ class SinusoidalPosEmb(nn.Module):
65
+ def __init__(self, dim):
66
+ super().__init__()
67
+ self.dim = dim
68
+
69
+ def forward(self, x):
70
+ device = x.device
71
+ half_dim = self.dim // 2
72
+ emb = math.log(10000) / (half_dim - 1)
73
+ emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
74
+ emb = x[:, None] * emb[None, :] * 1.0
75
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
76
+ return emb
77
+
78
+
79
+
80
+ def _normalize_axes(axes: tuple[int, ...], ndim: int) -> tuple[int, ...]:
81
+ return tuple(ax if ax >= 0 else ndim + ax for ax in axes)
82
+
83
+ class DenseGeneral(nn.Module):
84
+ """
85
+ PyTorch equivalent of flax.linen.DenseGeneral with shapes defined at init.
86
+
87
+ Stores weights (`kernel`) in the same layout as Jax and uses torch.tensordot
88
+ for the generalized matrix multiplication. Weight/bias shapes are calculated
89
+ and parameters created during initialization based on config.
90
+ `load_weights` validates shapes and copies data.
91
+
92
+ Attributes:
93
+ axis (Tuple[int, ...]): Input axis or axes to contract.
94
+ in_shapes (Tuple[int, ...]): Sizes of the input dimensions specified by `axis`.
95
+ out_features (Tuple[int, ...]): Shape of the output features (non-contracted dims).
96
+ use_bias (bool): Whether to add a bias term.
97
+ weight (nn.Parameter): The kernel parameter.
98
+ bias (Optional[nn.Parameter]): The bias parameter (if use_bias=True).
99
+ """
100
+
101
+ def __init__(
102
+ self,
103
+ in_shapes: tuple[int, ...],
104
+ out_features: tuple[int, ...],
105
+ axis: tuple[int, ...] = (-1,),
106
+ #weight_dtype: torch.dtype = None,
107
+ #device: torch.device = None,
108
+ ):
109
+ super().__init__()
110
+ self.in_shapes = in_shapes
111
+ self.out_features = out_features
112
+ self.axis = axis
113
+ self.kernel_shape = self.in_shapes + self.out_features
114
+
115
+ # factory_kwargs = {"device": device, "dtype": weight_dtype}
116
+ self.weight = nn.Parameter(torch.empty(self.kernel_shape))
117
+ torch.nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
118
+ # torch.nn.init.normal_(self.weight, std=.02)
119
+
120
+ def forward(self, inputs: Tensor) -> Tensor:
121
+ norm_axis = _normalize_axes(self.axis, inputs.ndim)
122
+ kernel_contract_axes = tuple(range(len(norm_axis)))
123
+
124
+ output = torch.tensordot(
125
+ inputs.to(self.weight.dtype),
126
+ self.weight,
127
+ dims=(norm_axis, kernel_contract_axes),
128
+ ).to(inputs.dtype)
129
+ return output
130
+
131
+
132
+ class MlpBlock(nn.Module):
133
+ """MLP block using DenseGeneral."""
134
+
135
+ def __init__(self, embed_dim: int, intermediate_dim: int, out_dim:int=None):
136
+ super().__init__()
137
+
138
+ self.wi_fused = DenseGeneral(
139
+ in_shapes=(embed_dim,),
140
+ out_features=(2, intermediate_dim),
141
+ axis=(-1,),
142
+ )
143
+ if out_dim is None :
144
+ out_dim = embed_dim
145
+
146
+ self.wo = DenseGeneral(
147
+ in_shapes=(intermediate_dim,),
148
+ out_features=(out_dim,),
149
+ axis=(-1,),
150
+ )
151
+
152
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
153
+ """Forward pass."""
154
+ fused_x = self.wi_fused(x)
155
+
156
+ gate = fused_x[..., 0, :]
157
+ up = fused_x[..., 1, :]
158
+
159
+ hidden = torch.mul(F.silu(gate), up)
160
+
161
+ output = self.wo(hidden)
162
+ return output
163
+
164
+
165
+ class LlamaAdaptiveRMSNorm(nn.Module):
166
+ def __init__(self, hidden_size=1024, eps=1e-6, dim_cond=1024):
167
+ super().__init__()
168
+ self.to_weight = nn.Linear(dim_cond, hidden_size)
169
+ nn.init.zeros_(self.to_weight.weight)
170
+ nn.init.ones_(self.to_weight.bias)
171
+ self.variance_epsilon = eps
172
+ self._is_hf_initialized = True # disable automatic init
173
+
174
+ def forward(self, hidden_states, cond_embedding):
175
+ input_dtype = hidden_states.dtype
176
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
177
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
178
+
179
+ weight = self.to_weight(cond_embedding)
180
+ if len(weight.shape) == 2:
181
+ weight = weight.unsqueeze(1)
182
+
183
+ return (weight * hidden_states).to(input_dtype)
184
+
185
+
186
+ class RotaryEmbedding(nn.Module):
187
+ """Rotary Position Embedding (RoPE) implementation in PyTorch."""
188
+
189
+ def __init__(
190
+ self,
191
+ embedding_dims: int,
192
+ min_timescale: int = 1,
193
+ max_timescale: int = 10000,
194
+ ):
195
+ super().__init__()
196
+ if embedding_dims % 2 != 0:
197
+ raise ValueError("Embedding dim must be even for RoPE.")
198
+ self.embedding_dims = embedding_dims
199
+ self.min_timescale = min_timescale
200
+ self.max_timescale = max_timescale
201
+
202
+ half_embedding_dim = embedding_dims // 2
203
+ fraction = (2.0 * torch.arange(0, half_embedding_dim)) / embedding_dims
204
+ timescale = (self.min_timescale * (self.max_timescale / self.min_timescale) ** fraction).to(torch.float32)
205
+ self.register_buffer("timescale", timescale, persistent=False)
206
+
207
+ def forward(self, inputs: torch.Tensor, position: torch.Tensor):
208
+ """Applies RoPE."""
209
+ position = position.unsqueeze(-1).unsqueeze(-1)
210
+ sinusoid_inp = position / self.timescale
211
+ sin = torch.sin(sinusoid_inp)
212
+ cos = torch.cos(sinusoid_inp)
213
+ first_half, second_half = torch.chunk(inputs.to(torch.float32), 2, dim=-1)
214
+ first_part = first_half * cos - second_half * sin
215
+ second_part = second_half * cos + first_half * sin
216
+ return torch.cat((first_part, second_part), dim=-1)
217
+
218
+ def apply_rope(self, inputs: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor):
219
+ first_half, second_half = torch.chunk(inputs.to(torch.float32), 2, dim=-1)
220
+ first_part = first_half * cos - second_half * sin
221
+ second_part = second_half * cos + first_half * sin
222
+ return torch.cat((first_part, second_part), dim=-1)
223
+
224
+ class selfAttention(nn.Module):
225
+ """Attention using DenseGeneral."""
226
+
227
+ def __init__(
228
+ self,
229
+ config,
230
+ q_embed_dim: int,
231
+ kv_embed_dim: int,
232
+ num_query_heads: int,
233
+ num_kv_heads: int,
234
+ head_dim: int,
235
+ is_cross_attn: bool = False,
236
+ out_embed_dim: int = None,
237
+ output_attentions=False,
238
+ ):
239
+ super().__init__()
240
+ self.num_query_heads = num_query_heads
241
+ self.num_kv_heads = num_kv_heads
242
+ self.head_dim = head_dim
243
+ self.is_cross_attn = is_cross_attn
244
+ self.output_dim = out_embed_dim if out_embed_dim is not None else q_embed_dim
245
+ self.projected_query_dim = num_query_heads * head_dim
246
+ if num_query_heads % num_kv_heads != 0:
247
+ raise ValueError(f"num_query_heads ({num_query_heads}) must be divisible by num_kv_heads ({num_kv_heads})")
248
+ self.num_gqa_groups = num_query_heads // num_kv_heads
249
+ self.kv_embed_dim = kv_embed_dim
250
+ self.q_embed_dim = q_embed_dim
251
+ self.output_attentions = output_attentions
252
+ self.dropout_rate = config.model.dropout_rate
253
+ # self.dropout = nn.Dropout(config.dropout_rate)
254
+
255
+ # --- Projection Layers using DenseGeneral ---
256
+ self.q_proj = DenseGeneral(
257
+ in_shapes=(q_embed_dim,),
258
+ out_features=(num_query_heads, head_dim),
259
+ axis=(-1,),
260
+ )
261
+ self.k_proj = DenseGeneral(
262
+ in_shapes=(kv_embed_dim,),
263
+ out_features=(num_kv_heads, head_dim),
264
+ axis=(-1,),
265
+ )
266
+ self.v_proj = DenseGeneral(
267
+ in_shapes=(kv_embed_dim,),
268
+ out_features=(num_kv_heads, head_dim),
269
+ axis=(-1,),
270
+ )
271
+ self.o_proj = DenseGeneral(
272
+ in_shapes=(num_query_heads, head_dim),
273
+ out_features=(self.output_dim,),
274
+ axis=(-2, -1),
275
+ )
276
+
277
+ # --- Rotary Embedding ---
278
+ self.rotary_emb = RotaryEmbedding(
279
+ embedding_dims=self.head_dim,
280
+ min_timescale=config.model.rope_min_timescale,
281
+ max_timescale=config.model.rope_max_timescale,
282
+ )
283
+
284
+ self.is_fused_qkv = False
285
+
286
+ def forward(
287
+ self,
288
+ X: torch.Tensor, # (B, T, D) T = 1 in AR generation
289
+ q_positions: torch.Tensor, # (B, T)
290
+ kv_positions: torch.Tensor = None, # (B, S)
291
+ attn_mask: torch.Tensor = None, # None in Decoder self Attention, Valid mask in Others
292
+ cache: KVCache = None, # None in Encoder, KVCache in Decoder
293
+ prefill: bool = False,
294
+ is_causal: bool = False,
295
+ ) :
296
+ """
297
+ Performs attention calculation with optional KV caching.
298
+
299
+ Args:
300
+ Xq: Query tensor (B, T, D). T=1 during single-step decoding.
301
+ Xkv: Key/Value source tensor (B, S, E). S=1 during single-step decoding for self-attn.
302
+ q_positions: Positions for queries (B, T).
303
+ kv_positions: Positions for keys/values (B, S). If None, uses q_positions.
304
+ attn_mask: Attention mask.
305
+ cache: KVCache.
306
+ prefill: If True, use prefill mode.
307
+
308
+ Returns:
309
+ A tuple containing:
310
+ - output: The attention output tensor (B, T, output_dim).
311
+ - present_kv: The K/V state to be cached for the next step ((B, N, S_new, H), (B, N, S_new, H)). For self-attn, S_new = S_past + S. For cross-attn, S_new = S_kv.
312
+ """
313
+ if kv_positions is None:
314
+ kv_positions = q_positions
315
+
316
+ original_dtype = X.dtype
317
+
318
+
319
+ Xq_BxTxNxH = self.q_proj(X)
320
+ Xk_BxSxKxH = self.k_proj(X)
321
+ Xv_BxSxKxH = self.v_proj(X)
322
+
323
+ position = q_positions.unsqueeze(-1).unsqueeze(-1)
324
+ sinusoid_inp = position / self.rotary_emb.timescale
325
+ sin = torch.sin(sinusoid_inp)
326
+ cos = torch.cos(sinusoid_inp)
327
+
328
+ Xq_BxTxNxH = self.rotary_emb.apply_rope(Xq_BxTxNxH, sin, cos)
329
+ Xk_BxSxKxH = self.rotary_emb.apply_rope(Xk_BxSxKxH, sin, cos)
330
+
331
+ Xq_BxNxTxH = Xq_BxTxNxH.transpose(1, 2)
332
+
333
+ attn_k = None
334
+ attn_v = None
335
+
336
+ Xk_BxKxSxH = Xk_BxSxKxH.transpose(1, 2) # (B, K, S, H)
337
+ Xv_BxKxSxH = Xv_BxSxKxH.transpose(1, 2) # (B, K, S, H)
338
+
339
+ if cache is None:
340
+ attn_k = Xk_BxKxSxH
341
+ attn_v = Xv_BxKxSxH
342
+ else:
343
+ attn_k, attn_v = cache.update(Xk_BxKxSxH, Xv_BxKxSxH, current_idx)
344
+
345
+ # print(Xq_BxNxTxH.size(), attn_k.size(), attn_v.size())
346
+
347
+ # print(attn_mask)
348
+ attn_output = F.scaled_dot_product_attention(
349
+ Xq_BxNxTxH,
350
+ attn_k,
351
+ attn_v,
352
+ attn_mask=attn_mask if not is_causal else None,
353
+ scale=None,
354
+ enable_gqa=self.num_gqa_groups > 1,
355
+ is_causal=is_causal,
356
+ dropout_p=self.dropout_rate if self.training else 0.0
357
+ )
358
+
359
+ attn_output = attn_output.transpose(1, 2).contiguous() # (B, T, N, H)
360
+ output = self.o_proj(attn_output)
361
+
362
+ return output.to(original_dtype)
363
+
364
+ class CrossAttention(nn.Module):
365
+ """Cross-Attention using DenseGeneral."""
366
+
367
+ def __init__(
368
+ self,
369
+ config,
370
+ q_embed_dim: int,
371
+ kv_embed_dim: int,
372
+ num_query_heads: int,
373
+ num_kv_heads: int,
374
+ head_dim: int,
375
+ out_embed_dim: int = None,
376
+ output_attentions=False
377
+ ):
378
+ super().__init__()
379
+ self.num_query_heads = num_query_heads
380
+ self.num_kv_heads = num_kv_heads
381
+ self.head_dim = head_dim
382
+ self.output_dim = out_embed_dim if out_embed_dim is not None else q_embed_dim
383
+ self.projected_query_dim = num_query_heads * head_dim
384
+ if num_query_heads % num_kv_heads != 0:
385
+ raise ValueError(f"num_query_heads ({num_query_heads}) must be divisible by num_kv_heads ({num_kv_heads})")
386
+ self.num_gqa_groups = num_query_heads // num_kv_heads
387
+ self.output_attentions=output_attentions
388
+ self.dropout_rate = config.model.dropout_rate
389
+ # --- Projection Layers using DenseGeneral ---
390
+ self.q_proj = DenseGeneral(
391
+ in_shapes=(q_embed_dim,),
392
+ out_features=(num_query_heads, head_dim),
393
+ axis=(-1,),
394
+ )
395
+ self.k_proj = DenseGeneral(
396
+ in_shapes=(kv_embed_dim,),
397
+ out_features=(num_kv_heads, head_dim),
398
+ axis=(-1,),
399
+ )
400
+ self.v_proj = DenseGeneral(
401
+ in_shapes=(kv_embed_dim,),
402
+ out_features=(num_kv_heads, head_dim),
403
+ axis=(-1,),
404
+ )
405
+ self.o_proj = DenseGeneral(
406
+ in_shapes=(num_query_heads, head_dim),
407
+ out_features=(self.output_dim,),
408
+ axis=(-2, -1),
409
+ )
410
+
411
+ # --- Rotary Embedding ---
412
+ self.rotary_emb = RotaryEmbedding(
413
+ embedding_dims=self.head_dim,
414
+ min_timescale=config.model.rope_min_timescale,
415
+ max_timescale=config.model.rope_max_timescale,
416
+ )
417
+
418
+ def forward(
419
+ self,
420
+ Xq: torch.Tensor, # (B, T, D) T = 1 in AR generation
421
+ q_positions: torch.Tensor, # (B, T),
422
+ Xkv: torch.Tensor = None, # (B, S)
423
+ kv_positions: torch.Tensor = None, # (B, S)
424
+ attn_mask: torch.Tensor = None, # None in Decoder self Attention, Valid mask in Others
425
+ cache: KVCache = None, # None in Encoder, KVCache in Decoder
426
+ is_causal: bool = False,
427
+ ):
428
+ """
429
+ Performs attention calculation with optional KV caching.
430
+
431
+ Args:
432
+ Xq: Query tensor (B, T, D). T=1 during single-step decoding.
433
+ Xkv: Key/Value source tensor (B, S, E). S=1 during single-step decoding for self-attn.
434
+ q_positions: Positions for queries (B, T).
435
+ kv_positions: Positions for keys/values (B, S). If None, uses q_positions.
436
+ attn_mask: Attention mask.
437
+ cache: KVCache.
438
+
439
+ Returns:
440
+ A tuple containing:
441
+ - output: The attention output tensor (B, T, output_dim).
442
+ - present_kv: The K/V state to be cached for the next step ((B, N, S_new, H), (B, N, S_new, H)). For self-attn, S_new = S_past + S. For cross-attn, S_new = S_kv.
443
+ """
444
+ if kv_positions is None:
445
+ kv_positions = q_positions
446
+ original_dtype = Xq.dtype
447
+
448
+ Xq_BxTxNxH = self.q_proj(Xq)
449
+ Xq_BxTxNxH = self.rotary_emb(Xq_BxTxNxH, position=q_positions)
450
+ Xq_BxNxTxH = Xq_BxTxNxH.transpose(1, 2)
451
+
452
+ attn_k = None
453
+ attn_v = None
454
+ if cache is not None :
455
+ attn_k, attn_v = cache.k, cache.v
456
+ else :
457
+ attn_k = self.k_proj(Xkv)
458
+ attn_v = self.v_proj(Xkv)
459
+ attn_k = self.rotary_emb(attn_k, position=kv_positions)
460
+ attn_k = attn_k.transpose(1, 2)
461
+ attn_v = attn_v.transpose(1, 2)
462
+
463
+ attn_output = F.scaled_dot_product_attention(
464
+ Xq_BxNxTxH,
465
+ attn_k,
466
+ attn_v,
467
+ attn_mask=attn_mask if not is_causal else None,
468
+ scale=None,
469
+ enable_gqa=self.num_gqa_groups > 1,
470
+ is_causal=is_causal,
471
+ dropout_p=self.dropout_rate if self.training else 0.0
472
+ )
473
+ if self.output_attentions :
474
+ attn_weight = attn_output @ torch.linalg.pinv(attn_v)
475
+
476
+ attn_output = attn_output.transpose(1, 2).contiguous() # (B, T, N, H)
477
+ output = self.o_proj(attn_output)
478
+
479
+ if self.output_attentions :
480
+ return output, attn_weight
481
+ return output.to(original_dtype)
482
+
483
+
484
+ class EncoderLayer(nn.Module):
485
+ """Transformer Encoder Layer using DenseGeneral."""
486
+
487
+ def __init__(self, config):
488
+ super().__init__()
489
+ self.config = config
490
+ model_config = config.model
491
+ enc_config = config.model.encoder
492
+ embed_dim = enc_config.n_embd
493
+
494
+ # self.pre_sa_norm = RMSNorm(
495
+ # embed_dim,
496
+ # eps=model_config.normalization_layer_epsilon,
497
+ # dtype=torch.float32,
498
+ # )
499
+ self.pre_sa_norm = LlamaAdaptiveRMSNorm(
500
+ hidden_size=embed_dim, dim_cond=embed_dim
501
+ )
502
+ self.self_attention = selfAttention(
503
+ config,
504
+ q_embed_dim=embed_dim,
505
+ kv_embed_dim=embed_dim,
506
+ num_query_heads=enc_config.n_head,
507
+ num_kv_heads=enc_config.n_head,
508
+ head_dim=enc_config.head_dim,
509
+ is_cross_attn=False,
510
+ out_embed_dim=embed_dim,
511
+ )
512
+ # self.post_sa_norm = RMSNorm(
513
+ # embed_dim,
514
+ # eps=model_config.normalization_layer_epsilon,
515
+ # dtype=torch.float32,
516
+ # )
517
+ self.post_sa_norm = LlamaAdaptiveRMSNorm(
518
+ hidden_size=embed_dim, dim_cond=embed_dim
519
+ )
520
+ self.mlp = MlpBlock(embed_dim=embed_dim, intermediate_dim=enc_config.n_hidden)
521
+ self.dropout = nn.Dropout(config.model.dropout_rate)
522
+
523
+ def forward(
524
+ self,
525
+ x: torch.Tensor,
526
+ state: EncoderInferenceState,
527
+ cond_emb: torch.Tensor = None
528
+ ) -> torch.Tensor:
529
+
530
+ residual = x
531
+ x_norm = self.pre_sa_norm(x, cond_embedding=cond_emb)
532
+
533
+ sa_out = self.self_attention(
534
+ X=x_norm,
535
+ q_positions=state.positions,
536
+ kv_positions=state.positions,
537
+ attn_mask=state.attn_mask,
538
+ )
539
+ x = residual + self.dropout(sa_out)
540
+
541
+ residual = x
542
+ x_norm = self.post_sa_norm(x, cond_embedding=cond_emb)
543
+ mlp_out = self.mlp(x_norm)
544
+ x = residual + self.dropout(mlp_out)
545
+
546
+ return x
547
+
548
+
549
+ class Decoder(nn.Module):
550
+ """Transformer Decoder Stack using DenseGeneral."""
551
+
552
+ def __init__(self, config):
553
+ super().__init__()
554
+ self.config = config
555
+ model_config = config.model
556
+ dec_config = config.model.decoder
557
+ data_config = config.data
558
+ self.num_layers = dec_config.n_layer
559
+
560
+ # self.embeddings = nn.Embedding(model_config.tgt_vocab_size, dec_config.n_embd)
561
+ self.mask_ratio_generator = stats.truncnorm((config.model.mask_ratio_min - 1.0) / 0.25, 0, loc=1.0, scale=0.25)
562
+
563
+ self.sep_emb = nn.Parameter(torch.zeros(1, 1, dec_config.n_embd))# nn.Embedding(1, dec_config.n_embd)
564
+ torch.nn.init.normal_(self.sep_emb, std=.02)
565
+
566
+ self.mask_emb = nn.Parameter(torch.zeros(1, config.model.inp_dim))# nn.Embedding(1, config.model.inp_dim)
567
+ torch.nn.init.normal_(self.mask_emb, std=.02)
568
+
569
+ self.embedding_dense = DenseGeneral(
570
+ in_shapes=(dec_config.inp_dim,),
571
+ out_features=(1, dec_config.n_embd),
572
+ axis=(-1,),
573
+ )
574
+
575
+ self.layers = nn.ModuleList(
576
+ [DecoderLayer(config=config) for _ in range(self.num_layers)]
577
+ )
578
+
579
+ # self.norm = RMSNorm(
580
+ # dec_config.n_embd,
581
+ # eps=model_config.normalization_layer_epsilon,
582
+ # dtype=torch.float32,
583
+ # )
584
+ self.norm = LlamaAdaptiveRMSNorm(
585
+ hidden_size=embed_dim, dim_cond=embed_dim
586
+ )
587
+ self.dropout = nn.Dropout(config.model.dropout_rate)
588
+
589
+ self.reconstructor = MlpBlock(
590
+ embed_dim=dec_config.n_embd,
591
+ intermediate_dim=dec_config.n_hidden,
592
+ out_dim = dec_config.inp_dim
593
+ )
594
+
595
+
596
+ def get_ids(self, text_input_ids, max_len, pad_value=1):
597
+ bs, seq_len = text_input_ids.size()
598
+ padding_size = max_len - seq_len
599
+
600
+ padding_tensor = torch.empty(bs, padding_size, device=text_input_ids.device).fill_(pad_value).long()
601
+ return torch.cat((text_input_ids, padding_tensor), dim=1)
602
+
603
+ def mask_prob(self, t):
604
+ return torch.sin(t * np.pi / 2).to(t.device)
605
+
606
+ def get_t(self, x0) :
607
+ t = torch.rand(x0.shape[0], device=x0.device, requires_grad=False)
608
+ t = torch.clamp(t, 1e-5, 1.0)
609
+ return t
610
+
611
+ def mask_tgt_embeddings(self, x0):
612
+ # x0: semantic tokens (B, T)
613
+ t = self.get_t(x0)
614
+ new_t = t
615
+ mask_prob = self.mask_prob(new_t) # (B,)
616
+ # if mask_prob[i] < 0.2, mask_prob[i] = 0.2
617
+ mask_prob = torch.where(
618
+ mask_prob < 0.2, torch.ones_like(mask_prob) * 0.2, mask_prob
619
+ )
620
+ # Add mask
621
+ target_mask = torch.bernoulli(torch.ones_like(x0[:, :, 0]) * mask_prob[..., None])
622
+ # mask = torch.cat((torch.zeros_like(prefix), target_mask), dim=1)
623
+
624
+ # mask
625
+ xt = x0.clone()
626
+
627
+ # replace by pad embedding
628
+ # pad_emb = self.mask_emb.repeat(x0.shape[0], x0.shape[1], 1).to(x0.dtype) #self.pad_emb(torch.zeros(1, dtype=torch.int32, device=x0.device)).squeeze(0) # torch.zeros(1, device=x0.device)
629
+ xt[(target_mask==1)] = self.mask_emb.to(xt.dtype)
630
+
631
+ return xt, target_mask
632
+
633
+ def random_masking(self, x, orders):
634
+ # generate token mask
635
+ bsz, seq_len, embed_dim = x.shape
636
+ mask_rate = self.mask_ratio_generator.rvs(1)[0]
637
+ num_masked_tokens = int(np.ceil(seq_len * mask_rate))
638
+ mask = torch.zeros(bsz, seq_len, device=x.device)
639
+ mask = torch.scatter(mask, dim=-1, index=orders[:, :num_masked_tokens].to(x.device),
640
+ src=torch.ones(bsz, seq_len, device=x.device))
641
+ return mask.long()
642
+ def sample_orders(self, bsz, seq_len =32 ):
643
+ # generate a batch of random generation orders
644
+ orders = []
645
+ for _ in range(bsz):
646
+ order = np.array(list(range(seq_len)))
647
+ np.random.shuffle(order)
648
+ orders.append(order)
649
+ orders = torch.Tensor(np.array(orders)).long()
650
+ return orders
651
+
652
+ def mask_input(self, x) :
653
+ bs, seq_len, _ = x.size()
654
+ orders = self.sample_orders(bs,seq_len)
655
+ mask = self.random_masking(x, orders)
656
+ xt = x.clone()
657
+ xt[(mask==1)] = self.mask_emb.to(xt.dtype)
658
+ return xt, mask
659
+
660
+ def forward(
661
+ self,
662
+ enc_state: EncoderInferenceState,
663
+ enc_out: torch.Tensor,
664
+ quote_embs: torch.Tensor,
665
+ dec_in : torch.Tensor,
666
+ text_input_ids: torch.Tensor,
667
+ labels:torch.Tensor = None) -> torch.Tensor:
668
+
669
+ if self.training :
670
+ # x_orig = dec_in
671
+ # x, target_mask = self.mask_tgt_embeddings(dec_in)
672
+ x, target_mask = self.mask_input(dec_in)
673
+ # x = self.embedding_dense(x).squeeze(2)
674
+
675
+ else :
676
+ # x_orig = self.embedding_dense(dec_in).squeeze(2)
677
+ # full of pad tokens
678
+ # bs, seq_len, _ = dec_in.size()
679
+ # x = self.mask_emb.unsqueeze(1).repeat(bs, seq_len,1)
680
+
681
+ # x =
682
+ # x = self.embedding_dense(x.unsqueeze(1))#.squeeze(2)
683
+ # x = pad_emb.unsqueeze(1).expand(dec_in.size(0),dec_in.size(1),1)
684
+ target_mask=None
685
+ x = dec_in
686
+
687
+ x = self.embedding_dense(x).squeeze(2)
688
+
689
+ # sep_emb = self.sep_emb(torch.zeros(1, dtype=torch.int32, device=dec_in.device)).expand(dec_in.size(0), 1, -1)
690
+
691
+ x = torch.cat((quote_embs, self.sep_emb.repeat(x.size(0), 1,1).to(x.dtype), x), dim = 1)
692
+
693
+ dec_in_dummy = self.get_ids(text_input_ids, max_len = x.size(1))
694
+ # print(dec_in_dummy)
695
+ state = DecoderInferenceState.new(
696
+ self.config, enc_state, enc_out, dec_in_dummy
697
+ )
698
+ # print(state.attn_mask[1,0, 8:, 8:])
699
+ cross_attentions = ()
700
+ for i, layer in enumerate(self.layers):
701
+ x, cattns = layer(x, state)
702
+ cross_attentions += (cattns,)
703
+
704
+ # Final Norm
705
+ x = self.norm(x)
706
+ # print(x[:,-32:].size())
707
+
708
+ # reconstructed_input = self.reconstructor(self.dropout(x[:,-32:]).unsqueeze(1))
709
+ reconstructed_input = self.reconstructor(self.dropout(x[:,-32:])).squeeze(2)
710
+
711
+ if self.training :
712
+ loss1 = F.mse_loss(
713
+ reconstructed_input[:,-32:][(target_mask==1)],
714
+ dec_in[(target_mask==1)],
715
+ reduction="mean",
716
+ )
717
+ loss2 = F.l1_loss(
718
+ reconstructed_input[:,-32:][(target_mask==1)],
719
+ dec_in[(target_mask==1)],
720
+ reduction="mean",
721
+ )
722
+ mask_loss = loss1 + loss2
723
+ else :
724
+ if labels is not None :
725
+ loss1 = F.mse_loss(
726
+ reconstructed_input[:,-32:],
727
+ labels,
728
+ reduction="mean",
729
+ )
730
+ loss2 = F.l1_loss(
731
+ reconstructed_input[:,-32:],
732
+ labels,
733
+ reduction="mean",
734
+ )
735
+ mask_loss = loss1 + loss2
736
+ else :
737
+ mask_loss = None
738
+
739
+
740
+
741
+ out = QuoteTTSOutput(
742
+ logits=x,
743
+ mask_loss=mask_loss,
744
+ cross_attentions=cross_attentions,
745
+ expressive_latents=reconstructed_input,
746
+ target_mask=target_mask)#, kl_div_loss=loss_kl, mu=mu, logvar=logvar)
747
+ return out
748
+
749
+
750
+ class Encoder(nn.Module):
751
+ """Transformer Decoder Stack using DenseGeneral."""
752
+
753
+ def __init__(self, config):
754
+ super().__init__()
755
+ self.config = config
756
+ model_config = config.model
757
+ dec_config = config.model.decoder
758
+ data_config = config.data
759
+ self.num_layers = dec_config.n_layer
760
+
761
+ # self.embeddings = nn.Embedding(model_config.tgt_vocab_size, dec_config.n_embd)
762
+
763
+ # self.embedding_dense = DenseGeneral(
764
+ # in_shapes=(dec_config.inp_dim,),
765
+ # out_features=(1, dec_config.n_embd),
766
+ # axis=(-1,),
767
+ # )
768
+ self.embedding_dense = nn.Linear(dec_config.inp_dim, dec_config.n_embd, bias=True)
769
+ torch.nn.init.xavier_uniform_(self.embedding_dense.weight)
770
+ torch.nn.init.constant_(self.embedding_dense.bias, 0)
771
+
772
+ self.sep_emb = nn.Parameter(torch.zeros(1, 1, dec_config.n_embd))# nn.Embedding(1, dec_config.n_embd)
773
+ torch.nn.init.normal_(self.sep_emb, std=.02)
774
+
775
+ # self.z_proj_ln = nn.LayerNorm(dec_config.n_embd, eps=1e-6)
776
+ # self.encoder_pos_embed_learned = nn.Embedding(1024, dec_config.n_embd)
777
+ # torch.nn.init.normal_(self.encoder_pos_embed_learned.weight.data, std=.02)
778
+
779
+ # self.ref_dense = DenseGeneral(
780
+ # in_shapes=(dec_config.inp_dim * 32,),
781
+ # out_features=(1, dec_config.n_embd),
782
+ # axis=(-1,),
783
+ # )
784
+ # self.embedding_dense = IdentityConvNeXtV2(in_chans=1, depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], num_classes=1024)
785
+
786
+ self.layers = nn.ModuleList(
787
+ [EncoderLayer(config=config) for _ in range(self.num_layers)]
788
+ )
789
+
790
+ # self.norm = RMSNorm(
791
+ # dec_config.n_embd,
792
+ # eps=model_config.normalization_layer_epsilon,
793
+ # dtype=torch.float32,
794
+ # )
795
+ self.norm = LlamaAdaptiveRMSNorm(
796
+ hidden_size=embed_dim, dim_cond=embed_dim
797
+ )
798
+ self.dropout = nn.Dropout(config.model.dropout_rate)
799
+
800
+ def get_ids(self, text_input_ids, max_len, pad_value=1):
801
+ bs, seq_len = text_input_ids.size()
802
+ padding_size = max_len - seq_len
803
+
804
+ padding_tensor = torch.empty(bs, padding_size, device=text_input_ids.device).fill_(pad_value).long()
805
+ return torch.cat((text_input_ids, padding_tensor), dim=1)
806
+
807
+ def forward(
808
+ self,
809
+ x : torch.Tensor,
810
+ c: torch.Tensor) -> torch.Tensor:
811
+
812
+
813
+ bsz, seq_len, embed_dim = context_embs.shape
814
+
815
+ x = self.embedding_dense(audio_in).squeeze(2)
816
+ # ref_x = self.ref_dense(ref_in.view(x.size(0), -1)).squeeze(2)
817
+ # print(context_embs.size(), x.size())
818
+ x = torch.cat((context_embs, self.sep_emb.repeat(bsz, 1,1).to(x.dtype), x), dim = 1)
819
+ # x = x + ref_x
820
+
821
+ mask_with_buffer = torch.cat([torch.zeros(bsz, seq_len + 1, device=x.device), mask], dim=1)
822
+
823
+ # positional embeddings to let the model know the initial positions
824
+ # positions = torch.arange(x.size(1), device=x.device).unsqueeze(0).repeat(bsz,1).long()
825
+ # x = x + self.encoder_pos_embed_learned(positions)
826
+ # x = self.z_proj_ln(x)
827
+
828
+ # dropping
829
+ x = x[(1-mask_with_buffer).nonzero(as_tuple=True)].reshape(bsz, -1, embed_dim)
830
+
831
+ # state
832
+ enc_in_dummy = self.get_ids(text_input_ids, max_len = x.size(1))
833
+ state = EncoderInferenceState.new(
834
+ self.config, enc_in_dummy
835
+ )
836
+ # print(state.attn_mask[1,0, 8:, 8:])
837
+ # cross_attentions = ()
838
+ for i, layer in enumerate(self.layers):
839
+ x = layer(x, state)
840
+ # cross_attentions += (cattns,)
841
+
842
+ # Final Norm
843
+ x = self.norm(x)
844
+ # reconstructed_input = self.reconstructor(self.dropout(x[:,-32:])).squeeze(2)
845
+
846
+ # gt_latents = audio_in.clone().detach()
847
+ # x = x[:,-32:] + self.diffusion_pos_embed_learned
848
+
849
+ # loss = self.forward_loss(x, gt_latents, target_mask)
850
+
851
+ # out = QuoteTTSOutput(
852
+ # logits=x,
853
+ # mask_loss=None,
854
+ # expressive_latents=None)
855
+ #, kl_div_loss=loss_kl, mu=mu, logvar=logvar)
856
+ return x
857
+
858
+ class TimestepEmbedder(nn.Module):
859
+ """
860
+ Embeds scalar timesteps into vector representations.
861
+ """
862
+ def __init__(self, hidden_size, frequency_embedding_size=256):
863
+ super().__init__()
864
+ self.mlp = nn.Sequential(
865
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
866
+ nn.SiLU(),
867
+ nn.Linear(hidden_size, hidden_size, bias=True),
868
+ )
869
+ self.frequency_embedding_size = frequency_embedding_size
870
+
871
+ @staticmethod
872
+ def timestep_embedding(t, dim, max_period=10000):
873
+ """
874
+ Create sinusoidal timestep embeddings.
875
+ :param t: a 1-D Tensor of N indices, one per batch element.
876
+ These may be fractional.
877
+ :param dim: the dimension of the output.
878
+ :param max_period: controls the minimum frequency of the embeddings.
879
+ :return: an (N, D) Tensor of positional embeddings.
880
+ """
881
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
882
+ half = dim // 2
883
+ freqs = torch.exp(
884
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
885
+ ).to(device=t.device)
886
+ args = t[:, None].float() * freqs[None]
887
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
888
+ if dim % 2:
889
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
890
+ return embedding
891
+
892
+ def forward(self, t):
893
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
894
+ t_emb = self.mlp(t_freq)
895
+ return t_emb
896
+
897
+ class Conv1DFinalLayer(nn.Module):
898
+ """
899
+ The final layer of CrossAttnDiT.
900
+ """
901
+ def __init__(self, hidden_size, out_channels):
902
+ super().__init__()
903
+ self.norm_final = nn.GroupNorm(16,hidden_size)
904
+ self.conv1d = nn.Conv1d(hidden_size, out_channels,kernel_size=1)
905
+
906
+ def forward(self, x): # x:(B,C,T)
907
+ x = self.norm_final(x)
908
+ x = self.conv1d(x)
909
+ return x
910
+
911
+ class Conv1DFinalLayer(nn.Module):
912
+ """
913
+ The final layer of DiT.
914
+ """
915
+ def __init__(self, hidden_size, out_channels):
916
+ super().__init__()
917
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
918
+ # self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
919
+ self.conv1d = nn.Conv1d(hidden_size, out_channels, kernel_size=1)
920
+ self.adaLN_modulation = nn.Sequential(
921
+ nn.SiLU(),
922
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True)
923
+ )
924
+ def modulate(self, x, shift, scale):
925
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
926
+
927
+ def forward(self, x, c):
928
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
929
+ x = self.modulate(self.norm_final(x), shift, scale)
930
+
931
+ x = self.conv1d(x.transpose(1,2))
932
+ return x#.transpose(1,2)
933
+
934
+ class EncoderDecoder(
935
+ nn.Module,
936
+ ):
937
+ def __init__(self, config):
938
+ super().__init__()
939
+ self.config = config
940
+
941
+ # self.encoder = T5Encoder.from_pretrained(config.model.base_encoder_path, config.model.ft_encoder_path).encoder
942
+ self.context_encoder = T5EncoderModel.from_pretrained(config.model.base_encoder_path)
943
+ # for p in self.context_encoder.parameters():
944
+ # p.requires_grad = False
945
+ # self.context_encoder = self.context_encoder.eval()
946
+ kernel_size=5
947
+ self.proj_in = self.proj_in = nn.Conv1d(config.model.inp_dim,config.model.encoder.n_embd,kernel_size=kernel_size,padding=kernel_size//2)
948
+ self.layers = nn.ModuleList(
949
+ [EncoderLayer(config=config) for _ in range(config.model.encoder.n_layer)]
950
+ )
951
+ self.sep_emb = nn.Parameter(torch.zeros(1, 1, config.model.encoder.n_embd))# nn.Embedding(1, dec_config.n_embd)
952
+
953
+ self.norm = LlamaAdaptiveRMSNorm(
954
+ hidden_size=config.model.encoder.n_embd, dim_cond=config.model.encoder.n_embd
955
+ )
956
+
957
+ self.timestep_embedding = TimestepEmbedder(config.model.encoder.n_embd)
958
+ # here we *2 because we also learn sigma
959
+ self.final_layer = Conv1DFinalLayer(config.model.encoder.n_embd, config.model.inp_dim * 2)
960
+
961
+ self.initialize_weights()
962
+
963
+ def initialize_weights(self):
964
+ # Initialize transformer layers:
965
+ # def _basic_init(module):
966
+ # if isinstance(module, nn.Linear):
967
+ # torch.nn.init.xavier_uniform_(module.weight)
968
+ # if module.bias is not None:
969
+ # nn.init.constant_(module.bias, 0)
970
+ for n,m in self.named_modules() :
971
+ if (isinstance(m, nn.Linear)) & ("context_encoder" not in n) :
972
+ torch.nn.init.xavier_uniform_(m.weight)
973
+ if m.bias is not None:
974
+ nn.init.constant_(m.bias, 0)
975
+
976
+ # self.apply(_basic_init)
977
+ # Initialize timestep embedding MLP:
978
+ nn.init.normal_(self.timestep_embedding.mlp[0].weight, std=0.02)
979
+ nn.init.normal_(self.timestep_embedding.mlp[2].weight, std=0.02)
980
+
981
+ nn.init.normal_(self.sep_emb, std=0.02)
982
+
983
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
984
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
985
+
986
+ def get_ids(self, text_input_ids, max_len, pad_value=1):
987
+ bs, seq_len = text_input_ids.size()
988
+ padding_size = max_len - seq_len
989
+
990
+ padding_tensor = torch.empty(bs, padding_size, device=text_input_ids.device).fill_(pad_value).long()
991
+ return torch.cat((text_input_ids, padding_tensor), dim=1)
992
+
993
+ def forward(
994
+ self,
995
+ x : torch.Tensor,
996
+ t : torch.Tensor,
997
+ y: torch.Tensor,
998
+ ) :
999
+
1000
+ # x: [B, inp_dim ,32]
1001
+
1002
+ bsz, _ , _ = x.size()
1003
+
1004
+ # diffusion step embedding
1005
+ diffusion_step_emb = self.timestep_embedding(t) # [B, H]
1006
+
1007
+ # context
1008
+ enc_state = EncoderInferenceState.new(self.context_encoder.config, y)
1009
+ c_emb = self.context_encoder(input_ids=y,attention_mask=enc_state.padding_mask).last_hidden_state # [ B, S, H]
1010
+
1011
+ c = diffusion_step_emb + c_emb[:, -1]
1012
+ # audio in
1013
+ x = self.proj_in(x).transpose(1,2) # [ B, 32, H]
1014
+
1015
+ # transformer input
1016
+ # x = torch.cat((c_emb, self.sep_emb.repeat(bsz, 1,1).to(x.dtype), x), dim = 1) # [B, S+1+32, H]
1017
+
1018
+ # get the right mask for encoder to avoid attend to pad tokens from context
1019
+ # enc_in_dummy = self.get_ids(y, max_len = x.size(1))
1020
+ enc_in_dummy = torch.ones(bsz, 32, device=x.device)
1021
+ state = EncoderInferenceState.new(
1022
+ self.config, enc_in_dummy
1023
+ )
1024
+ for i, layer in enumerate(self.layers):
1025
+ x = layer(x, state, cond_emb=c)
1026
+
1027
+ x = self.norm(x, cond_embedding=c)
1028
+
1029
+ x = x[:, -32:]
1030
+ x = self.final_layer(x, c=c) # [N, inp_dim * 2, 32]
1031
+ # print(x.size())
1032
+ return x
1033
+
1034
+ # gt_latents = transformer_in.clone().detach()
1035
+ # loss = self.forward_loss(z, gt_latents, mask)
1036
+
1037
+ # out = QuoteTTSOutput(
1038
+ # logits=z,
1039
+ # loss=loss,
1040
+ # expressive_latents=None)
1041
+ # return out
1042
+
1043
+
1044
+
1045
+ @classmethod
1046
+ def from_pretrained(cls, path: str, config_path: str= None):
1047
+ if config_path:
1048
+ with open(config_path) as f :
1049
+ config = yaml.safe_load(f)
1050
+ else :
1051
+ config = Config()
1052
+
1053
+ model = cls(config)
1054
+ model.load_state_dict(torch.load(os.path.join(path, "pytorch_model.bin"), map_location="cpu"))
1055
+ return model
1056
+
1057
+ # @torch.no_grad()
1058
+ # def sample_all(self, context, quote,num_iter=10, seq_len=32):
1059
+ # expressive_latents = self.sample_tokens(context,quote,num_iter,seq_len)
1060
+ # out = self.decoder()
1061
+
1062
+ def mask_by_order(mask_len, order, bsz, seq_len):
1063
+ masking = torch.zeros(bsz, seq_len)
1064
+ masking = torch.scatter(masking, dim=-1, index=order[:, :mask_len.long()], src=torch.ones(bsz, seq_len)).bool()
1065
+ return masking
1066
+
1067
+
1068
+ def top_p_sample(logits, thres=0.9):
1069
+ k = math.ceil((1 - thres) * logits.shape[-1])
1070
+ val, ind = logits.topk(k, dim=-1)
1071
+ probs = torch.full_like(logits, float("-inf"))
1072
+ probs.scatter_(2, ind, val)
1073
+ return probs
1074
+
1075
+
1076
+ def log(t, eps=1e-10):
1077
+ return torch.log(t + eps)
1078
+
1079
+
1080
+ def gumbel_noise(t):
1081
+ noise = torch.zeros_like(t).uniform_(0, 1)
1082
+ return -log(-log(noise))
1083
+
1084
+
1085
+ def gumbel_sample(t, temperature=1.0, dim=-1):
1086
+ return ((t / max(temperature, 1e-10)) + gumbel_noise(t)).argmax(dim=dim)
1087
+
1088
+
1089
+ def apply_top_k_only(
1090
+ logits: torch.Tensor,
1091
+ k: torch.Tensor,
1092
+ ) -> torch.Tensor:
1093
+ """
1094
+ Apply top-k mask to the logits.
1095
+
1096
+ This implementation doesn't involve sorting the entire vocab.
1097
+
1098
+ The logits tensor may be updated in-place.
1099
+ """
1100
+ no_top_k_mask = k == logits.shape[1]
1101
+ # Set non-top-k rows to 1 so that we can gather.
1102
+ k = k.masked_fill(no_top_k_mask, 1)
1103
+ max_top_k = k.max()
1104
+ # topk.values tensor has shape [batch_size, max_top_k].
1105
+ # Convert top k to 0-based index in range [0, max_top_k).
1106
+ k_index = k.sub_(1).unsqueeze(1)
1107
+ top_k_mask = logits.topk(max_top_k, dim=1).values.gather(1, k_index.long())
1108
+ # Handle non-topk rows.
1109
+ top_k_mask.masked_fill_(no_top_k_mask.unsqueeze(1), -float("inf"))
1110
+ logits.masked_fill_(logits < top_k_mask, -float("inf"))
1111
+ return logits
1112
+
1113
+ def apply_top_k_top_p(
1114
+ logits: torch.Tensor,
1115
+ k: Optional[torch.Tensor],
1116
+ p: Optional[torch.Tensor],
1117
+ ) -> torch.Tensor:
1118
+ """Apply top-k and top-p masks to the logits.
1119
+
1120
+ If a top-p is used, this function will sort the logits tensor,
1121
+ which can be slow for large batches.
1122
+
1123
+ The logits tensor may be updated in-place.
1124
+ """
1125
+ if p is None:
1126
+ if k is None:
1127
+ return logits
1128
+
1129
+ # Avoid sorting vocab for top-k only case.
1130
+ return apply_top_k_only(logits, k)
1131
+
1132
+ logits_sort, logits_idx = logits.sort(dim=-1, descending=False)
1133
+
1134
+ if k is not None:
1135
+ # Apply top-k.
1136
+ top_k_mask = logits_sort.size(1) - k.to(torch.long) # shape: B
1137
+ # Get all the top_k values.
1138
+ top_k_mask = logits_sort.gather(1, top_k_mask.unsqueeze(dim=1))
1139
+ top_k_mask = logits_sort < top_k_mask
1140
+ logits_sort.masked_fill_(top_k_mask, -float("inf"))
1141
+
1142
+ if p is not None:
1143
+ # Apply top-p.
1144
+ probs_sort = logits_sort.softmax(dim=-1)
1145
+ probs_sum = torch.cumsum(probs_sort, dim=-1, out=probs_sort)
1146
+ top_p_mask = probs_sum <= 1 - p.unsqueeze(dim=1)
1147
+ # at least one
1148
+ top_p_mask[:, -1] = False
1149
+ logits_sort.masked_fill_(top_p_mask, -float("inf"))
1150
+
1151
+ # Re-sort the probabilities.
1152
+ logits = logits_sort.scatter(dim=-1, index=logits_idx, src=logits_sort)
1153
+ return logits
1154
+
1155
+ def _sample_next_token(
1156
+ logits_BCxV: torch.Tensor,
1157
+ temperature: float,
1158
+ top_p: float,
1159
+ top_k: int
1160
+ ):
1161
+ if temperature in [0, None]:
1162
+ return torch.argmax(logits_BCxV, dim=-1)
1163
+
1164
+ logits_BCxV = logits_BCxV / temperature
1165
+ logits = apply_top_k_top_p(logits_BCxV, torch.tensor([top_k]), torch.tensor([top_p]))
1166
+
1167
+ final_probs_BCxV = torch.softmax(logits, dim=-1)
1168
+
1169
+ sampled_indices_BC = torch.multinomial(final_probs_BCxV, num_samples=1)
1170
+ sampled_indices_C = sampled_indices_BC.squeeze(-1)
1171
+ return sampled_indices_C
1172
+
1173
+ # def _sample_next_token(
1174
+ # logits_BCxV: torch.Tensor,
1175
+ # temperature: float,
1176
+ # top_p: float,
1177
+ # top_k: int,
1178
+ # audio_eos_value: int,
1179
+ # ) -> torch.Tensor:
1180
+ # if temperature == 0.0:
1181
+ # return torch.argmax(logits_BCxV, dim=-1)
1182
+
1183
+ # logits_BCxV = logits_BCxV / temperature
1184
+
1185
+ # if audio_eos_value is not None and audio_eos_value >= 0:
1186
+ # top_logit_indices_BC = torch.argmax(logits_BCxV, dim=-1)
1187
+ # eos_not_highest_mask_BC = top_logit_indices_BC != audio_eos_value
1188
+ # mask_eos_unless_highest_BCxV = torch.zeros_like(logits_BCxV, dtype=torch.bool)
1189
+ # mask_eos_unless_highest_BCxV[eos_not_highest_mask_BC, audio_eos_value] = True
1190
+ # logits_BCxV = logits_BCxV.masked_fill(mask_eos_unless_highest_BCxV, -torch.inf)
1191
+
1192
+ # if top_k is not None:
1193
+ # _, top_k_indices_BCxV = torch.topk(logits_BCxV, k=top_k, dim=-1)
1194
+ # mask = torch.ones_like(logits_BCxV, dtype=torch.bool)
1195
+ # mask = mask.scatter(dim=-1, index=top_k_indices_BCxV, value=False)
1196
+ # logits_BCxV = logits_BCxV.masked_fill(mask, -torch.inf)
1197
+
1198
+ # if top_p < 1.0:
1199
+ # probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
1200
+ # sorted_probs_BCxV, sorted_indices_BCxV = torch.sort(probs_BCxV, dim=-1, descending=True)
1201
+ # cumulative_probs_BCxV = torch.cumsum(sorted_probs_BCxV, dim=-1)
1202
+
1203
+ # sorted_indices_to_remove_BCxV = cumulative_probs_BCxV > top_p
1204
+ # sorted_indices_to_remove_BCxV = torch.roll(sorted_indices_to_remove_BCxV, shifts=1, dims=-1)
1205
+ # sorted_indices_to_remove_BCxV[..., 0] = torch.zeros_like(sorted_indices_to_remove_BCxV[..., 0])
1206
+
1207
+ # indices_to_remove_BCxV = torch.zeros_like(sorted_indices_to_remove_BCxV)
1208
+ # indices_to_remove_BCxV = indices_to_remove_BCxV.scatter(
1209
+ # dim=-1, index=sorted_indices_BCxV, src=sorted_indices_to_remove_BCxV
1210
+ # )
1211
+ # logits_BCxV = logits_BCxV.masked_fill(indices_to_remove_BCxV, -torch.inf)
1212
+
1213
+ # final_probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
1214
+
1215
+ # sampled_indices_BC = torch.multinomial(final_probs_BCxV, num_samples=1)
1216
+ # sampled_indices_C = sampled_indices_BC.squeeze(-1)
1217
+ # return sampled_indices_C
1218
+
1219
+
1220
+ # @torch.no_grad()
1221
+ # def generate(
1222
+ # self,
1223
+ # enc_in: torch.Tensor,
1224
+ # temperature: float,
1225
+ # top_p: float,
1226
+ # top_k: int,
1227
+ # output_attentions=False) :
1228
+
1229
+ # enc_in_uncond = torch.zeros_like(enc_in)
1230
+ # enc_in = torch.cat((enc_in, enc_in_uncond), dim=0) # [B, T]
1231
+ # enc_state = EncoderInferenceState.new(self.config, enc_in)
1232
+ # enc_out = self.encoder(enc_in, enc_state)
1233
+
1234
+ # dec_in = torch.tensor([4096], device=enc_in.device).long().unsqueeze(0)
1235
+ # dec_in_uncond = torch.tensor([4096], device=enc_in.device).long().unsqueeze(0)
1236
+ # dec_in = torch.cat((dec_in, dec_in_uncond), dim=0)
1237
+
1238
+ # dec_state = DecoderInferenceState.new(
1239
+ # self.config, enc_state, enc_out, dec_in
1240
+ # )
1241
+ # dec_state.cross_attn_mask = dec_state.cross_attn_mask[:,:,[0], :]
1242
+ # # Masking CA for CFG
1243
+ # dec_state.cross_attn_mask[-1,:,:, :] = False
1244
+
1245
+ # cnt = 0
1246
+ # cross_attns = ()
1247
+ # all_logits = ()
1248
+ # while cnt < 34 :
1249
+ # dec_state.prepare_step(0, cnt+1)
1250
+ # # Masking CA for CFG
1251
+ # dec_state.cross_attn_mask[-1,:,:, :] = False
1252
+ # out = self.decoder(dec_in, dec_state)
1253
+ # cross_attns += (out.cross_attentions, )
1254
+ # logits = out['logits']
1255
+ # # print(logits.size())
1256
+ # # print(logits[0])
1257
+ # # print(logits[1])
1258
+ # logits = logits[0] + self.config.model.cfg_val * (logits[0] - logits[1])
1259
+ # # logits = logits[0]
1260
+ # # print(logits.size())
1261
+ # all_logits += (logits,)
1262
+
1263
+ # ntp = _sample_next_token(
1264
+ # logits.squeeze(1)[-1],
1265
+ # temperature=temperature,
1266
+ # top_k=top_k,
1267
+ # top_p=top_p,
1268
+ # audio_eos_value=4097)
1269
+ # # print(dec_in.size(), ntp.size(), ntp)
1270
+ # # dec_in = torch.cat((dec_in, ntp.unsqueeze(0).view(-1,1)), dim=1)
1271
+
1272
+ # dec_in = torch.cat((dec_in, torch.stack((ntp.unsqueeze(0), ntp.unsqueeze(0)))), dim=1)
1273
+
1274
+ # if ntp.item() == 4097 :
1275
+ # break
1276
+ # cnt += 1
1277
+ # return dec_in, all_logits, cross_attns
1278
+
1279
+ # def _sample_next_token(
1280
+ # logits_BCxV: torch.Tensor,
1281
+ # temperature: float,
1282
+ # top_p: float,
1283
+ # top_k: int,
1284
+ # audio_eos_value: int,
1285
+ # ) -> torch.Tensor:
1286
+ # if temperature == 0.0:
1287
+ # return torch.argmax(logits_BCxV, dim=-1)
1288
+
1289
+ # logits_BCxV = logits_BCxV / temperature
1290
+
1291
+ # if audio_eos_value is not None and audio_eos_value >= 0:
1292
+ # top_logit_indices_BC = torch.argmax(logits_BCxV, dim=-1)
1293
+ # eos_not_highest_mask_BC = top_logit_indices_BC != audio_eos_value
1294
+ # mask_eos_unless_highest_BCxV = torch.zeros_like(logits_BCxV, dtype=torch.bool)
1295
+ # mask_eos_unless_highest_BCxV[eos_not_highest_mask_BC, audio_eos_value] = True
1296
+ # logits_BCxV = logits_BCxV.masked_fill(mask_eos_unless_highest_BCxV, -torch.inf)
1297
+
1298
+ # if top_k is not None:
1299
+ # _, top_k_indices_BCxV = torch.topk(logits_BCxV, k=top_k, dim=-1)
1300
+ # mask = torch.ones_like(logits_BCxV, dtype=torch.bool)
1301
+ # mask = mask.scatter(dim=-1, index=top_k_indices_BCxV, value=False)
1302
+ # logits_BCxV = logits_BCxV.masked_fill(mask, -torch.inf)
1303
+
1304
+ # if top_p < 1.0:
1305
+ # probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
1306
+ # sorted_probs_BCxV, sorted_indices_BCxV = torch.sort(probs_BCxV, dim=-1, descending=True)
1307
+ # cumulative_probs_BCxV = torch.cumsum(sorted_probs_BCxV, dim=-1)
1308
+
1309
+ # sorted_indices_to_remove_BCxV = cumulative_probs_BCxV > top_p
1310
+ # sorted_indices_to_remove_BCxV = torch.roll(sorted_indices_to_remove_BCxV, shifts=1, dims=-1)
1311
+ # sorted_indices_to_remove_BCxV[..., 0] = torch.zeros_like(sorted_indices_to_remove_BCxV[..., 0])
1312
+
1313
+ # indices_to_remove_BCxV = torch.zeros_like(sorted_indices_to_remove_BCxV)
1314
+ # indices_to_remove_BCxV = indices_to_remove_BCxV.scatter(
1315
+ # dim=-1, index=sorted_indices_BCxV, src=sorted_indices_to_remove_BCxV
1316
+ # )
1317
+ # logits_BCxV = logits_BCxV.masked_fill(indices_to_remove_BCxV, -torch.inf)
1318
+
1319
+ # final_probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
1320
+
1321
+ # sampled_indices_BC = torch.multinomial(final_probs_BCxV, num_samples=1)
1322
+ # sampled_indices_C = sampled_indices_BC.squeeze(-1)
1323
+ # return sampled_indices_C
1324
+