-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03_ddsp_audio_synthesis_guide.py
More file actions
2000 lines (1619 loc) · 71.4 KB
/
Copy path03_ddsp_audio_synthesis_guide.py
File metadata and controls
2000 lines (1619 loc) · 71.4 KB
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ---
# jupyter:
# jupytext:
# formats: py:percent,ipynb
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# ---
# %% [markdown]
"""
# DDSP: Differentiable Digital Signal Processing
| Metadata | Value |
|----------|-------|
| **Level** | Advanced |
| **Runtime** | ~3 hrs (GPU, full NSynth) / ~2 min (quick smoke) |
| **Prerequisites** | JAX, Flax NNX, audio/DSP basics, custom operator patterns |
| **Memory** | ~6 GB VRAM (GPU, full) / ~4 GB VRAM (GPU, quick) |
| **Devices** | GPU recommended, CPU supported |
| **Dataset** | Procedural audio in quick mode; NSynth gansynth_subset in full mode |
| **Format** | Python + Jupyter |
## Overview
This example re-implements the core architecture from **DDSP: Differentiable
Digital Signal Processing** (Engel et al., ICLR 2020) using datarax's
extensibility features. We create **3 custom operators** for audio synthesis
that extend `OperatorModule` directly — proving that datarax's operator
system works for any domain, not just images.
**Key insight**: DDSP shows that classical DSP operations (oscillators,
filters, reverb) can be made differentiable and trained end-to-end, requiring
100x less training data than neural audio models. Datarax's operator system
makes this natural — just subclass `OperatorModule`, add `nnx.Param`, and
the DAG executor handles the rest.
## Learning Goals
By the end of this example, you will be able to:
1. **Create** custom `OperatorModule` subclasses for non-image domains (audio)
2. **Implement** differentiable DSP primitives (harmonic synth, noise filter, reverb)
3. **Compose** parallel + sequential pipelines using `CompositeOperatorModule`
4. **Train** an audio synthesis model using multi-scale spectral loss on audio data
5. **Understand** how datarax's extensibility enables any-domain differentiable pipelines
## Reference
- Paper: Engel et al., "DDSP: Differentiable Digital Signal Processing" (ICLR 2020)
— [arXiv:2001.04643](https://arxiv.org/abs/2001.04643)
- Code: [github.com/magenta/ddsp](https://github.com/magenta/ddsp) (TensorFlow)
- JAX ref: [github.com/PapayaResearch/synthax](https://github.com/PapayaResearch/synthax)
"""
# %% [markdown]
"""
## Setup & Prerequisites
### Required Knowledge
- [Custom Operators](../../core/02_operators_tutorial.py) — OperatorModule pattern
- [DAG Pipelines](../dag/01_dag_fundamentals_guide.py) — Parallel, Merge nodes
- Basic audio/DSP concepts (sample rate, FFT, harmonics)
### Installation
```bash
# Install datarax with data dependencies (includes tensorflow-datasets)
uv pip install "datarax[data]"
# No additional audio libraries needed — all DSP is in pure JAX
```
**Estimated Time:** ~3 hrs on GPU (full, 10K NSynth samples) / ~2 min (quick smoke)
"""
# %%
# === Imports ===
from dataclasses import dataclass, field
from typing import Any
import jax
import jax.numpy as jnp
import numpy as np
import optax
from flax import nnx
from substrax.artifacts import resolve_output_dir
from datarax.core.config import OperatorConfig
from datarax.core.element_batch import Batch
from datarax.core.operator import OperatorModule
from datarax.operators import (
CompositeOperatorConfig,
CompositeOperatorModule,
CompositionStrategy,
)
from datarax.operators.modality.audio import LoudnessConfig, LoudnessOperator
from datarax.pipeline import Pipeline
from datarax.sources import MemorySource, MemorySourceConfig
def exp_sigmoid(x, exponent=10.0, max_value=2.0, threshold=1e-7):
"""Exponentiated Sigmoid pointwise nonlinearity (DDSP paper, Engel et al. 2020).
Attempt at bounds: [threshold, max_value] with logarithmic response.
Used for amplitude activations in both harmonic and noise synthesis.
Reference: ddsp/core.py — ``exp_sigmoid``
"""
return max_value * jax.nn.sigmoid(x) ** jnp.log(exponent) + threshold
import warnings
import matplotlib
from datarax.operators.modality.audio.crepe_model import load_crepe_weights_from_path
from datarax.operators.modality.audio.f0_operator import CrepeF0Config, CrepeF0Operator
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# Output directory for saved figures
OUTPUT_DIR = resolve_output_dir("examples").path
def plot_specgram(ax, audio, sample_rate=16000):
"""Plot spectrogram on axes with standard DDSP visualization settings."""
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
ax.specgram(
audio,
Fs=sample_rate,
NFFT=1024,
noverlap=768,
cmap="magma",
vmin=-80,
vmax=0,
)
# %% [markdown]
r"""
## Core Concepts
### DDSP Architecture
DDSP's key innovation: replace opaque neural audio generation with
**differentiable classical DSP**. The architecture:
1. **Decoder**: Maps audio features (f0, loudness) → synthesis parameters
2. **Harmonic Synth**: Additive synthesis with phase accumulation
3. **Noise Synth**: Filtered white noise with learned frequency response
4. **Reverb**: Trainable FIR impulse response for room acoustics
5. **Loss**: Multi-scale spectral comparison with ground truth
```
DDSP Autoencoder
┌─────────────────────────────────────────────────────────────┐
│ │
│ Audio Features (f0, loudness) → [Decoder] │
│ (GRU + MLP) │
│ │ │
│ ┌────┴────┐ │
│ ▼ ▼ │
│ [Harmonic [Filtered │
│ Synth] Noise] ← Parallel │
│ │ │ │
│ └─────┬──────┘ │
│ ▼ │
│ WEIGHTED_PARALLEL (sum) │
│ │ │
│ ▼ │
│ [Reverb] ← Trainable IR │
│ │ │
│ ▼ │
│ Resynthesized Audio │
│ │ │
│ ▼ │
│ Multi-Scale Spectral Loss │
│ │ │
│ jax.grad → update decoder + operators │
└─────────────────────────────────────────────────────────────┘
```
### Why Custom Operators?
Datarax's image operators (`BrightnessOperator`, etc.) extend `ModalityOperator`
which provides image-specific helpers (`_extract_field`, `_apply_clip_range`).
For audio, we extend `OperatorModule` directly — there's no audio base class
(yet), which is exactly the point: **datarax is extensible to any domain**.
Each custom operator follows the same pattern:
1. Create a companion `Config` dataclass extending `OperatorConfig`
2. Add `nnx.Param` for learnable parameters in `__init__`
3. Implement `apply()` with the standard signature
### Amplitude Activation: ``exp_sigmoid``
The reference DDSP uses an exponentiated sigmoid nonlinearity for amplitude
outputs (both harmonic and noise). This bounds values to ``[1e-7, 2.0]`` with
a logarithmic response, giving stable gradients across the dynamic range:
$$
\\text{exp\_sigmoid}(x) = 2.0 \\cdot \\sigma(x)^{\\ln 10} + 10^{-7}
$$
Unlike ``softplus`` (unbounded) or ``softmax`` (zero-sum competition between
harmonics), it keeps every amplitude bounded and independent of the others.
### Multi-Scale Spectral Loss
DDSP uses spectral loss instead of waveform MSE because:
- Waveform MSE penalizes phase differences (which humans can't hear)
- Spectral loss compares frequency content across multiple time scales
- FFT sizes [64, 128, 256, 512, 1024, 2048] capture both fine detail and global structure
$$
\\mathcal{L} = \\sum_{s \\in \\text{scales}} \\left(
\\|\\hat{S}_s - S_s\\|_1 + \\alpha \\|\\log \\hat{S}_s - \\log S_s\\|_1
\\right)
$$
"""
# %% [markdown]
"""
## Implementation
### Step 1: Load Audio Data + Extract Features via Datarax Operators
Quick mode generates a tiny deterministic NSynth-like smoke dataset so this
guide runs in CI without downloading external archives. Full mode loads raw
instrument recordings from NSynth and extracts audio features **using datarax's
own audio operators** — the same `OperatorModule` pattern used for synthesis
later in this guide:
1. **`LoudnessOperator`** (pure JAX, learnable weights):
STFT → power spectrum → A-weighted loudness in dB.
Frequency weights are `nnx.Param`, initialized from IEC 61672.
2. **`CrepeF0Operator`** (Flax NNX CREPE port):
Frames audio → normalizes → runs CREPE CNN → decodes pitch.
All weights are `nnx.Param` — enable fine-tuning during training.
Each sample produces:
- `audio`: (64000,) float32 — 4 seconds at 16 kHz
- `f0_hz`: (1000,) — CREPE pitch estimates at 250 Hz frame rate
- `loudness`: (1000,) — A-weighted loudness in dB
**Why datarax operators instead of crepe + librosa?**
- Same `apply(data, state, metadata)` contract as the synthesis operators below
- Pure JAX — vmap/JIT/grad compatible, GPU-accelerated
- No external Python dependencies (crepe, librosa) needed at runtime
"""
# %%
# Step 1: Load audio dataset
SAMPLE_RATE = 16000
AUDIO_LENGTH = 64000 # 4 seconds at 16 kHz
N_FRAMES = 1000 # Feature frames at 250 Hz frame rate
FRAME_RATE = 250 # Hz
N_HARMONICS = 100 # Paper uses 100 harmonics
N_NOISE_BANDS = 65 # Number of frequency bins for noise filter
# === Training Configuration ===
# All mode-dependent settings in one place. QUICK_MODE=True for fast demos
# (~15 min GPU), False for full training (~3 hrs GPU, ~31K steps).
@dataclass(frozen=True)
class TrainConfig:
"""Immutable training configuration — all mode-dependent settings."""
n_train: int
n_test: int
num_epochs: int
batch_size: int
loss_fft_sizes: tuple[int, ...]
use_synthetic_data: bool
QUICK_CONFIG = TrainConfig(
n_train=8,
n_test=4,
num_epochs=1,
batch_size=2,
# Fewer FFT scales reduces XLA compilation time significantly
# (each scale adds a separate STFT + gradient computation to the XLA graph)
loss_fft_sizes=(512,),
use_synthetic_data=True,
)
FULL_CONFIG = TrainConfig(
n_train=10000,
n_test=500,
num_epochs=100,
batch_size=32,
loss_fft_sizes=(64, 128, 256, 512, 1024, 2048),
use_synthetic_data=False,
)
QUICK_MODE = True
cfg = QUICK_CONFIG if QUICK_MODE else FULL_CONFIG
_DDSP_EXAMPLE_COMPLETED = False
def generate_synthetic_ddsp_data(
n_train: int,
n_test: int,
*,
seed: int = 42,
) -> tuple[dict, dict]:
"""Generate a tiny deterministic NSynth-like dataset for quick smoke runs.
Full mode still uses real NSynth recordings. Quick mode keeps CI and local
examples self-contained while exercising the same datarax source, operator,
synthesis, loss, and training paths.
"""
rng = np.random.default_rng(seed)
n_total = n_train + n_test
frame_axis = np.linspace(0.0, 1.0, N_FRAMES, dtype=np.float32)
sample_axis = np.linspace(0.0, 1.0, AUDIO_LENGTH, dtype=np.float32)
audio_all = np.empty((n_total, AUDIO_LENGTH), dtype=np.float32)
f0_all = np.empty((n_total, N_FRAMES), dtype=np.float32)
loudness_all = np.empty((n_total, N_FRAMES), dtype=np.float32)
for idx in range(n_total):
base_f0 = rng.uniform(110.0, 660.0)
vibrato_rate = rng.uniform(3.0, 6.0)
vibrato_phase = rng.uniform(0.0, 2.0 * np.pi)
f0_hz = base_f0 * (
1.0 + 0.015 * np.sin(2.0 * np.pi * vibrato_rate * frame_axis + vibrato_phase)
)
attack = np.minimum(frame_axis / 0.08, 1.0)
decay = np.exp(-2.0 * frame_axis)
loudness = 0.25 + 0.65 * attack * decay
sample_f0 = np.interp(sample_axis, frame_axis, f0_hz).astype(np.float32)
sample_amp = np.interp(sample_axis, frame_axis, loudness).astype(np.float32)
phase = np.cumsum(2.0 * np.pi * sample_f0 / SAMPLE_RATE).astype(np.float32)
waveform = np.zeros(AUDIO_LENGTH, dtype=np.float32)
for harmonic in range(1, 6):
waveform += (1.0 / harmonic) * np.sin(harmonic * phase).astype(np.float32)
waveform *= sample_amp
waveform += rng.normal(0.0, 0.002, size=AUDIO_LENGTH).astype(np.float32)
waveform /= max(float(np.max(np.abs(waveform))), 1e-8)
audio_all[idx] = waveform.astype(np.float32)
f0_all[idx] = f0_hz.astype(np.float32)
loudness_all[idx] = loudness.astype(np.float32)
f0_midi = 12.0 * np.log2(np.maximum(f0_all, 1e-5) / 440.0) + 69.0
f0_scaled = np.clip(f0_midi / 127.0, 0.0, 1.0).astype(np.float32)
train_data = {
"audio": audio_all[:n_train],
"f0": f0_scaled[:n_train],
"loudness": loudness_all[:n_train],
"f0_hz": f0_all[:n_train],
}
test_data = {
"audio": audio_all[n_train:],
"f0": f0_scaled[n_train:],
"loudness": loudness_all[n_train:],
"f0_hz": f0_all[n_train:],
}
return train_data, test_data
def load_nsynth(
n_train: int = 10000,
n_test: int = 500,
*,
synthetic: bool = False,
) -> tuple[dict, dict]:
"""Load NSynth gansynth_subset and extract features with datarax operators.
Downloads via tensorflow_datasets on first run (~1 GB). Computes f0 with
datarax's CrepeF0Operator (Flax NNX CREPE port) and loudness with
LoudnessOperator (pure JAX A-weighted STFT). Results are cached to disk.
Args:
n_train: Number of training samples to use.
n_test: Number of test samples to use.
Returns:
Tuple of (train_data, test_data) dicts with keys:
audio: (N, 64000) float32
f0: (N, 1000) float32 — MIDI-normalized f0 in [0,1]
loudness: (N, 1000) float32 — dB-range normalized loudness in [0,1]
f0_hz: (N, 1000) float32 — raw f0 in Hz
"""
if synthetic:
return generate_synthetic_ddsp_data(n_train=n_train, n_test=n_test)
import csv
import glob
import os as _os
import tensorflow as tf
# Prevent TF from claiming GPU memory (only JAX needs it)
tf.config.set_visible_devices([], "GPU")
# ---- Fast path: bypass Beam entirely ----
# The TFDS gansynth_subset.f0_and_loudness config runs CREPE (a CNN) on
# every audio clip via Apache Beam, which takes 30+ minutes even with
# multi-processing. Instead, we:
# 1. Read raw NSynth TFRecords directly (already downloaded)
# 2. Filter to GANSynth subset (acoustic instruments, MIDI pitch [24,84])
# 3. Compute f0 and loudness with datarax's audio operators — pure JAX,
# GPU-accelerated, only for the samples we need (not all ~290K)
data_dir = _os.environ.get("TFDS_DATA_DIR", None)
if data_dir is None:
data_dir = _os.path.join(_os.path.expanduser("~"), "tensorflow_datasets")
# Step 1: Download raw NSynth data if needed (uses TFDS downloader)
import tensorflow_datasets as tfds
tfds.builder("nsynth/gansynth_subset", data_dir=data_dir)
dl_manager = tfds.download.DownloadManager(
download_dir=_os.path.join(data_dir, "downloads"),
extract_dir=_os.path.join(data_dir, "downloads", "extracted"),
)
dl_urls = {
"examples": {
"train": "http://download.magenta.tensorflow.org/datasets/nsynth/nsynth-train.tfrecord.tar",
},
"gansynth_splits": "http://download.magenta.tensorflow.org/datasets/nsynth/nsynth-gansynth_splits.csv",
}
dl_paths = dl_manager.download_and_extract(dl_urls)
# Step 2: Load GANSynth split IDs (acoustic instruments, pitch [24,84])
gansynth_train_ids = set()
with tf.io.gfile.GFile(dl_paths["gansynth_splits"]) as f:
reader = csv.DictReader(f) # type: ignore[reportArgumentType]
for row in reader:
if row["split"] == "train":
gansynth_train_ids.add(row["id"])
print(f" GANSynth train subset: {len(gansynth_train_ids)} note IDs")
# Step 3: Read raw TFRecords, filter to GANSynth subset, collect samples
train_dir = dl_paths["examples"]["train"] # type: ignore[reportIndexIssue]
if _os.path.isdir(train_dir):
tfrecord_files = sorted(glob.glob(_os.path.join(train_dir, "*.tfrecord*")))
else:
tfrecord_files = [train_dir]
# Parse raw NSynth TFRecord format
feature_spec = {
"audio": tf.io.FixedLenFeature([64000], tf.float32),
"note_str": tf.io.FixedLenFeature([], tf.string),
}
n_total = n_train + n_test
# Over-read to ensure enough samples after filtering + shuffling
n_read_target = n_total * 2
raw_ds = tf.data.TFRecordDataset(tfrecord_files, num_parallel_reads=8)
audio_list = []
note_ids = []
for raw_record in raw_ds:
parsed = tf.io.parse_single_example(raw_record, feature_spec)
note_id = parsed["note_str"].numpy().decode("utf-8")
if note_id in gansynth_train_ids:
audio_list.append(parsed["audio"].numpy())
note_ids.append(note_id)
if len(audio_list) >= n_read_target:
break
print(f" Loaded {len(audio_list)} GANSynth samples from raw TFRecords")
# Shuffle and trim to exact count
rng_load = np.random.RandomState(42)
load_indices = rng_load.permutation(len(audio_list))[:n_total]
audio_arr = np.stack([audio_list[i] for i in load_indices])
# Step 4: Compute f0 and loudness with datarax audio operators
# These use the same OperatorModule.apply() contract as the synthesis
# operators below — showing that datarax is extensible to any domain.
#
# Check disk cache first (feature extraction is a one-time cost)
cache_path = _os.path.join(data_dir, f"nsynth_ddsp_cache_{n_total}.npz")
if _os.path.exists(cache_path):
print(f" Loading cached features from {cache_path}")
cached = np.load(cache_path)
audio_all = cached["audio"]
f0_all = cached["f0_hz"]
loudness_all = cached["loudness"]
else:
# Create datarax feature extraction operators
rngs = nnx.Rngs(0)
loudness_op = LoudnessOperator(LoudnessConfig(), rngs=rngs)
f0_op = CrepeF0Operator(
CrepeF0Config(differentiable=False, batch_strategy="scan"),
rngs=rngs,
)
load_crepe_weights_from_path(f0_op.crepe_model)
f0_op.eval()
print(f" Extracting features with datarax operators for {len(audio_arr)} samples...")
f0_list, loudness_list = [], []
# Batched extraction — call operators directly with Batch objects.
# __call__ → apply_batch → scan(apply), processing elements sequentially.
# CREPE uses jax.lax.scan internally for frame chunking AND
# batch_strategy="scan" processes elements sequentially (O(1) memory).
extract_batch_size = 16
for start in range(0, len(audio_arr), extract_batch_size):
end = min(start + extract_batch_size, len(audio_arr))
audio_batch = jnp.array(audio_arr[start:end])
batch = Batch.from_parts(data={"audio": audio_batch}, states={})
loud_out = loudness_op(batch)
loudness_list.append(np.array(loud_out.get_data()["loudness"]))
f0_out = f0_op(batch)
f0_list.append(np.array(f0_out.get_data()["f0_hz"]))
if end % 50 == 0 or end == len(audio_arr):
print(f" Processed {end}/{len(audio_arr)} samples")
audio_all = np.stack([audio_list[i] for i in load_indices])
f0_all = np.concatenate(f0_list, axis=0)
loudness_all = np.concatenate(loudness_list, axis=0)
# Cache to disk for subsequent runs
np.savez(cache_path, audio=audio_all, f0_hz=f0_all, loudness=loudness_all)
print(f" Cached features to {cache_path}")
# Normalize audio to [-1, 1]
audio_max = np.max(np.abs(audio_all), axis=1, keepdims=True)
audio_all = audio_all / np.maximum(audio_max, 1e-8)
# Scale loudness to [0, 1] via fixed dB range (matching DDSP paper)
DB_RANGE = 80.0
loudness_norm = np.clip(loudness_all / DB_RANGE + 1.0, 0.0, 1.0)
# Scale f0 to [0, 1] via MIDI note normalization (perceptually uniform, matching DDSP paper)
f0_midi = 12.0 * np.log2(np.maximum(f0_all, 1e-5) / 440.0) + 69.0
f0_scaled = np.clip(f0_midi / 127.0, 0.0, 1.0)
# Shuffle with fixed seed and split
rng = np.random.RandomState(42)
n_total = len(audio_all)
indices = rng.permutation(n_total)
n_train = min(n_train, n_total - n_test)
train_idx = indices[:n_train]
test_idx = indices[n_train : n_train + n_test]
train_data = {
"audio": audio_all[train_idx],
"f0": f0_scaled[train_idx],
"loudness": loudness_norm[train_idx],
"f0_hz": f0_all[train_idx], # Keep raw Hz for synthesis
}
test_data = {
"audio": audio_all[test_idx],
"f0": f0_scaled[test_idx],
"loudness": loudness_norm[test_idx],
"f0_hz": f0_all[test_idx],
}
return train_data, test_data
# Load data
dataset_label = "procedural DDSP smoke dataset" if cfg.use_synthetic_data else "NSynth dataset"
print(f"Loading {dataset_label} ({cfg.n_train} train, {cfg.n_test} test)...")
train_data, test_data = load_nsynth(
n_train=cfg.n_train,
n_test=cfg.n_test,
synthetic=cfg.use_synthetic_data,
)
# Wrap in MemorySource
train_source = MemorySource(MemorySourceConfig(), data=train_data, rngs=nnx.Rngs(0))
test_source = MemorySource(MemorySourceConfig(), data=test_data, rngs=nnx.Rngs(1))
print(
f"Train: audio={train_data['audio'].shape}, "
f"f0={train_data['f0'].shape}, "
f"loudness={train_data['loudness'].shape}"
)
print(
f"Sample rate: {SAMPLE_RATE} Hz, Audio length: {AUDIO_LENGTH} samples "
f"({AUDIO_LENGTH / SAMPLE_RATE:.1f}s)"
)
print(f"Feature frames: {N_FRAMES} @ {FRAME_RATE} Hz frame rate")
# Expected output (QUICK_MODE=True):
# Train: audio=(8, 64000), f0=(8, 1000), loudness=(8, 1000)
# Sample rate: 16000 Hz, Audio length: 64000 samples (4.0s)
# Feature frames: 1000 @ 250 Hz frame rate
# %%
# Visualize sample audio waveforms and their spectrograms
fig, axes = plt.subplots(2, 3, figsize=(16, 8))
time_axis = np.arange(AUDIO_LENGTH) / SAMPLE_RATE
for i in range(3):
audio = train_data["audio"][i]
f0_val = float(train_data["f0_hz"][i, N_FRAMES // 2]) # Mid-point f0
# Waveform (top row) — show first 4000 samples (~250ms)
n_show = 4000
axes[0, i].plot(time_axis[:n_show], audio[:n_show], color="steelblue", linewidth=0.5)
axes[0, i].set_xlabel("Time (s)")
axes[0, i].set_ylabel("Amplitude")
axes[0, i].set_title(f"Sample {i + 1}: f0 ~ {f0_val:.0f} Hz")
axes[0, i].set_xlim(0, n_show / SAMPLE_RATE)
axes[0, i].grid(True, alpha=0.3)
# Spectrogram (bottom row)
plot_specgram(axes[1, i], audio)
axes[1, i].set_xlabel("Time (s)")
axes[1, i].set_ylabel("Frequency (Hz)")
axes[1, i].set_ylim(0, 4000)
axes[1, i].set_title("Spectrogram (harmonics visible)")
fig.suptitle(
f"{dataset_label.title()} — Waveforms and Spectrograms\n"
"Each sample is a 4-second signal with f0 and loudness controls",
fontsize=12,
)
plt.tight_layout()
plt.savefig(
OUTPUT_DIR / "cv-ddsp-dataset-samples.png",
dpi=150,
bbox_inches="tight",
facecolor="white",
)
plt.close()
print(f"Saved: {OUTPUT_DIR / 'cv-ddsp-dataset-samples.png'}")
# %% [markdown]
"""
### Step 2: Custom Audio Operators (Extending OperatorModule)
These operators extend `OperatorModule` directly — not `ModalityOperator` —
because there's no audio-specific base class. This showcases datarax's
extensibility: you can build operators for any data type.
Each operator follows the standard contract:
- `OperatorConfig` subclass for configuration
- `nnx.Param` for learnable parameters
- `apply(data, state, metadata, key, stats) → (data, state, metadata)`
**Critical design choices**: The harmonic synthesizer uses **per-frame synthesis**
with upsampling from frame rate (250 Hz) to sample rate (16 kHz) via linear
interpolation, matching the DDSP paper (Engel et al. 2020). Phase accumulation
(`cumsum`) on the upsampled f0 ensures smooth phase continuity — without it,
frequency changes create phase discontinuities (audible clicks).
"""
# %%
# Step 2: Custom DDSP operators
# --- Operator 1: Harmonic Synthesizer ---
@dataclass(frozen=True)
class HarmonicSynthConfig(OperatorConfig):
"""Configuration for Harmonic Synthesizer.
Attributes:
n_harmonics: Number of harmonics to synthesize
n_frames: Number of input feature frames (for upsampling to sample rate)
sample_rate: Audio sample rate in Hz
audio_length: Number of output audio samples
"""
n_harmonics: int = field(default=N_HARMONICS, kw_only=True)
n_frames: int = field(default=N_FRAMES, kw_only=True)
sample_rate: int = field(default=SAMPLE_RATE, kw_only=True)
audio_length: int = field(default=AUDIO_LENGTH, kw_only=True)
class HarmonicSynthOperator(OperatorModule):
"""Differentiable harmonic additive synthesizer with phase accumulation.
Generates audio as a sum of sinusoidal harmonics using continuous phase
accumulation (matching the DDSP paper's Harmonic synth):
phase[t] = cumsum(2π * f0[t] / sample_rate)
audio = Σ amplitudes[k] * sin(k * phase)
Phase accumulation is critical for differentiable synthesis — it ensures
smooth phase continuity when f0 varies over time (unlike instantaneous
phase `sin(2π * k * f0 * t)` which creates artifacts).
Harmonics above the Nyquist frequency are filtered out.
"""
def __init__(self, config: HarmonicSynthConfig, *, rngs: nnx.Rngs | None = None):
"""Initialize HarmonicSynthOperator."""
super().__init__(config, rngs=rngs)
self.config: HarmonicSynthConfig = config
def apply(
self,
data: dict[str, Any],
state: dict[str, Any],
metadata: dict[str, Any] | None,
key: Any = None,
stats: dict[str, Any] | None = None,
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any] | None]:
"""Synthesize audio from per-frame harmonic amplitudes and f0.
Upsamples frame-rate controls to sample-rate via linear interpolation,
then performs additive synthesis with time-varying phase accumulation
(matching Engel et al. 2020, Section 3.1).
Expected data keys:
- 'amplitudes': (n_frames, n_harmonics) — per-frame harmonic amplitudes
- 'f0_hz': (n_frames,) — fundamental frequency in Hz per frame
Output data keys (added/updated):
- 'audio': (audio_length,) — synthesized waveform
"""
amplitudes = data["amplitudes"] # (n_frames, n_harmonics)
f0_hz = data["f0_hz"] # (n_frames,)
n_harmonics = self.config.n_harmonics
n_frames = self.config.n_frames
sr = self.config.sample_rate
length = self.config.audio_length
# Upsample f0 from frame rate → sample rate (linear interpolation)
frame_times = jnp.linspace(0, 1, n_frames)
sample_times = jnp.linspace(0, 1, length)
f0_upsampled = jnp.interp(sample_times, frame_times, f0_hz) # (audio_length,)
# Upsample per-harmonic amplitudes: (n_frames, n_harmonics) → (audio_length, n_harmonics)
amp_upsampled = jax.vmap(
lambda amp_k: jnp.interp(sample_times, frame_times, amp_k),
in_axes=1,
out_axes=1,
)(amplitudes) # (audio_length, n_harmonics)
# Phase accumulation with time-varying f0
phase_inc = 2.0 * jnp.pi * f0_upsampled / sr # (audio_length,)
phase = jnp.cumsum(phase_inc) # (audio_length,)
# Harmonic indices: 1, 2, ..., n_harmonics
harmonic_k = jnp.arange(1, n_harmonics + 1, dtype=jnp.float32)
# Nyquist filtering (per-sample, since f0 varies over time)
nyquist = sr / 2.0
valid_mask = (f0_upsampled[:, None] * harmonic_k[None, :]) < nyquist
amp_upsampled = amp_upsampled * valid_mask
# Sinusoid generation + weighted sum
harmonics = jnp.sin(harmonic_k[None, :] * phase[:, None]) # (audio_length, n_harmonics)
audio = jnp.sum(amp_upsampled * harmonics, axis=1) # (audio_length,)
out_data = {**data, "audio": audio}
return out_data, state, metadata
# --- Operator 2: Filtered Noise ---
@dataclass(frozen=True)
class FilteredNoiseConfig(OperatorConfig):
"""Configuration for Filtered Noise synthesizer.
Attributes:
audio_length: Number of output audio samples
n_noise_bands: Number of frequency bands for noise filter
"""
audio_length: int = field(default=AUDIO_LENGTH, kw_only=True)
n_noise_bands: int = field(default=N_NOISE_BANDS, kw_only=True)
class FilteredNoiseOperator(OperatorModule):
"""Differentiable filtered noise synthesizer.
Generates audio by filtering white noise in the frequency domain:
1. Generate white noise
2. FFT → multiply by learned frequency response → IFFT
The frequency magnitudes are provided as input (from decoder) and passed
through ``exp_sigmoid`` (bounded [1e-7, 2.0]) before interpolation,
matching the DDSP reference (ddsp/synths.py). Uses a fixed noise seed
for deterministic gradient computation.
"""
def __init__(self, config: FilteredNoiseConfig, *, rngs: nnx.Rngs | None = None):
"""Initialize FilteredNoiseOperator."""
super().__init__(config, rngs=rngs)
self.config: FilteredNoiseConfig = config
# Fixed noise for deterministic gradients
noise = jax.random.normal(jax.random.key(0), (config.audio_length,))
self.fixed_noise = nnx.Variable(noise)
def apply(
self,
data: dict[str, Any],
state: dict[str, Any],
metadata: dict[str, Any] | None,
key: Any = None,
stats: dict[str, Any] | None = None,
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any] | None]:
"""Filter noise using learned frequency magnitudes.
Expected data keys:
- 'noise_magnitudes': (n_frames, n_noise_bands) — per-frame filter shape
Output data keys (added/updated):
- 'audio': (audio_length,) — filtered noise waveform
"""
noise_magnitudes = data["noise_magnitudes"] # (n_frames, n_noise_bands)
# Average over time frames (simplification — paper uses per-frame overlap-add)
magnitudes = jnp.mean(noise_magnitudes, axis=0) # (n_noise_bands,)
noise = self.fixed_noise[...] # (audio_length,)
# FFT-based filtering
noise_fft = jnp.fft.rfft(noise) # (audio_length//2 + 1,)
n_fft = noise_fft.shape[0]
# Interpolate magnitudes to match FFT size
x_interp = jnp.linspace(0, 1, n_fft)
x_orig = jnp.linspace(0, 1, magnitudes.shape[0])
filter_response = jnp.interp(x_interp, x_orig, exp_sigmoid(magnitudes))
# Apply filter and IFFT
filtered_fft = noise_fft * filter_response
audio = jnp.fft.irfft(filtered_fft, n=self.config.audio_length)
out_data = {**data, "audio": audio}
return out_data, state, metadata
# --- Operator 3: Reverb ---
@dataclass(frozen=True)
class ReverbConfig(OperatorConfig):
"""Configuration for trainable Reverb operator.
Attributes:
ir_length: Length of impulse response in samples
sample_rate: Audio sample rate in Hz
"""
ir_length: int = field(default=SAMPLE_RATE, kw_only=True) # 1 second IR
sample_rate: int = field(default=SAMPLE_RATE, kw_only=True)
class ReverbOperator(OperatorModule):
"""Differentiable reverb via trainable FIR impulse response.
Applies room acoustics by convolving the input audio with a learned
impulse response (IR). The IR is initialized with exponential decay
(approximating a simple room) and optimized end-to-end.
Uses FFT-based convolution for efficiency.
Matches DDSP paper's Reverb effect (ddsp/effects.py).
"""
def __init__(self, config: ReverbConfig, *, rngs: nnx.Rngs | None = None):
"""Initialize ReverbOperator."""
super().__init__(config, rngs=rngs)
self.config: ReverbConfig = config
# Learnable impulse response (init = exponential decay)
decay = jnp.exp(-jnp.arange(config.ir_length, dtype=jnp.float32) * 5.0 / config.ir_length)
self.impulse_response = nnx.Param(decay * 0.1)
def apply(
self,
data: dict[str, Any],
state: dict[str, Any],
metadata: dict[str, Any] | None,
key: Any = None,
stats: dict[str, Any] | None = None,
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any] | None]:
"""Apply reverb to audio via FFT-based convolution.
Expected data keys:
- 'audio': (audio_length,) — input audio
Output data keys (updated):
- 'audio': (audio_length,) — reverbed audio (same length)
"""
audio = data["audio"] # (audio_length,)
ir = self.impulse_response[...] # (ir_length,)
# FFT-based convolution
n_fft = audio.shape[0] + ir.shape[0] - 1
# Round up to next power of 2 for FFT efficiency
n_fft_padded = 1 << (n_fft - 1).bit_length()
audio_fft = jnp.fft.rfft(audio, n=n_fft_padded)
ir_fft = jnp.fft.rfft(ir, n=n_fft_padded)
convolved = jnp.fft.irfft(audio_fft * ir_fft, n=n_fft_padded)
# Trim to original length
reverbed = convolved[: audio.shape[0]]
out_data = {**data, "audio": reverbed}
return out_data, state, metadata
# Verify operators
print("Verifying DDSP operators...")
# Test harmonic synth (per-frame inputs)
h_config = HarmonicSynthConfig()
h_op = HarmonicSynthOperator(h_config)
h_batch = Batch.from_parts(
data={
"amplitudes": jnp.ones((1, N_FRAMES, N_HARMONICS)) * 0.1,
"f0_hz": jnp.ones((1, N_FRAMES)) * 440.0,
},
states={},
)
h_result = h_op(h_batch)
h_out = h_result.get_data()
print(f" HarmonicSynth: output keys={list(h_out.keys())}, audio shape={h_out['audio'].shape}")
# Test filtered noise (per-frame input)
n_config = FilteredNoiseConfig()
n_op = FilteredNoiseOperator(n_config)
n_batch = Batch.from_parts(
data={"noise_magnitudes": jnp.ones((1, N_FRAMES, N_NOISE_BANDS))},
states={},
)
n_result = n_op(n_batch)
n_out = n_result.get_data()
print(f" FilteredNoise: output keys={list(n_out.keys())}, audio shape={n_out['audio'].shape}")
# Test reverb
r_config = ReverbConfig()
r_op = ReverbOperator(r_config)
r_batch = Batch.from_parts(
data={"audio": jnp.sin(jnp.linspace(0, 10, AUDIO_LENGTH))[None]},
states={},
)
r_result = r_op(r_batch)
r_out = r_result.get_data()
print(
f" Reverb: IR params={r_op.impulse_response[...].shape[0]}, audio shape={r_out['audio'].shape}"
)
# Count total operator parameters
total_op_params = sum(
p.size for op in [h_op, n_op, r_op] for p in jax.tree.leaves(nnx.state(op, nnx.Param))
)
print(f"\nTotal operator parameters: {total_op_params:,}")
# Expected output:
# HarmonicSynth: output keys=['amplitudes', 'f0_hz', 'audio'], audio shape=(1, 64000)
# FilteredNoise: output keys=['noise_magnitudes', 'audio'], audio shape=(1, 64000)
# Reverb: IR params=16000, audio shape=(1, 64000)
# Total operator parameters: 16,000
# %% [markdown]
"""
### Step 3: DDSP Decoder (Paper-Accurate Architecture)
The paper's "decoder" maps audio features (f0, loudness) to synthesis
parameters. It follows the architecture from Section 3.1:
f0 + loudness → Linear(2→512) → GRU(512) → MLP(512, 3 layers) → heads
The MLP stack uses the Artifex pattern: `nnx.List` for dynamic layer
collections with `LayerNorm` + `ReLU` activation at each layer.
**Why "decoder", not "encoder"?** The paper calls this a decoder because
it maps *extracted audio features* to *synthesis parameters* — the inverse
direction of an encoder. Previous versions of this example incorrectly
called it "encoder".
"""
# %%
# Step 3: DDSP Decoder
class DDSPDecoder(nnx.Module):
"""RNN-FC decoder predicting synth params from audio features.
Architecture (matching paper Section 3.1):
f0 + loudness → Linear(2→hidden) → GRU(hidden) →
MLP(hidden, n_layers) → output heads
Output activations use ``exp_sigmoid`` (bounded [1e-7, 2.0]) for amplitude
and harmonic distribution heads, matching the reference DDSP implementation.
Noise head bias is initialized to -5.0 so noise starts near-zero.
Uses nnx.List for the MLP layer collection (Artifex pattern) to
allow arbitrary depth without hardcoding layer count.
Args:
hidden_dim: Hidden dimension for GRU and MLP layers.