pmetal-vocoder 0.4.0

Neural vocoder (BigVGAN) for text-to-speech synthesis
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Weight-normalized convolution layers for BigVGAN.
//!
//! BigVGAN uses weight normalization instead of batch/layer normalization
//! for all convolution layers. This provides stable training without
//! normalization-induced artifacts in audio generation.

use crate::error::Result;
use mlx_rs::Array;
use mlx_rs::module::Param;

/// Weight-normalized 1D convolution.
///
/// Applies weight normalization: W = g * (v / ||v||)
/// where g is the magnitude and v is the direction.
#[derive(Debug)]
pub struct WeightNormConv1d {
    /// Direction parameter (unnormalized weights).
    pub weight_v: Param<Array>,
    /// Magnitude parameter (scalar per output channel).
    pub weight_g: Param<Array>,
    /// Optional bias.
    pub bias: Option<Param<Array>>,
    /// Input channels.
    pub in_channels: i32,
    /// Output channels.
    pub out_channels: i32,
    /// Kernel size.
    pub kernel_size: i32,
    /// Stride.
    pub stride: i32,
    /// Padding.
    pub padding: i32,
    /// Dilation.
    pub dilation: i32,
    /// Groups for grouped convolution.
    pub groups: i32,
}

impl WeightNormConv1d {
    /// Create a new weight-normalized Conv1d.
    ///
    /// # Arguments
    /// * `in_channels` - Number of input channels
    /// * `out_channels` - Number of output channels
    /// * `kernel_size` - Kernel size
    /// * `stride` - Stride (default 1)
    /// * `padding` - Padding (default 0)
    /// * `dilation` - Dilation (default 1)
    /// * `groups` - Groups (default 1)
    /// * `bias` - Whether to use bias (default true)
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        in_channels: i32,
        out_channels: i32,
        kernel_size: i32,
        stride: Option<i32>,
        padding: Option<i32>,
        dilation: Option<i32>,
        groups: Option<i32>,
        bias: Option<bool>,
    ) -> Result<Self> {
        let stride = stride.unwrap_or(1);
        let padding = padding.unwrap_or(0);
        let dilation = dilation.unwrap_or(1);
        let groups = groups.unwrap_or(1);
        let use_bias = bias.unwrap_or(true);

        // Initialize weights using Kaiming uniform
        let fan_in = (in_channels / groups) * kernel_size;
        let bound = (1.0 / fan_in as f32).sqrt();

        // Weight shape for Conv1d: [out_channels, in_channels/groups, kernel_size]
        let weight_v = mlx_rs::random::uniform::<_, f32>(
            -bound,
            bound,
            &[out_channels, in_channels / groups, kernel_size],
            None,
        )?;

        // Compute initial magnitude ||v||
        let norm = weight_norm(&weight_v)?;
        let weight_g = norm;

        let bias = if use_bias {
            Some(Param::new(mlx_rs::ops::zeros::<f32>(&[out_channels])?))
        } else {
            None
        };

        Ok(Self {
            weight_v: Param::new(weight_v),
            weight_g: Param::new(weight_g),
            bias,
            in_channels,
            out_channels,
            kernel_size,
            stride,
            padding,
            dilation,
            groups,
        })
    }

    /// Compute normalized weight: W = g * (v / ||v||)
    fn compute_weight(&self) -> Result<Array> {
        let v = self.weight_v.as_ref();
        let g = self.weight_g.as_ref();

        // Normalize v along all dims except output channel
        let norm = weight_norm(v)?;
        let v_normalized = v.divide(&norm)?;

        // Scale by magnitude
        Ok(v_normalized.multiply(g)?)
    }

    /// Forward pass.
    ///
    /// # Arguments
    /// * `x` - Input tensor [batch, in_channels, length] (NCL format)
    ///
    /// # Returns
    /// Output tensor [batch, out_channels, new_length] (NCL format)
    pub fn forward(&self, x: &Array) -> Result<Array> {
        let weight = self.compute_weight()?;

        // MLX conv1d expects:
        // - input: [N, H, C_in] (NLC format)
        // - weight: [C_out, K, C_in] (OKI format)
        // Our tensors are in:
        // - input: [N, C_in, H] (NCL format)
        // - weight: [C_out, C_in/groups, K] (OIK format)

        // Transpose input from NCL to NLC: [batch, channels, length] -> [batch, length, channels]
        let x_nlc = x.transpose_axes(&[0, 2, 1])?;

        // Transpose weight from OIK to OKI: [out, in, kernel] -> [out, kernel, in]
        let weight_oki = weight.transpose_axes(&[0, 2, 1])?;

        // Apply 1D convolution
        let output = mlx_rs::ops::conv1d(
            &x_nlc,
            &weight_oki,
            self.stride,
            self.padding,
            self.dilation,
            self.groups,
        )?;

        // Transpose output from NLC back to NCL: [batch, length, channels] -> [batch, channels, length]
        let output = output.transpose_axes(&[0, 2, 1])?;

        // Add bias if present
        if let Some(bias) = &self.bias {
            // Reshape bias for broadcasting: [out_channels] -> [1, out_channels, 1]
            let bias_reshaped = bias.as_ref().reshape(&[1, self.out_channels, 1])?;
            Ok(output.add(&bias_reshaped)?)
        } else {
            Ok(output)
        }
    }
}

