aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDjshinshin <129614060+Djshinshin@users.noreply.github.com>2026-08-14 01:32:43 +0800
committerDjshinshin <129614060+Djshinshin@users.noreply.github.com>2026-08-14 01:32:43 +0800
commit46c09a1f9337fb5b254ff54b630e01eee4c992c4 (patch)
tree7d9f2f847b4a424fa865ef1124c83652bd803b58
parente121224ba49630846e3a4dcbdfdccb74d637842d (diff)
downloadapollo-gfx803-46c09a1f9337fb5b254ff54b630e01eee4c992c4.tar.gz
Address inference review feedback
-rw-r--r--.github/workflows/cpu-unit-tests.yml25
-rw-r--r--MACOS_ARM64.md17
-rw-r--r--README.md12
-rw-r--r--inference.py52
-rw-r--r--tests/test_inference.py78
5 files changed, 160 insertions, 24 deletions
diff --git a/.github/workflows/cpu-unit-tests.yml b/.github/workflows/cpu-unit-tests.yml
new file mode 100644
index 0000000..4248fbb
--- /dev/null
+++ b/.github/workflows/cpu-unit-tests.yml
@@ -0,0 +1,25 @@
+name: CPU unit tests
+
+on:
+ pull_request:
+ push:
+ branches: [main]
+
+jobs:
+ unit-tests:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.10"
+ cache: pip
+ - name: Install CPU test dependencies
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install torch==2.11.0 --index-url https://download.pytorch.org/whl/cpu
+ python -m pip install numpy==1.26.4 huggingface-hub==1.27.0 soundfile==0.14.0
+ - name: Compile and run unit tests
+ run: |
+ python -m py_compile inference.py tests/test_inference.py
+ python -m unittest discover -s tests -v
diff --git a/MACOS_ARM64.md b/MACOS_ARM64.md
index e379e18..6802116 100644
--- a/MACOS_ARM64.md
+++ b/MACOS_ARM64.md
@@ -27,8 +27,12 @@ python inference.py \
```
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:
+`JusperLee/Apollo` `pytorch_model.bin` from Hugging Face. Custom checkpoints
+must be existing local files; arbitrary remote repositories are rejected
+because the upstream loader uses PyTorch deserialization. Only use local
+checkpoints from sources you trust. The official checkpoint used for local
+validation had this SHA-256 digest (recorded for reproducibility, not enforced
+as a gate so that future official updates remain possible):
```text
99d9af7f1ff20e63c393035513a655392818d66b4d7fc23d658175c1f15e8d76
@@ -41,8 +45,8 @@ 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 |
+| MPS | 5.78 s | 412.0 MiB | 4.83 GiB |
+| CPU | 316.46 s | 3.76 GiB | 3.27 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
@@ -60,7 +64,10 @@ correlation of `0.999999991468`. The input SHA-256 remained unchanged:
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.
+- Apollo validates sample rate, basic shape, and finite samples on CPU before
+ downloading the checkpoint or moving the input to an accelerator.
+- Apollo expects 44.1 kHz audio. Input and output paths must not identify the
+ same file, including through a hard link.
## Known limitations
diff --git a/README.md b/README.md
index 9e3cb02..f0a2181 100644
--- a/README.md
+++ b/README.md
@@ -82,11 +82,13 @@ python inference.py \
--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.
+`--device=auto` prefers CUDA, then Apple Silicon MPS, and finally CPU. The
+default downloads the official `JusperLee/Apollo` checkpoint from Hugging Face.
+For a custom checkpoint, `--checkpoint` accepts only an existing local file;
+arbitrary remote repositories are rejected because the upstream checkpoint
+loader deserializes the file with PyTorch. See
+[Apple Silicon macOS notes](MACOS_ARM64.md) for a tested MPS setup and current
+limitations.
## 📊 Results
diff --git a/inference.py b/inference.py
index ee14325..720d214 100644
--- a/inference.py
+++ b/inference.py
@@ -11,6 +11,8 @@ import look2hear.models
SAMPLE_RATE = 44_100
DEVICE_CHOICES = ("auto", "cuda", "mps", "cpu")
+OFFICIAL_CHECKPOINT = "JusperLee/Apollo"
+LOCAL_CHECKPOINT_SUFFIXES = {".bin", ".ckpt", ".pt", ".pth", ".safetensors"}
def select_device(requested):
@@ -30,24 +32,47 @@ def select_device(requested):
def resolve_checkpoint(reference):
- """Resolve a local checkpoint path or download one from Hugging Face."""
+ """Resolve the official remote checkpoint or an existing local file."""
+ reference = str(reference)
+ if reference == OFFICIAL_CHECKPOINT:
+ return Path(
+ hf_hub_download(
+ repo_id=OFFICIAL_CHECKPOINT, filename="pytorch_model.bin"
+ )
+ )
+
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")
+ if path.exists():
+ raise IsADirectoryError(f"Checkpoint must be a file, not a directory: {path}")
+ if (
+ path.suffix.lower() in LOCAL_CHECKPOINT_SUFFIXES
+ or path.is_absolute()
+ or reference.startswith(("./", "../", "~/"))
+ ):
+ raise FileNotFoundError(f"Local checkpoint not found: {path}")
+ raise ValueError(
+ "Unsupported checkpoint source. Use JusperLee/Apollo or an existing "
+ "local checkpoint file."
)
-def load_audio(file_path, device):
+def load_audio(file_path):
audio, sample_rate = sf.read(
file_path, dtype="float32", always_2d=True
)
+ if sample_rate != SAMPLE_RATE:
+ raise ValueError(
+ f"Apollo expects {SAMPLE_RATE} Hz audio, got {sample_rate} Hz."
+ )
+ if audio.shape[0] == 0 or audio.shape[1] == 0:
+ raise ValueError("Input audio must contain at least one sample and channel.")
+ if not np.isfinite(audio).all():
+ raise ValueError("Input audio contains NaN or infinite values.")
# 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
+ return audio, sample_rate
def save_audio(file_path, audio, sample_rate):
@@ -62,14 +87,13 @@ def run_inference(input_wav, output_wav, checkpoint, requested_device="auto"):
output_path = Path(output_wav)
if input_path.resolve() == output_path.resolve():
raise ValueError("Input and output paths must be different.")
+ if output_path.exists() and input_path.samefile(output_path):
+ raise ValueError("Input and output paths must not reference the same file.")
device = select_device(requested_device)
+ test_data, sample_rate = load_audio(input_path)
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."
- )
+ test_data = test_data.to(device)
model = look2hear.models.BaseModel.from_pretrain(
str(checkpoint_path),
@@ -94,8 +118,8 @@ def main():
)
parser.add_argument(
"--checkpoint",
- default="JusperLee/Apollo",
- help="Local checkpoint path or Hugging Face repository ID",
+ default=OFFICIAL_CHECKPOINT,
+ help="JusperLee/Apollo or an existing local checkpoint file",
)
parser.add_argument(
"--device",
diff --git a/tests/test_inference.py b/tests/test_inference.py
index 3385184..7e0e64f 100644
--- a/tests/test_inference.py
+++ b/tests/test_inference.py
@@ -1,4 +1,5 @@
import hashlib
+import os
from pathlib import Path
import tempfile
import unittest
@@ -52,6 +53,44 @@ class DeviceSelectionTests(unittest.TestCase):
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)
@@ -95,6 +134,45 @@ class InferenceTests(unittest.TestCase):
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()