ethiotech4848 commited on
Commit
79f6575
·
verified ·
1 Parent(s): a073fd6

Upload 6 files

Browse files
Files changed (6) hide show
  1. dia/__init__.py +6 -0
  2. dia/audio.py +181 -0
  3. dia/config.py +180 -0
  4. dia/layers.py +926 -0
  5. dia/model.py +879 -0
  6. dia/state.py +247 -0
dia/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .model import Dia
2
+
3
+
4
+ __all__ = [
5
+ "Dia",
6
+ ]
dia/audio.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typing as tp
2
+
3
+ import torch
4
+
5
+
6
+ def build_delay_indices(
7
+ B: int, T: int, C: int, delay_pattern: tp.List[int]
8
+ ) -> tp.Tuple[torch.Tensor, torch.Tensor]:
9
+ """
10
+ Precompute (t_idx_BxTxC, indices_BTCx3) so that out[t, c] = in[t - delay[c], c].
11
+ Negative t_idx => BOS; t_idx >= T => PAD.
12
+ """
13
+ delay_arr = torch.tensor(delay_pattern, dtype=torch.int32)
14
+
15
+ t_idx_BxT = torch.broadcast_to(
16
+ torch.arange(T, dtype=torch.int32)[None, :],
17
+ [B, T],
18
+ )
19
+ t_idx_BxTx1 = t_idx_BxT[..., None]
20
+ t_idx_BxTxC = t_idx_BxTx1 - delay_arr.view(1, 1, C)
21
+
22
+ b_idx_BxTxC = torch.broadcast_to(
23
+ torch.arange(B, dtype=torch.int32).view(B, 1, 1),
24
+ [B, T, C],
25
+ )
26
+ c_idx_BxTxC = torch.broadcast_to(
27
+ torch.arange(C, dtype=torch.int32).view(1, 1, C),
28
+ [B, T, C],
29
+ )
30
+
31
+ # We must clamp time indices to [0..T-1] so gather_nd equivalent won't fail
32
+ t_clamped_BxTxC = torch.clamp(t_idx_BxTxC, 0, T - 1)
33
+
34
+ indices_BTCx3 = torch.stack(
35
+ [
36
+ b_idx_BxTxC.reshape(-1),
37
+ t_clamped_BxTxC.reshape(-1),
38
+ c_idx_BxTxC.reshape(-1),
39
+ ],
40
+ dim=1,
41
+ ).long() # Ensure indices are long type for indexing
42
+
43
+ return t_idx_BxTxC, indices_BTCx3
44
+
45
+
46
+ def apply_audio_delay(
47
+ audio_BxTxC: torch.Tensor,
48
+ pad_value: int,
49
+ bos_value: int,
50
+ precomp: tp.Tuple[torch.Tensor, torch.Tensor],
51
+ ) -> torch.Tensor:
52
+ """
53
+ Applies the delay pattern to batched audio tokens using precomputed indices,
54
+ inserting BOS where t_idx < 0 and PAD where t_idx >= T.
55
+
56
+ Args:
57
+ audio_BxTxC: [B, T, C] int16 audio tokens (or int32/float)
58
+ pad_value: the padding token
59
+ bos_value: the BOS token
60
+ precomp: (t_idx_BxTxC, indices_BTCx3) from build_delay_indices
61
+
62
+ Returns:
63
+ result_BxTxC: [B, T, C] delayed audio tokens
64
+ """
65
+ device = audio_BxTxC.device # Get device from input tensor
66
+ t_idx_BxTxC, indices_BTCx3 = precomp
67
+ t_idx_BxTxC = t_idx_BxTxC.to(device) # Move precomputed indices to device
68
+ indices_BTCx3 = indices_BTCx3.to(device)
69
+
70
+ # Equivalent of tf.gather_nd using advanced indexing
71
+ # Ensure indices are long type if not already (build_delay_indices should handle this)
72
+ gathered_flat = audio_BxTxC[
73
+ indices_BTCx3[:, 0], indices_BTCx3[:, 1], indices_BTCx3[:, 2]
74
+ ]
75
+ gathered_BxTxC = gathered_flat.view(audio_BxTxC.shape)
76
+
77
+ # Create masks on the correct device
78
+ mask_bos = t_idx_BxTxC < 0 # => place bos_value
79
+ mask_pad = t_idx_BxTxC >= audio_BxTxC.shape[1] # => place pad_value
80
+
81
+ # Create scalar tensors on the correct device
82
+ bos_tensor = torch.tensor(bos_value, dtype=audio_BxTxC.dtype, device=device)
83
+ pad_tensor = torch.tensor(pad_value, dtype=audio_BxTxC.dtype, device=device)
84
+
85
+ # If mask_bos, BOS; else if mask_pad, PAD; else original gather
86
+ # All tensors should now be on the same device
87
+ result_BxTxC = torch.where(
88
+ mask_bos, bos_tensor, torch.where(mask_pad, pad_tensor, gathered_BxTxC)
89
+ )
90
+
91
+ return result_BxTxC
92
+
93
+
94
+ def build_revert_indices(
95
+ B: int, T: int, C: int, delay_pattern: tp.List[int]
96
+ ) -> tp.Tuple[torch.Tensor, torch.Tensor]:
97
+ """
98
+ Precompute indices for the revert operation using PyTorch.
99
+
100
+ Returns:
101
+ A tuple (t_idx_BxTxC, indices_BTCx3) where:
102
+ - t_idx_BxTxC is a tensor of shape [B, T, C] computed as time indices plus the delay.
103
+ - indices_BTCx3 is a tensor of shape [B*T*C, 3] used for gathering, computed from:
104
+ batch indices, clamped time indices, and channel indices.
105
+ """
106
+ # Use default device unless specified otherwise; assumes inputs might define device later
107
+ device = None # Or determine dynamically if needed, e.g., from a model parameter
108
+
109
+ delay_arr = torch.tensor(delay_pattern, dtype=torch.int32, device=device)
110
+
111
+ t_idx_BT1 = torch.broadcast_to(torch.arange(T, device=device).unsqueeze(0), [B, T])
112
+ t_idx_BT1 = t_idx_BT1.unsqueeze(-1)
113
+
114
+ t_idx_BxTxC = torch.minimum(
115
+ t_idx_BT1 + delay_arr.view(1, 1, C),
116
+ torch.tensor(T - 1, device=device),
117
+ )
118
+ b_idx_BxTxC = torch.broadcast_to(
119
+ torch.arange(B, device=device).view(B, 1, 1), [B, T, C]
120
+ )
121
+ c_idx_BxTxC = torch.broadcast_to(
122
+ torch.arange(C, device=device).view(1, 1, C), [B, T, C]
123
+ )
124
+
125
+ indices_BTCx3 = torch.stack(
126
+ [
127
+ b_idx_BxTxC.reshape(-1),
128
+ t_idx_BxTxC.reshape(-1),
129
+ c_idx_BxTxC.reshape(-1),
130
+ ],
131
+ axis=1,
132
+ ).long() # Ensure indices are long type
133
+
134
+ return t_idx_BxTxC, indices_BTCx3
135
+
136
+
137
+ def revert_audio_delay(
138
+ audio_BxTxC: torch.Tensor,
139
+ pad_value: int,
140
+ precomp: tp.Tuple[torch.Tensor, torch.Tensor],
141
+ T: int,
142
+ ) -> torch.Tensor:
143
+ """
144
+ Reverts a delay pattern from batched audio tokens using precomputed indices (PyTorch version).
145
+
146
+ Args:
147
+ audio_BxTxC: Input delayed audio tensor
148
+ pad_value: Padding value for out-of-bounds indices
149
+ precomp: Precomputed revert indices tuple containing:
150
+ - t_idx_BxTxC: Time offset indices tensor
151
+ - indices_BTCx3: Gather indices tensor for original audio
152
+ T: Original sequence length before padding
153
+
154
+ Returns:
155
+ Reverted audio tensor with same shape as input
156
+ """
157
+ t_idx_BxTxC, indices_BTCx3 = precomp
158
+ device = audio_BxTxC.device # Get device from input tensor
159
+
160
+ # Move precomputed indices to the same device as audio_BxTxC if they aren't already
161
+ t_idx_BxTxC = t_idx_BxTxC.to(device)
162
+ indices_BTCx3 = indices_BTCx3.to(device)
163
+
164
+ # Using PyTorch advanced indexing (equivalent to tf.gather_nd or np equivalent)
165
+ gathered_flat = audio_BxTxC[
166
+ indices_BTCx3[:, 0], indices_BTCx3[:, 1], indices_BTCx3[:, 2]
167
+ ]
168
+ gathered_BxTxC = gathered_flat.view(
169
+ audio_BxTxC.size()
170
+ ) # Use .size() for robust reshaping
171
+
172
+ # Create pad_tensor on the correct device
173
+ pad_tensor = torch.tensor(pad_value, dtype=audio_BxTxC.dtype, device=device)
174
+ # Create T tensor on the correct device for comparison
175
+ T_tensor = torch.tensor(T, device=device)
176
+
177
+ result_BxTxC = torch.where(
178
+ t_idx_BxTxC >= T_tensor, pad_tensor, gathered_BxTxC
179
+ ) # Changed np.where to torch.where
180
+
181
+ return result_BxTxC
dia/config.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration management module for the Dia model.
2
+
3
+ This module provides comprehensive configuration management for the Dia model,
4
+ utilizing Pydantic for validation. It defines configurations for data processing,
5
+ model architecture (encoder and decoder), and training settings.
6
+
7
+ Key components:
8
+ - DataConfig: Parameters for data loading and preprocessing.
9
+ - EncoderConfig: Architecture details for the encoder module.
10
+ - DecoderConfig: Architecture details for the decoder module.
11
+ - ModelConfig: Combined model architecture settings.
12
+ - TrainingConfig: Training hyperparameters and settings.
13
+ - DiaConfig: Master configuration combining all components.
14
+ """
15
+
16
+ import os
17
+
18
+ from pydantic import BaseModel, Field
19
+
20
+
21
+ class EncoderConfig(BaseModel, frozen=True):
22
+ """Configuration for the encoder component of the Dia model.
23
+
24
+ Attributes:
25
+ model_type: Type of the model, defaults to "dia_encoder".
26
+ hidden_size: Size of the encoder layers, defaults to 1024.
27
+ intermediate_size: Size of the "intermediate" (i.e., feed-forward) layer in the encoder, defaults to 4096.
28
+ num_hidden_layers: Number of hidden layers in the encoder, defaults to 12.
29
+ num_attention_heads: Number of attention heads in the encoder, defaults to 16.
30
+ num_key_value_heads: Number of key-value heads in the encoder, defaults to 16.
31
+ head_dim: Dimension of each attention head, defaults to 128.
32
+ hidden_act: Activation function in the encoder, defaults to "silu".
33
+ max_position_embeddings: Maximum number of position embeddings, defaults to 1024.
34
+ initializer_range: Range for initializing weights, defaults to 0.02.
35
+ norm_eps: Epsilon value for normalization layers, defaults to 1e-5.
36
+ rope_theta: Theta value for RoPE, defaults to 10000.0.
37
+ rope_scaling: Optional scaling factor for RoPE.
38
+ vocab_size: Vocabulary size, defaults to 256.
39
+ """
40
+
41
+ head_dim: int = Field(default=128, gt=0)
42
+ hidden_act: str = Field(default="silu")
43
+ hidden_size: int = Field(default=1024, gt=0)
44
+ initializer_range: float = Field(default=0.02)
45
+ intermediate_size: int = Field(default=4096, gt=0)
46
+ max_position_embeddings: int = Field(default=1024, gt=0)
47
+ model_type: str = Field(default="dia_encoder")
48
+ norm_eps: float = Field(default=1e-5)
49
+ num_attention_heads: int = Field(default=16, gt=0)
50
+ num_hidden_layers: int = Field(default=12, gt=0)
51
+ num_key_value_heads: int = Field(default=16, gt=0)
52
+ rope_scaling: float | None = Field(default=None)
53
+ rope_theta: float = Field(default=10000.0)
54
+ vocab_size: int = Field(default=256, gt=0)
55
+
56
+
57
+ class DecoderConfig(BaseModel, frozen=True):
58
+ """Configuration for the decoder component of the Dia model.
59
+
60
+ Attributes:
61
+ model_type: Type of the model, defaults to "dia_decoder".
62
+ hidden_size: Size of the decoder layers, defaults to 2048.
63
+ intermediate_size: Size of the "intermediate" (i.e., feed-forward) layer in the decoder, defaults to 8192.
64
+ num_hidden_layers: Number of hidden layers in the decoder, defaults to 18.
65
+ num_attention_heads: Number of attention heads in the decoder, defaults to 16.
66
+ num_key_value_heads: Number of key-value heads in the decoder, defaults to 4.
67
+ head_dim: Dimension of each attention head, defaults to 128.
68
+ cross_hidden_size: Size of the cross-attention layers, defaults to 1024.
69
+ cross_num_attention_heads: Number of attention heads in the cross-attention mechanism, defaults to 16.
70
+ cross_num_key_value_heads: Number of key-value heads in the cross-attention mechanism, defaults to 16.
71
+ cross_head_dim: Dimension of each cross-attention head, defaults to 128.
72
+ hidden_act: Activation function in the decoder, defaults to "silu".
73
+ max_position_embeddings: Maximum number of position embeddings in the decoder, defaults to 3072.
74
+ initializer_range: Range for initializing weights in the decoder, defaults to 0.02.
75
+ norm_eps: Epsilon value for normalization layers in the decoder, defaults to 1e-5.
76
+ rope_theta: Theta value for RoPE in the decoder, defaults to 10000.0.
77
+ rope_scaling: Optional scaling factor for RoPE in the decoder.
78
+ vocab_size: Vocabulary size for the decoder, defaults to 1028.
79
+ num_channels: Number of channels in the decoder, defaults to 9.
80
+ """
81
+
82
+ cross_head_dim: int = Field(default=128, gt=0)
83
+ cross_hidden_size: int = Field(default=1024, gt=0)
84
+ cross_num_attention_heads: int = Field(default=16, gt=0)
85
+ cross_num_key_value_heads: int = Field(default=16, gt=0)
86
+ head_dim: int = Field(default=128, gt=0)
87
+ hidden_act: str = Field(default="silu")
88
+ hidden_size: int = Field(default=2048, gt=0)
89
+ initializer_range: float = Field(default=0.02)
90
+ intermediate_size: int = Field(default=8192, gt=0)
91
+ max_position_embeddings: int = Field(default=3072, gt=0)
92
+ model_type: str = Field(default="dia_decoder")
93
+ norm_eps: float = Field(default=1e-5)
94
+ num_attention_heads: int = Field(default=16, gt=0)
95
+ num_channels: int = Field(default=9, gt=0)
96
+ num_hidden_layers: int = Field(default=18, gt=0)
97
+ num_key_value_heads: int = Field(default=4, gt=0)
98
+ rope_scaling: float | None = Field(default=None)
99
+ rope_theta: float = Field(default=10000.0)
100
+ vocab_size: int = Field(default=1028, gt=0)
101
+
102
+
103
+ class DiaConfig(BaseModel, frozen=True):
104
+ """Main configuration container for the Dia model architecture.
105
+
106
+ Attributes:
107
+ model_type: Type of the model, defaults to "dia".
108
+ is_encoder_decoder: Flag indicating if the model is an encoder-decoder type, defaults to True.
109
+ encoder: Configuration for the encoder component.
110
+ decoder: Configuration for the decoder component.
111
+ src_vocab_size: Size of the source (text) vocabulary.
112
+ tgt_vocab_size: Size of the target (audio code) vocabulary.
113
+ initializer_range: Range for initializing weights, defaults to 0.02.
114
+ norm_eps: Epsilon value for normalization layers, defaults to 1e-5.
115
+ torch_dtype: Data type for model weights in PyTorch, defaults to "float32".
116
+ bos_token_id: Beginning-of-sequence token ID, defaults to 1026.
117
+ eos_token_id: End-of-sequence token ID, defaults to 1024.
118
+ pad_token_id: Padding token ID, defaults to 1025.
119
+ rope_theta: Theta value for RoPE, defaults to 10000.0.
120
+ rope_scaling: Optional scaling factor for RoPE.
121
+ transformers_version: Version of the transformers library, defaults to "4.53.0.dev0".
122
+ architectures: List of model architectures, defaults to ["DiaForConditionalGeneration"].
123
+ delay_pattern: List of delay values for each audio channel, defaults to [0,8,9,10,11,12,13,14,15].
124
+ """
125
+
126
+ architectures: list[str] = Field(
127
+ default_factory=lambda: ["DiaForConditionalGeneration"]
128
+ )
129
+ bos_token_id: int = Field(default=1026)
130
+ decoder_config: DecoderConfig
131
+ delay_pattern: list[int] = Field(
132
+ default_factory=lambda: [0, 8, 9, 10, 11, 12, 13, 14, 15]
133
+ )
134
+ encoder_config: EncoderConfig
135
+ eos_token_id: int = Field(default=1024)
136
+ initializer_range: float = Field(default=0.02)
137
+ is_encoder_decoder: bool = Field(default=True)
138
+ model_type: str = Field(default="dia")
139
+ norm_eps: float = Field(default=1e-5)
140
+ pad_token_id: int = Field(default=1025)
141
+ torch_dtype: str = Field(default="float32")
142
+ transformers_version: str = Field(default="4.53.0.dev0")
143
+
144
+ def save(self, path: str) -> None:
145
+ """Save the current configuration instance to a JSON file.
146
+
147
+ Ensures the parent directory exists and the file has a .json extension.
148
+
149
+ Args:
150
+ path: The target file path to save the configuration.
151
+
152
+ Raises:
153
+ ValueError: If the path is not a file with a .json extension.
154
+ """
155
+ os.makedirs(os.path.dirname(path), exist_ok=True)
156
+ config_json = self.model_dump_json(indent=2)
157
+ with open(path, "w") as f:
158
+ f.write(config_json)
159
+
160
+ @classmethod
161
+ def load(cls, path: str) -> "DiaConfig | None":
162
+ """Load and validate a Dia configuration from a JSON file.
163
+
164
+ Args:
165
+ path: The path to the configuration file.
166
+
167
+ Returns:
168
+ A validated DiaConfig instance if the file exists and is valid,
169
+ otherwise None if the file is not found.
170
+
171
+ Raises:
172
+ ValueError: If the path does not point to an existing .json file.
173
+ pydantic.ValidationError: If the JSON content fails validation against the DiaConfig schema.
174
+ """
175
+ try:
176
+ with open(path, "r") as f:
177
+ content = f.read()
178
+ return cls.model_validate_json(content)
179
+ except FileNotFoundError:
180
+ return None
dia/layers.py ADDED
@@ -0,0 +1,926 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ from .config import DecoderConfig, DiaConfig, EncoderConfig
9
+ from .state import DecoderInferenceState, EncoderInferenceState, KVCache
10
+
11
+
12
+ def _normalize_axes(axes: tuple[int, ...], ndim: int) -> tuple[int, ...]:
13
+ return tuple(ax if ax >= 0 else ndim + ax for ax in axes)
14
+
15
+
16
+ class DenseGeneral(nn.Module):
17
+ """
18
+ PyTorch equivalent of flax.linen.DenseGeneral with shapes defined at init.
19
+ Stores weights (`kernel`) in the same layout as Jax and uses torch.tensordot
20
+ for the generalized matrix multiplication. Weight/bias shapes are calculated
21
+ and parameters created during initialization based on config.
22
+ `load_weights` validates shapes and copies data.
23
+ Attributes:
24
+ axis (Tuple[int, ...]): Input axis or axes to contract.
25
+ in_shapes (Tuple[int, ...]): Sizes of the input dimensions specified by `axis`.
26
+ out_features (Tuple[int, ...]): Shape of the output features (non-contracted dims).
27
+ use_bias (bool): Whether to add a bias term.
28
+ weight (nn.Parameter): The kernel parameter.
29
+ bias (Optional[nn.Parameter]): The bias parameter (if use_bias=True).
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ in_shapes: tuple[int, ...],
35
+ out_features: tuple[int, ...],
36
+ axis: tuple[int, ...] = (-1,),
37
+ weight_dtype: torch.dtype | None = None,
38
+ device: torch.device | None = None,
39
+ ):
40
+ super().__init__()
41
+ self.in_shapes = in_shapes
42
+ self.out_features = out_features
43
+ self.axis = axis
44
+ self.kernel_shape = self.in_shapes + self.out_features
45
+
46
+ factory_kwargs = {"device": device, "dtype": weight_dtype}
47
+ self.weight = nn.Parameter(torch.empty(self.kernel_shape, **factory_kwargs))
48
+
49
+ def forward(self, inputs: Tensor) -> Tensor:
50
+ norm_axis = _normalize_axes(self.axis, inputs.ndim)
51
+ kernel_contract_axes = tuple(range(len(norm_axis)))
52
+
53
+ output = torch.tensordot(
54
+ inputs.to(self.weight.dtype),
55
+ self.weight,
56
+ dims=(norm_axis, kernel_contract_axes),
57
+ ).to(inputs.dtype)
58
+ return output
59
+
60
+
61
+ class MlpBlock(nn.Module):
62
+ """MLP block using DenseGeneral."""
63
+
64
+ def __init__(
65
+ self, embed_dim: int, intermediate_dim: int, compute_dtype: torch.dtype
66
+ ):
67
+ super().__init__()
68
+ self.dtype = compute_dtype
69
+
70
+ self.wi_fused = DenseGeneral(
71
+ in_shapes=(embed_dim,),
72
+ out_features=(2, intermediate_dim),
73
+ axis=(-1,),
74
+ weight_dtype=compute_dtype,
75
+ )
76
+
77
+ self.wo = DenseGeneral(
78
+ in_shapes=(intermediate_dim,),
79
+ out_features=(embed_dim,),
80
+ axis=(-1,),
81
+ weight_dtype=compute_dtype,
82
+ )
83
+
84
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
85
+ """Forward pass."""
86
+ fused_x = self.wi_fused(x)
87
+
88
+ gate = fused_x[..., 0, :]
89
+ up = fused_x[..., 1, :]
90
+
91
+ hidden = torch.mul(F.silu(gate), up).to(self.dtype)
92
+
93
+ output = self.wo(hidden)
94
+ return output
95
+
96
+
97
+ class RotaryEmbedding(nn.Module):
98
+ """Rotary Position Embedding (RoPE) implementation in PyTorch."""
99
+
100
+ def __init__(
101
+ self,
102
+ embedding_dims: int,
103
+ min_timescale: int = 1,
104
+ max_timescale: int = 10000,
105
+ dtype: torch.dtype = torch.float32,
106
+ ):
107
+ super().__init__()
108
+ if embedding_dims % 2 != 0:
109
+ raise ValueError("Embedding dim must be even for RoPE.")
110
+ self.embedding_dims = embedding_dims
111
+ self.min_timescale = min_timescale
112
+ self.max_timescale = max_timescale
113
+ self.compute_dtype = dtype
114
+
115
+ half_embedding_dim = embedding_dims // 2
116
+ fraction = (2.0 * torch.arange(0, half_embedding_dim)) / embedding_dims
117
+ timescale = (
118
+ self.min_timescale * (self.max_timescale / self.min_timescale) ** fraction
119
+ ).to(torch.float32)
120
+ self.register_buffer("timescale", timescale, persistent=False)
121
+
122
+ def forward(self, inputs: torch.Tensor, position: torch.Tensor):
123
+ """Applies RoPE."""
124
+ position = position.unsqueeze(-1).unsqueeze(-1)
125
+ sinusoid_inp = position / self.timescale
126
+ sin = torch.sin(sinusoid_inp)
127
+ cos = torch.cos(sinusoid_inp)
128
+ first_half, second_half = torch.chunk(inputs.to(torch.float32), 2, dim=-1)
129
+ first_part = first_half * cos - second_half * sin
130
+ second_part = second_half * cos + first_half * sin
131
+ return torch.cat(
132
+ (first_part.to(self.compute_dtype), second_part.to(self.compute_dtype)),
133
+ dim=-1,
134
+ )
135
+
136
+ def apply_rope(self, inputs: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor):
137
+ first_half, second_half = torch.chunk(inputs.to(torch.float32), 2, dim=-1)
138
+ first_part = first_half * cos - second_half * sin
139
+ second_part = second_half * cos + first_half * sin
140
+ return torch.cat(
141
+ (first_part.to(self.compute_dtype), second_part.to(self.compute_dtype)),
142
+ dim=-1,
143
+ )
144
+
145
+
146
+ def custom_scaled_dot_product_attention(
147
+ query: torch.Tensor,
148
+ key: torch.Tensor,
149
+ value: torch.Tensor,
150
+ attn_mask: torch.Tensor | None = None,
151
+ scale: float = 1.0,
152
+ is_causal: bool = False,
153
+ num_gqa_groups: int = 1,
154
+ ) -> torch.Tensor:
155
+ """
156
+ Custom scaled dot-product attention with GQA support for MPS compatibility.
157
+
158
+ Args:
159
+ query: (B, N_q, T, H) - Query tensor, N_q = num_query_heads
160
+ key: (B, N_kv, S, H) - Key tensor, N_kv = num_kv_heads
161
+ value: (B, N_kv, S, H) - Value tensor
162
+ attn_mask: (B, 1, T, S) - Attention mask, optional
163
+ scale: Scaling factor for attention scores
164
+ is_causal: If True, apply causal masking
165
+ num_gqa_groups: Number of query groups per KV head (N_q / N_kv)
166
+
167
+ Returns:
168
+ output: (B, N_q, T, H) - Attention output
169
+ """
170
+ B, N_q, T, H = query.shape
171
+ _, N_kv, S, _ = key.shape
172
+
173
+ # For GQA, repeat key and value tensors to match query heads
174
+ if num_gqa_groups > 1:
175
+ key = key.repeat_interleave(num_gqa_groups, dim=1) # (B, N_q, S, H)
176
+ value = value.repeat_interleave(num_gqa_groups, dim=1) # (B, N_q, S, H)
177
+
178
+ # Compute attention scores: (B, N_q, T, H) @ (B, N_q, H, S) -> (B, N_q, T, S)
179
+ scores = torch.matmul(query, key.transpose(-1, -2)) * scale
180
+
181
+ # Apply causal mask if needed
182
+ if is_causal:
183
+ causal_mask = torch.tril(
184
+ torch.ones(T, S, dtype=torch.bool, device=query.device)
185
+ )
186
+ scores = scores.masked_fill(~causal_mask, float("-inf"))
187
+
188
+ # Apply attention mask if provided
189
+ if attn_mask is not None:
190
+ scores = scores.masked_fill(~attn_mask, float("-inf"))
191
+
192
+ # Softmax over the last dimension (S)
193
+ attn_weights = F.softmax(scores, dim=-1)
194
+
195
+ # Compute output: (B, N_q, T, S) @ (B, N_q, S, H) -> (B, N_q, T, H)
196
+ output = torch.matmul(attn_weights, value)
197
+
198
+ return output
199
+
200
+
201
+ class CrossAttention(nn.Module):
202
+ """Cross-Attention using DenseGeneral."""
203
+
204
+ def __init__(
205
+ self,
206
+ config: EncoderConfig | DecoderConfig,
207
+ q_embed_dim: int,
208
+ kv_embed_dim: int,
209
+ num_query_heads: int,
210
+ num_kv_heads: int,
211
+ head_dim: int,
212
+ compute_dtype: torch.dtype,
213
+ out_embed_dim: int | None = None,
214
+ ):
215
+ super().__init__()
216
+ self.num_query_heads = num_query_heads
217
+ self.num_kv_heads = num_kv_heads
218
+ self.head_dim = head_dim
219
+ self.output_dim = out_embed_dim if out_embed_dim is not None else q_embed_dim
220
+ self.projected_query_dim = num_query_heads * head_dim
221
+ if num_query_heads % num_kv_heads != 0:
222
+ raise ValueError(
223
+ f"num_query_heads ({num_query_heads}) must be divisible by num_kv_heads ({num_kv_heads})"
224
+ )
225
+ self.num_gqa_groups = num_query_heads // num_kv_heads
226
+
227
+ # --- Projection Layers using DenseGeneral ---
228
+ self.q_proj = DenseGeneral(
229
+ in_shapes=(q_embed_dim,),
230
+ out_features=(num_query_heads, head_dim),
231
+ axis=(-1,),
232
+ weight_dtype=compute_dtype,
233
+ )
234
+ self.k_proj = DenseGeneral(
235
+ in_shapes=(kv_embed_dim,),
236
+ out_features=(num_kv_heads, head_dim),
237
+ axis=(-1,),
238
+ weight_dtype=compute_dtype,
239
+ )
240
+ self.v_proj = DenseGeneral(
241
+ in_shapes=(kv_embed_dim,),
242
+ out_features=(num_kv_heads, head_dim),
243
+ axis=(-1,),
244
+ weight_dtype=compute_dtype,
245
+ )
246
+ self.o_proj = DenseGeneral(
247
+ in_shapes=(num_query_heads, head_dim),
248
+ out_features=(self.output_dim,),
249
+ axis=(-2, -1),
250
+ weight_dtype=compute_dtype,
251
+ )
252
+
253
+ # --- Rotary Embedding ---
254
+ self.rotary_emb = RotaryEmbedding(
255
+ embedding_dims=self.head_dim,
256
+ max_timescale=config.rope_theta,
257
+ dtype=compute_dtype,
258
+ )
259
+
260
+ def forward(
261
+ self,
262
+ Xq: torch.Tensor, # (B, T, D) T = 1 in AR generation
263
+ q_positions: torch.Tensor, # (B, T)
264
+ kv_positions: torch.Tensor | None = None, # (B, S)
265
+ attn_mask: torch.Tensor
266
+ | None = None, # None in Decoder Self Attention, Valid mask in Others
267
+ cache: KVCache | None = None, # None in Encoder, KVCache in Decoder
268
+ is_causal: bool = False,
269
+ ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:
270
+ """
271
+ Performs attention calculation with optional KV caching.
272
+
273
+ Args:
274
+ Xq: Query tensor (B, T, D). T=1 during single-step decoding.
275
+ Xkv: Key/Value source tensor (B, S, E). S=1 during single-step decoding for self-attn.
276
+ q_positions: Positions for queries (B, T).
277
+ kv_positions: Positions for keys/values (B, S). If None, uses q_positions.
278
+ attn_mask: Attention mask.
279
+ cache: KVCache.
280
+
281
+ Returns:
282
+ A tuple containing:
283
+ - output: The attention output tensor (B, T, output_dim).
284
+ - 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.
285
+ """
286
+ if kv_positions is None:
287
+ kv_positions = q_positions
288
+ original_dtype = Xq.dtype
289
+
290
+ Xq_BxTxNxH = self.q_proj(Xq)
291
+ Xq_BxNxTxH = Xq_BxTxNxH.transpose(1, 2)
292
+
293
+ attn_k: torch.Tensor | None = None
294
+ attn_v: torch.Tensor | None = None
295
+
296
+ attn_k, attn_v = cache.k, cache.v
297
+
298
+ # Use custom attention for MPS backend, otherwise use optimized PyTorch function
299
+ is_mps = Xq.device.type == "mps" and torch.backends.mps.is_available()
300
+ if is_mps:
301
+ attn_output = custom_scaled_dot_product_attention(
302
+ query=Xq_BxNxTxH,
303
+ key=attn_k,
304
+ value=attn_v,
305
+ attn_mask=attn_mask if not is_causal else None,
306
+ scale=1.0,
307
+ is_causal=is_causal,
308
+ num_gqa_groups=self.num_gqa_groups,
309
+ )
310
+ else:
311
+ attn_output = F.scaled_dot_product_attention(
312
+ Xq_BxNxTxH,
313
+ attn_k,
314
+ attn_v,
315
+ attn_mask=attn_mask if not is_causal else None,
316
+ scale=1.0,
317
+ enable_gqa=self.num_gqa_groups > 1,
318
+ is_causal=is_causal,
319
+ )
320
+
321
+ attn_output = attn_output.transpose(1, 2).contiguous() # (B, T, N, H)
322
+ output = self.o_proj(attn_output)
323
+
324
+ return output.to(original_dtype)
325
+
326
+
327
+ class FusedQKV(nn.Module):
328
+ def __init__(
329
+ self,
330
+ in_features: int,
331
+ out_features: int,
332
+ bias: bool = False,
333
+ num_q_heads: int = 1,
334
+ q_head_dim: int = 1,
335
+ num_kv_heads: int = 1,
336
+ kv_head_dim: int = 1,
337
+ ):
338
+ super().__init__()
339
+ self.num_q_heads = num_q_heads
340
+ self.q_head_dim = q_head_dim
341
+ self.num_kv_heads = num_kv_heads
342
+ self.kv_head_dim = kv_head_dim
343
+ self.q_output_dim = num_q_heads * q_head_dim
344
+ self.kv_output_dim = num_kv_heads * kv_head_dim
345
+ self.linear = nn.Linear(in_features, out_features, bias=bias)
346
+
347
+ def forward(
348
+ self, inputs: torch.Tensor
349
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
350
+ x = self.linear(inputs)
351
+
352
+ q, k, v = x.split(
353
+ [self.q_output_dim, self.kv_output_dim, self.kv_output_dim], dim=-1
354
+ )
355
+
356
+ q = q.reshape(q.shape[:-1] + (self.num_q_heads, self.q_head_dim))
357
+ k = k.reshape(k.shape[:-1] + (self.num_kv_heads, self.kv_head_dim))
358
+ v = v.reshape(v.shape[:-1] + (self.num_kv_heads, self.kv_head_dim))
359
+
360
+ return q, k, v
361
+
362
+
363
+ class SelfAttention(nn.Module):
364
+ """Attention using DenseGeneral."""
365
+
366
+ def __init__(
367
+ self,
368
+ config: DiaConfig,
369
+ q_embed_dim: int,
370
+ kv_embed_dim: int,
371
+ num_query_heads: int,
372
+ num_kv_heads: int,
373
+ head_dim: int,
374
+ compute_dtype: torch.dtype,
375
+ out_embed_dim: int | None = None,
376
+ ):
377
+ super().__init__()
378
+ self.num_query_heads = num_query_heads
379
+ self.num_kv_heads = num_kv_heads
380
+ self.head_dim = head_dim
381
+ self.output_dim = out_embed_dim if out_embed_dim is not None else q_embed_dim
382
+ self.projected_query_dim = num_query_heads * head_dim
383
+ if num_query_heads % num_kv_heads != 0:
384
+ raise ValueError(
385
+ f"num_query_heads ({num_query_heads}) must be divisible by num_kv_heads ({num_kv_heads})"
386
+ )
387
+ self.num_gqa_groups = num_query_heads // num_kv_heads
388
+ self.kv_embed_dim = kv_embed_dim
389
+ self.q_embed_dim = q_embed_dim
390
+
391
+ # --- Projection Layers using DenseGeneral ---
392
+ self.q_proj = DenseGeneral(
393
+ in_shapes=(q_embed_dim,),
394
+ out_features=(num_query_heads, head_dim),
395
+ axis=(-1,),
396
+ weight_dtype=compute_dtype,
397
+ )
398
+ self.k_proj = DenseGeneral(
399
+ in_shapes=(kv_embed_dim,),
400
+ out_features=(num_kv_heads, head_dim),
401
+ axis=(-1,),
402
+ weight_dtype=compute_dtype,
403
+ )
404
+ self.v_proj = DenseGeneral(
405
+ in_shapes=(kv_embed_dim,),
406
+ out_features=(num_kv_heads, head_dim),
407
+ axis=(-1,),
408
+ weight_dtype=compute_dtype,
409
+ )
410
+ self.o_proj = DenseGeneral(
411
+ in_shapes=(num_query_heads, head_dim),
412
+ out_features=(self.output_dim,),
413
+ axis=(-2, -1),
414
+ weight_dtype=compute_dtype,
415
+ )
416
+
417
+ # --- Rotary Embedding ---
418
+ self.rotary_emb = RotaryEmbedding(
419
+ embedding_dims=self.head_dim,
420
+ max_timescale=config.rope_theta,
421
+ dtype=compute_dtype,
422
+ )
423
+
424
+ self.is_fused_qkv = False
425
+
426
+ def get_linear_weight(self, dense: DenseGeneral):
427
+ W_dg = dense.weight.data
428
+
429
+ out_features = 1
430
+ input_features = 1
431
+ for dim in dense.out_features:
432
+ out_features *= dim
433
+ for dim in dense.in_shapes:
434
+ input_features *= dim
435
+
436
+ W_dg_reshaped_for_linear_T = W_dg.reshape(input_features, out_features)
437
+ linear_weight = W_dg_reshaped_for_linear_T.transpose(0, 1).contiguous()
438
+ return linear_weight
439
+
440
+ def patch_fused_qkv(self):
441
+ q_proj_weight = self.get_linear_weight(self.q_proj)
442
+ k_proj_weight = self.get_linear_weight(self.k_proj)
443
+ v_proj_weight = self.get_linear_weight(self.v_proj)
444
+
445
+ self.qkv = FusedQKV(
446
+ self.kv_embed_dim,
447
+ (
448
+ self.num_query_heads * self.head_dim
449
+ + 2 * (self.num_kv_heads * self.head_dim)
450
+ ),
451
+ bias=False,
452
+ num_q_heads=self.num_query_heads,
453
+ q_head_dim=self.head_dim,
454
+ num_kv_heads=self.num_kv_heads,
455
+ kv_head_dim=self.head_dim,
456
+ )
457
+ self.qkv.linear.weight.data = torch.cat(
458
+ [q_proj_weight, k_proj_weight, v_proj_weight], dim=0
459
+ )
460
+
461
+ # print(f"qkv.weight.shape: {self.qkv.linear.weight.shape}")
462
+ self.is_fused_qkv = True
463
+
464
+ def forward(
465
+ self,
466
+ X: torch.Tensor, # (B, T, D) T = 1 in AR generation
467
+ q_positions: torch.Tensor, # (B, T)
468
+ kv_positions: torch.Tensor | None = None, # (B, S)
469
+ attn_mask: torch.Tensor
470
+ | None = None, # None in Decoder Self Attention, Valid mask in Others
471
+ cache: KVCache | None = None, # None in Encoder, KVCache in Decoder
472
+ prefill: bool = False,
473
+ is_causal: bool = False,
474
+ current_idx: torch.Tensor | None = None,
475
+ ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:
476
+ """
477
+ Performs attention calculation with optional KV caching.
478
+ Args:
479
+ Xq: Query tensor (B, T, D). T=1 during single-step decoding.
480
+ Xkv: Key/Value source tensor (B, S, E). S=1 during single-step decoding for self-attn.
481
+ q_positions: Positions for queries (B, T).
482
+ kv_positions: Positions for keys/values (B, S). If None, uses q_positions.
483
+ attn_mask: Attention mask.
484
+ cache: KVCache.
485
+ prefill: If True, use prefill mode.
486
+ Returns:
487
+ A tuple containing:
488
+ - output: The attention output tensor (B, T, output_dim).
489
+ - 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.
490
+ """
491
+ if kv_positions is None:
492
+ kv_positions = q_positions
493
+
494
+ original_dtype = X.dtype
495
+
496
+ if self.is_fused_qkv:
497
+ Xq_BxTxNxH, Xk_BxSxKxH, Xv_BxSxKxH = self.qkv(X)
498
+ else:
499
+ Xq_BxTxNxH = self.q_proj(X)
500
+ Xk_BxSxKxH = self.k_proj(X)
501
+ Xv_BxSxKxH = self.v_proj(X)
502
+
503
+ position = q_positions.unsqueeze(-1).unsqueeze(-1)
504
+ sinusoid_inp = position / self.rotary_emb.timescale
505
+ sin = torch.sin(sinusoid_inp)
506
+ cos = torch.cos(sinusoid_inp)
507
+
508
+ Xq_BxTxNxH = self.rotary_emb.apply_rope(Xq_BxTxNxH, sin, cos)
509
+ Xk_BxSxKxH = self.rotary_emb.apply_rope(Xk_BxSxKxH, sin, cos)
510
+
511
+ Xq_BxNxTxH = Xq_BxTxNxH.transpose(1, 2)
512
+
513
+ attn_k: torch.Tensor | None = None
514
+ attn_v: torch.Tensor | None = None
515
+
516
+ Xk_BxKxSxH = Xk_BxSxKxH.transpose(1, 2) # (B, K, S, H)
517
+ Xv_BxKxSxH = Xv_BxSxKxH.transpose(1, 2) # (B, K, S, H)
518
+
519
+ if cache is None:
520
+ attn_k = Xk_BxKxSxH
521
+ attn_v = Xv_BxKxSxH
522
+ elif prefill:
523
+ attn_k, attn_v = Xk_BxKxSxH, Xv_BxKxSxH
524
+ cache.prefill(attn_k, attn_v)
525
+ else:
526
+ attn_k, attn_v = cache.update(Xk_BxKxSxH, Xv_BxKxSxH, current_idx)
527
+
528
+ # Use custom attention for MPS backend, otherwise use optimized PyTorch function
529
+ is_mps = Xv_BxSxKxH.device.type == "mps" and torch.backends.mps.is_available()
530
+ if is_mps:
531
+ attn_output = custom_scaled_dot_product_attention(
532
+ query=Xq_BxNxTxH,
533
+ key=attn_k,
534
+ value=attn_v,
535
+ attn_mask=attn_mask if not is_causal else None,
536
+ scale=1.0,
537
+ is_causal=is_causal,
538
+ num_gqa_groups=self.num_gqa_groups,
539
+ )
540
+ else:
541
+ attn_output = F.scaled_dot_product_attention(
542
+ Xq_BxNxTxH,
543
+ attn_k,
544
+ attn_v,
545
+ attn_mask=attn_mask if not is_causal else None,
546
+ scale=1.0,
547
+ enable_gqa=self.num_gqa_groups > 1,
548
+ is_causal=is_causal,
549
+ )
550
+
551
+ attn_output = attn_output.transpose(1, 2).contiguous() # (B, T, N, H)
552
+ output = self.o_proj(attn_output)
553
+
554
+ return output.to(original_dtype)
555
+
556
+
557
+ class EncoderLayer(nn.Module):
558
+ """Transformer Encoder Layer using DenseGeneral."""
559
+
560
+ def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
561
+ super().__init__()
562
+ self.config = config
563
+ enc_config = config.encoder_config
564
+ embed_dim = enc_config.hidden_size
565
+ self.compute_dtype = compute_dtype
566
+
567
+ self.pre_sa_norm = RMSNorm(
568
+ embed_dim,
569
+ eps=enc_config.norm_eps,
570
+ dtype=torch.float32,
571
+ )
572
+ self.self_attention = SelfAttention(
573
+ enc_config,
574
+ q_embed_dim=embed_dim,
575
+ kv_embed_dim=embed_dim,
576
+ num_query_heads=enc_config.num_attention_heads,
577
+ num_kv_heads=enc_config.num_key_value_heads,
578
+ head_dim=enc_config.head_dim,
579
+ compute_dtype=compute_dtype,
580
+ out_embed_dim=embed_dim,
581
+ )
582
+ self.post_sa_norm = RMSNorm(
583
+ embed_dim,
584
+ eps=enc_config.norm_eps,
585
+ dtype=torch.float32,
586
+ )
587
+ self.mlp = MlpBlock(
588
+ embed_dim=embed_dim,
589
+ intermediate_dim=enc_config.intermediate_size,
590
+ compute_dtype=compute_dtype,
591
+ )
592
+
593
+ def forward(
594
+ self,
595
+ x: torch.Tensor,
596
+ state: EncoderInferenceState,
597
+ ) -> torch.Tensor:
598
+ residual = x
599
+ x_norm = self.pre_sa_norm(x).to(self.compute_dtype)
600
+
601
+ sa_out = self.self_attention(
602
+ X=x_norm,
603
+ q_positions=state.positions,
604
+ kv_positions=state.positions,
605
+ attn_mask=state.attn_mask,
606
+ )
607
+ x = residual + sa_out
608
+
609
+ residual = x
610
+ x_norm = self.post_sa_norm(x).to(self.compute_dtype)
611
+ mlp_out = self.mlp(x_norm)
612
+ x = residual + mlp_out
613
+
614
+ return x
615
+
616
+
617
+ class Encoder(nn.Module):
618
+ """Transformer Encoder Stack using DenseGeneral."""
619
+
620
+ def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
621
+ super().__init__()
622
+ self.config = config
623
+ enc_config = config.encoder_config
624
+ self.compute_dtype = compute_dtype
625
+
626
+ self.embedding = nn.Embedding(
627
+ enc_config.vocab_size,
628
+ enc_config.hidden_size,
629
+ dtype=compute_dtype,
630
+ )
631
+ self.layers = nn.ModuleList(
632
+ [
633
+ EncoderLayer(config, compute_dtype)
634
+ for _ in range(enc_config.num_hidden_layers)
635
+ ]
636
+ )
637
+ self.norm = RMSNorm(
638
+ enc_config.hidden_size,
639
+ eps=enc_config.norm_eps,
640
+ dtype=torch.float32,
641
+ )
642
+
643
+ def forward(
644
+ self,
645
+ x_ids: torch.Tensor,
646
+ state: EncoderInferenceState,
647
+ ) -> torch.Tensor:
648
+ x = self.embedding(x_ids)
649
+
650
+ for layer in self.layers:
651
+ x = layer(x, state)
652
+
653
+ x = self.norm(x).to(self.compute_dtype)
654
+ return x
655
+
656
+
657
+ class DecoderLayer(nn.Module):
658
+ """Transformer Decoder Layer using DenseGeneral."""
659
+
660
+ def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
661
+ super().__init__()
662
+ self.config = config
663
+ dec_config = config.decoder_config
664
+ enc_config = config.encoder_config
665
+ dec_embed_dim = dec_config.hidden_size
666
+ enc_embed_dim = enc_config.hidden_size
667
+ self.compute_dtype = compute_dtype
668
+
669
+ # Norms
670
+ self.pre_sa_norm = RMSNorm(
671
+ dec_embed_dim,
672
+ eps=dec_config.norm_eps,
673
+ dtype=torch.float32,
674
+ )
675
+ self.pre_ca_norm = RMSNorm(
676
+ dec_embed_dim,
677
+ eps=dec_config.norm_eps,
678
+ dtype=torch.float32,
679
+ )
680
+ self.pre_mlp_norm = RMSNorm(
681
+ dec_embed_dim,
682
+ eps=dec_config.norm_eps,
683
+ dtype=torch.float32,
684
+ )
685
+
686
+ # Self-Attention (GQA) with Causal Masking
687
+ self.self_attention = SelfAttention(
688
+ dec_config,
689
+ q_embed_dim=dec_embed_dim,
690
+ kv_embed_dim=dec_embed_dim,
691
+ num_query_heads=dec_config.num_attention_heads,
692
+ num_kv_heads=dec_config.num_key_value_heads,
693
+ head_dim=dec_config.head_dim,
694
+ compute_dtype=compute_dtype,
695
+ out_embed_dim=dec_embed_dim,
696
+ )
697
+ # Cross-Attention (MHA)
698
+ self.cross_attention = CrossAttention(
699
+ dec_config,
700
+ q_embed_dim=dec_embed_dim,
701
+ kv_embed_dim=enc_embed_dim, # Note kv_embed_dim
702
+ num_query_heads=dec_config.cross_num_attention_heads,
703
+ num_kv_heads=dec_config.cross_num_key_value_heads,
704
+ head_dim=dec_config.cross_head_dim,
705
+ compute_dtype=compute_dtype,
706
+ out_embed_dim=dec_embed_dim,
707
+ )
708
+ # MLP
709
+ self.mlp = MlpBlock(
710
+ embed_dim=dec_embed_dim,
711
+ intermediate_dim=dec_config.intermediate_size,
712
+ compute_dtype=compute_dtype,
713
+ )
714
+
715
+ def forward(
716
+ self,
717
+ x: torch.Tensor,
718
+ state: DecoderInferenceState,
719
+ self_attn_cache: KVCache | None = None,
720
+ cross_attn_cache: KVCache | None = None,
721
+ prefill: bool = False,
722
+ current_idx: int = 0,
723
+ ) -> torch.Tensor:
724
+ residual = x
725
+ x_norm = self.pre_sa_norm(x).to(self.compute_dtype)
726
+
727
+ self_attn_mask = state.casual_attn_mask[None, None, current_idx]
728
+
729
+ sa_out = self.self_attention(
730
+ X=x_norm, # (2, 1, D)
731
+ q_positions=state.dec_positions, # (2, 1)
732
+ kv_positions=state.dec_positions, # (2, 1)
733
+ attn_mask=self_attn_mask,
734
+ cache=self_attn_cache,
735
+ prefill=prefill,
736
+ is_causal=prefill,
737
+ current_idx=current_idx,
738
+ )
739
+
740
+ x = residual + sa_out
741
+
742
+ residual = x
743
+ x_norm = self.pre_ca_norm(x).to(self.compute_dtype)
744
+ ca_out = self.cross_attention(
745
+ Xq=x_norm,
746
+ q_positions=state.dec_positions,
747
+ kv_positions=state.enc_positions,
748
+ attn_mask=state.cross_attn_mask,
749
+ cache=cross_attn_cache,
750
+ )
751
+ x = residual + ca_out
752
+
753
+ residual = x
754
+ x_norm = self.pre_mlp_norm(x).to(self.compute_dtype)
755
+ mlp_out = self.mlp(x_norm)
756
+ x = residual + mlp_out
757
+
758
+ return x
759
+
760
+
761
+ class Decoder(nn.Module):
762
+ """Transformer Decoder Stack using DenseGeneral."""
763
+
764
+ def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
765
+ super().__init__()
766
+ self.config = config
767
+ dec_config = config.decoder_config
768
+ self.num_channels = dec_config.num_channels
769
+ self.num_layers = dec_config.num_hidden_layers
770
+
771
+ self.embeddings = nn.ModuleList(
772
+ [
773
+ nn.Embedding(
774
+ dec_config.vocab_size, dec_config.hidden_size, dtype=compute_dtype
775
+ )
776
+ for _ in range(self.num_channels)
777
+ ]
778
+ )
779
+ self.layers = nn.ModuleList(
780
+ [
781
+ DecoderLayer(config=config, compute_dtype=compute_dtype)
782
+ for _ in range(self.num_layers)
783
+ ]
784
+ )
785
+
786
+ self.norm = RMSNorm(
787
+ dec_config.hidden_size,
788
+ eps=dec_config.norm_eps,
789
+ dtype=torch.float32,
790
+ )
791
+
792
+ self.logits_dense = DenseGeneral(
793
+ in_shapes=(dec_config.hidden_size,),
794
+ out_features=(self.num_channels, dec_config.vocab_size),
795
+ axis=(-1,),
796
+ weight_dtype=compute_dtype,
797
+ )
798
+
799
+ def precompute_cross_attn_cache(
800
+ self,
801
+ enc_out: torch.Tensor, # (B, S, E)
802
+ ) -> list[KVCache]:
803
+ """
804
+ Computes the Key and Value tensors for cross-attention for each layer from the encoder output.
805
+ """
806
+ per_layer_kv_cache: list[KVCache] = []
807
+
808
+ for layer in self.layers:
809
+ cross_attn_module = layer.cross_attention
810
+ k_proj = cross_attn_module.k_proj(enc_out)
811
+ v_proj = cross_attn_module.v_proj(enc_out)
812
+
813
+ k = k_proj.transpose(1, 2)
814
+ v = v_proj.transpose(1, 2)
815
+
816
+ per_layer_kv_cache.append(KVCache.from_kv(k, v))
817
+
818
+ return per_layer_kv_cache
819
+
820
+ def decode_step(
821
+ self,
822
+ tgt_ids_Bx1xC: torch.Tensor, # [B, 1, C]
823
+ state: DecoderInferenceState,
824
+ current_idx: int,
825
+ ) -> torch.Tensor:
826
+ """
827
+ Performs a single decoding step, managing KV caches layer by layer.
828
+ Returns:
829
+ A tuple containing:
830
+ - logits_Bx1xCV: The final output logits for the current step (B, 1, C*V), cast to float32.
831
+ """
832
+
833
+ x = None
834
+ for i in range(self.num_channels):
835
+ channel_tokens = tgt_ids_Bx1xC[..., i]
836
+ channel_embed = self.embeddings[i](channel_tokens)
837
+ x = channel_embed if x is None else x + channel_embed
838
+
839
+ for i, layer in enumerate(self.layers):
840
+ self_cache = state.self_attn_cache[i]
841
+ cross_cache = state.cross_attn_cache[i]
842
+ x = layer(
843
+ x, # (2, 1, D)
844
+ state,
845
+ self_attn_cache=self_cache,
846
+ cross_attn_cache=cross_cache,
847
+ current_idx=current_idx,
848
+ )
849
+
850
+ x = self.norm(x)
851
+ logits_Bx1xCxV = self.logits_dense(x)
852
+
853
+ return logits_Bx1xCxV.to(torch.float32)
854
+
855
+ def forward(
856
+ self, tgt_ids_BxTxC: torch.Tensor, state: DecoderInferenceState
857
+ ) -> torch.Tensor:
858
+ """
859
+ Forward pass for the Decoder stack, managing KV caches.
860
+ Args:
861
+ tgt_ids_BxTxC: Target token IDs (B, T, C).
862
+ encoder_out: Output from the encoder (B, S, E).
863
+ tgt_positions: Positions for target sequence (B, T).
864
+ src_positions: Positions for source sequence (B, S).
865
+ self_attn_mask: Mask for self-attention.
866
+ cross_attn_mask: Mask for cross-attention.
867
+ past_key_values: List containing the self-attention KV cache for each layer
868
+ from the previous decoding step. `len(past_key_values)` should
869
+ equal `num_layers`.
870
+ precomputed_cross_attn_kv: A single tuple containing the pre-computed K/V cache
871
+ derived from `encoder_out`. This is passed identically
872
+ to all layers.
873
+ Returns:
874
+ A tuple containing:
875
+ - logits: The final output logits (B, T, C * V), cast to float32.
876
+ - present_key_values: A list containing the updated self-attention KV cache
877
+ for each layer for the *current* decoding step.
878
+ """
879
+ _, _, num_channels_in = tgt_ids_BxTxC.shape
880
+ assert num_channels_in == self.num_channels, "Input channels mismatch"
881
+
882
+ # Embeddings
883
+ x = None
884
+ for i in range(self.num_channels):
885
+ channel_tokens = tgt_ids_BxTxC[..., i]
886
+ channel_embed = self.embeddings[i](channel_tokens)
887
+ x = channel_embed if x is None else x + channel_embed
888
+
889
+ for i, layer in enumerate(self.layers):
890
+ self_cache = state.self_attn_cache[i]
891
+ cross_cache = state.cross_attn_cache[i]
892
+ x = layer(
893
+ x,
894
+ state,
895
+ self_attn_cache=self_cache,
896
+ cross_attn_cache=cross_cache,
897
+ prefill=True,
898
+ )
899
+
900
+ # Final Norm
901
+ x = self.norm(x)
902
+ logits_BxTxCxV = self.logits_dense(x)
903
+
904
+ return logits_BxTxCxV.to(torch.float32)
905
+
906
+
907
+ class DiaModel(
908
+ nn.Module,
909
+ PyTorchModelHubMixin,
910
+ repo_url="https://github.com/nari-labs/dia",
911
+ pipeline_tag="text-to-speech",
912
+ license="apache-2.0",
913
+ coders={
914
+ DiaConfig: (
915
+ lambda x: x.model_dump(),
916
+ lambda data: DiaConfig.model_validate(data),
917
+ ),
918
+ },
919
+ ):
920
+ """PyTorch Dia Model using DenseGeneral."""
921
+
922
+ def __init__(self, config: DiaConfig, compute_dtype: torch.dtype):
923
+ super().__init__()
924
+ self.config = config
925
+ self.encoder = Encoder(config, compute_dtype)
926
+ self.decoder = Decoder(config, compute_dtype)
dia/model.py ADDED
@@ -0,0 +1,879 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from enum import Enum
3
+ from typing import Callable
4
+
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn.functional as F
8
+ import torchaudio
9
+
10
+ from .audio import (
11
+ apply_audio_delay,
12
+ build_delay_indices,
13
+ build_revert_indices,
14
+ revert_audio_delay,
15
+ )
16
+ from .config import DiaConfig
17
+ from .layers import DiaModel
18
+ from .state import DecoderInferenceState, DecoderOutput, EncoderInferenceState
19
+
20
+
21
+ DEFAULT_SAMPLE_RATE = 44100
22
+ SAMPLE_RATE_RATIO = 512
23
+
24
+
25
+ def _get_default_device():
26
+ if torch.cuda.is_available():
27
+ return torch.device("cuda")
28
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
29
+ return torch.device("mps")
30
+ return torch.device("cpu")
31
+
32
+
33
+ def _sample_next_token(
34
+ logits_BCxV: torch.Tensor,
35
+ temperature: float,
36
+ top_p: float,
37
+ top_k: int | None,
38
+ audio_eos_value: int,
39
+ ) -> torch.Tensor:
40
+ if temperature == 0.0:
41
+ return torch.argmax(logits_BCxV, dim=-1)
42
+
43
+ logits_BCxV = logits_BCxV / temperature
44
+
45
+ if audio_eos_value is not None and audio_eos_value >= 0:
46
+ top_logit_indices_BC = torch.argmax(logits_BCxV, dim=-1)
47
+ eos_not_highest_mask_BC = top_logit_indices_BC != audio_eos_value
48
+ mask_eos_unless_highest_BCxV = torch.zeros_like(logits_BCxV, dtype=torch.bool)
49
+ mask_eos_unless_highest_BCxV[eos_not_highest_mask_BC, audio_eos_value] = True
50
+ logits_BCxV = logits_BCxV.masked_fill(mask_eos_unless_highest_BCxV, -torch.inf)
51
+ eos_highest_mask_BC = top_logit_indices_BC == audio_eos_value
52
+ mask_eos_highest_BCxV = torch.zeros_like(logits_BCxV, dtype=torch.bool)
53
+ mask_eos_highest_BCxV[eos_highest_mask_BC, :audio_eos_value] = True
54
+ logits_BCxV = logits_BCxV.masked_fill(mask_eos_highest_BCxV, -torch.inf)
55
+
56
+ if top_k is not None:
57
+ _, top_k_indices_BCxV = torch.topk(logits_BCxV, k=top_k, dim=-1)
58
+ mask = torch.ones_like(logits_BCxV, dtype=torch.bool)
59
+ mask = mask.scatter(dim=-1, index=top_k_indices_BCxV, value=False)
60
+ logits_BCxV = logits_BCxV.masked_fill(mask, -torch.inf)
61
+
62
+ if top_p < 1.0:
63
+ probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
64
+ sorted_probs_BCxV, sorted_indices_BCxV = torch.sort(
65
+ probs_BCxV, dim=-1, descending=True
66
+ )
67
+ cumulative_probs_BCxV = torch.cumsum(sorted_probs_BCxV, dim=-1)
68
+
69
+ sorted_indices_to_remove_BCxV = cumulative_probs_BCxV > top_p
70
+ sorted_indices_to_remove_BCxV = torch.roll(
71
+ sorted_indices_to_remove_BCxV, shifts=1, dims=-1
72
+ )
73
+ sorted_indices_to_remove_BCxV[..., 0] = torch.zeros_like(
74
+ sorted_indices_to_remove_BCxV[..., 0]
75
+ )
76
+
77
+ indices_to_remove_BCxV = torch.zeros_like(sorted_indices_to_remove_BCxV)
78
+ indices_to_remove_BCxV = indices_to_remove_BCxV.scatter(
79
+ dim=-1, index=sorted_indices_BCxV, src=sorted_indices_to_remove_BCxV
80
+ )
81
+ logits_BCxV = logits_BCxV.masked_fill(indices_to_remove_BCxV, -torch.inf)
82
+
83
+ final_probs_BCxV = torch.softmax(logits_BCxV, dim=-1)
84
+
85
+ sampled_indices_BC = torch.multinomial(final_probs_BCxV, num_samples=1)
86
+ sampled_indices_C = sampled_indices_BC.squeeze(-1)
87
+ return sampled_indices_C
88
+
89
+
90
+ class ComputeDtype(str, Enum):
91
+ FLOAT32 = "float32"
92
+ FLOAT16 = "float16"
93
+ BFLOAT16 = "bfloat16"
94
+
95
+ def to_dtype(self) -> torch.dtype:
96
+ if self == ComputeDtype.FLOAT32:
97
+ return torch.float32
98
+ elif self == ComputeDtype.FLOAT16:
99
+ return torch.float16
100
+ elif self == ComputeDtype.BFLOAT16:
101
+ return torch.bfloat16
102
+ else:
103
+ raise ValueError(f"Unsupported compute dtype: {self}")
104
+
105
+
106
+ class Dia:
107
+ def __init__(
108
+ self,
109
+ config: DiaConfig,
110
+ compute_dtype: str | ComputeDtype = ComputeDtype.FLOAT32,
111
+ device: torch.device | None = None,
112
+ load_dac: bool = True,
113
+ ):
114
+ """Initializes the Dia model.
115
+
116
+ Args:
117
+ config: The configuration object for the model.
118
+ compute_dtype: The computation dtype to use.
119
+ device: The device to load the model onto. If None, will automatically select the best available device.
120
+ load_dac: Whether to load the DAC model.
121
+
122
+ Raises:
123
+ RuntimeError: If there is an error loading the DAC model.
124
+ """
125
+ super().__init__()
126
+ self.config = config
127
+ self.device = device if device is not None else _get_default_device()
128
+ if isinstance(compute_dtype, str):
129
+ compute_dtype = ComputeDtype(compute_dtype)
130
+ self.compute_dtype = compute_dtype.to_dtype()
131
+ self.model: DiaModel = DiaModel(config, self.compute_dtype)
132
+ self.dac_model = None
133
+ self._compiled_step = None
134
+ self.load_dac = load_dac
135
+
136
+ if not self.load_dac:
137
+ print("Warning: DAC model will not be loaded. This is not recommended.")
138
+
139
+ if torch.cuda.is_available():
140
+ torch.backends.cuda.matmul.allow_tf32 = True
141
+
142
+ @classmethod
143
+ def from_local(
144
+ cls,
145
+ config_path: str,
146
+ checkpoint_path: str,
147
+ compute_dtype: str | ComputeDtype = ComputeDtype.FLOAT32,
148
+ device: torch.device | None = None,
149
+ load_dac: bool = True,
150
+ ) -> "Dia":
151
+ """Loads the Dia model from local configuration and checkpoint files.
152
+
153
+ Args:
154
+ config_path: Path to the configuration JSON file.
155
+ checkpoint_path: Path to the model checkpoint (.pth) file.
156
+ compute_dtype: The computation dtype to use.
157
+ device: The device to load the model onto. If None, will automatically select the best available device.
158
+ load_dac: Whether to load the DAC model.
159
+
160
+ Returns:
161
+ An instance of the Dia model loaded with weights and set to eval mode.
162
+
163
+ Raises:
164
+ FileNotFoundError: If the config or checkpoint file is not found.
165
+ RuntimeError: If there is an error loading the checkpoint.
166
+ """
167
+ config = DiaConfig.load(config_path)
168
+ if config is None:
169
+ raise FileNotFoundError(f"Config file not found at {config_path}")
170
+
171
+ dia = cls(config, compute_dtype, device, load_dac)
172
+
173
+ try:
174
+ state_dict = torch.load(checkpoint_path, map_location=dia.device)
175
+ dia.model.load_state_dict(state_dict)
176
+ except FileNotFoundError:
177
+ raise FileNotFoundError(f"Checkpoint file not found at {checkpoint_path}")
178
+ except Exception as e:
179
+ raise RuntimeError(
180
+ f"Error loading checkpoint from {checkpoint_path}"
181
+ ) from e
182
+
183
+ dia.model.to(dia.device)
184
+ dia.model.eval()
185
+ if load_dac:
186
+ dia._load_dac_model()
187
+ return dia
188
+
189
+ @classmethod
190
+ def from_pretrained(
191
+ cls,
192
+ model_name: str = "nari-labs/Dia-1.6B-0626",
193
+ compute_dtype: str | ComputeDtype = ComputeDtype.FLOAT32,
194
+ device: torch.device | None = None,
195
+ load_dac: bool = True,
196
+ ) -> "Dia":
197
+ """Loads the Dia model from a Hugging Face Hub repository.
198
+
199
+ Downloads the configuration and checkpoint files from the specified
200
+ repository ID and then loads the model.
201
+
202
+ Args:
203
+ model_name: The Hugging Face Hub repository ID (e.g., "nari-labs/Dia-1.6B-0626").
204
+ compute_dtype: The computation dtype to use.
205
+ device: The device to load the model onto. If None, will automatically select the best available device.
206
+ load_dac: Whether to load the DAC model.
207
+
208
+ Returns:
209
+ An instance of the Dia model loaded with weights and set to eval mode.
210
+
211
+ Raises:
212
+ FileNotFoundError: If config or checkpoint download/loading fails.
213
+ RuntimeError: If there is an error loading the checkpoint.
214
+ """
215
+ if isinstance(compute_dtype, str):
216
+ compute_dtype = ComputeDtype(compute_dtype)
217
+
218
+ # Load model directly using DiaModel's from_pretrained which handles HF download
219
+ try:
220
+ loaded_model = DiaModel.from_pretrained(
221
+ model_name, compute_dtype=compute_dtype.to_dtype()
222
+ )
223
+ except Exception as e:
224
+ raise RuntimeError(
225
+ f"Error loading model from Hugging Face Hub ({model_name})"
226
+ ) from e
227
+
228
+ config = loaded_model.config # Get config from the loaded model
229
+ dia = cls(config, compute_dtype, device, load_dac)
230
+
231
+ dia.model = loaded_model # Assign the already loaded model
232
+ dia.model.to(dia.device)
233
+ dia.model.eval()
234
+ if load_dac:
235
+ dia._load_dac_model()
236
+ return dia
237
+
238
+ def _load_dac_model(self):
239
+ """Loads the Descript Audio Codec (DAC) model.
240
+
241
+ Downloads the DAC model if necessary and loads it onto the specified device.
242
+ Sets the DAC model to evaluation mode.
243
+
244
+ Raises:
245
+ RuntimeError: If downloading or loading the DAC model fails.
246
+ """
247
+ import dac
248
+
249
+ try:
250
+ dac_model_path = dac.utils.download()
251
+ dac_model = dac.DAC.load(dac_model_path).to(self.device)
252
+ dac_model.eval() # Ensure DAC is in eval mode
253
+ except Exception as e:
254
+ raise RuntimeError("Failed to load DAC model") from e
255
+ self.dac_model = dac_model
256
+
257
+ def _encode_text(self, text: str) -> torch.Tensor:
258
+ """Encodes the input text string into a tensor of token IDs using byte-level encoding.
259
+
260
+ Special tokens [S1] and [S2] are replaced by their byte values. The resulting
261
+ sequence is truncated to the maximum configured text length.
262
+
263
+ Args:
264
+ text: The input text string.
265
+
266
+ Returns:
267
+ A tensor containing the encoded byte token IDs.
268
+ """
269
+ max_len = self.config.encoder_config.max_position_embeddings
270
+
271
+ byte_text = text.encode("utf-8")
272
+ # Replace special tokens with their byte values if needed by the specific tokenizer/config
273
+ # Assuming byte values 1 and 2 are correct placeholders based on original code
274
+ replaced_bytes = byte_text.replace(b"[S1]", b"\x01").replace(b"[S2]", b"\x02")
275
+ text_tokens = list(replaced_bytes)
276
+ return torch.tensor(
277
+ text_tokens[:max_len],
278
+ dtype=torch.long,
279
+ device=self.device,
280
+ )
281
+
282
+ def _pad_text_input(self, text_tokens: list[torch.Tensor]) -> torch.Tensor:
283
+ """Pads the text input to the maximum length."""
284
+ text_pad_value = 0
285
+ max_len = self.config.encoder_config.max_position_embeddings
286
+ batch_size = len(text_tokens)
287
+
288
+ src_tokens = torch.full(
289
+ (batch_size, 1, max_len),
290
+ fill_value=text_pad_value,
291
+ dtype=torch.long,
292
+ device=self.device,
293
+ )
294
+ for i in range(batch_size):
295
+ current_len = len(text_tokens[i])
296
+ src_tokens[i, 0, :current_len] = text_tokens[i]
297
+ return src_tokens
298
+
299
+ def _prepare_audio_prompt(
300
+ self, audio_prompts: list[torch.Tensor | None]
301
+ ) -> tuple[torch.Tensor, list[int]]:
302
+ """Prepares the audio prompt tensor for the decoder.
303
+
304
+ Handles padding, adds the beginning-of-sequence (BOS) token, applies the
305
+ delay pattern, and determines the number of prefill steps for each item
306
+ in the batch.
307
+
308
+ Args:
309
+ audio_prompts: A list of audio prompt tensors (encoded DAC frames) or None.
310
+ Each tensor should have shape [T, C].
311
+
312
+ Returns:
313
+ A tuple containing:
314
+ - delayed_batch (torch.Tensor): The prepared audio prompt tensor with
315
+ delays applied, shape [B, T_max_padded, C].
316
+ - prefill_steps (list[int]): A list containing the number of valid
317
+ tokens (including BOS) for each prompt in the batch.
318
+ """
319
+ num_channels = self.config.decoder_config.num_channels
320
+ audio_bos_value = self.config.bos_token_id
321
+ delay_pattern = self.config.delay_pattern
322
+ max_delay_pattern = max(delay_pattern)
323
+ batch_size = len(audio_prompts)
324
+
325
+ max_len = (
326
+ max(p.shape[0] if p is not None else 0 for p in audio_prompts)
327
+ + max_delay_pattern
328
+ )
329
+ prefill_steps = []
330
+
331
+ prefill = torch.full(
332
+ (batch_size, max_len, num_channels),
333
+ fill_value=-1,
334
+ dtype=torch.int,
335
+ device=self.device,
336
+ )
337
+
338
+ prefill[:, 0, :] = audio_bos_value
339
+
340
+ for i in range(batch_size):
341
+ prompt = audio_prompts[i]
342
+ if prompt is not None:
343
+ prompt = prompt.to(device=self.device, dtype=torch.int)
344
+ prefill[i, 1 : prompt.shape[0] + 1, :] = prompt
345
+ prefill_steps.append(prompt.shape[0] + 1)
346
+ else:
347
+ prefill_steps.append(1)
348
+
349
+ delay_precomp = build_delay_indices(
350
+ B=batch_size,
351
+ T=max_len,
352
+ C=num_channels,
353
+ delay_pattern=delay_pattern,
354
+ )
355
+
356
+ delayed_batch = apply_audio_delay(
357
+ audio_BxTxC=prefill,
358
+ pad_value=-1,
359
+ bos_value=audio_bos_value,
360
+ precomp=delay_precomp,
361
+ )
362
+
363
+ return delayed_batch, prefill_steps
364
+
365
+ def _prepare_generation(
366
+ self,
367
+ text: torch.Tensor,
368
+ audio_prompts: list[torch.Tensor | None],
369
+ max_tokens: int | None = None,
370
+ attn_fn: Callable = F.scaled_dot_product_attention,
371
+ ):
372
+ """Initializes the model state for generation.
373
+
374
+ Encodes the text input (conditional and unconditional), prepares the
375
+ encoder and decoder states (including KV caches and cross-attention),
376
+ prepares the audio prompt, and performs the initial decoder prefill steps
377
+ based on the audio prompts.
378
+
379
+ Args:
380
+ text: The padded text input tensor, shape [B, 1, T_text].
381
+ audio_prompts: A list of prepared audio prompt tensors or None.
382
+
383
+ Returns:
384
+ A tuple containing:
385
+ - dec_state (DecoderInferenceState): The initialized decoder state.
386
+ - dec_output (DecoderOutput): The initialized decoder output manager,
387
+ containing the prefilled audio tokens.
388
+ """
389
+ batch_size = text.shape[0]
390
+
391
+ enc_input_uncond = torch.zeros_like(text)
392
+ enc_input_cond = text
393
+ stacked_inputs = torch.stack([enc_input_uncond, enc_input_cond], dim=1)
394
+ enc_input = stacked_inputs.view(2 * batch_size, -1)
395
+
396
+ enc_state = EncoderInferenceState.new(self.config, enc_input_cond)
397
+ encoder_out = self.model.encoder(enc_input, enc_state)
398
+
399
+ dec_cross_attn_cache = self.model.decoder.precompute_cross_attn_cache(
400
+ encoder_out
401
+ )
402
+ dec_state = DecoderInferenceState.new(
403
+ self.config,
404
+ enc_state,
405
+ encoder_out,
406
+ dec_cross_attn_cache,
407
+ self.compute_dtype,
408
+ max_generation_length=max_tokens,
409
+ )
410
+ prefill, prefill_steps = self._prepare_audio_prompt(audio_prompts)
411
+
412
+ dec_output = DecoderOutput.new(batch_size, self.config, self.device)
413
+ dec_output.prefill(prefill, prefill_steps)
414
+
415
+ dec_step = min(prefill_steps) - 1
416
+ if dec_step > 0:
417
+ dec_state.prepare_step(0, dec_step)
418
+ tokens_BxTxC = dec_output.get_tokens_at(0, dec_step).repeat_interleave(
419
+ 2, dim=0
420
+ )
421
+ self.model.decoder.forward(tokens_BxTxC, dec_state)
422
+
423
+ return dec_state, dec_output
424
+
425
+ def _decoder_step(
426
+ self,
427
+ tokens_Bx1xC: torch.Tensor,
428
+ dec_state: DecoderInferenceState,
429
+ cfg_scale: float,
430
+ temperature: float,
431
+ top_p: float,
432
+ top_k: int,
433
+ current_idx: int,
434
+ ) -> torch.Tensor:
435
+ """Performs a single step of the decoder inference.
436
+
437
+ Takes the tokens from the previous step, runs them through the decoder
438
+ (for both conditional and unconditional paths), applies classifier-free
439
+ guidance (CFG), samples the next token using temperature, top-p, and top-k
440
+ sampling, and applies constraints (e.g., preventing EOS in certain channels).
441
+
442
+ Args:
443
+ tokens_Bx1xC: The input tokens for the current step, shape [2*B, 1, C].
444
+ Repeated for CFG (unconditional and conditional).
445
+ dec_state: The current state of the decoder (KV caches, etc.).
446
+ cfg_scale: The scale factor for classifier-free guidance.
447
+ temperature: The temperature for sampling.
448
+ top_p: The cumulative probability threshold for top-p sampling.
449
+ top_k: The number of top logits to consider for top-k sampling.
450
+ current_idx: The current generation step index.
451
+
452
+ Returns:
453
+ torch.Tensor: The sampled next tokens for each item in the batch,
454
+ shape [B, C].
455
+ """
456
+ B = tokens_Bx1xC.shape[0] // 2
457
+
458
+ audio_eos_value = self.config.eos_token_id
459
+ logits_Bx1xCxV = self.model.decoder.decode_step(
460
+ tokens_Bx1xC, dec_state, current_idx
461
+ )
462
+
463
+ logits_last_2BxCxV = logits_Bx1xCxV[:, -1]
464
+ logits_last_Bx2xCxV = logits_last_2BxCxV.view(
465
+ B, 2, *logits_last_2BxCxV.shape[1:]
466
+ )
467
+
468
+ uncond_logits_BxCxV = logits_last_Bx2xCxV[:, 0, :, :] # Shape [B, C, V]
469
+ cond_logits_BxCxV = logits_last_Bx2xCxV[:, 1, :, :] # Shape [B, C, V]
470
+ logits_BxCxV = cond_logits_BxCxV + cfg_scale * (
471
+ cond_logits_BxCxV - uncond_logits_BxCxV
472
+ )
473
+
474
+ _, top_k_indices_BxCxk = torch.topk(logits_BxCxV, k=top_k, dim=-1)
475
+ mask_BxCxV = torch.ones_like(logits_BxCxV, dtype=torch.bool)
476
+ mask_BxCxV = mask_BxCxV.scatter(dim=-1, index=top_k_indices_BxCxk, value=False)
477
+ logits_BxCxV = cond_logits_BxCxV.masked_fill(mask_BxCxV, -torch.inf)
478
+
479
+ logits_BxCxV[:, :, audio_eos_value + 1 :] = torch.full_like(
480
+ logits_BxCxV[:, :, audio_eos_value + 1 :],
481
+ fill_value=-torch.inf,
482
+ )
483
+ logits_BxCxV[:, 1:, audio_eos_value:] = torch.full_like(
484
+ logits_BxCxV[:, 1:, audio_eos_value:],
485
+ fill_value=-torch.inf,
486
+ )
487
+
488
+ flat_logits_BCxV = logits_BxCxV.view(
489
+ B * self.config.decoder_config.num_channels, -1
490
+ )
491
+
492
+ pred_BC = _sample_next_token(
493
+ flat_logits_BCxV.float(),
494
+ temperature=temperature,
495
+ top_p=top_p,
496
+ top_k=top_k,
497
+ audio_eos_value=audio_eos_value,
498
+ )
499
+
500
+ pred_BxC = pred_BC.view(B, self.config.decoder_config.num_channels)
501
+ return pred_BxC
502
+
503
+ def _generate_output(
504
+ self, generated_codes: torch.Tensor, lengths_Bx: torch.Tensor
505
+ ) -> list[np.ndarray]:
506
+ """Converts generated delayed codes into audio waveforms.
507
+
508
+ Reverts the delay pattern applied during generation, decodes the resulting
509
+ codebook using the DAC model (if loaded), and returns a list of audio
510
+ waveforms as NumPy arrays. If DAC is not loaded, returns the raw codebook indices.
511
+
512
+ Args:
513
+ generated_codes: The tensor of generated audio codes with delays,
514
+ shape [B, T_gen, C].
515
+ lengths_Bx: A tensor containing the valid length of generated codes
516
+ (excluding padding and BOS/EOS markers) for each item
517
+ in the batch, shape [B].
518
+
519
+ Returns:
520
+ A list of NumPy arrays, where each array represents the generated audio
521
+ waveform for one item in the batch. If DAC is not loaded, returns the
522
+ raw, reverted codebook indices as NumPy arrays.
523
+ """
524
+ num_channels = self.config.decoder_config.num_channels
525
+ batch_size = generated_codes.shape[0]
526
+ seq_length = generated_codes.shape[1]
527
+ delay_pattern = self.config.delay_pattern
528
+ audio_pad_value = self.config.pad_token_id
529
+ max_delay_pattern = max(delay_pattern)
530
+
531
+ revert_precomp = build_revert_indices(
532
+ B=batch_size,
533
+ T=seq_length,
534
+ C=num_channels,
535
+ delay_pattern=delay_pattern,
536
+ )
537
+
538
+ codebook = revert_audio_delay(
539
+ audio_BxTxC=generated_codes,
540
+ pad_value=audio_pad_value,
541
+ precomp=revert_precomp,
542
+ T=seq_length,
543
+ )[:, :-max_delay_pattern, :]
544
+
545
+ min_valid_index = 0
546
+ max_valid_index = 1023
547
+ invalid_mask = (codebook < min_valid_index) | (codebook > max_valid_index)
548
+ codebook[invalid_mask] = 0
549
+
550
+ audios = []
551
+
552
+ if self.load_dac:
553
+ for i in range(batch_size):
554
+ audio = self._decode(codebook[i, : lengths_Bx[i], :])
555
+ audio_np = audio.cpu().numpy()
556
+ audios.append(audio_np)
557
+ else:
558
+ for i in range(batch_size):
559
+ audios.append(codebook[i, : lengths_Bx[i], :].cpu().numpy())
560
+ return audios
561
+
562
+ @torch.no_grad()
563
+ @torch.inference_mode()
564
+ def _encode(self, audio: torch.Tensor) -> torch.Tensor:
565
+ """
566
+ Encodes the given audio waveform into a tensor of DAC codebook indices
567
+ """
568
+ audio = audio.unsqueeze(0)
569
+ audio_data = self.dac_model.preprocess(audio, DEFAULT_SAMPLE_RATE)
570
+ _, encoded_frame, _, _, _ = self.dac_model.encode(audio_data)
571
+ encoded_frame: torch.Tensor
572
+ return encoded_frame.squeeze(0).transpose(0, 1)
573
+
574
+ @torch.no_grad()
575
+ @torch.inference_mode()
576
+ def _decode(self, audio_codes: torch.Tensor) -> torch.Tensor:
577
+ """
578
+ Decodes the given frames into an output audio waveform
579
+ """
580
+ audio_codes = audio_codes.unsqueeze(0).transpose(1, 2)
581
+ audio_values, _, _ = self.dac_model.quantizer.from_codes(audio_codes)
582
+ audio_values = self.dac_model.decode(audio_values)
583
+ audio_values: torch.Tensor
584
+ return audio_values.squeeze()
585
+
586
+ def load_audio(self, audio_path: str) -> torch.Tensor:
587
+ """Loads and preprocesses an audio file for use as a prompt.
588
+
589
+ Loads the audio file, resamples it to the target sample rate if necessary,
590
+ preprocesses it using the DAC model's preprocessing, and encodes it into
591
+ DAC codebook indices.
592
+
593
+ Args:
594
+ audio_path: Path to the audio file.
595
+
596
+ Returns:
597
+ torch.Tensor: The encoded audio prompt as DAC codebook indices,
598
+ shape [T, C].
599
+
600
+ Raises:
601
+ RuntimeError: If the DAC model is not loaded (`load_dac=False` during init).
602
+ FileNotFoundError: If the audio file cannot be found.
603
+ Exception: If there's an error during loading or processing.
604
+ """
605
+ if self.dac_model is None:
606
+ raise RuntimeError(
607
+ "DAC model is required for loading audio prompts but was not loaded."
608
+ )
609
+ audio, sr = torchaudio.load(audio_path, channels_first=True) # C, T
610
+ if sr != DEFAULT_SAMPLE_RATE:
611
+ audio = torchaudio.functional.resample(audio, sr, DEFAULT_SAMPLE_RATE)
612
+ # Convert to mono if stereo
613
+ if audio.shape[0] > 1:
614
+ audio = torch.mean(
615
+ audio, dim=0, keepdim=True
616
+ ) # Average channels to get mono
617
+ return self._encode(audio.to(self.device))
618
+
619
+ def save_audio(self, path: str, audio: np.ndarray):
620
+ """Saves the generated audio waveform to a file.
621
+
622
+ Uses the soundfile library to write the NumPy audio array to the specified
623
+ path with the default sample rate.
624
+
625
+ Args:
626
+ path: The path where the audio file will be saved.
627
+ audio: The audio waveform as a NumPy array.
628
+ """
629
+ import soundfile as sf
630
+
631
+ sf.write(path, audio, DEFAULT_SAMPLE_RATE)
632
+
633
+ @torch.inference_mode()
634
+ def generate(
635
+ self,
636
+ text: str | list[str],
637
+ max_tokens: int = 3072,
638
+ cfg_scale: float = 3.0,
639
+ temperature: float = 1.2,
640
+ top_p: float = 0.95,
641
+ use_torch_compile: bool = False,
642
+ cfg_filter_top_k: int = 45,
643
+ audio_prompt: list[str | torch.Tensor | None]
644
+ | str
645
+ | torch.Tensor
646
+ | None = None,
647
+ audio_prompt_path: list[str | torch.Tensor | None]
648
+ | str
649
+ | torch.Tensor
650
+ | None = None,
651
+ use_cfg_filter: bool | None = None,
652
+ verbose: bool = False,
653
+ ) -> np.ndarray | list[np.ndarray]:
654
+ """Generates audio corresponding to the input text.
655
+
656
+ Args:
657
+ text: The input text prompt, or a list of text prompts for batch generation.
658
+ max_tokens: The maximum number of audio tokens to generate per prompt.
659
+ Defaults to the model's configured audio length if None.
660
+ cfg_scale: The scale factor for classifier-free guidance (CFG). Higher values
661
+ lead to stronger guidance towards the text prompt.
662
+ temperature: The temperature for sampling. Higher values increase randomness.
663
+ top_p: The cumulative probability threshold for nucleus (top-p) sampling.
664
+ use_torch_compile: Whether to compile the generation steps using torch.compile.
665
+ Can significantly speed up generation after the initial
666
+ compilation overhead. Defaults to False.
667
+ cfg_filter_top_k: The number of top logits to consider during CFG filtering.
668
+ (Note: This parameter name might be slightly misleading based
669
+ on the code; it's used in the `_sample_next_token` function.)
670
+ audio_prompt: An audio prompt or list of prompts to condition the generation.
671
+ Can be a file path (str), a pre-loaded tensor (DAC codes), or None.
672
+ If a list, its length must match the batch size of the text input.
673
+ audio_prompt_path: (Deprecated) Use `audio_prompt` instead.
674
+ use_cfg_filter: (Deprecated) This parameter is no longer used.
675
+ verbose: If True, prints progress information during generation, including
676
+ speed metrics.
677
+
678
+ Returns:
679
+ If a single text prompt was provided, returns a NumPy array containing the
680
+ generated audio waveform.
681
+ If a list of text prompts was provided, returns a list of NumPy arrays,
682
+ each corresponding to a prompt in the input list. Returns None for a
683
+ sequence if no audio was generated for it.
684
+ """
685
+ batch_size = len(text) if isinstance(text, list) else 1
686
+ audio_eos_value = self.config.eos_token_id
687
+ audio_pad_value = self.config.pad_token_id
688
+ delay_pattern = self.config.delay_pattern
689
+ max_delay_pattern = max(delay_pattern)
690
+ delay_pattern_Cx = torch.tensor(
691
+ delay_pattern, device=self.device, dtype=torch.long
692
+ )
693
+ self.model.eval()
694
+
695
+ if audio_prompt_path:
696
+ print("Warning: audio_prompt_path is deprecated. Use audio_prompt instead.")
697
+ audio_prompt = audio_prompt_path
698
+ if use_cfg_filter is not None:
699
+ print("Warning: use_cfg_filter is deprecated.")
700
+
701
+ if verbose:
702
+ total_start_time = time.time()
703
+
704
+ if use_torch_compile and not hasattr(self, "_compiled"):
705
+ # Compilation can take about a minute.
706
+ self._prepare_generation = torch.compile(
707
+ self._prepare_generation, dynamic=True, fullgraph=True
708
+ )
709
+ self._decoder_step = torch.compile(
710
+ self._decoder_step, fullgraph=True, mode="max-autotune"
711
+ )
712
+ self._compiled = True
713
+
714
+ if isinstance(audio_prompt, list):
715
+ audio_prompt = [
716
+ self.load_audio(p) if isinstance(p, str) else p for p in audio_prompt
717
+ ]
718
+ elif isinstance(audio_prompt, str):
719
+ audio_prompt = [self.load_audio(audio_prompt)]
720
+ elif isinstance(audio_prompt, torch.Tensor):
721
+ audio_prompt = [audio_prompt]
722
+ elif audio_prompt is None:
723
+ audio_prompt = [None] * batch_size
724
+
725
+ assert len(audio_prompt) == batch_size, (
726
+ "Number of audio prompts must match batch size"
727
+ )
728
+
729
+ if isinstance(text, list):
730
+ text = [self._encode_text(t) for t in text]
731
+ else:
732
+ text = [self._encode_text(text)]
733
+ text = self._pad_text_input(text)
734
+
735
+ dec_state, dec_output = self._prepare_generation(
736
+ text, audio_prompt, max_tokens=max_tokens
737
+ )
738
+ dec_step = min(dec_output.prefill_steps) - 1
739
+ current_idx = torch.tensor([dec_step], device=self.device)
740
+
741
+ eos_detected_Bx = torch.zeros(
742
+ (batch_size,), dtype=torch.bool, device=self.device
743
+ )
744
+ eos_countdown_Bx = torch.full(
745
+ (batch_size,), -1, dtype=torch.long, device=self.device
746
+ )
747
+ finished_step_Bx = torch.full(
748
+ (batch_size,), -1, dtype=torch.long, device=self.device
749
+ )
750
+
751
+ bos_over = False
752
+
753
+ if verbose:
754
+ print("generate: starting generation loop")
755
+ if use_torch_compile:
756
+ print(
757
+ "generate: using use_torch_compile=True, the first step may be slow"
758
+ )
759
+ start_time = time.time()
760
+
761
+ # --- Generation Loop ---
762
+ while dec_step < max_tokens:
763
+ if (eos_countdown_Bx == 0).all():
764
+ break
765
+
766
+ current_step_idx = dec_step + 1
767
+ torch.compiler.cudagraph_mark_step_begin()
768
+ dec_state.prepare_step(dec_step)
769
+ tokens_Bx1xC = dec_output.get_tokens_at(dec_step).repeat_interleave(
770
+ 2, dim=0
771
+ ) # Repeat for CFG
772
+
773
+ pred_BxC = self._decoder_step(
774
+ tokens_Bx1xC,
775
+ dec_state,
776
+ cfg_scale,
777
+ temperature,
778
+ top_p,
779
+ cfg_filter_top_k,
780
+ current_idx,
781
+ )
782
+
783
+ current_idx += 1
784
+
785
+ active_mask_Bx = eos_countdown_Bx != 0
786
+ eos_trigger_Bx = torch.zeros_like(active_mask_Bx)
787
+ if active_mask_Bx.any():
788
+ is_eos_token = (~eos_detected_Bx[active_mask_Bx]) & (
789
+ pred_BxC[active_mask_Bx, 0] == audio_eos_value
790
+ )
791
+ is_max_len = current_step_idx >= max_tokens - max_delay_pattern
792
+ eos_trigger_Bx[active_mask_Bx] = is_eos_token | is_max_len
793
+ eos_detected_Bx |= eos_trigger_Bx
794
+ start_countdown_mask_Bx = eos_trigger_Bx & (eos_countdown_Bx < 0)
795
+ if start_countdown_mask_Bx.any():
796
+ eos_countdown_Bx[start_countdown_mask_Bx] = max_delay_pattern
797
+ finished_step_Bx[start_countdown_mask_Bx] = current_step_idx
798
+
799
+ padding_mask_Bx = eos_countdown_Bx > 0
800
+ if padding_mask_Bx.any():
801
+ pred_active_BxC = pred_BxC[padding_mask_Bx].clone()
802
+ countdown_active_Bx = eos_countdown_Bx[padding_mask_Bx]
803
+ step_after_eos_Bx = max_delay_pattern - countdown_active_Bx
804
+ step_after_eos_Bx_ = step_after_eos_Bx.unsqueeze(1)
805
+ delay_pattern_Cx_ = delay_pattern_Cx.unsqueeze(0)
806
+ eos_mask_NxC = step_after_eos_Bx_ == delay_pattern_Cx_
807
+ pad_mask_NxC = step_after_eos_Bx_ > delay_pattern_Cx_
808
+ pred_active_BxC[eos_mask_NxC] = audio_eos_value
809
+ pred_active_BxC[pad_mask_NxC] = audio_pad_value
810
+ pred_BxC[padding_mask_Bx] = pred_active_BxC
811
+ eos_countdown_Bx[padding_mask_Bx] -= 1
812
+
813
+ # --- Update BOS flag (Original) ---
814
+ if not bos_over:
815
+ bos_over = all(
816
+ dec_step - prefill_step > max_delay_pattern
817
+ for prefill_step in dec_output.prefill_steps
818
+ )
819
+
820
+ dec_output.update_one(pred_BxC, current_step_idx, not bos_over)
821
+
822
+ dec_step += 1
823
+
824
+ if verbose and dec_step % 86 == 0:
825
+ duration = time.time() - start_time
826
+ if duration > 0:
827
+ print(
828
+ f"generate step {dec_step}: speed={86 * batch_size / duration:.3f} tokens/s, realtime factor={batch_size / duration:.3f}x"
829
+ )
830
+ start_time = time.time()
831
+
832
+ # --- Finalize and Extract Output ---
833
+ final_step = dec_step + 1
834
+
835
+ finished_step_Bx[finished_step_Bx == -1] = final_step - max_delay_pattern
836
+
837
+ prefill_steps_tensor = torch.tensor(
838
+ dec_output.prefill_steps, device=self.device
839
+ )
840
+ lengths_Bx = finished_step_Bx - prefill_steps_tensor
841
+ lengths_Bx = torch.clamp(lengths_Bx, min=0)
842
+
843
+ max_len = lengths_Bx.max().item() + max_delay_pattern
844
+ outputs = []
845
+
846
+ if max_len > 0:
847
+ num_channels = self.config.decoder_config.num_channels
848
+ audio_pad_value = self.config.pad_token_id
849
+ generated_codes = torch.full(
850
+ (batch_size, max_len, num_channels),
851
+ fill_value=audio_pad_value,
852
+ dtype=torch.long,
853
+ device=self.device,
854
+ )
855
+
856
+ for i in range(batch_size):
857
+ start_step = dec_output.prefill_steps[i]
858
+ actual_len = lengths_Bx[i].item() + max_delay_pattern
859
+ if actual_len > 0:
860
+ tokens_to_copy = dec_output.generated_tokens[
861
+ i, start_step : start_step + actual_len, :
862
+ ]
863
+ generated_codes[i, :actual_len, :] = tokens_to_copy
864
+
865
+ if verbose:
866
+ avg_steps = lengths_Bx.float().mean().item()
867
+ total_duration = time.time() - total_start_time
868
+ print(
869
+ f"generate: avg steps={avg_steps:.1f}, total duration={total_duration:.3f}s"
870
+ )
871
+
872
+ del dec_state
873
+
874
+ outputs = self._generate_output(generated_codes, lengths_Bx)
875
+ else:
876
+ print("Warning: Nothing generated for any sequence in the batch.")
877
+ outputs = [None] * batch_size
878
+
879
+ return outputs if batch_size > 1 else outputs[0]
dia/state.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+ from .config import DiaConfig
7
+
8
+
9
+ def create_attn_mask(
10
+ q_padding_mask_1d: torch.Tensor,
11
+ k_padding_mask_1d: torch.Tensor,
12
+ device: torch.device,
13
+ is_causal: bool = False,
14
+ ) -> torch.Tensor:
15
+ """
16
+ Creates the attention mask (self or cross) mimicking JAX segment ID logic.
17
+ """
18
+ # B1, Tq = q_padding_mask_1d.shape
19
+ # B2, Tk = k_padding_mask_1d.shape
20
+
21
+ p_mask_q = q_padding_mask_1d.unsqueeze(2) # Shape [B, Tq, 1]
22
+ p_mask_k = k_padding_mask_1d.unsqueeze(1) # Shape [B, 1, Tk]
23
+
24
+ mask = p_mask_q & p_mask_k
25
+ if is_causal:
26
+ # assert Tq == Tk, "Causal mask requires query and key sequence lengths to be equal"
27
+ causal_mask_2d = torch.tril(
28
+ torch.ones_like(mask[0], dtype=torch.bool, device=device)
29
+ ) # Shape [B, Tq, Tk]
30
+ causal_mask = mask & causal_mask_2d # Shape [B, Tq, Tk]
31
+ return causal_mask.unsqueeze(1) # Shape [B, 1, Tq, Tk]
32
+ else:
33
+ return mask.unsqueeze(1) # Shape [B, 1, Tq, Tk]
34
+
35
+
36
+ @dataclass
37
+ class EncoderInferenceState:
38
+ """Parameters specifically for encoder inference."""
39
+
40
+ max_seq_len: int
41
+ device: torch.device
42
+ positions: torch.Tensor
43
+ padding_mask: torch.Tensor
44
+ attn_mask: torch.Tensor
45
+
46
+ @classmethod
47
+ def new(cls, config: DiaConfig, cond_src: torch.Tensor) -> "EncoderInferenceState":
48
+ """Creates EtorchrInferenceParams from DiaConfig and a device."""
49
+ device = cond_src.device
50
+
51
+ positions = torch.arange(
52
+ config.encoder_config.max_position_embeddings,
53
+ dtype=torch.float32,
54
+ device=device,
55
+ ).unsqueeze(0)
56
+ padding_mask = (cond_src.squeeze(1) != 0).to(device).repeat_interleave(2, dim=0)
57
+ attn_mask = create_attn_mask(
58
+ padding_mask, padding_mask, device, is_causal=False
59
+ )
60
+
61
+ return cls(
62
+ max_seq_len=config.encoder_config.max_position_embeddings,
63
+ device=device,
64
+ positions=positions,
65
+ padding_mask=padding_mask,
66
+ attn_mask=attn_mask,
67
+ )
68
+
69
+
70
+ class KVCache(torch.nn.Module):
71
+ k: torch.Tensor
72
+ v: torch.Tensor
73
+
74
+ def __init__(
75
+ self,
76
+ batch_size: int,
77
+ num_heads: int,
78
+ max_len: int,
79
+ head_dim: int,
80
+ dtype: torch.dtype,
81
+ device: torch.device,
82
+ k: torch.Tensor | None = None,
83
+ v: torch.Tensor | None = None,
84
+ ):
85
+ k = (
86
+ torch.zeros(
87
+ (2 * batch_size, num_heads, max_len, head_dim),
88
+ dtype=dtype,
89
+ device=device,
90
+ )
91
+ if k is None
92
+ else k
93
+ )
94
+ v = (
95
+ torch.zeros(
96
+ (2 * batch_size, num_heads, max_len, head_dim),
97
+ dtype=dtype,
98
+ device=device,
99
+ )
100
+ if v is None
101
+ else v
102
+ )
103
+ super().__init__()
104
+
105
+ self.register_buffer("k", k)
106
+ self.register_buffer("v", v)
107
+
108
+ @classmethod
109
+ def from_kv(cls, k: torch.Tensor, v: torch.Tensor) -> "KVCache":
110
+ return cls(
111
+ batch_size=k.shape[0] // 2,
112
+ num_heads=k.shape[1],
113
+ max_len=k.shape[2],
114
+ head_dim=k.shape[3],
115
+ dtype=k.dtype,
116
+ device=k.device,
117
+ k=k,
118
+ v=v,
119
+ )
120
+
121
+ def update(
122
+ self, k: torch.Tensor, v: torch.Tensor, current_idx: torch.Tensor
123
+ ) -> tuple[torch.Tensor, torch.Tensor]:
124
+ k_out, v_out = self.k, self.v
125
+ k_out[:, :, current_idx, :] = k
126
+ v_out[:, :, current_idx, :] = v
127
+ return self.k, self.v
128
+
129
+ def prefill(self, k: torch.Tensor, v: torch.Tensor):
130
+ prefill_len = k.shape[2]
131
+ self.k[:, :, :prefill_len, :] = k
132
+ self.v[:, :, :prefill_len, :] = v
133
+
134
+
135
+ @dataclass
136
+ class DecoderInferenceState:
137
+ """Parameters specifically for decoder inference."""
138
+
139
+ device: torch.device
140
+ dtype: torch.dtype
141
+ enc_out: torch.Tensor
142
+ enc_positions: torch.Tensor
143
+ dec_positions: torch.Tensor
144
+ self_attn_cache: list[KVCache]
145
+ cross_attn_cache: list[KVCache]
146
+ casual_attn_mask: torch.Tensor
147
+ cross_attn_mask: torch.Tensor
148
+
149
+ @classmethod
150
+ def new(
151
+ cls,
152
+ config: DiaConfig,
153
+ enc_state: EncoderInferenceState,
154
+ enc_out: torch.Tensor,
155
+ dec_cross_attn_cache: list[KVCache],
156
+ compute_dtype: torch.dtype,
157
+ max_generation_length: Optional[int] = None,
158
+ ) -> "DecoderInferenceState":
159
+ """Creates DecoderInferenceParams from DiaConfig and a device."""
160
+ device = enc_out.device
161
+ max_audio_len = (
162
+ max_generation_length or config.decoder_config.max_position_embeddings
163
+ )
164
+ batch_size = enc_out.shape[0] // 2
165
+
166
+ dec_positions = torch.full(
167
+ (2 * batch_size, 1), fill_value=0, dtype=torch.int32, device=device
168
+ )
169
+ causal_mask = torch.tril(
170
+ torch.ones(max_audio_len, max_audio_len, dtype=torch.bool, device=device)
171
+ )
172
+ dec_mask = torch.ones((2 * batch_size, 1), dtype=torch.bool, device=device)
173
+ cross_attn_mask = create_attn_mask(
174
+ dec_mask, enc_state.padding_mask, device, is_causal=False
175
+ )
176
+
177
+ self_attn_cache = [
178
+ KVCache(
179
+ batch_size,
180
+ config.decoder_config.num_key_value_heads,
181
+ max_audio_len,
182
+ config.decoder_config.head_dim,
183
+ compute_dtype,
184
+ device,
185
+ )
186
+ for _ in range(config.decoder_config.num_hidden_layers)
187
+ ]
188
+
189
+ return cls(
190
+ device=device,
191
+ dtype=compute_dtype,
192
+ enc_out=enc_out,
193
+ enc_positions=enc_state.positions,
194
+ dec_positions=dec_positions,
195
+ self_attn_cache=self_attn_cache,
196
+ cross_attn_cache=dec_cross_attn_cache,
197
+ casual_attn_mask=causal_mask,
198
+ cross_attn_mask=cross_attn_mask,
199
+ )
200
+
201
+ def prepare_step(self, step_from: int, step_to: int | None = None) -> None:
202
+ if step_to is None:
203
+ step_to = step_from + 1
204
+ self.dec_positions = torch.arange(
205
+ step_from, step_to, dtype=torch.int32, device=self.device
206
+ ).unsqueeze(0)
207
+
208
+
209
+ @dataclass
210
+ class DecoderOutput:
211
+ generated_tokens: torch.Tensor
212
+ prefill_steps: list[int]
213
+
214
+ @classmethod
215
+ def new(
216
+ cls, batch_size: int, config: DiaConfig, device: torch.device
217
+ ) -> "DecoderOutput":
218
+ max_audio_len = config.decoder_config.max_position_embeddings
219
+ return cls(
220
+ generated_tokens=torch.full(
221
+ (batch_size, max_audio_len, config.decoder_config.num_channels),
222
+ fill_value=-1,
223
+ dtype=torch.int,
224
+ device=device,
225
+ ),
226
+ prefill_steps=[],
227
+ )
228
+
229
+ def get_tokens_at(self, step_from: int, step_to: int | None = None) -> torch.Tensor:
230
+ if step_to is None:
231
+ step_to = step_from + 1
232
+ return self.generated_tokens[:, step_from:step_to, :]
233
+
234
+ def update_one(self, dec_out: torch.Tensor, step: int, apply_mask: bool = False):
235
+ dec_out = dec_out.to(self.generated_tokens.dtype)
236
+ if apply_mask:
237
+ mask = self.generated_tokens[:, step, :] == -1
238
+ self.generated_tokens[:, step, :] = torch.where(
239
+ mask, dec_out, self.generated_tokens[:, step, :]
240
+ )
241
+ else:
242
+ self.generated_tokens[:, step, :] = dec_out
243
+
244
+ def prefill(self, dec_out: torch.Tensor, prefill_steps: list[int]):
245
+ length = dec_out.shape[1]
246
+ self.generated_tokens[:, :length, :] = dec_out
247
+ self.prefill_steps = prefill_steps