diff options
| author | Djshinshin <129614060+Djshinshin@users.noreply.github.com> | 2026-08-13 23:57:35 +0800 |
|---|---|---|
| committer | Djshinshin <129614060+Djshinshin@users.noreply.github.com> | 2026-08-13 23:57:35 +0800 |
| commit | e121224ba49630846e3a4dcbdfdccb74d637842d (patch) | |
| tree | 0c37f448bea5c89b321fd1c830de8b01012696b6 | |
| parent | 6eec5c9ffae9a92f0c11352b28a53bd178728bf1 (diff) | |
| download | apollo-gfx803-e121224ba49630846e3a4dcbdfdccb74d637842d.tar.gz | |
Add device-agnostic inference support
| -rw-r--r-- | .gitignore | 7 | ||||
| -rw-r--r-- | MACOS_ARM64.md | 79 | ||||
| -rw-r--r-- | README.md | 11 | ||||
| -rw-r--r-- | inference.py | 125 | ||||
| -rw-r--r-- | requirements-macos-arm64.txt | 8 | ||||
| -rw-r--r-- | tests/test_inference.py | 100 |
6 files changed, 308 insertions, 22 deletions
@@ -1,2 +1,7 @@ *.pyc -*.DS_Store
\ No newline at end of file +*.DS_Store +.venv/ +/models/ +/smoke_test_output/ +/output.wav +/apollo_*_smoke.wav diff --git a/MACOS_ARM64.md b/MACOS_ARM64.md new file mode 100644 index 0000000..e379e18 --- /dev/null +++ b/MACOS_ARM64.md @@ -0,0 +1,79 @@ +# Apple Silicon macOS inference + +The upstream `look2hear.yml` records a Linux CUDA baseline with +`torch==2.0.0+cu118` and `torchaudio==2.0.1+cu118`; it cannot be installed +unchanged on macOS arm64. The MPS smoke test for this change used native arm64 +Python 3.10, PyTorch 2.11.0, and TorchAudio 2.11.0. The inference entry point +uses SoundFile for WAV I/O so that it works with both the older baseline and +newer TorchAudio releases whose I/O depends on TorchCodec. + +Create and activate an isolated environment, then install the macOS runtime +requirements: + +```bash +python3.10 -m venv .venv +source .venv/bin/activate +python -m pip install -r requirements-macos-arm64.txt +``` + +Run the repository's public six-second test WAV on MPS: + +```bash +python inference.py \ + --device=mps \ + --checkpoint=models/pytorch_model.bin \ + --in_wav=asserts/input_wav.wav \ + --out_wav=apollo_mps_smoke.wav +``` + +If `--checkpoint` is omitted, inference downloads the official +`JusperLee/Apollo` `pytorch_model.bin` from Hugging Face. The checkpoint used +for local validation had this SHA-256 digest: + +```text +99d9af7f1ff20e63c393035513a655392818d66b4d7fc23d658175c1f15e8d76 +``` + +## Local validation reference + +The public six-second WAV was tested on an Apple M3 with 24 GB unified memory +and macOS 27.0. These are reference measurements, not performance guarantees: + +| Device | End-to-end time | Maximum RSS | Peak memory footprint | +| --- | ---: | ---: | ---: | +| MPS | 5.71 s | 408.5 MiB | 5.57 GiB | +| CPU | 335.79 s | 3.75 GiB | 3.14 GiB | + +Both outputs were stereo, 44.1 kHz, six seconds long, and contained no NaN or +infinite values. Comparing the float32 CPU and MPS WAV outputs gave a maximum +absolute difference of `0.000249214470387`, RMSE of `2.02574076096e-05`, and +correlation of `0.999999991468`. The input SHA-256 remained unchanged: + +```text +3c9a053913c3016b493ddc0b92e21a4e682e8fb5f872dafc945154155bddf771 +``` + +## Device behavior + +- `auto` preserves CUDA as the first choice, then selects MPS, then CPU. +- `cuda`, `mps`, and `cpu` explicitly select one backend and fail clearly if + the requested accelerator is unavailable. +- The model and input are moved to the same device. Output is detached and + moved to CPU before it is written. +- Apollo expects 44.1 kHz audio. Input and output paths must be different. + +## Known limitations + +- MPS validation covered the public stereo, 44.1 kHz, six-second test WAV on + PyTorch 2.11.0. MPS operator support can vary with PyTorch and macOS versions. +- PyTorch 2.11.0 emitted non-fatal STFT/iSTFT output-resize deprecation warnings + during the MPS run. +- CUDA remains the first `auto` choice and follows the original inference + behavior, but CUDA was not hardware-tested on the Apple Silicon validation + machine. +- Training and dataset evaluation still contain CUDA-specific configuration; + this change only makes the public inference entry point device-agnostic. +- There is no long-audio chunking or crossfade in this change. Long inputs may + require substantially more memory. +- A successful technical smoke test is not a listening-quality review and does + not prove that information missing from a lossy source was truly recovered. @@ -76,9 +76,18 @@ python train.py --conf_dir=configs/apollo.yml To evaluate the Apollo model, run the following command: ```bash -python inference.py --in_wav=assets/input.wav --out_wav=assets/output.wav +python inference.py \ + --in_wav=asserts/input_wav.wav \ + --out_wav=output.wav \ + --device=auto ``` +`--device=auto` prefers CUDA, then Apple Silicon MPS, and finally CPU. Use +`--checkpoint=/path/to/pytorch_model.bin` for an existing local checkpoint; +otherwise the official `JusperLee/Apollo` checkpoint is downloaded from +Hugging Face. See [Apple Silicon macOS notes](MACOS_ARM64.md) for a tested MPS +setup and current limitations. + ## 📊 Results *Here, you can include a brief overview of the performance metrics or results that Apollo achieves using different bitrates* diff --git a/inference.py b/inference.py index 872c77c..ee14325 100644 --- a/inference.py +++ b/inference.py @@ -1,30 +1,115 @@ -import os -import torch -import torchaudio import argparse +from pathlib import Path + +from huggingface_hub import hf_hub_download +import numpy as np +import soundfile as sf +import torch + import look2hear.models -def load_audio(file_path): - audio, samplerate = torchaudio.load(file_path) - return audio.unsqueeze(0).cuda() # [1, 1, samples] -def save_audio(file_path, audio, samplerate=44100): - audio = audio.squeeze(0).cpu() - torchaudio.save(file_path, audio, samplerate) +SAMPLE_RATE = 44_100 +DEVICE_CHOICES = ("auto", "cuda", "mps", "cpu") -def main(input_wav, output_wav): - os.environ['CUDA_VISIBLE_DEVICES'] = "0" - model = look2hear.models.BaseModel.from_pretrain("JusperLee/Apollo", sr=44100, win=20, feature_dim=256, layer=6).cuda() - test_data = load_audio(input_wav) - with torch.no_grad(): - out = model(test_data) - save_audio(output_wav, out) +def select_device(requested): + """Resolve an inference device, preferring CUDA, then MPS, then CPU.""" + if requested == "auto": + if torch.cuda.is_available(): + return torch.device("cuda") + if torch.backends.mps.is_available(): + return torch.device("mps") + return torch.device("cpu") -if __name__ == "__main__": + if requested == "cuda" and not torch.cuda.is_available(): + raise RuntimeError("CUDA was requested but is not available.") + if requested == "mps" and not torch.backends.mps.is_available(): + raise RuntimeError("MPS was requested but is not available.") + return torch.device(requested) + + +def resolve_checkpoint(reference): + """Resolve a local checkpoint path or download one from Hugging Face.""" + path = Path(reference).expanduser() + if path.is_file(): + return path + if path.suffix: + raise FileNotFoundError(f"Checkpoint not found: {path}") + return Path( + hf_hub_download(repo_id=reference, filename="pytorch_model.bin") + ) + + +def load_audio(file_path, device): + audio, sample_rate = sf.read( + file_path, dtype="float32", always_2d=True + ) + # SoundFile uses [samples, channels]; Apollo uses [batch, channels, samples]. + audio = torch.from_numpy(np.ascontiguousarray(audio.T)).unsqueeze(0) + return audio.to(device), sample_rate + + +def save_audio(file_path, audio, sample_rate): + output_path = Path(file_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + audio = audio.detach().squeeze(0).to("cpu").numpy().T + sf.write(output_path, audio, sample_rate, subtype="FLOAT") + + +def run_inference(input_wav, output_wav, checkpoint, requested_device="auto"): + input_path = Path(input_wav) + output_path = Path(output_wav) + if input_path.resolve() == output_path.resolve(): + raise ValueError("Input and output paths must be different.") + + device = select_device(requested_device) + checkpoint_path = resolve_checkpoint(checkpoint) + test_data, sample_rate = load_audio(input_path, device) + if sample_rate != SAMPLE_RATE: + raise ValueError( + f"Apollo expects {SAMPLE_RATE} Hz audio, got {sample_rate} Hz." + ) + + model = look2hear.models.BaseModel.from_pretrain( + str(checkpoint_path), + sr=SAMPLE_RATE, + win=20, + feature_dim=256, + layer=6, + ).to(device).eval() + with torch.inference_mode(): + output = model(test_data) + save_audio(output_path, output, sample_rate) + return device + + +def main(): parser = argparse.ArgumentParser(description="Audio Inference Script") - parser.add_argument("--in_wav", type=str, required=True, help="Path to input wav file") - parser.add_argument("--out_wav", type=str, required=True, help="Path to output wav file") + parser.add_argument( + "--in_wav", type=Path, required=True, help="Path to input WAV file" + ) + parser.add_argument( + "--out_wav", type=Path, required=True, help="Path to output WAV file" + ) + parser.add_argument( + "--checkpoint", + default="JusperLee/Apollo", + help="Local checkpoint path or Hugging Face repository ID", + ) + parser.add_argument( + "--device", + choices=DEVICE_CHOICES, + default="auto", + help="Inference device (auto prefers CUDA, then MPS, then CPU)", + ) args = parser.parse_args() - main(args.in_wav, args.out_wav) + device = run_inference( + args.in_wav, args.out_wav, args.checkpoint, args.device + ) + print(f"Inference completed on {device}: {args.out_wav}") + + +if __name__ == "__main__": + main() diff --git a/requirements-macos-arm64.txt b/requirements-macos-arm64.txt new file mode 100644 index 0000000..1883e34 --- /dev/null +++ b/requirements-macos-arm64.txt @@ -0,0 +1,8 @@ +# Native Apple Silicon inference/smoke-test environment. +# The upstream look2hear.yml is a linux-64 CUDA environment. +torch==2.11.0 +torchaudio==2.11.0 +numpy==1.26.4 +huggingface-hub==1.27.0 +omegaconf==2.3.0 +soundfile==0.14.0 diff --git a/tests/test_inference.py b/tests/test_inference.py new file mode 100644 index 0000000..3385184 --- /dev/null +++ b/tests/test_inference.py @@ -0,0 +1,100 @@ +import hashlib +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 + + def forward(self, audio): + self.input_device = audio.device + 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_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_refuses_to_overwrite_input(self): + path = Path("same.wav") + with self.assertRaisesRegex(ValueError, "must be different"): + inference.run_inference(path, path, "checkpoint.bin", "cpu") + + +if __name__ == "__main__": + unittest.main() |
