Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ is a Fréchet distance; lower is better.

## Leaderboard

All models are evaluated with the same SLIP protocol. Lower is better.
The leaderboard reports the public benchmark scores. The paper reports framewise Slerp scores for its own set of
eleven candidates. Lower is better.

| VAE | Frame rate (Hz) | Latent dim | SeedTTS-Eval | LibriSpeech-PC test-clean |
| --- | ---: | ---: | ---: | ---: |
Expand Down Expand Up @@ -65,7 +66,8 @@ slip datasets download-librispeech-pc \

## Evaluation

Connect a VAE through an adapter, point a YAML config to the adapter and dataset manifest, then run:
Connect a VAE through an adapter, point a YAML config to the adapter and dataset manifest, then run. By default,
the CLI uses the paper settings: framewise Slerp and sampling seed `1234`.

```bash
slip check-adapter configs/my_vae.yaml
Expand All @@ -74,13 +76,13 @@ slip report runs/my_vae
```

See [`examples/README.md`](examples/README.md) for the adapter template, config fields, and a complete Semantic-VAE
example. Interrupted evaluations can be resumed by running the same command again.
example. Interrupted framewise evaluations can be resumed by running the same command again. To resume a run
created by the earlier trajectory-level CLI, use `slip evaluate configs/my_vae.yaml --interpolation trajectory --seed 1234`.

## Metric

SLIP uses exact cross-utterance cosine top-10 retrieval, deterministic neighbor sampling, trajectory-level Slerp at
`alpha=0.5`, and HuBERT Base layer 9 features. The fixed settings are listed in
[`docs/slip.md`](docs/slip.md).
The paper uses framewise Slerp with sampling seed `1234`. See [`docs/slip.md`](docs/slip.md) for the run setup
and the trajectory-level mode used by the earlier CLI.

<!--
## Acknowledgements
Expand Down
32 changes: 30 additions & 2 deletions docs/slip.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# SLIP
# SLIP scoring protocols

For each dataset split:

1. Encode every utterance and discard padded latent frames.
2. Build a bank of all latent frames in the split.
3. For each source frame, exclude frames from the same utterance and retrieve the exact cosine top 10.
4. Sample one of the ten neighbors with the fixed per-item seed.
5. Apply one Slerp angle to the full latent trajectory at `alpha=0.5`, then decode it.
5. Apply Slerp at `alpha=0.5`, then decode the entire perturbed sequence.
6. Resample real and decoded speech to 16 kHz.
7. Extract HuBERT Base hidden layer 9 and mean-pool valid frames.
8. Compute Gaussian Fréchet distance with `1e-6` covariance regularization.
Expand All @@ -19,3 +19,31 @@ facebook/hubert-base-ls960@cbd73bd518689ab98a9370c74165f4875ccd97d5

Neighbor search is exact and chunked to limit memory use. Batch and chunk sizes may be adjusted without changing the
metric. Invalid adapter output, insufficient cross-utterance frames, or a missing HuBERT checkpoint stops the run.

## Trajectory and framewise runs

The CLI defaults to computing one Slerp angle for each pair of latent frames, as in the paper.
The input manifest defines the eligible neighbor pools. The repository's SeedTTS-Eval preparation
places English and Mandarin in separate pools, and the CLI computes one Fréchet distance over all prepared items
for each seed.

The paper uses seed `1234` on SeedTTS-Eval and LibriSpeech-PC test-clean. Point the config at the desired benchmark's
prepared target-audio manifest and a fresh output directory:

```bash
slip evaluate configs/my_vae.yaml
```

The run lock records the sampling seed and identifies framewise runs so scores and intermediate results cannot
be mixed with trajectory caches. Select a separate output directory for each benchmark and adapter. Exact historical
scores also depend on the input manifest, VAE checkpoint, and historical sampling implementation. The public
leaderboard contains its own benchmark scores.

To resume a trajectory-level evaluation started with the earlier CLI, use its existing output directory and run:

```bash
slip evaluate configs/my_vae.yaml --interpolation trajectory --seed 1234
```

The Python API retains its trajectory-level default for compatibility. To select the paper settings when calling
`SlipEvaluator` or `evaluate` directly, pass `settings=SlipSettings(interpolation="framewise", seed=1234)`.
14 changes: 14 additions & 0 deletions src/slip_audio/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from slip_audio.data.manifest import load_manifest
from slip_audio.data.registry import download_librispeech, prepare_seedtts
from slip_audio.pipeline import SlipEvaluator
from slip_audio.settings import SLIP_SETTINGS, SlipSettings
from slip_audio.types import AudioBatch


Expand Down Expand Up @@ -96,6 +97,7 @@ def command_evaluate(args: argparse.Namespace) -> None:
neighbor_chunk_size=int(runtime.get("neighbor_chunk_size", 256)),
local_files_only=bool(runtime.get("local_files_only", False)),
offload_vae_during_search=bool(runtime.get("offload_vae_during_search", True)),
settings=SlipSettings(seed=args.seed, interpolation=args.interpolation),
).run()
print(f"SLIP={result.score:.8f}")
print(f"Metrics={result.metrics_path}")
Expand Down Expand Up @@ -136,6 +138,18 @@ def build_parser() -> argparse.ArgumentParser:

