kudioenhance 1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. kudioenhance-1.0/LICENSE.txt +21 -0
  2. kudioenhance-1.0/PKG-INFO +636 -0
  3. kudioenhance-1.0/README.md +600 -0
  4. kudioenhance-1.0/pyproject.toml +70 -0
  5. kudioenhance-1.0/setup.cfg +4 -0
  6. kudioenhance-1.0/src/kudioenhance/__init__.py +60 -0
  7. kudioenhance-1.0/src/kudioenhance/_version.py +4 -0
  8. kudioenhance-1.0/src/kudioenhance/checkpoint.py +80 -0
  9. kudioenhance-1.0/src/kudioenhance/cli.py +207 -0
  10. kudioenhance-1.0/src/kudioenhance/config.py +345 -0
  11. kudioenhance-1.0/src/kudioenhance/data.py +342 -0
  12. kudioenhance-1.0/src/kudioenhance/datasets.py +328 -0
  13. kudioenhance-1.0/src/kudioenhance/evaluate.py +133 -0
  14. kudioenhance-1.0/src/kudioenhance/features.py +143 -0
  15. kudioenhance-1.0/src/kudioenhance/inference.py +194 -0
  16. kudioenhance-1.0/src/kudioenhance/models/__init__.py +21 -0
  17. kudioenhance-1.0/src/kudioenhance/models/_defaults.py +67 -0
  18. kudioenhance-1.0/src/kudioenhance/models/convolutional.py +67 -0
  19. kudioenhance-1.0/src/kudioenhance/models/crn.py +157 -0
  20. kudioenhance-1.0/src/kudioenhance/models/dense.py +45 -0
  21. kudioenhance-1.0/src/kudioenhance/models/recurrent.py +56 -0
  22. kudioenhance-1.0/src/kudioenhance/models/registry.py +185 -0
  23. kudioenhance-1.0/src/kudioenhance/models/unet.py +118 -0
  24. kudioenhance-1.0/src/kudioenhance/pipeline.py +167 -0
  25. kudioenhance-1.0/src/kudioenhance/train.py +413 -0
  26. kudioenhance-1.0/src/kudioenhance.egg-info/PKG-INFO +636 -0
  27. kudioenhance-1.0/src/kudioenhance.egg-info/SOURCES.txt +41 -0
  28. kudioenhance-1.0/src/kudioenhance.egg-info/dependency_links.txt +1 -0
  29. kudioenhance-1.0/src/kudioenhance.egg-info/entry_points.txt +2 -0
  30. kudioenhance-1.0/src/kudioenhance.egg-info/requires.txt +11 -0
  31. kudioenhance-1.0/src/kudioenhance.egg-info/top_level.txt +1 -0
  32. kudioenhance-1.0/tests/test_checkpoint.py +160 -0
  33. kudioenhance-1.0/tests/test_cli.py +94 -0
  34. kudioenhance-1.0/tests/test_config.py +142 -0
  35. kudioenhance-1.0/tests/test_data.py +332 -0
  36. kudioenhance-1.0/tests/test_datasets.py +416 -0
  37. kudioenhance-1.0/tests/test_features.py +86 -0
  38. kudioenhance-1.0/tests/test_mask.py +242 -0
  39. kudioenhance-1.0/tests/test_models.py +164 -0
  40. kudioenhance-1.0/tests/test_models_2d.py +275 -0
  41. kudioenhance-1.0/tests/test_package.py +64 -0
  42. kudioenhance-1.0/tests/test_pipeline.py +262 -0
  43. kudioenhance-1.0/tests/test_train.py +326 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RL
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,636 @@
1
+ Metadata-Version: 2.4
2
+ Name: kudioenhance
3
+ Version: 1.0
4
+ Summary: Train and run learned speech-enhancement (denoising) models on top of the kudio audio toolkit.
5
+ Author: RL
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/recklight/KudioEnhance
8
+ Project-URL: Issues, https://github.com/recklight/KudioEnhance/issues
9
+ Project-URL: Kudio, https://pypi.org/project/kudio/
10
+ Keywords: speech-enhancement,denoising,audio,deep-learning,pytorch,spectrogram
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE.txt
26
+ Requires-Dist: kudio>=3.7.1
27
+ Requires-Dist: numpy>=1.22
28
+ Requires-Dist: PyYAML>=6.0
29
+ Requires-Dist: torch>=2.4.1
30
+ Provides-Extra: eval
31
+ Requires-Dist: kudio[eval]>=3.7.1; extra == "eval"
32
+ Provides-Extra: dev
33
+ Requires-Dist: kudioenhance[eval]; extra == "dev"
34
+ Requires-Dist: pytest>=8.2; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ # KudioEnhance
38
+
39
+ **English** | [繁體中文](https://github.com/recklight/KudioEnhance/blob/master/README.zh-TW.md)
40
+
41
+ [![PyPI](https://img.shields.io/pypi/v/kudioenhance.svg)](https://pypi.org/project/kudioenhance/)
42
+ [![Python](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/)
43
+ [![PyTorch](https://img.shields.io/badge/PyTorch-2.4.1%2B-ee4c2c.svg)](https://pytorch.org/)
44
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/recklight/KudioEnhance/blob/master/LICENSE.txt)
45
+ [![kudio](https://img.shields.io/pypi/v/kudio.svg?label=kudio)](https://pypi.org/project/kudio/)
46
+
47
+ **Train and run learned speech-enhancement (denoising) models**, built on the
48
+ [`kudio`](https://pypi.org/project/kudio/) audio toolkit.
49
+
50
+ Three stages, one config file:
51
+
52
+ [![KudioEnhance workflow](https://raw.githubusercontent.com/recklight/KudioEnhance/master/docs/images/workflow.png)](https://raw.githack.com/recklight/KudioEnhance/master/docs/workflow.html?theme=dark)
53
+
54
+ The figure is a link to an interactive version — [open it online](https://raw.githack.com/recklight/KudioEnhance/master/docs/workflow.html?theme=dark), or open `docs/workflow.html` from a checkout. You can zoom, search for a node, or trace the path between two of them, and most boxes carry a link to the lines of source they were drawn from, at the commit they were checked against.
55
+
56
+ Each stage reads what the one before it wrote, so you can re-train without
57
+ re-mixing and re-evaluate without re-training. `run` does all three in order.
58
+
59
+ Models work in the **log-power spectrogram domain** and reuse the noisy phase —
60
+ the standard magnitude-only enhancement setup. Feature extraction and
61
+ reconstruction both go through `kudio`, so what the model sees is exactly what
62
+ any other kudio-based tool produces.
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ pip install kudioenhance
68
+ ```
69
+
70
+ The command is `kudioenhance` and the package `import kudioenhance`.
71
+
72
+ Needs **Python 3.9+** and **PyTorch ≥ 2.4.1**. The models are plain
73
+ `torch.nn` modules, trained by a loop in this package — no Keras, no
74
+ Lightning. Older torch wheels, and 2.4.0's on Windows, were built against
75
+ NumPy 1, which nothing stops pip from installing beside NumPy 2, and there
76
+ they fail at the first `torch.from_numpy`.
77
+
78
+ On Linux the default `torch` wheel bundles CUDA and runs to several
79
+ gigabytes. Without an NVIDIA GPU, install the CPU-only build **first** and pip
80
+ will keep it when it installs this package:
81
+
82
+ ```bash
83
+ pip install torch --index-url https://download.pytorch.org/whl/cpu
84
+ pip install kudioenhance
85
+ ```
86
+
87
+ The Windows and macOS wheels on PyPI carry no CUDA, so they stay small.
88
+ Training takes an NVIDIA GPU whenever torch can see one (`device: auto` in the
89
+ `train` section), so the same config works on both kinds of machine. Apple's
90
+ GPUs are not used: torch can drive them through `mps`, but this package does
91
+ not ask it to, and on a Mac training runs on the CPU.
92
+
93
+ STOI and SDR are optional: `pip install "kudioenhance[eval]"`. **PESQ is a
94
+ separate extra**, `pip install "kudio[pesq]"`, because it builds from source
95
+ — a C compiler, and the MSVC Build Tools on Windows — so it is deliberately
96
+ left out of `[eval]` and `[all]`, which would otherwise stop installing.
97
+
98
+ PESQ comes on two scales. `evaluate` reports MOS-LQO by default; pass
99
+ `--pesq-scale raw` for the narrowband P.862 score most enhancement papers
100
+ quote. They are different scales, not different roundings: raw 2.03 is about
101
+ 1.65 MOS-LQO.
102
+
103
+ ## Quick start
104
+
105
+ ```bash
106
+ kudioenhance init config.yaml # starter config
107
+ kudioenhance run -c config.yaml -n exp1
108
+ ```
109
+
110
+ That mixes the dataset, trains, and prints the before/after scores:
111
+
112
+ ```
113
+ si_sdr -4.812 -> 6.933 (+11.745)
114
+ snr -4.998 -> 5.221 (+10.219)
115
+ seg_snr -6.114 -> 1.870 (+7.984)
116
+ report -> runs/exp1/report.csv
117
+ ```
118
+
119
+ Then denoise anything with the trained run:
120
+
121
+ ```bash
122
+ kudioenhance denoise runs/exp1 noisy.wav enhanced.wav
123
+ kudioenhance denoise runs/exp1 noisy/ clean/ --recursive --report
124
+ ```
125
+
126
+ The folder form loads the model **once** for the whole tree, mirrors the input's
127
+ directory structure, and with `--report` says how far the noise floor moved.
128
+
129
+ And afterwards, whether it actually learned anything:
130
+
131
+ ```bash
132
+ kudioenhance curves -c config.yaml -n exp1
133
+ ```
134
+
135
+ ```
136
+ 3 epoch(s), monitoring val_loss
137
+ best 0.12172 at epoch 3
138
+ first 0.28104 last 0.12172
139
+ ```
140
+
141
+ A training loop hands back its curves and almost every script drops them,
142
+ which makes "did it converge, or stop early because validation was already
143
+ climbing?" unanswerable the moment the terminal closes. They are written to
144
+ `runs/exp1/history.json` (and `history.png` when matplotlib is around). If the
145
+ best epoch was the *first* one the command says so and exits non-zero — that is
146
+ what "this did not learn" looks like.
147
+
148
+ ### Stage by stage
149
+
150
+ ```bash
151
+ kudioenhance synth -c config.yaml -n exp1 # mix + freeze the splits
152
+ kudioenhance train -c config.yaml -n exp1 # fit (--epochs 1 to smoke-test)
153
+ kudioenhance evaluate -c config.yaml -n exp1 # score (--full adds PESQ/STOI)
154
+ ```
155
+
156
+ Each stage reads what the previous one wrote, so you can re-train without
157
+ re-mixing, or re-evaluate without re-training.
158
+
159
+ ## Configuration
160
+
161
+ ```yaml
162
+ audio: # STFT geometry, shared by features and reconstruction
163
+ sr: 16000
164
+ n_fft: 512
165
+ hop_length: 256
166
+ win_length: 512
167
+
168
+ data:
169
+ clean_dir: data/clean
170
+ noise_dir: data/noise
171
+ mixed_dir: runs/mixed
172
+ snr_db: [-5, 0, 5]
173
+ rt60: [] # reverberation times in seconds; [] = no rooms
174
+ drr_db: 0.0 # how close the microphone is, in dB
175
+ reverberant_target: false # train to remove the noise and leave the room
176
+ channel: null # telephone / voip / mu_law / a_law, or null
177
+ mode: regular # 'regular' = one mix per clean file; 'inc' = every combination
178
+ seed: 17 # makes the mixture and the splits reproducible
179
+ val_split: 0.1
180
+ test_split: 0.1
181
+
182
+ model:
183
+ name: ddae # ddae | blstm | conv_ae | crn | unet
184
+ target: spectrum # spectrum | irm -- see "What the network is asked to produce"
185
+ context: 2 # frame-wise models: ±frames stacked into the input
186
+ n_frames: 64 # sequence models: frames per training window
187
+ units: null # layer widths; null = the architecture's default
188
+ dropout: 0.1
189
+
190
+ train:
191
+ epochs: 50
192
+ batch_size: 256 # ddae needs 2 or more; the sequence models train on 1
193
+ learning_rate: 0.001
194
+ patience: 8
195
+ out_dir: runs
196
+ device: auto # auto | cpu | cuda | cuda:1
197
+ seed: null # weights, dropout and batch order; null = data.seed
198
+ streaming: false # true: read the features from disk every epoch
199
+ shuffle_buffer: 0 # streaming only: examples held back for mixing
200
+ ```
201
+
202
+ Every key is a typed dataclass field. A typo fails at load time and names the
203
+ offending key — it does not silently fall back to a default three stages later.
204
+
205
+ ## Models
206
+
207
+ ```bash
208
+ kudioenhance models
209
+ ```
210
+
211
+ ```
212
+ blstm stacked bidirectional LSTM units: [1024, 1024, 1024]
213
+ conv_ae dilated Conv1D autoencoder, residual units: [1024, 1024, 1024]
214
+ crn causal conv-recurrent network (Tan & Wang 2018) units: [16, 32, 64, 64, 64]
215
+ ddae dense denoising autoencoder, frame-wise units: [1024, 1024, 1024]
216
+ unet 2-D U-Net over time and frequency, non-causal units: [16, 32, 64, 128]
217
+ ```
218
+
219
+ | Name | Input layout | Causal | What it is, and when to choose it |
220
+ |---|---|---|---|
221
+ | `ddae` | `(N, bins × (2·context+1))` | no — sees ±`context` frames | Dense denoising autoencoder. Frame-wise, fast, a solid baseline. |
222
+ | `blstm` | `(N, n_frames, bins)` | no | Stacked bidirectional LSTM. Temporal context in both directions. |
223
+ | `conv_ae` | `(N, n_frames, bins)` | no | Dilated Conv1D autoencoder with a residual connection — starts from "pass the signal through" rather than from noise. |
224
+ | `crn` | `(N, n_frames, bins)` | **yes** | Convolutional recurrent network after Tan & Wang, *A convolutional recurrent neural network for real-time speech enhancement* (Interspeech 2018): a strided 2-D convolutional encoder over time and frequency, an LSTM over time, and a mirrored decoder that takes each encoder layer's output back in. Choose it when the output must not wait for what comes next. |
225
+ | `unet` | `(N, n_frames, bins)` | no — about 50 frames ahead | 2-D U-Net over time and frequency: convolution blocks, halving both axes on the way down, skip connections on the way back up. Choose it for offline enhancement of whole files; at about half a million parameters it is also the smallest model here at the default widths. |
226
+
227
+ Sequence models are trained on fixed-length windows, but nothing in them
228
+ fixes the length of the time axis, so the same weights enhance a whole
229
+ utterance in one pass. The two 2-D models also take any `n_fft`: they pad
230
+ time and frequency internally as far as their halvings need, and crop back.
231
+
232
+ **Causal** means the output for a frame depends on that frame and earlier
233
+ ones only — the convolutions in `crn` are padded on the past side, its LSTM
234
+ runs forwards, and a test holds it to that. It is what a real-time port
235
+ needs, but this package does not stream: `Enhancer` still enhances a whole
236
+ file at once, and the STFT adds a window of latency of its own.
237
+
238
+ **`model.units`** is the list of layer widths: a dense layer's units, an
239
+ LSTM's, a convolution's filters or channels. Left as `null` it takes the
240
+ architecture's default, listed above. A width of 1024 is sensible for a
241
+ dense layer and absurd for a 2-D convolution, each of whose channels is a
242
+ whole time-frequency map, so the default belongs to the architecture. Set it
243
+ to a list to choose the widths yourself. Training writes the widths it
244
+ actually built into the run's `config.yaml`, so a run keeps loading even if a
245
+ later release changes a default.
246
+
247
+ `crn`'s LSTM reads every channel at every bin left after halving the bins
248
+ once per layer, so its size grows with `n_fft`: about 1.8M parameters at
249
+ `n_fft: 256`, 5.5M at 512 and 19M at 1024. For a large `n_fft`, add a layer
250
+ to halve once more — `units: [16, 32, 64, 64, 64, 64]` brings 1024 back to
251
+ 5.6M. Nothing in `unet` depends on the number of bins.
252
+
253
+ Adding an architecture is a builder function plus one `REGISTRY` entry —
254
+ there is no `if/elif` chain to extend in three places. The entry's
255
+ `default_units` is what `units: null` builds; leave it out and the
256
+ architecture gets the 1024-wide stack the first three share.
257
+
258
+ ### What the network is asked to produce
259
+
260
+ `model.target` is a separate choice from `model.name`, and every architecture
261
+ supports both:
262
+
263
+ | Target | The network outputs | |
264
+ |---|---|---|
265
+ | `spectrum` | the clean log-power spectrogram, directly | unbounded output; it has to learn the *level* as well as the shape |
266
+ | `irm` | an **ideal ratio mask** in `[0, 1]` | bounded, so a sigmoid cannot produce an impossible answer, and the level comes from the input |
267
+
268
+ ```yaml
269
+ model:
270
+ name: ddae
271
+ target: irm
272
+ ```
273
+
274
+ The mask is `sqrt(|S|² / (|S|² + |N|²))` — how much of each time-frequency bin
275
+ is speech — and applying it is an addition in the log domain, so the network
276
+ only ever decides *how much to keep*.
277
+
278
+ **Measured on this repo's own smoke corpus, three epochs of a small `ddae`:**
279
+
280
+ | target | SI-SDR |
281
+ |---|---|
282
+ | `spectrum` | +0.05 → **−7.59 dB** |
283
+ | `irm` | +0.05 → **+2.61 dB** |
284
+ | an oracle mask | −3.02 → **+14.16 dB** |
285
+
286
+ An undertrained spectrum model has not learned the level yet, so it outputs
287
+ something loud and wrong; an undertrained mask model is already useful, because
288
+ the worst it can do is keep or drop what was already there. The oracle row is
289
+ the ceiling this target aims at.
290
+
291
+ That is a tiny model on a tiny corpus, not a benchmark — but it is the reason
292
+ mask targets are the usual choice, made visible in about twenty seconds.
293
+
294
+ ## Rooms
295
+
296
+ Noise is additive and a room is convolutive, and a real recording has both.
297
+ `data.rt60` puts the speech through a room before the noise is mixed in:
298
+
299
+ ```yaml
300
+ data:
301
+ snr_db: [-5, 0, 5]
302
+ rt60: [0.3, 0.6, 0.9] # a fourth axis -- in `inc` mode, x3 the files
303
+ drr_db: 0.0 # +10 is a close mic, 0 is a metre or two
304
+ ```
305
+
306
+ The SNR is then measured against the **reverberant** speech, because that is
307
+ what is competing with the noise at the microphone.
308
+
309
+ **By default the clean file stays the target.** A model trained on that is
310
+ asked to undo the room as well as the noise, which is a standard setup and a
311
+ choice worth making on purpose rather than discovering.
312
+
313
+ `reverberant_target: true` changes it. `kudio.Synthesizer` then writes the
314
+ reverberant-but-clean signal to `TARGETS/` beside each mixture — the same
315
+ speech with the room left on — and training asks the model to remove the
316
+ noise and **leave** the room, which is a different and easier problem, and
317
+ the honest one when the deployment keeps its room.
318
+
319
+ It also makes the `irm` target correct. The mask is built from
320
+ `noisy - reference`, and with a room on the speech the dry clean file is not
321
+ what was mixed, so that subtraction hands the reverberation to the *noise*
322
+ and the mask asks the model to strip the room's own tail as if it were noise.
323
+ Against the reverberant target the subtraction is the noise again.
324
+
325
+ Each mixture records the room it was built in — `Pair.rt60`, and the file name
326
+ carries it too (`speech_white_0dB_rt600ms.wav`), so a manifest says what every
327
+ example was asked to survive.
328
+
329
+ ## The channel
330
+
331
+ The third kind of degradation, and the one that is neither additive nor
332
+ convolutive: a codec quantises, a link drops packets, a converter throws bits
333
+ away.
334
+
335
+ ```yaml
336
+ data:
337
+ channel: telephone # 300-3400 Hz at 8 kHz through G.711
338
+ ```
339
+
340
+ `telephone`, `telephone_a`, `voip` (G.711 with 5% of packets lost in runs of
341
+ four, held), `mu_law`, `a_law`. It is applied to the **mixture**, noise and
342
+ all, because a wire carries whatever reached the microphone.
343
+
344
+ **It is not an axis.** Unlike `snr_db` and `rt60` it is constant for the
345
+ dataset and does not appear in the file names: a corpus is recorded over a
346
+ phone line or it is not. `Pair.channel` records which link, and the target
347
+ does not go down it — asking a model to reproduce G.711 is not denoising.
348
+
349
+ ## Datasets
350
+
351
+ Point `clean_dir` and `noise_dir` at any two folders. Public sets that work
352
+ well out of the box:
353
+
354
+ - **[VoiceBank-DEMAND](https://datashare.ed.ac.uk/handle/10283/2791)** — the standard speech-enhancement benchmark (comes pre-mixed; use its clean/noisy folders directly and skip the synth stage).
355
+ - **[LibriSpeech](https://www.openslr.org/12/)** + **[DEMAND](https://zenodo.org/record/1227121)** or **[MUSAN](https://www.openslr.org/17/)** — mix them yourself at the SNRs you care about.
356
+ - **[ESC-50](https://github.com/karolpiczak/ESC-50)** — environmental noise, handy for non-speech targets.
357
+
358
+ Set a `seed` and the mixture is reproducible: the same noise offsets, the same
359
+ pairings, the same splits.
360
+
361
+ ## Training data: in memory or streamed
362
+
363
+ By default training holds its features in memory: they are computed once,
364
+ and every epoch is a full shuffle of the whole set. That is the right choice
365
+ for the tens of hours these models are normally trained on.
366
+
367
+ A frame-wise model (`ddae`) sees every frame with its ±`context` neighbours,
368
+ and stacking those for the whole set up front used to multiply the memory by
369
+ `2·context + 1` — eleven times over at `context: 5`. The training set now
370
+ keeps each frame once, in a `kudio.ContextFrames`, and stacks the neighbours
371
+ of the rows a batch draws as it draws them. The rows are the same, and so is
372
+ the run: a test holds the set to the stacked matrix row for row, and fitting
373
+ on either gives the same weights to the last bit. Sequence models' windows
374
+ were never larger than their features.
375
+
376
+ What is left is the features themselves, input and target: at 16 kHz with
377
+ the default STFT, about 0.46 GB per hour of training audio. When that does
378
+ not fit, stream:
379
+
380
+ ```yaml
381
+ train:
382
+ streaming: true
383
+ shuffle_buffer: 25000 # a hundred 4-second files of ddae frames
384
+ ```
385
+
386
+ Nothing is held then. Every epoch reads the training files again, in a fresh
387
+ order, and computes each one's examples as it goes — the same examples, row
388
+ for row, as the in-memory set. The price is that pass over the audio, every
389
+ epoch: reading, resampling and the STFT, done by the training process between
390
+ batches.
391
+
392
+ - **The normalisation** is fitted by one extra pass before the first epoch, a
393
+ file at a time. It is kudio's formula — the mean, the population standard
394
+ deviation and the same `1e-8` added to it — summed in float64, and an
395
+ in-memory run fits it the same way, a file's spectrogram at a time, so the
396
+ two modes normalise with the same statistics to the bit. (kudio's own
397
+ `Standardizer.fit` sums in float32, and on an hour of frames drifts from
398
+ the true statistics by a few parts in 10⁵; this stays within a part in
399
+ 10⁷.)
400
+ - **Validation** is streamed too, in manifest order, and its batches fall
401
+ exactly where the in-memory set's would, so it scores what the in-memory
402
+ set would score.
403
+ - **The shuffle buffer.** Each file's examples join a pool, and every batch is
404
+ drawn at random from everything in it, for as long as at least
405
+ `shuffle_buffer` examples would be left waiting; when the files run out the
406
+ rest goes out in random order. An example is a frame for `ddae` and an
407
+ `n_frames` window for the sequence models. To mix well, let the buffer span
408
+ a hundred files or so: a hundred times the frames in a typical file, or
409
+ the windows in one. It costs that many inputs and targets of memory: 6 KB
410
+ an example for `ddae` at 257 bins and `context: 2`, 132 KB for a 64-frame
411
+ window.
412
+ - **`shuffle_buffer: 0` holds nothing back.** The files still come in a fresh
413
+ order and each file's examples are shuffled, but every batch is drawn from
414
+ the file being read and what earlier draws left over, less than a batch —
415
+ neighbouring frames of one recording, which trains worse. Training warns
416
+ when it is asked for. In memory the setting is not used.
417
+ - **It repeats.** The order of the files and every draw from the pool come
418
+ from `train.seed`, so a streamed run repeats to the last digit on the CPU,
419
+ as an in-memory one does. It is a different run from the in-memory one,
420
+ though: the same examples, in a different order.
421
+
422
+ `kudioenhance.data.build_dataset` is what both modes go through, and
423
+ `train.fit` takes what it returns in place of arrays:
424
+
425
+ ```python
426
+ from kudioenhance.data import build_dataset
427
+ from kudioenhance.train import fit
428
+
429
+ train_set, std = build_dataset(train_pairs, cfg, sequence=False, fit=True)
430
+ history = fit(model, train_set, None, cfg, "runs/exp1/ddae.pt")
431
+ ```
432
+
433
+ `build_arrays` still returns the plain stacked matrices, for code that wants
434
+ them.
435
+
436
+ ## Python API
437
+
438
+ ```python
439
+ from kudioenhance import Config, Enhancer, pipeline
440
+
441
+ cfg = Config.from_yaml("config.yaml")
442
+ summary = pipeline.run(cfg, "exp1") # synth + train + evaluate
443
+
444
+ enh = Enhancer.load("runs/exp1") # model + stats + config together
445
+ clean = enh.enhance_file("noisy.wav", "enhanced.wav")
446
+ result = enh.enhance_folder("noisy/", "clean/", report=True)
447
+ print(result, result.mean_reduction_db())
448
+ ```
449
+
450
+ The model is loaded once for the whole tree, and the result is a
451
+ `kudio.EnhanceFolderResult` — the same shape `kudio.convert_folder` returns, so
452
+ "I processed a folder" has one answer whatever did the processing.
453
+
454
+ A trained run also drops straight into kudio's comparison table, beside the
455
+ statistical methods:
456
+
457
+ ```python
458
+ import kudio
459
+ kudio.compare_enhancers(y, sr, ['logmmse', ('exp1', enh.enhance)],
460
+ reference=clean)
461
+ ```
462
+
463
+ `Enhancer.load` reads the model, its normalisation statistics **and** the STFT
464
+ geometry that produced them from the same run directory, so inference can never
465
+ silently disagree with training.
466
+
467
+ ### What a run directory holds
468
+
469
+ ```
470
+ runs/exp1/
471
+ ├── config.yaml # the experiment, as it was trained
472
+ ├── ddae.pt # the weights: <model.name>.pt
473
+ ├── stats.npz # the Standardizer the features went through
474
+ ├── history.json # the curves (and history.png with matplotlib)
475
+ ├── train.json val.json test.json manifest.json
476
+ └── report.csv # after evaluate
477
+ ```
478
+
479
+ The `.pt` file is a plain dictionary — a format tag, the architecture and
480
+ target it was trained as, and a `state_dict` — read back with
481
+ `torch.load(..., weights_only=True)`. Nothing in it is a pickled class, so
482
+ opening a run somebody sent you cannot run their code, and `Enhancer.load`
483
+ rebuilds the network from `config.yaml` before pouring the weights in. It is
484
+ also the best epoch, always: training checkpoints whenever the monitored loss
485
+ improves and puts those weights back into the model when it stops.
486
+
487
+ Set `train.seed` (or just `data.seed`) and the initial weights, the dropout
488
+ masks and the order of the batches all come from it, so on the CPU a run
489
+ repeats to the last digit. Some GPU kernels are not deterministic, so there
490
+ it repeats closely rather than exactly.
491
+
492
+ ## Layout
493
+
494
+ ```
495
+ docs/
496
+ ├── images/workflow.png # the README figure
497
+ └── workflow.html # the same diagram, interactive
498
+ src/kudioenhance/
499
+ ├── config.py # typed dataclasses, YAML in/out, run paths
500
+ ├── data.py # mixing, manifests, splits, training sets
501
+ ├── datasets.py # the training set as torch sees it: held or streamed
502
+ ├── features.py # spectrogram / context stacking / windows / Standardizer
503
+ ├── models/
504
+ │ ├── registry.py # name -> builder + data layout
505
+ │ ├── dense.py # ddae
506
+ │ ├── recurrent.py # blstm
507
+ │ ├── convolutional.py # conv_ae
508
+ │ ├── crn.py # crn
509
+ │ └── unet.py # unet
510
+ ├── train.py # the training loop: Adam, checkpoints, early stopping
511
+ ├── checkpoint.py # the .pt format
512
+ ├── inference.py # Enhancer
513
+ ├── evaluate.py # per-file scoring + CSV report
514
+ ├── pipeline.py # the three stages
515
+ └── cli.py # kudioenhance
516
+ ```
517
+
518
+ Model builders return plain `torch.nn.Module`s; `train.py` owns the
519
+ optimiser, the loss and the loop. That keeps architectures inspectable without
520
+ committing to an optimisation setup.
521
+
522
+ ## Tests
523
+
524
+ From a checkout, with the development extras:
525
+
526
+ ```bash
527
+ git clone https://github.com/recklight/KudioEnhance.git
528
+ cd KudioEnhance
529
+ pip install -e ".[dev]"
530
+ pytest -q
531
+ ```
532
+
533
+ 229 tests. The suite builds a tiny synthetic corpus in a temp directory and runs
534
+ the whole pipeline — mix, train one epoch, enhance, score — in seconds. Tests
535
+ that need PyTorch ask for it by name and skip cleanly when it is not
536
+ installed; the other 105 still run.
537
+
538
+ The mask tests check the *formula*, not just that it runs: all-speech gives 1,
539
+ all-noise gives 0, equal power gives 1/√2, and an oracle mask has to actually
540
+ improve SI-SDR. Those hold or the target is wrong, whatever the loss curve
541
+ says. The architecture tests work the same way: change any frame after *t*
542
+ and `crn`'s output up to *t* has to stay the same bit for bit, while
543
+ `unet`'s has to move, because its description says it is non-causal. And the
544
+ training sets: the in-memory one has to hand back the stacked matrix's rows
545
+ bit for bit, so does a streamed pass in manifest order, and a shuffled epoch
546
+ has to be every example exactly once, in the same order again from the same
547
+ seed. The two modes have to normalise with the same statistics, to the bit.
548
+
549
+ ## Known limits
550
+
551
+ - A streamed epoch reads and transforms its files in the training process,
552
+ one at a time, between batches. There are no loader worker processes, so a
553
+ GPU can end up waiting on the CPU; an in-memory run pays that cost once.
554
+ - Magnitude-only enhancement: the phase is the noisy input's. Phase-aware or
555
+ time-domain models are a different architecture family.
556
+ - Sequence models enhance a whole file in one pass. For `crn` and `unet` that
557
+ means a feature map per channel per bin for every frame: about half a
558
+ gigabyte per minute of 16 kHz audio at the default widths, so split long
559
+ recordings before enhancing them.
560
+ - The `irm` target needs the noise, and takes it as `noisy - reference` in the
561
+ time domain. That is exact for anything `kudio.Synthesizer` mixed, and wrong
562
+ for a corpus whose noisy and clean files are separate recordings rather than
563
+ a sum. In a reverberant dataset the reference has to be the reverberant
564
+ target, or the room's tail is handed to the noise -- see
565
+ `reverberant_target` above.
566
+
567
+ ### Since 0.2.0
568
+
569
+ The models are **native PyTorch**; 0.1 was TensorFlow and Keras 3. The configs
570
+ are unchanged — `train.device` and `train.seed` are new and optional — and so
571
+ are the architectures, down to Keras's initialisation, BatchNorm momentum and
572
+ LSTM forget-gate bias, so a config tuned on 0.1 keeps its meaning on 0.2 —
573
+ though not its exact numbers, since the two frameworks' kernels differ.
574
+
575
+ The weights are not. A run directory trained by 0.1 holds `ddae.keras` and no
576
+ `ddae.pt`, and `Enhancer.load` says so and asks for a retrain rather than
577
+ reporting a missing file. The config and the frozen splits in it can be
578
+ reused as they are:
579
+
580
+ ```bash
581
+ kudioenhance train -c runs/exp1/config.yaml -n exp1
582
+ ```
583
+
584
+ `fit` returns the curves as a plain dict instead of a Keras `History`, and
585
+ `compile_model` is a deprecated no-op kept so 0.1-era scripts that call
586
+ `fit(compile_model(...))` still run. `build_callbacks` is gone, and importing
587
+ it fails: `fit` does the checkpointing, the early stopping and the
588
+ learning-rate halving itself, so code that built Keras callbacks for
589
+ `model.fit` calls `kudioenhance.train.fit` instead.
590
+
591
+ `train.batch_size` has to be 2 or more for `ddae`, and training says so before
592
+ it reads any audio; a `ddae` training set of a single frame is refused too.
593
+ Its BatchNorm takes a variance over the batch, and one example has none. 0.1
594
+ accepted a batch size of 1, but Keras normalised each unit to a constant
595
+ there, so nothing below the last BatchNorm ever trained. The sequence models
596
+ still train on a batch of one window.
597
+
598
+ The normalisation statistics are now summed in float64 in memory as well as
599
+ streamed, so the same training set gives a `stats.npz` a little different
600
+ from 0.1's: a few parts in 10⁵ on an hour of audio, less on a smaller set.
601
+
602
+ Training goes through `build_dataset` instead of `build_arrays`, so a
603
+ frame-wise model's context is no longer stacked for the whole set in memory;
604
+ the run is the same to the last digit. `fit` takes the dataset in place of
605
+ `x` with `y=None`, and still takes arrays. `train.streaming` is new, and
606
+ `train.shuffle_buffer`, which was in the config but read by nothing, now
607
+ sizes the streamed shuffle — and only that.
608
+
609
+ Two architectures are new, `crn` and `unet`, and `model.units` now defaults
610
+ to `null`, meaning the architecture's own widths. A config that sets `units`
611
+ builds what it did, and so does one that left it out: `ddae`, `blstm` and
612
+ `conv_ae` still default to `[1024, 1024, 1024]`. Code that reads
613
+ `cfg.model.units` directly can now find `None` there;
614
+ `kudioenhance.models.resolve_units(cfg)` returns a copy with the widths
615
+ spelled out.
616
+
617
+ ### Since 3.5.0
618
+
619
+ `Pair`, `save_manifest`, `load_manifest` and `split_pairs` now come from
620
+ **kudio** — nothing in them was specific to denoising. The JSON on disk is
621
+ unchanged and the names are still importable from `kudioenhance.data`, but
622
+ kudio's `split_pairs` is stricter: `val_split + test_split >= 1.0` raises
623
+ instead of quietly handing everything to training.
624
+
625
+ ## Related
626
+
627
+ - **[kudio](https://pypi.org/project/kudio/)** — the audio toolkit underneath.
628
+ - **[KudioStudio](https://pypi.org/project/kudiostudio/)** — desktop workbench
629
+ for the same toolkit. With this package installed alongside it
630
+ (`pip install "kudiostudio[enhance]"`), its Enhance panel loads the run
631
+ directories produced here, so you can listen to a model's output and score
632
+ it interactively instead of only reading the CSV.
633
+
634
+ ## Licence
635
+
636
+ MIT — see [LICENSE.txt](https://github.com/recklight/KudioEnhance/blob/master/LICENSE.txt).