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
|
import hashlib
import os
from pathlib import Path
import tempfile
import unittest
from unittest import mock
import numpy as np
import soundfile as sf
import torch
import inference
class IdentityModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.anchor = torch.nn.Parameter(torch.zeros(()))
self.input_device = None
self.input_devices = []
self.input_lengths = []
self.input_batch_sizes = []
def forward(self, audio):
self.input_device = audio.device
self.input_devices.append(audio.device)
self.input_lengths.append(audio.shape[-1])
self.input_batch_sizes.append(audio.shape[0])
return audio
class ShortOutputModel(IdentityModel):
def forward(self, audio):
super().forward(audio)
return audio[..., :-1]
class DegradedEdgesModel(IdentityModel):
"""Identity, except both edges of every input come back wrong.
This mimics the real model, whose output within ~0.5 s of either edge of
its input differs from a well-placed prediction — mildly at the start,
strongly at the end. The marker is infinity so nothing wrong can hide:
with enough chunk padding it is sliced away before the crossfade
arithmetic, and with none it floods through the crossfades.
"""
MARKER = float("inf")
def __init__(self, degraded_samples):
super().__init__()
self.degraded_samples = degraded_samples
def forward(self, audio):
audio = super().forward(audio).clone()
audio[..., : self.degraded_samples] = self.MARKER
audio[..., -self.degraded_samples :] = self.MARKER
return audio
class DeviceSelectionTests(unittest.TestCase):
@mock.patch.object(torch.backends.mps, "is_available", return_value=True)
@mock.patch.object(torch.cuda, "is_available", return_value=True)
def test_auto_prefers_cuda_over_mps(self, cuda_available, mps_available):
self.assertEqual(inference.select_device("auto"), torch.device("cuda"))
@mock.patch.object(torch.backends.mps, "is_available", return_value=True)
@mock.patch.object(torch.cuda, "is_available", return_value=False)
def test_auto_uses_mps_when_cuda_is_unavailable(
self, cuda_available, mps_available
):
self.assertEqual(inference.select_device("auto"), torch.device("mps"))
@mock.patch.object(torch.backends.mps, "is_available", return_value=False)
@mock.patch.object(torch.cuda, "is_available", return_value=False)
def test_auto_falls_back_to_cpu(self, cuda_available, mps_available):
self.assertEqual(inference.select_device("auto"), torch.device("cpu"))
@mock.patch.object(torch.cuda, "is_available", return_value=False)
def test_explicit_unavailable_cuda_fails(self, cuda_available):
with self.assertRaisesRegex(RuntimeError, "CUDA was requested"):
inference.select_device("cuda")
@mock.patch.object(torch.backends.mps, "is_available", return_value=False)
def test_explicit_unavailable_mps_fails(self, mps_available):
with self.assertRaisesRegex(RuntimeError, "MPS was requested"):
inference.select_device("mps")
class InferenceTests(unittest.TestCase):
def test_official_checkpoint_downloads_from_trusted_repository(self):
with mock.patch.object(
inference,
"hf_hub_download",
return_value="/cache/pytorch_model.bin",
) as download:
path = inference.resolve_checkpoint(inference.OFFICIAL_CHECKPOINT)
self.assertEqual(path, Path("/cache/pytorch_model.bin"))
download.assert_called_once_with(
repo_id=inference.OFFICIAL_CHECKPOINT,
filename="pytorch_model.bin",
)
def test_existing_local_checkpoint_is_accepted(self):
with tempfile.TemporaryDirectory() as directory:
checkpoint = Path(directory) / "model.pth"
checkpoint.touch()
self.assertEqual(inference.resolve_checkpoint(checkpoint), checkpoint)
def test_arbitrary_hugging_face_repository_is_rejected(self):
for reference in ("someone/model", "someone/model.v2"):
with self.subTest(reference=reference), mock.patch.object(
inference, "hf_hub_download"
) as download:
with self.assertRaisesRegex(ValueError, "Unsupported checkpoint"):
inference.resolve_checkpoint(reference)
download.assert_not_called()
def test_missing_local_checkpoint_has_clear_error(self):
with self.assertRaisesRegex(FileNotFoundError, "Local checkpoint not found"):
inference.resolve_checkpoint("models/missing.pth")
def test_checkpoint_directory_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
with self.assertRaisesRegex(IsADirectoryError, "must be a file"):
inference.resolve_checkpoint(directory)
def test_cpu_inference_preserves_input_and_audio_shape(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
input_path = root / "input.wav"
output_path = root / "output.wav"
checkpoint_path = root / "checkpoint.bin"
checkpoint_path.touch()
samples = np.linspace(-0.5, 0.5, inference.SAMPLE_RATE)
stereo = np.stack((samples, -samples), axis=1).astype(np.float32)
sf.write(input_path, stereo, inference.SAMPLE_RATE, subtype="FLOAT")
input_digest = hashlib.sha256(input_path.read_bytes()).hexdigest()
model = IdentityModel()
with mock.patch.object(
inference.look2hear.models.BaseModel,
"from_pretrain",
return_value=model,
):
device = inference.run_inference(
input_path,
output_path,
checkpoint_path,
requested_device="cpu",
)
output, sample_rate = sf.read(
output_path, dtype="float32", always_2d=True
)
self.assertEqual(device, torch.device("cpu"))
self.assertEqual(model.input_device, torch.device("cpu"))
self.assertEqual(sample_rate, inference.SAMPLE_RATE)
self.assertEqual(output.shape, stereo.shape)
self.assertTrue(np.isfinite(output).all())
self.assertEqual(
hashlib.sha256(input_path.read_bytes()).hexdigest(), input_digest
)
def test_chunked_cpu_inference_preserves_samples_and_limits_chunk_size(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
input_path = root / "input.wav"
output_path = root / "output.wav"
checkpoint_path = root / "checkpoint.bin"
checkpoint_path.touch()
sample_count = int(inference.SAMPLE_RATE * 1.8)
samples = np.linspace(-0.5, 0.5, sample_count, dtype=np.float32)
stereo = np.stack((samples, -samples), axis=1)
sf.write(input_path, stereo, inference.SAMPLE_RATE, subtype="FLOAT")
input_digest = hashlib.sha256(input_path.read_bytes()).hexdigest()
model = IdentityModel()
with mock.patch.object(
inference.look2hear.models.BaseModel,
"from_pretrain",
return_value=model,
):
device = inference.run_inference(
input_path,
output_path,
checkpoint_path,
requested_device="cpu",
chunk_seconds=0.5,
overlap_seconds=0.1,
chunk_batch_size=2,
)
output, sample_rate = sf.read(
output_path, dtype="float32", always_2d=True
)
self.assertEqual(device, torch.device("cpu"))
self.assertEqual(sample_rate, inference.SAMPLE_RATE)
self.assertEqual(output.shape, stereo.shape)
np.testing.assert_allclose(output, stereo, rtol=0, atol=1e-6)
self.assertGreater(len(model.input_lengths), 1)
self.assertEqual(
set(model.input_lengths), {int(inference.SAMPLE_RATE * 0.5)}
)
self.assertEqual(model.input_batch_sizes, [2, 2, 1])
self.assertEqual(set(model.input_devices), {torch.device("cpu")})
self.assertEqual(
hashlib.sha256(input_path.read_bytes()).hexdigest(), input_digest
)
def test_chunk_padding_discards_degraded_input_edges(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
input_path = root / "input.wav"
output_path = root / "output.wav"
checkpoint_path = root / "checkpoint.bin"
checkpoint_path.touch()
sample_count = int(inference.SAMPLE_RATE * 1.8)
samples = np.linspace(-0.5, 0.5, sample_count, dtype=np.float32)
stereo = np.stack((samples, -samples), axis=1)
sf.write(input_path, stereo, inference.SAMPLE_RATE, subtype="FLOAT")
# 0.5 s chunks, 0.1 s overlap. The model degrades 0.05 s at
# each edge of its input, and chunk padding of the same 0.05 s
# discards exactly those samples.
degraded_seconds = 0.05
degraded_samples = int(degraded_seconds * inference.SAMPLE_RATE)
model = DegradedEdgesModel(
degraded_samples=degraded_samples
)
with mock.patch.object(
inference.look2hear.models.BaseModel,
"from_pretrain",
return_value=model,
):
inference.run_inference(
input_path,
output_path,
checkpoint_path,
requested_device="cpu",
chunk_seconds=0.5,
overlap_seconds=0.1,
chunk_pad_seconds=degraded_seconds,
)
output, _ = sf.read(output_path, dtype="float32", always_2d=True)
# Padding is real neighboring audio, so the first chunk starts
# at the file start and its degraded head is kept because there
# is nothing before the file to pad with. The check therefore
# starts after the file's first degraded_seconds. The same
# symmetry applies at the end of the file.
np.testing.assert_allclose(
output[degraded_samples:-degraded_samples],
stereo[degraded_samples:-degraded_samples],
rtol=0,
atol=1e-6,
)
def test_unpadded_chunks_leak_degraded_edges(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
input_path = root / "input.wav"
output_path = root / "output.wav"
checkpoint_path = root / "checkpoint.bin"
checkpoint_path.touch()
sample_count = int(inference.SAMPLE_RATE * 1.8)
samples = np.linspace(-0.5, 0.5, sample_count, dtype=np.float32)
stereo = np.stack((samples, -samples), axis=1)
sf.write(input_path, stereo, inference.SAMPLE_RATE, subtype="FLOAT")
# The same scenario with chunk padding off: the degraded edges
# reach the output through the overlap crossfades.
model = DegradedEdgesModel(
degraded_samples=int(0.05 * inference.SAMPLE_RATE)
)
with mock.patch.object(
inference.look2hear.models.BaseModel,
"from_pretrain",
return_value=model,
):
inference.run_inference(
input_path,
output_path,
checkpoint_path,
requested_device="cpu",
chunk_seconds=0.5,
overlap_seconds=0.1,
chunk_pad_seconds=0.0,
)
output, _ = sf.read(output_path, dtype="float32", always_2d=True)
self.assertFalse(np.isfinite(output).all())
def test_chunk_padding_wider_than_the_hop_reproduces_the_input(self):
"""
Regression test
`padded_start` was `start - chunk_pad_samples` for every chunk after
the first, which goes negative once the padding exceeds the hop, and
makes slicing index from the end of the file
The test reproduces the bug, it needs padding wider than the hop,
so the file has to hold at least two chunks: 0.5 s chunks with
a 0.1 s overlap leave a 0.4 s hop, and 0.5 s of padding exceeds it.
The second chunk starts at 0.4 s, giving `padded_start = -0.1 s`.
"""
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
input_path = root / "input.wav"
output_path = root / "output.wav"
checkpoint_path = root / "checkpoint.bin"
checkpoint_path.touch()
sample_count = int(inference.SAMPLE_RATE * 1.8)
samples = np.linspace(-0.5, 0.5, sample_count, dtype=np.float32)
stereo = np.stack((samples, -samples), axis=1)
sf.write(input_path, stereo, inference.SAMPLE_RATE, subtype="FLOAT")
model = IdentityModel()
with mock.patch.object(
inference.look2hear.models.BaseModel,
"from_pretrain",
return_value=model,
):
inference.run_inference(
input_path,
output_path,
checkpoint_path,
requested_device="cpu",
chunk_seconds=0.5,
overlap_seconds=0.1,
chunk_pad_seconds=0.5,
)
output, _ = sf.read(output_path, dtype="float32", always_2d=True)
np.testing.assert_allclose(output, stereo, rtol=0, atol=1e-6)
def test_short_input_uses_original_full_file_path(self):
audio = torch.zeros(1, 2, inference.SAMPLE_RATE // 4)
model = IdentityModel()
output = inference.run_model(
model,
audio,
torch.device("cpu"),
chunk_samples=inference.SAMPLE_RATE,
overlap_samples=inference.SAMPLE_RATE // 4,
)
self.assertEqual(model.input_lengths, [audio.shape[-1]])
self.assertTrue(torch.equal(output, audio))
def test_chunk_settings_reject_invalid_durations(self):
invalid_settings = (
(0, 0, "positive finite"),
(float("inf"), 0, "positive finite"),
(1, -0.1, "non-negative finite"),
(1, float("nan"), "non-negative finite"),
(1, 0.6, "half the chunk"),
)
for chunk_seconds, overlap_seconds, message in invalid_settings:
with self.subTest(
chunk_seconds=chunk_seconds, overlap_seconds=overlap_seconds
), self.assertRaisesRegex(ValueError, message):
inference.resolve_chunking(chunk_seconds, overlap_seconds)
def test_chunking_rejects_short_model_output(self):
audio = torch.zeros(1, 2, 100)
with self.assertRaisesRegex(RuntimeError, "shorter"):
inference.run_model(
ShortOutputModel(),
audio,
torch.device("cpu"),
chunk_samples=60,
overlap_samples=10,
)
def test_chunking_rejects_invalid_batch_size(self):
audio = torch.zeros(1, 2, 100)
for batch_size in (0, -1, 1.5, True):
with self.subTest(batch_size=batch_size), self.assertRaisesRegex(
ValueError, "positive integer"
):
inference.run_model(
IdentityModel(),
audio,
torch.device("cpu"),
chunk_samples=60,
overlap_samples=10,
chunk_batch_size=batch_size,
)
def test_invalid_batch_size_fails_before_checkpoint_download(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
input_path = root / "input.wav"
sf.write(
input_path,
np.zeros((100, 2), dtype=np.float32),
inference.SAMPLE_RATE,
)
with mock.patch.object(inference, "hf_hub_download") as download:
with self.assertRaisesRegex(ValueError, "positive integer"):
inference.run_inference(
input_path,
root / "output.wav",
inference.OFFICIAL_CHECKPOINT,
"cpu",
chunk_seconds=1,
overlap_seconds=0,
chunk_batch_size=0,
)
download.assert_not_called()
def test_refuses_to_overwrite_input(self):
path = Path("same.wav")
with self.assertRaisesRegex(ValueError, "must be different"):
inference.run_inference(path, path, "checkpoint.bin", "cpu")
def test_wrong_sample_rate_fails_before_download_or_device_transfer(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
input_path = root / "input.wav"
sf.write(input_path, np.zeros((100, 2), dtype=np.float32), 48_000)
with mock.patch.object(
inference, "hf_hub_download"
) as download, mock.patch.object(torch.Tensor, "to") as transfer:
with self.assertRaisesRegex(ValueError, "expects 44100 Hz"):
inference.run_inference(
input_path,
root / "output.wav",
inference.OFFICIAL_CHECKPOINT,
"cpu",
)
download.assert_not_called()
transfer.assert_not_called()
def test_refuses_hard_link_output_alias(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
input_path = root / "input.wav"
output_path = root / "output.wav"
sf.write(
input_path,
np.zeros((100, 2), dtype=np.float32),
inference.SAMPLE_RATE,
)
try:
os.link(input_path, output_path)
except OSError as error:
self.skipTest(f"hard links are unavailable: {error}")
with self.assertRaisesRegex(ValueError, "same file"):
inference.run_inference(
input_path, output_path, "checkpoint.bin", "cpu"
)
if __name__ == "__main__":
unittest.main()
|