/// Weight-normalized transposed 1D convolution.
///
/// Used for upsampling in the generator.
#[derive(Debug)]
pub struct WeightNormConvTranspose1d {
    /// Direction parameter (unnormalized weights).
    pub weight_v: Param<Array>,
    /// Magnitude parameter.
    pub weight_g: Param<Array>,
    /// Optional bias.
    pub bias: Option<Param<Array>>,
    /// Input channels.
    pub in_channels: i32,
    /// Output channels.
    pub out_channels: i32,
    /// Kernel size.
    pub kernel_size: i32,
    /// Stride.
    pub stride: i32,
    /// Padding.
    pub padding: i32,
    /// Output padding for ambiguous output size.
    pub output_padding: i32,
    /// Dilation.
    pub dilation: i32,
    /// Groups.
    pub groups: i32,
}

impl WeightNormConvTranspose1d {
    /// Create a new weight-normalized ConvTranspose1d.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        in_channels: i32,
        out_channels: i32,
        kernel_size: i32,
        stride: Option<i32>,
        padding: Option<i32>,
        output_padding: Option<i32>,
        dilation: Option<i32>,
        groups: Option<i32>,
        bias: Option<bool>,
    ) -> Result<Self> {
        let stride = stride.unwrap_or(1);
        let padding = padding.unwrap_or(0);
        let output_padding = output_padding.unwrap_or(0);
        let dilation = dilation.unwrap_or(1);
        let groups = groups.unwrap_or(1);
        let use_bias = bias.unwrap_or(true);

        // Initialize weights
        let fan_in = in_channels * kernel_size;
        let bound = (1.0 / fan_in as f32).sqrt();

        // Weight shape for ConvTranspose1d: [in_channels, out_channels/groups, kernel_size]
        let weight_v = mlx_rs::random::uniform::<_, f32>(
            -bound,
            bound,
            &[in_channels, out_channels / groups, kernel_size],
            None,
        )?;

        let norm = weight_norm(&weight_v)?;
        let weight_g = norm;

        let bias = if use_bias {
            Some(Param::new(mlx_rs::ops::zeros::<f32>(&[out_channels])?))
        } else {
            None
        };

        Ok(Self {
            weight_v: Param::new(weight_v),
            weight_g: Param::new(weight_g),
            bias,
            in_channels,
            out_channels,
            kernel_size,
            stride,
            padding,
            output_padding,
            dilation,
            groups,
        })
    }

    /// Compute normalized weight.
    fn compute_weight(&self) -> Result<Array> {
        let v = self.weight_v.as_ref();
        let g = self.weight_g.as_ref();

        let norm = weight_norm(v)?;
        let v_normalized = v.divide(&norm)?;

        Ok(v_normalized.multiply(g)?)
    }

    /// Forward pass.
    ///
    /// # Arguments
    /// * `x` - Input tensor [batch, in_channels, length]
    ///
    /// # Returns
    /// Upsampled tensor [batch, out_channels, length * stride]
    pub fn forward(&self, x: &Array) -> Result<Array> {
        let weight = self.compute_weight()?;

        // Compute output length (for reference)
        let input_length = x.dim(2);
        let _output_length = (input_length - 1) * self.stride - 2 * self.padding
            + self.dilation * (self.kernel_size - 1)
            + self.output_padding
            + 1;

        // Apply transposed convolution
        // MLX conv_transpose expects weight shape [out_channels, in_channels/groups, kernel_size]
        // but our weight is [in_channels, out_channels/groups, kernel_size]
        // Need to transpose axes 0 and 1
        let weight_transposed = weight.transpose_axes(&[1, 0, 2])?;

        // Use conv_general for transposed convolution
        // For now, implement using manual upsampling + conv
        let output = conv_transpose_1d_manual(
            x,
            &weight_transposed,
            self.stride,
            self.padding,
            self.output_padding,
            self.dilation,
            self.groups,
        )?;

        // Add bias if present
        if let Some(bias) = &self.bias {
            let bias_reshaped = bias.as_ref().reshape(&[1, self.out_channels, 1])?;
            Ok(output.add(&bias_reshaped)?)
        } else {
            Ok(output)
        }
    }
}