evaluate = commands.add_parser("evaluate", help="Run or resume SLIP")
evaluate.add_argument("config")
evaluate.add_argument(
"--interpolation",
choices=("framewise", "trajectory"),
default="framewise",
help="Slerp angle scope (default: %(default)s). Use trajectory to resume older benchmark runs.",
)
evaluate.add_argument(
"--seed",
type=int,
default=SLIP_SETTINGS.seed,
help="Base neighbor-sampling seed (default: %(default)s).",
)
evaluate.set_defaults(func=command_evaluate)

report = commands.add_parser("report", help="Print a completed result")
Expand Down
31 changes: 24 additions & 7 deletions src/slip_audio/core/interpolation.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
from __future__ import annotations

from typing import Literal

import torch
import torch.nn.functional as F

Interpolation = Literal["trajectory", "framewise"]


def slerp(
source: torch.Tensor,
neighbor: torch.Tensor,
*,
alpha: float = 0.5,
eps: float = 1e-6,
mode: Interpolation = "trajectory",
) -> torch.Tensor:
"""Apply trajectory-level Slerp to equal ``[B, C, T]`` latent tensors."""
"""Apply Slerp to equal ``[B, C, T]`` latent tensors."""

if source.shape != neighbor.shape or source.ndim != 3:
raise ValueError(
Expand All @@ -20,17 +25,29 @@ def slerp(
if not 0.0 <= float(alpha) <= 1.0:
raise ValueError("alpha must be in [0, 1].")

source_flat = F.normalize(source.flatten(1), p=2, dim=1, eps=eps)
neighbor_flat = F.normalize(neighbor.flatten(1), p=2, dim=1, eps=eps)
cosine = (source_flat * neighbor_flat).sum(dim=1).clamp(-1.0, 1.0)
theta = torch.acos(cosine).view(-1, 1, 1)
if mode == "trajectory":
normalized_source = F.normalize(source.flatten(1), p=2, dim=1, eps=eps)
normalized_neighbor = F.normalize(neighbor.flatten(1), p=2, dim=1, eps=eps)
cosine = (normalized_source * normalized_neighbor).sum(dim=1).view(-1, 1, 1)
zero_norm = None
elif mode == "framewise":
normalized_source = F.normalize(source, p=2, dim=1, eps=eps)
normalized_neighbor = F.normalize(neighbor, p=2, dim=1, eps=eps)
cosine = (normalized_source * normalized_neighbor).sum(dim=1, keepdim=True)
zero_norm = (source.norm(dim=1, keepdim=True) <= eps) | (neighbor.norm(dim=1, keepdim=True) <= eps)
else:
raise ValueError(f"Unknown Slerp mode: {mode!r}.")
theta = torch.acos(cosine.clamp(-1.0, 1.0))
sin_theta = torch.sin(theta)
source_weight = torch.sin((1.0 - float(alpha)) * theta) / sin_theta.clamp_min(eps)
neighbor_weight = torch.sin(float(alpha) * theta) / sin_theta.clamp_min(eps)
spherical = source_weight * source + neighbor_weight * neighbor
linear = (1.0 - float(alpha)) * source + float(alpha) * neighbor
# Parallel trajectories make the spherical formula singular; use linear interpolation in that limit.
result = torch.where(sin_theta.abs() < eps, linear, spherical)
# Singular angles and zero-norm frame pairs use the linear interpolation limit.
fallback = sin_theta.abs() < eps
if zero_norm is not None:
fallback = fallback | zero_norm
result = torch.where(fallback, linear, spherical)
if not bool(torch.isfinite(result).all()):
raise ValueError("Slerp produced NaN or infinite values.")
return result
6 changes: 4 additions & 2 deletions src/slip_audio/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from slip_audio.core.neighbors import sample_topk_frame_neighbors
from slip_audio.data.manifest import AudioItem, artifact_name, load_manifest, manifest_fingerprint
from slip_audio.features import HubertFeatureExtractor
from slip_audio.settings import SLIP_SETTINGS
from slip_audio.settings import SLIP_SETTINGS, SlipSettings
from slip_audio.types import AudioBatch, LatentBatch, VAEAdapter


Expand Down Expand Up @@ -72,11 +72,12 @@ def __init__(
local_files_only: bool = False,
offload_vae_during_search: bool = True,
feature_extractor: Any | None = None,
settings: SlipSettings = SLIP_SETTINGS,
) -> None:
self.adapter = adapter
self.items = load_manifest(manifest) if not isinstance(manifest, list) else list(manifest)
self.output_dir = Path(output_dir).expanduser().resolve()
self.settings = SLIP_SETTINGS
self.settings = settings
self.device = str(device)
self.encode_batch_size = int(encode_batch_size)
self.feature_batch_size = int(feature_batch_size)
Expand Down Expand Up @@ -229,6 +230,7 @@ def _perturb(self) -> None:
source.to(self.device),
neighbor.to(self.device),
alpha=self.settings.alpha,
mode=self.settings.interpolation,
).cpu()
target.parent.mkdir(parents=True, exist_ok=True)
torch.save(
Expand Down
9 changes: 8 additions & 1 deletion src/slip_audio/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from dataclasses import asdict, dataclass
from typing import Any

from slip_audio.core.interpolation import Interpolation


@dataclass(frozen=True)
class SlipSettings:
Expand All @@ -16,9 +18,14 @@ class SlipSettings:
feature_revision: str = "cbd73bd518689ab98a9370c74165f4875ccd97d5"
feature_layer: int = 9
frechet_eps: float = 1e-6
interpolation: Interpolation = "trajectory"

def to_dict(self) -> dict[str, Any]:
return asdict(self)
settings = asdict(self)
if self.interpolation == "trajectory":
# Existing trajectory-mode run locks omitted this field.
settings.pop("interpolation")
return settings


SLIP_SETTINGS = SlipSettings()
9 changes: 9 additions & 0 deletions tests/test_interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,12 @@ def test_slerp_handles_parallel_vectors() -> None:
source = torch.ones(1, 2, 3)
actual = slerp(source, source * 2, alpha=0.25)
torch.testing.assert_close(actual, source * 1.25)


def test_framewise_slerp_uses_distinct_angles_and_original_norms() -> None:
source = torch.tensor([[[2.0, 1.0, 0.0], [0.0, 0.0, 0.0]]])
neighbor = torch.tensor([[[0.0, 2.0, 4.0], [3.0, 0.0, 2.0]]])
actual = slerp(source, neighbor, alpha=0.5, mode="framewise")
root_two = 2**0.5
expected = torch.tensor([[[2 / root_two, 1.5, 2.0], [3 / root_two, 0.0, 1.0]]])
torch.testing.assert_close(actual, expected)
38 changes: 35 additions & 3 deletions tests/test_pipeline.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from __future__ import annotations

import json
from pathlib import Path

import numpy as np
import pytest
import torch
import torch.nn.functional as F

from slip_audio import cli
from slip_audio.audio import load_audio, save_audio
from slip_audio.data.manifest import AudioItem, write_manifest
from slip_audio.pipeline import SlipEvaluator
Expand Down Expand Up @@ -60,7 +63,7 @@ def extract(self, paths: list[Path], *, batch_size: int = 8) -> np.ndarray:
return np.asarray(rows, dtype=np.float64)


def test_pipeline_runs_and_resumes_without_loading_hubert(tmp_path: Path) -> None:
def make_test_manifest(tmp_path: Path) -> Path:
audio_dir = tmp_path / "audio"
audio_dir.mkdir()
items = []
Expand All @@ -70,7 +73,11 @@ def test_pipeline_runs_and_resumes_without_loading_hubert(tmp_path: Path) -> Non
path = audio_dir / f"item{index}.wav"
save_audio(path, waveform, 16000)
items.append(AudioItem(id=f"item{index}", audio_path=path, split="test"))
manifest = write_manifest(items, tmp_path / "manifest.jsonl")
return write_manifest(items, tmp_path / "manifest.jsonl")


def test_pipeline_runs_and_resumes_without_loading_hubert(tmp_path: Path) -> None:
manifest = make_test_manifest(tmp_path)
output = tmp_path / "run"
evaluator = SlipEvaluator(
adapter=ToyAdapter(),
Expand All @@ -86,5 +93,30 @@ def test_pipeline_runs_and_resumes_without_loading_hubert(tmp_path: Path) -> Non
assert np.isfinite(first.score)
assert first.score == second.score
assert first.num_items == 4
assert (output / "metrics.json").exists()
metrics = json.loads((output / "metrics.json").read_text(encoding="utf-8"))
assert "interpolation" not in metrics["configuration"]
assert len(list((output / "decoded" / "test").glob("*.wav"))) == 4


def test_cli_framewise_protocol_is_resumable_and_keeps_its_own_cache(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
manifest = make_test_manifest(tmp_path)
output = tmp_path / "run"
config = {"runtime": {"device": "cpu", "encode_batch_size": 2, "neighbor_chunk_size": 8}}
monkeypatch.setattr(cli, "_run_inputs", lambda _: (config, ToyAdapter(), manifest, str(output)))
monkeypatch.setattr(
cli, "SlipEvaluator", lambda **kwargs: SlipEvaluator(**kwargs, feature_extractor=ToyFeatureExtractor())
)
args = ["evaluate", "toy.yaml"]
cli.main(args)

metrics_path = output / "metrics.json"
metrics = json.loads(metrics_path.read_text(encoding="utf-8"))
assert metrics["configuration"]["interpolation"] == "framewise"
assert metrics["configuration"]["seed"] == 1234
assert np.isfinite(metrics["slip"])
cli.main(args)
assert json.loads(metrics_path.read_text(encoding="utf-8")) == metrics
with pytest.raises(RuntimeError, match="Use a new output directory"):
cli.main([*args, "--interpolation", "trajectory", "--seed", "1234"])
Loading