gasmichel commited on
Commit
bfd4528
·
verified ·
1 Parent(s): 08ca90c

Upload layers_diffusion_4.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. layers_diffusion_4.py +1490 -0
layers_diffusion_4.py ADDED
@@ -0,0 +1,1490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ context_embs: torch.Tensor,
810
+ audio_in : torch.Tensor,
811
+ ref_in : torch.Tensor,
812
+ text_input_ids: torch.Tensor,
813
+ mask: torch.Tensor) -> torch.Tensor:
814
+
815
+
816
+ bsz, seq_len, embed_dim = context_embs.shape
817
+
818
+ x = self.embedding_dense(audio_in).squeeze(2)
819
+ # ref_x = self.ref_dense(ref_in.view(x.size(0), -1)).squeeze(2)
820
+ # print(context_embs.size(), x.size())
821
+ x = torch.cat((context_embs, self.sep_emb.repeat(bsz, 1,1).to(x.dtype), x), dim = 1)
822
+ # x = x + ref_x
823
+
824
+ mask_with_buffer = torch.cat([torch.zeros(bsz, seq_len + 1, device=x.device), mask], dim=1)
825
+
826
+ # positional embeddings to let the model know the initial positions
827
+ # positions = torch.arange(x.size(1), device=x.device).unsqueeze(0).repeat(bsz,1).long()
828
+ # x = x + self.encoder_pos_embed_learned(positions)
829
+ # x = self.z_proj_ln(x)
830
+
831
+ # dropping
832
+ x = x[(1-mask_with_buffer).nonzero(as_tuple=True)].reshape(bsz, -1, embed_dim)
833
+
834
+ # state
835
+ enc_in_dummy = self.get_ids(text_input_ids, max_len = x.size(1))
836
+ state = EncoderInferenceState.new(
837
+ self.config, enc_in_dummy
838
+ )
839
+ # print(state.attn_mask[1,0, 8:, 8:])
840
+ # cross_attentions = ()
841
+ for i, layer in enumerate(self.layers):
842
+ x = layer(x, state)
843
+ # cross_attentions += (cattns,)
844
+
845
+ # Final Norm
846
+ x = self.norm(x)
847
+ # reconstructed_input = self.reconstructor(self.dropout(x[:,-32:])).squeeze(2)
848
+
849
+ # gt_latents = audio_in.clone().detach()
850
+ # x = x[:,-32:] + self.diffusion_pos_embed_learned
851
+
852
+ # loss = self.forward_loss(x, gt_latents, target_mask)
853
+
854
+ # out = QuoteTTSOutput(
855
+ # logits=x,
856
+ # mask_loss=None,
857
+ # expressive_latents=None)
858
+ #, kl_div_loss=loss_kl, mu=mu, logvar=logvar)
859
+ return x
860
+
861
+
862
+ class MaskedEncoder(nn.Module):
863
+ """Transformer Decoder Stack using DenseGeneral."""
864
+
865
+ def __init__(self, config):
866
+ super().__init__()
867
+ self.config = config
868
+ model_config = config.model
869
+ dec_config = config.model.decoder
870
+ data_config = config.data
871
+ self.num_layers = dec_config.n_layer
872
+
873
+ # self.embeddings = nn.Embedding(model_config.tgt_vocab_size, dec_config.n_embd)
874
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, dec_config.n_embd))# nn.Embedding(1, config.model.inp_dim)
875
+ torch.nn.init.normal_(self.mask_token, std=.02)
876
+
877
+ # self.embedding_dense = DenseGeneral(
878
+ # in_shapes=(dec_config.n_embd,),
879
+ # out_features=(1, dec_config.n_embd),
880
+ # axis=(-1,),
881
+ # )
882
+ self.embedding_dense = nn.Linear(dec_config.inp_dim, dec_config.n_embd, bias=True)
883
+ torch.nn.init.xavier_uniform_(self.embedding_dense.weight)
884
+ torch.nn.init.constant_(self.embedding_dense.bias, 0)
885
+
886
+ self.layers = nn.ModuleList(
887
+ [EncoderLayer(config=config) for _ in range(self.num_layers)]
888
+ )
889
+
890
+ # self.norm = RMSNorm(
891
+ # dec_config.n_embd,
892
+ # eps=model_config.normalization_layer_epsilon,
893
+ # dtype=torch.float32,
894
+ # )
895
+ self.norm = LlamaAdaptiveRMSNorm(
896
+ hidden_size=dec_config.n_embd, dim_cond=dec_config.n_embd
897
+ )
898
+ # self.decoder_pos_embed_learned = nn.Embedding(1024, dec_config.n_embd)
899
+ # torch.nn.init.normal_(self.decoder_pos_embed_learned.weight.data, std=.02)
900
+
901
+ # self.diffusion_pos_embed_learned = nn.Parameter(torch.zeros(1, 32, config.model.decoder.n_embd))
902
+ # torch.nn.init.normal_(self.diffusion_pos_embed_learned, std=.02)
903
+
904
+ def get_ids(self, text_input_ids, max_len, pad_value=1):
905
+ bs, seq_len = text_input_ids.size()
906
+ padding_size = max_len - seq_len
907
+
908
+ padding_tensor = torch.empty(bs, padding_size, device=text_input_ids.device).fill_(pad_value).long()
909
+ return torch.cat((text_input_ids, padding_tensor), dim=1)
910
+
911
+ def forward(
912
+ self,
913
+ audio_in: torch.Tensor,
914
+ context_embs: torch.Tensor,
915
+ mask: torch.Tensor,
916
+ text_input_ids : torch.Tensor,
917
+ cond_emb: torch.Tensor) -> torch.Tensor:
918
+
919
+ bsz, seq_len = text_input_ids.shape
920
+
921
+ x = self.embedding_dense(audio_in).squeeze(2)
922
+
923
+ mask_with_buffer = torch.cat([torch.zeros(bsz, seq_len, device=x.device), mask], dim=1)
924
+
925
+ # mask tokens
926
+ x = torch.cat((context_embs, x), dim = 1)
927
+ # mask target tokens
928
+ x[(mask_with_buffer).nonzero(as_tuple=True)] = self.mask_token.to(x.dtype)
929
+
930
+ # positions = torch.arange(x_after_pad.size(1), device=x_after_pad.device).unsqueeze(0).repeat(bsz,1).long()
931
+ # x = x_after_pad + self.decoder_pos_embed_learned(positions)
932
+
933
+ # avoid attending to pad tokens
934
+ enc_in_dummy = self.get_ids(text_input_ids, max_len = x.size(1))
935
+ state = EncoderInferenceState.new(
936
+ self.config, enc_in_dummy
937
+ )
938
+ # print(state.attn_mask[1,0, 8:, 8:])
939
+ # cross_attentions = ()
940
+ for i, layer in enumerate(self.layers):
941
+ x = layer(x, state, cond_emb=cond_emb)
942
+ # cross_attentions += (cattns,)
943
+
944
+ # Final Norm
945
+ x = self.norm(x, cond_embedding=cond_emb)
946
+ # reconstructed_input = self.reconstructor(self.dropout(x[:,-32:])).squeeze(2)
947
+
948
+ x = x[:,-32:]
949
+ # x = x + self.diffusion_pos_embed_learned
950
+
951
+ # loss = self.forward_loss(x, gt_latents, target_mask)
952
+
953
+ # out = QuoteTTSOutput(
954
+ # logits=x,
955
+ # mask_loss=loss,
956
+ # expressive_latents=None)
957
+ #, kl_div_loss=loss_kl, mu=mu, logvar=logvar)
958
+ return x
959
+
960
+ class EncoderDecoder(
961
+ nn.Module,
962
+ ):
963
+ def __init__(self, config):
964
+ super().__init__()
965
+ self.config = config
966
+ self.mask_ratio_generator = stats.truncnorm((config.model.mask_ratio_min - 1.0) / 0.25, 0, loc=1.0, scale=0.25)
967
+
968
+ # self.encoder = T5Encoder.from_pretrained(config.model.base_encoder_path, config.model.ft_encoder_path).encoder
969
+ self.context_encoder = T5EncoderModel.from_pretrained(config.model.base_encoder_path)
970
+ for p in self.context_encoder.parameters():
971
+ p.requires_grad = False
972
+ self.context_encoder = self.context_encoder.eval()
973
+
974
+ # self.encoder = Encoder(config)
975
+ self.decoder = MaskedEncoder(config)
976
+
977
+ self.diffloss = DiffLoss(
978
+ target_channels=config.model.inp_dim,
979
+ z_channels=1024,
980
+ width=1024,
981
+ depth=8,
982
+ num_sampling_steps='100',
983
+ grad_checkpointing=False
984
+ )
985
+
986
+ self.mask_step_embedding = SinusoidalPosEmb(config.model.decoder.n_embd)
987
+ self.mask_step_mlp = nn.Sequential(
988
+ nn.Linear(config.model.decoder.n_embd, config.model.decoder.n_embd * 4),
989
+ nn.SiLU(),
990
+ nn.Linear(config.model.decoder.n_embd * 4, config.model.decoder.n_embd),
991
+ )
992
+
993
+ # self.post_ln = nn.LayerNorm(config.model.decoder.n_embd)
994
+
995
+ # self.ref_dense = nn.Linear(config.model.inp_dim, config.model.decoder.n_embd, bias=True)
996
+ # torch.nn.init.xavier_uniform_(self.ref_dense.weight)
997
+ # torch.nn.init.constant_(self.ref_dense.bias, 0)
998
+
999
+ def random_masking(self, x, orders):
1000
+ # generate token mask
1001
+ bsz, seq_len, embed_dim = x.shape
1002
+ mask_rate = self.mask_ratio_generator.rvs(1)[0]
1003
+ num_masked_tokens = int(np.ceil(seq_len * mask_rate))
1004
+ mask = torch.zeros(bsz, seq_len, device=x.device)
1005
+ mask = torch.scatter(mask, dim=-1, index=orders[:, :num_masked_tokens].to(x.device),
1006
+ src=torch.ones(bsz, seq_len, device=x.device))
1007
+ return mask.long()
1008
+
1009
+ def sample_orders(self, bsz, seq_len =32 ):
1010
+ # generate a batch of random generation orders
1011
+ orders = []
1012
+ for _ in range(bsz):
1013
+ order = np.array(list(range(seq_len)))
1014
+ np.random.shuffle(order)
1015
+ orders.append(order)
1016
+ orders = torch.Tensor(np.array(orders)).long()
1017
+ return orders
1018
+
1019
+ # def mask_input(self, x) :
1020
+ # bs, seq_len, _ = x.size()
1021
+ # orders = self.sample_orders(bs,seq_len)
1022
+ # mask = self.random_masking(x, orders)
1023
+ # # xt = x.clone()
1024
+ # # xt[(mask==1)] = self.mask_emb.to(xt.dtype)
1025
+ # return mask
1026
+
1027
+ # def sample_orders(self, bsz, seq_len =32 ):
1028
+ # # generate a batch of random generation orders
1029
+ # orders = torch.arange(seq_len).unsqueeze(0).repeat(bsz,1)
1030
+ # return orders
1031
+
1032
+ def mask_prob(self, t):
1033
+ return torch.sin(t * np.pi / 2).to(t.device)
1034
+
1035
+ def get_mask(self, bsz, device, seq_len=32) :
1036
+ t = torch.rand(bsz, device=device, requires_grad=False)
1037
+ t = torch.clamp(t, 1e-5, 1.0)
1038
+ mask_prob = self.mask_prob(t)
1039
+ mask_prob = torch.where(
1040
+ mask_prob < 0.2, torch.ones_like(mask_prob) * 0.2, mask_prob
1041
+ )
1042
+ mask = torch.bernoulli(torch.ones(bsz, seq_len, device=device) * mask_prob[..., None]).long()
1043
+
1044
+ # bs, seq_len, _ = x.size()
1045
+ # orders = self.sample_orders(bs,seq_len)
1046
+ # mask = self.random_masking(x, orders)
1047
+ # xt = x.clone()
1048
+ # xt[(mask==1)] = self.mask_emb.to(xt.dtype)
1049
+ return t, mask
1050
+
1051
+ def forward_loss(self, z, target, mask, diffusion_batch_mul=4):
1052
+ bsz, seq_len, _ = target.shape
1053
+ target = target.reshape(bsz * seq_len, -1).repeat(diffusion_batch_mul, 1)
1054
+ z = z.reshape(bsz*seq_len, -1).repeat(diffusion_batch_mul, 1)
1055
+ mask = mask.reshape(bsz*seq_len).repeat(diffusion_batch_mul)
1056
+ loss = self.diffloss(z=z, target=target, mask=mask)
1057
+ return loss
1058
+
1059
+ def get_diff_t(self, x) :
1060
+ # 32 is sequence length here
1061
+ return torch.randint(0, self.diffloss.train_diffusion.num_timesteps, (x.shape[0] * 32, ), device=x.device)
1062
+
1063
+ def _forward(
1064
+ self,
1065
+ context: torch.Tensor,
1066
+ quote: torch.Tensor,
1067
+ dec_in_ref: torch.Tensor,
1068
+ transformer_in : torch.Tensor,
1069
+ dec_in_tgt: torch.Tensor,
1070
+ labels: torch.Tensor = None
1071
+ ) :
1072
+
1073
+ bsz, _ = context.size()
1074
+
1075
+ # diffusion step embedding
1076
+ # diff_t = self.get_diff_t(context)
1077
+ # diffusion_step_emb = self.diff_step_embedding(diff_t)
1078
+ # diffusion_step_emb = self.diff_step_mlp(diffusion_step_emb).reshape(bsz, 32, -1)
1079
+
1080
+ # mask step embedding
1081
+ mask_t, mask = self.get_mask(bsz, device=context.device)
1082
+ mask_perc_emb = self.mask_step_embedding(mask_t)
1083
+ mask_perc_emb = self.mask_step_mlp(mask_perc_emb)
1084
+
1085
+
1086
+ enc_state = EncoderInferenceState.new(self.context_encoder.config, context)
1087
+ enc_out = self.context_encoder(input_ids=context,attention_mask=enc_state.padding_mask).last_hidden_state
1088
+
1089
+ # quote_embs = self.get_quote_embs(quote)
1090
+
1091
+ # mask = self.mask_input(transformer_in)
1092
+ # x = self.encoder(enc_out, transformer_in, dec_in_ref, context, mask)
1093
+ z = self.decoder(
1094
+ transformer_in,
1095
+ enc_out,
1096
+ mask,
1097
+ context,
1098
+ cond_emb=mask_perc_emb)
1099
+
1100
+ # Reference latents
1101
+ # z_ref = self.post_ln(self.ref_dense(dec_in_ref) + quote_embs)
1102
+
1103
+ # z = torch.cat((z, z_ref), dim = -1)
1104
+ # print(t.size())
1105
+ gt_latents = transformer_in.clone().detach()
1106
+ loss = self.forward_loss(z, gt_latents, mask)
1107
+
1108
+ out = QuoteTTSOutput(
1109
+ logits=z,
1110
+ loss=loss,
1111
+ expressive_latents=None)
1112
+ return out
1113
+
1114
+
1115
+ def forward(
1116
+ self,
1117
+ context: torch.Tensor,
1118
+ quote: torch.Tensor,
1119
+ dec_in_ref: torch.Tensor,
1120
+ transformer_in: torch.Tensor = None,
1121
+ dec_in_tgt: torch.Tensor = None,
1122
+ labels: torch.Tensor = None):
1123
+ # if self.training :
1124
+ # if self.eval :
1125
+ # print(labels[0])
1126
+ if self.training :
1127
+ return self._forward(
1128
+ context=context,
1129
+ quote=quote,
1130
+ dec_in_ref=dec_in_ref,
1131
+ dec_in_tgt=dec_in_tgt,
1132
+ transformer_in=transformer_in,
1133
+ labels=labels)
1134
+ else :
1135
+ samples, z = self.sample_tokens(context, quote, dec_in_ref, num_iter=1)
1136
+ # print(samples)
1137
+ mask = torch.ones(z.size(0), z.size(1), device=context.device).long()
1138
+ # print(z.size())
1139
+ loss = self.forward_loss(z, transformer_in, mask, diffusion_batch_mul=1)
1140
+
1141
+ out = QuoteTTSOutput(
1142
+ logits=samples,
1143
+ loss=loss,
1144
+ labels=transformer_in)
1145
+ return out
1146
+
1147
+ @classmethod
1148
+ def from_pretrained(cls, path: str, config_path: str= None):
1149
+ if config_path:
1150
+ with open(config_path) as f :
1151
+ config = yaml.safe_load(f)
1152
+ else :
1153
+ config = Config()
1154
+
1155
+ model = cls(config)
1156
+ model.load_state_dict(torch.load(os.path.join(path, "pytorch_model.bin"), map_location="cpu"))
1157
+ return model
1158
+
1159
+ # @torch.no_grad()
1160
+ # def sample_all(self, context, quote,num_iter=10, seq_len=32):
1161
+ # expressive_latents = self.sample_tokens(context,quote,num_iter,seq_len)
1162
+ # out = self.decoder()
1163
+
1164
+ @torch.no_grad()
1165
+ def sample_tokens(self, context, quote, dec_in_ref, num_iter=10, seq_len=32, temperature=1.0):
1166
+
1167
+ bsz = context.size(0)
1168
+ enc_state = EncoderInferenceState.new(self.context_encoder.config, context)
1169
+ enc_out = self.context_encoder(input_ids=context,attention_mask=enc_state.padding_mask).last_hidden_state
1170
+
1171
+ # enc_state_ = EncoderInferenceState.new(self.context_encoder.config, quote)
1172
+ # quote_embs = self.context_encoder(input_ids=quote, attention_mask=enc_state_.padding_mask).last_hidden_state
1173
+ # quote_embs = quote_embs.mean(1, keepdims=True)
1174
+ # quote_embs = self.get_quote_embs(quote)
1175
+
1176
+ # ref latents
1177
+ # z_ref = self.post_ln(self.ref_dense(dec_in_ref) + quote_embs)
1178
+
1179
+ # init and sample generation orders
1180
+ tokens = torch.zeros(bsz, seq_len, dec_in_ref.size(2), device=context.device)#.repeat(bsz, seq_len, 1)
1181
+ # dec_in = torch.zeros(bsz, seq_len, self.config.model.decoder.n_embed).cuda()
1182
+ mask = torch.ones(bsz, seq_len, device=context.device)
1183
+ orders = self.sample_orders(bsz)
1184
+
1185
+ # indices = list(range(num_iter))
1186
+ h = 1.0/num_iter
1187
+ t_list = [1.0 - i * h for i in range(num_iter)]
1188
+ t_list.append(0.0)
1189
+
1190
+ # generate latents
1191
+ for step in range(num_iter):
1192
+ cur_tokens = tokens.clone()
1193
+ t = t_list[step] * torch.ones(bsz).to(mask.device)
1194
+ mask_perc_emb = self.mask_step_embedding(t)
1195
+ mask_perc_emb = self.mask_step_mlp(mask_perc_emb)
1196
+ # print(tokens[0])
1197
+ # print(curr_t
1198
+ # x = self.encoder(enc_out, cur_tokens, dec_in_ref, context, mask)
1199
+ z = self.decoder(cur_tokens, enc_out, mask, context, cond_emb=mask_perc_emb)
1200
+
1201
+ # mask ratio for the next round, following MaskGIT and MAGE.
1202
+ mask_ratio = torch.Tensor([t_list[step+1]]).to(context.device) #* torch.ones(bsz).to(mask.device)#np.cos(math.pi / 2. * (step + 1) / num_iter)
1203
+ # print(mask_ratio)
1204
+ # mask_len = torch.Tensor([np.floor(seq_len * mask_ratio)]).to(cur_tokens.device)
1205
+ mask_len = (self.mask_prob(mask_ratio) * seq_len).long()
1206
+
1207
+ # masks out at least one for the next iteration
1208
+ mask_len = torch.maximum(torch.Tensor([1]).to(context.device),
1209
+ torch.minimum(torch.sum(mask, dim=-1, keepdims=True) - 1, mask_len))
1210
+
1211
+ # get masking for next iteration and locations to be predicted in this iteration
1212
+ mask_next = mask_by_order(mask_len[0], orders, bsz, seq_len).to(cur_tokens.device)
1213
+ if step >= num_iter - 1:
1214
+ mask_to_pred = mask[:bsz].bool()
1215
+ else:
1216
+ mask_to_pred = torch.logical_xor(mask[:bsz].bool(), mask_next.bool())
1217
+ mask = mask_next
1218
+ # z = torch.cat((z, z_ref), dim = -1)
1219
+ full_z = z.clone()
1220
+ z = z[mask_to_pred.nonzero(as_tuple=True)]
1221
+ # sample token latents for this step
1222
+ # samples = out.expressive_latents[mask_to_pred.nonzero(as_tuple=True)]
1223
+ sampled_token_latent = self.diffloss.sample(z, temperature, cfg=1.0)
1224
+ cur_tokens[mask_to_pred.nonzero(as_tuple=True)] = sampled_token_latent
1225
+ tokens = cur_tokens.clone()
1226
+ # print(tokens[0,0])
1227
+ return tokens, full_z
1228
+
1229
+ def mask_by_order(mask_len, order, bsz, seq_len):
1230
+ masking = torch.zeros(bsz, seq_len)
1231
+ masking = torch.scatter(masking, dim=-1, index=order[:, :mask_len.long()], src=torch.ones(bsz, seq_len)).bool()
1232
+ return masking
1233
+
1234
+
1235
+ def top_p_sample(logits, thres=0.9):
1236
+ k = math.ceil((1 - thres) * logits.shape[-1])
1237
+ val, ind = logits.topk(k, dim=-1)
1238
+ probs = torch.full_like(logits, float("-inf"))
1239
+ probs.scatter_(2, ind, val)
1240
+ return probs
1241
+
1242
+
1243
+ def log(t, eps=1e-10):
1244
+ return torch.log(t + eps)
1245
+
1246
+
1247
+ def gumbel_noise(t):
1248
+ noise = torch.zeros_like(t).uniform_(0, 1)
1249
+ return -log(-log(noise))
1250
+
1251
+
1252
+ def gumbel_sample(t, temperature=1.0, dim=-1):
1253
+ return ((t / max(temperature, 1e-10)) + gumbel_noise(t)).argmax(dim=dim)
1254
+
1255
+
1256
+ def apply_top_k_only(
1257
+ logits: torch.Tensor,
1258
+ k: torch.Tensor,
1259
+ ) -> torch.Tensor:
1260
+ """
1261
+ Apply top-k mask to the logits.
1262
+
1263
+ This implementation doesn't involve sorting the entire vocab.
1264
+
1265
+ The logits tensor may be updated in-place.
1266
+ """
1267
+ no_top_k_mask = k == logits.shape[1]
1268
+ # Set non-top-k rows to 1 so that we can gather.
1269
+ k = k.masked_fill(no_top_k_mask, 1)
1270
+ max_top_k = k.max()
1271
+ # topk.values tensor has shape [batch_size, max_top_k].
1272
+ # Convert top k to 0-based index in range [0, max_top_k).
1273
+ k_index = k.sub_(1).unsqueeze(1)
1274
+ top_k_mask = logits.topk(max_top_k, dim=1).values.gather(1, k_index.long())
1275
+ # Handle non-topk rows.
1276
+ top_k_mask.masked_fill_(no_top_k_mask.unsqueeze(1), -float("inf"))
1277
+ logits.masked_fill_(logits < top_k_mask, -float("inf"))
1278
+ return logits
1279
+
1280
+ def apply_top_k_top_p(
1281
+ logits: torch.Tensor,
1282
+ k: Optional[torch.Tensor],
1283
+ p: Optional[torch.Tensor],
1284
+ ) -> torch.Tensor:
1285
+ """Apply top-k and top-p masks to the logits.
1286
+
1287
+ If a top-p is used, this function will sort the logits tensor,
1288
+ which can be slow for large batches.
1289
+
1290
+ The logits tensor may be updated in-place.
1291
+ """
1292
+ if p is None:
1293
+ if k is None:
1294
+ return logits
1295
+
1296
+ # Avoid sorting vocab for top-k only case.
1297
+ return apply_top_k_only(logits, k)
1298
+
1299
+ logits_sort, logits_idx = logits.sort(dim=-1, descending=False)
1300
+
1301
+ if k is not None:
1302
+ # Apply top-k.
1303
+ top_k_mask = logits_sort.size(1) - k.to(torch.long) # shape: B
1304
+ # Get all the top_k values.
1305
+ top_k_mask = logits_sort.gather(1, top_k_mask.unsqueeze(dim=1))
1306
+ top_k_mask = logits_sort < top_k_mask
1307
+ logits_sort.masked_fill_(top_k_mask, -float("inf"))
1308
+
1309
+ if p is not None:
1310
+ # Apply top-p.
1311
+ probs_sort = logits_sort.softmax(dim=-1)
1312
+ probs_sum = torch.cumsum(probs_sort, dim=-1, out=probs_sort)
1313
+ top_p_mask = probs_sum <= 1 - p.unsqueeze(dim=1)
1314
+ # at least one
1315
+ top_p_mask[:, -1] = False
1316
+ logits_sort.masked_fill_(top_p_mask, -float("inf"))
1317
+
1318
+ # Re-sort the probabilities.
1319
+ logits = logits_sort.scatter(dim=-1, index=logits_idx, src=logits_sort)
1320
+ return logits
1321
+
1322
+ def _sample_next_token(
1323
+ logits_BCxV: torch.Tensor,
1324
+ temperature: float,
1325
+ top_p: float,
1326
+ top_k: int
1327
+ ):
1328
+ if temperature in [0, None]:
1329
+ return torch.argmax(logits_BCxV, dim=-1)
1330
+
1331
+ logits_BCxV = logits_BCxV / temperature
1332
+ logits = apply_top_k_top_p(logits_BCxV, torch.tensor([top_k]), torch.tensor([top_p]))
1333
+
1334
+ final_probs_BCxV = torch.softmax(logits, dim=-1)
1335
+
1336
+ sampled_indices_BC = torch.multinomial(final_probs_BCxV, num_samples=1)
1337
+ sampled_indices_C = sampled_indices_BC.squeeze(-1)
1338
+ return sampled_indices_C
1339
+
1340
+ # def _sample_next_token(
1341
+ # logits_BCxV: torch.Tensor,
1342
+ # temperature: float,
1343
+ # top_p: float,
1344
+ # top_k: int,
1345
+ # audio_eos_value: int,
1346
+ # ) -> torch.Tensor:
1347
+ # if temperature == 0.0:
1348
+ # return torch.argmax(logits_BCxV, dim=-1)
1349
+
1350
+ # logits_BCxV = logits_BCxV / temperature
1351
+
1352
+ # if audio_eos_value is not None and audio_eos_value >= 0:
1353
+ # top_logit_indices_BC = torch.argmax(logits_BCxV, dim=-1)
1354
+ # eos_not_highest_mask_BC = top_logit_indices_BC != audio_eos_value
1355
+ # mask_eos_unless_highest_BCxV = torch.zeros_like(logits_BCxV, dtype=torch.bool)
1356
+ # mask_eos_unless_highest_BCxV[eos_not_highest_mask_BC, audio_eos_value] = True
1357
+ # logits_BCxV = logits_BCxV.masked_fill(mask_eos_unless_highest_BCxV, -torch.inf)
1358
+
1359
+ # if top_k is not None:
1360
+ # _, top_k_indices_BCxV = torch.topk(logits_BCxV, k=top_k, dim=-1)
1361
+ # mask = torch.ones_like(logits_BCxV, dtype=torch.bool)
1362
+ # mask = mask.scatter(dim=-1, index=top_k_indices_BCxV, value=False)
1363
+ # logits_BCxV = logits_BCxV.masked_fill(mask, -torch.inf)
1364
+
1365
+ # if top_p < 1.0:
1366
+ # probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
1367
+ # sorted_probs_BCxV, sorted_indices_BCxV = torch.sort(probs_BCxV, dim=-1, descending=True)
1368
+ # cumulative_probs_BCxV = torch.cumsum(sorted_probs_BCxV, dim=-1)
1369
+
1370
+ # sorted_indices_to_remove_BCxV = cumulative_probs_BCxV > top_p
1371
+ # sorted_indices_to_remove_BCxV = torch.roll(sorted_indices_to_remove_BCxV, shifts=1, dims=-1)
1372
+ # sorted_indices_to_remove_BCxV[..., 0] = torch.zeros_like(sorted_indices_to_remove_BCxV[..., 0])
1373
+
1374
+ # indices_to_remove_BCxV = torch.zeros_like(sorted_indices_to_remove_BCxV)
1375
+ # indices_to_remove_BCxV = indices_to_remove_BCxV.scatter(
1376
+ # dim=-1, index=sorted_indices_BCxV, src=sorted_indices_to_remove_BCxV
1377
+ # )
1378
+ # logits_BCxV = logits_BCxV.masked_fill(indices_to_remove_BCxV, -torch.inf)
1379
+
1380
+ # final_probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
1381
+
1382
+ # sampled_indices_BC = torch.multinomial(final_probs_BCxV, num_samples=1)
1383
+ # sampled_indices_C = sampled_indices_BC.squeeze(-1)
1384
+ # return sampled_indices_C
1385
+
1386
+
1387
+ # @torch.no_grad()
1388
+ # def generate(
1389
+ # self,
1390
+ # enc_in: torch.Tensor,
1391
+ # temperature: float,
1392
+ # top_p: float,
1393
+ # top_k: int,
1394
+ # output_attentions=False) :
1395
+
1396
+ # enc_in_uncond = torch.zeros_like(enc_in)
1397
+ # enc_in = torch.cat((enc_in, enc_in_uncond), dim=0) # [B, T]
1398
+ # enc_state = EncoderInferenceState.new(self.config, enc_in)
1399
+ # enc_out = self.encoder(enc_in, enc_state)
1400
+
1401
+ # dec_in = torch.tensor([4096], device=enc_in.device).long().unsqueeze(0)
1402
+ # dec_in_uncond = torch.tensor([4096], device=enc_in.device).long().unsqueeze(0)
1403
+ # dec_in = torch.cat((dec_in, dec_in_uncond), dim=0)
1404
+
1405
+ # dec_state = DecoderInferenceState.new(
1406
+ # self.config, enc_state, enc_out, dec_in
1407
+ # )
1408
+ # dec_state.cross_attn_mask = dec_state.cross_attn_mask[:,:,[0], :]
1409
+ # # Masking CA for CFG
1410
+ # dec_state.cross_attn_mask[-1,:,:, :] = False
1411
+
1412
+ # cnt = 0
1413
+ # cross_attns = ()
1414
+ # all_logits = ()
1415
+ # while cnt < 34 :
1416
+ # dec_state.prepare_step(0, cnt+1)
1417
+ # # Masking CA for CFG
1418
+ # dec_state.cross_attn_mask[-1,:,:, :] = False
1419
+ # out = self.decoder(dec_in, dec_state)
1420
+ # cross_attns += (out.cross_attentions, )
1421
+ # logits = out['logits']
1422
+ # # print(logits.size())
1423
+ # # print(logits[0])
1424
+ # # print(logits[1])
1425
+ # logits = logits[0] + self.config.model.cfg_val * (logits[0] - logits[1])
1426
+ # # logits = logits[0]
1427
+ # # print(logits.size())
1428
+ # all_logits += (logits,)
1429
+
1430
+ # ntp = _sample_next_token(
1431
+ # logits.squeeze(1)[-1],
1432
+ # temperature=temperature,
1433
+ # top_k=top_k,
1434
+ # top_p=top_p,
1435
+ # audio_eos_value=4097)
1436
+ # # print(dec_in.size(), ntp.size(), ntp)
1437
+ # # dec_in = torch.cat((dec_in, ntp.unsqueeze(0).view(-1,1)), dim=1)
1438
+
1439
+ # dec_in = torch.cat((dec_in, torch.stack((ntp.unsqueeze(0), ntp.unsqueeze(0)))), dim=1)
1440
+
1441
+ # if ntp.item() == 4097 :
1442
+ # break
1443
+ # cnt += 1
1444
+ # return dec_in, all_logits, cross_attns
1445
+
1446
+ # def _sample_next_token(
1447
+ # logits_BCxV: torch.Tensor,
1448
+ # temperature: float,
1449
+ # top_p: float,
1450
+ # top_k: int,
1451
+ # audio_eos_value: int,
1452
+ # ) -> torch.Tensor:
1453
+ # if temperature == 0.0:
1454
+ # return torch.argmax(logits_BCxV, dim=-1)
1455
+
1456
+ # logits_BCxV = logits_BCxV / temperature
1457
+
1458
+ # if audio_eos_value is not None and audio_eos_value >= 0:
1459
+ # top_logit_indices_BC = torch.argmax(logits_BCxV, dim=-1)
1460
+ # eos_not_highest_mask_BC = top_logit_indices_BC != audio_eos_value
1461
+ # mask_eos_unless_highest_BCxV = torch.zeros_like(logits_BCxV, dtype=torch.bool)
1462
+ # mask_eos_unless_highest_BCxV[eos_not_highest_mask_BC, audio_eos_value] = True
1463
+ # logits_BCxV = logits_BCxV.masked_fill(mask_eos_unless_highest_BCxV, -torch.inf)
1464
+
1465
+ # if top_k is not None:
1466
+ # _, top_k_indices_BCxV = torch.topk(logits_BCxV, k=top_k, dim=-1)
1467
+ # mask = torch.ones_like(logits_BCxV, dtype=torch.bool)
1468
+ # mask = mask.scatter(dim=-1, index=top_k_indices_BCxV, value=False)
1469
+ # logits_BCxV = logits_BCxV.masked_fill(mask, -torch.inf)
1470
+
1471
+ # if top_p < 1.0:
1472
+ # probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
1473
+ # sorted_probs_BCxV, sorted_indices_BCxV = torch.sort(probs_BCxV, dim=-1, descending=True)
1474
+ # cumulative_probs_BCxV = torch.cumsum(sorted_probs_BCxV, dim=-1)
1475
+
1476
+ # sorted_indices_to_remove_BCxV = cumulative_probs_BCxV > top_p
1477
+ # sorted_indices_to_remove_BCxV = torch.roll(sorted_indices_to_remove_BCxV, shifts=1, dims=-1)
1478
+ # sorted_indices_to_remove_BCxV[..., 0] = torch.zeros_like(sorted_indices_to_remove_BCxV[..., 0])
1479
+
1480
+ # indices_to_remove_BCxV = torch.zeros_like(sorted_indices_to_remove_BCxV)
1481
+ # indices_to_remove_BCxV = indices_to_remove_BCxV.scatter(
1482
+ # dim=-1, index=sorted_indices_BCxV, src=sorted_indices_to_remove_BCxV
1483
+ # )
1484
+ # logits_BCxV = logits_BCxV.masked_fill(indices_to_remove_BCxV, -torch.inf)
1485
+
1486
+ # final_probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
1487
+
1488
+ # sampled_indices_BC = torch.multinomial(final_probs_BCxV, num_samples=1)
1489
+ # sampled_indices_C = sampled_indices_BC.squeeze(-1)
1490
+ # return sampled_indices_C