/// Compute weight norm along all dims except first (output channels).
/// Returns shape [out_channels, 1, 1] for broadcasting.
fn weight_norm(weight: &Array) -> Result<Array> {
    // Sum of squares along dims 1 and 2
    let sq = weight.multiply(weight)?;
    let sum_sq = sq.sum_axes(&[1, 2], Some(true))?;
    let norm = sum_sq.sqrt()?;

    // Add small epsilon for numerical stability
    let eps = Array::from_f32(1e-12);
    Ok(norm.add(&eps)?)
}

/// Flip array along an axis by reversing the indices.
fn flip_axis(arr: &Array, axis: i32) -> Result<Array> {
    let axis_len = arr.dim(axis);
    // Create reversed indices
    let indices: Vec<i32> = (0..axis_len).rev().collect();
    let indices_arr = Array::from_slice(&indices, &[axis_len]);
    arr.take_axis(&indices_arr, axis).map_err(Into::into)
}

/// Manual implementation of transposed 1D convolution.
///
/// ConvTranspose1d(x) is equivalent to inserting (stride-1) zeros between samples,
/// then applying convolution with the transposed kernel.
///
/// Input is in NCL format: [batch, in_channels, length]
/// Weight is in OIK format: [out_channels, in_channels/groups, kernel_size]
fn conv_transpose_1d_manual(
    x: &Array,
    weight: &Array, // [out_channels, in_channels/groups, kernel_size]
    stride: i32,
    padding: i32,
    output_padding: i32,
    dilation: i32,
    groups: i32,
) -> Result<Array> {
    let batch = x.dim(0);
    let in_channels = x.dim(1);
    let in_length = x.dim(2);
    let out_channels = weight.dim(0);
    let kernel_size = weight.dim(2);

    // Helper to run conv1d with format conversion (NCL -> NLC -> NCL)
    let run_conv1d = |input: &Array, w: &Array, s: i32, p: i32, d: i32, g: i32| -> Result<Array> {
        // Input is NCL, convert to NLC
        let input_nlc = input.transpose_axes(&[0, 2, 1])?;
        // Weight is OIK, convert to OKI
        let weight_oki = w.transpose_axes(&[0, 2, 1])?;
        // Run conv1d
        let output_nlc = mlx_rs::ops::conv1d(&input_nlc, &weight_oki, s, p, d, g)?;
        // Convert output back to NCL
        output_nlc.transpose_axes(&[0, 2, 1]).map_err(Into::into)
    };

    if stride == 1 && padding == 0 && output_padding == 0 && dilation == 1 {
        // Simple case: just apply conv with flipped kernel
        let weight_flipped = flip_axis(weight, 2)?; // Flip along kernel axis (axis 2 in OIK)
        return run_conv1d(x, &weight_flipped, 1, kernel_size - 1, 1, groups);
    }

    // General case: insert zeros then convolve
    // Step 1: Insert (stride-1) zeros between samples
    let upsampled_length = (in_length - 1) * stride + 1;

    // Alternative: Use unfold-like operation
    // For now, use a simpler but less efficient approach with concatenation
    if stride > 1 {
        use mlx_rs::ops::indexing::IndexOp;
        // Create interleaved tensor
        let zeros_between =
            mlx_rs::ops::zeros::<f32>(&[batch, in_channels, in_length, stride - 1])?;
        let x_expanded = x.reshape(&[batch, in_channels, in_length, 1])?;
        let interleaved = mlx_rs::ops::concatenate_axis(&[&x_expanded, &zeros_between], -1)?;
        let interleaved = interleaved.reshape(&[batch, in_channels, in_length * stride])?;
        // Trim last (stride-1) zeros
        let upsampled = interleaved.index((.., .., ..upsampled_length));

        // Step 2: Flip kernel and apply convolution
        let weight_flipped = flip_axis(weight, 2)?;

        // Compute required padding for output size
        let conv_padding = dilation * (kernel_size - 1) - padding;
        let conv_padding = conv_padding.max(0);

        let output = run_conv1d(
            &upsampled,
            &weight_flipped,
            1,
            conv_padding,
            dilation,
            groups,
        )?;

        // Handle output_padding by adding zeros at the end
        if output_padding > 0 {
            let pad = mlx_rs::ops::zeros::<f32>(&[batch, out_channels, output_padding])?;
            return mlx_rs::ops::concatenate_axis(&[&output, &pad], -1).map_err(Into::into);
        }

        Ok(output)
    } else {
        // stride == 1, just apply transposed conv logic
        let weight_flipped = flip_axis(weight, 2)?;
        let conv_padding = dilation * (kernel_size - 1) - padding;
        let conv_padding = conv_padding.max(0);

        run_conv1d(x, &weight_flipped, 1, conv_padding, dilation, groups)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_weight_norm_conv1d_shape() {
        let conv =
            WeightNormConv1d::new(4, 8, 3, Some(1), Some(1), None, None, Some(true)).unwrap();

        let x = mlx_rs::random::normal::<f32>(&[2, 4, 16], None, None, None).unwrap();
        let y = conv.forward(&x).unwrap();
        y.eval().unwrap();

        // With padding=1, kernel=3, stride=1: output_len = input_len
        assert_eq!(y.shape(), &[2, 8, 16]);
    }

    #[test]
    fn test_weight_norm_conv1d_no_bias() {
        let conv =
            WeightNormConv1d::new(4, 8, 3, Some(1), Some(1), None, None, Some(false)).unwrap();

        let x = mlx_rs::random::normal::<f32>(&[2, 4, 16], None, None, None).unwrap();
        let y = conv.forward(&x).unwrap();
        y.eval().unwrap();

        assert_eq!(y.shape(), &[2, 8, 16]);
        assert!(conv.bias.is_none());
    }

    #[test]
    fn test_weight_norm_values() {
        // Weight normalization should make ||W|| = ||g||
        let conv = WeightNormConv1d::new(2, 4, 3, None, None, None, None, None).unwrap();

        let weight = conv.compute_weight().unwrap();
        weight.eval().unwrap();

        // The weight should be properly normalized
        assert_eq!(weight.shape(), &[4, 2, 3]);
    }

    #[test]
    fn test_conv_transpose1d_shape() {
        // stride=2 should double the length (approximately)
        let conv =
            WeightNormConvTranspose1d::new(8, 4, 4, Some(2), Some(1), None, None, None, Some(true))
                .unwrap();

        let x = mlx_rs::random::normal::<f32>(&[1, 8, 16], None, None, None).unwrap();
        let y = conv.forward(&x).unwrap();
        y.eval().unwrap();

        // ConvTranspose1d output: (L-1)*S - 2*P + D*(K-1) + OP + 1
        // = (16-1)*2 - 2*1 + 1*(4-1) + 0 + 1 = 30 - 2 + 3 + 1 = 32
        assert_eq!(y.shape(), &[1, 4, 32]);
    }

    #[test]
    fn test_conv_transpose1d_upsample_4x() {
        // Test 4x upsampling like BigVGAN
        let conv = WeightNormConvTranspose1d::new(
            512,
            256,
            16,
            Some(4),
            Some(6),
            None,
            None,
            None,
            Some(true),
        )
        .unwrap();

        let x = mlx_rs::random::normal::<f32>(&[1, 512, 8], None, None, None).unwrap();
        let y = conv.forward(&x).unwrap();
        y.eval().unwrap();

        // Output length should be approximately 4x input
        // (8-1)*4 - 2*6 + 1*(16-1) + 0 + 1 = 28 - 12 + 15 + 1 = 32
        assert_eq!(y.shape(), &[1, 256, 32]);
    }
}