anilkeshwani's picture
Add files using upload-large-folder tool
729e200 verified
Raw History Blame Contribute Delete
8.09 kB
"""Discrete speech unit (DSU) tokenizers matching the speech-integration MLS training data.
Each tokenizer exposes `sample_rate` (expected input rate) and `encode(wav)` where `wav` is a
1-D float32 torch tensor in [-1, 1] at 16 kHz (the rate of all MLS source audio). Resampling to the
tokenizer's native rate happens inside `encode`, so callers always pass 16 kHz audio.
Tokenizer names match the directory names used under eval_data/:
hubert_large_ll60k-layer_22, speechtokenizer-rvq_0, mimi-srvq_0, focalcodec
"""
from __future__ import annotations
import copy
import json
import os
import numpy as np
import torch
import torch.nn.functional as F
import torchaudio.functional as AF
INPUT_SR = 16_000
HUBERT_REPO = "facebook/hubert-large-ll60k"
HUBERT_LAYER = 22
KMEANS_REPO = "utter-project/SpireKMeans"
SPEECHTOKENIZER_REPO = "fnlp/SpeechTokenizer"
MIMI_REPO = "kyutai/mimi"
FOCALCODEC_REPO = "lucadellalib/focalcodec_50hz"
FOCALCODEC_REVISION = "d6d6d9524e52155c85193c2c3b8da1cf8842f019" # weights unchanged since 2025-02-11
def _hf_file(repo_id: str, filename: str, revision: str | None = None) -> str:
from huggingface_hub import hf_hub_download
return hf_hub_download(repo_id, filename, revision=revision)
KMEANS_REVISION = "bb0d1a04213141f3c61912989abec9641943af60"
KMEANS_CENTERS_NPY = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"downloads",
"spire_kmeans",
f"cluster_centers_{KMEANS_REVISION[:7]}.npy",
)
def load_kmeans_centers() -> np.ndarray:
"""Return the (5000, 1024) float32 centroids of utter-project/SpireKMeans.
The upstream file is a joblib pickle of a sklearn MiniBatchKMeans (sklearn 1.3.2). It was
unpickled once (it is the published k-means for this setup) and its centroids exported to .npy
by export_spire_kmeans_centers.py, so normal runs never unpickle downloaded data.
"""
return np.load(KMEANS_CENTERS_NPY, allow_pickle=False).astype(np.float32)
class HubertKMeansTokenizer:
"""HuBERT Large (LL-60k) layer-22 features + 5000-cluster k-means (SpireKMeans).
Mirrors sardalign.utils.features.SimpleHubertFeaturizer + sardalign.dump_km_label.ApplyKmeans:
the whole waveform is layer-normalized (task.cfg.normalize=True for HuBERT Large), then fed
unpadded; layer 22 output (before the final encoder LayerNorm) is assigned to the nearest centroid.
"""
name = "hubert_large_ll60k-layer_22"
sample_rate = 16_000
def __init__(self, device: torch.device):
from transformers import HubertModel
self.device = device
model = HubertModel.from_pretrained(HUBERT_REPO, torch_dtype=torch.float32)
# Drop unused top layers. Keep one extra: the encoder applies its final LayerNorm to the last
# hidden state, so with exactly 22 layers hidden_states[22] would be normalized.
model.encoder.layers = model.encoder.layers[: HUBERT_LAYER + 1]
self.model = model.eval().to(device)
C = torch.from_numpy(load_kmeans_centers().T).to(device) # (D, K)
self.C = C
self.Cnorm = (C**2).sum(0, keepdim=True)
@torch.inference_mode()
def encode(self, wav: torch.Tensor) -> list[int]:
x = wav.to(self.device, torch.float32)
x = F.layer_norm(x, x.shape).view(1, -1)
out = self.model(x, output_hidden_states=True)
feat = out.hidden_states[HUBERT_LAYER].squeeze(0) # (T, 1024)
dist = feat.pow(2).sum(1, keepdim=True) - 2 * feat @ self.C + self.Cnorm
return dist.argmin(dim=1).cpu().tolist()
class SpeechTokenizerRVQ0:
"""SpeechTokenizer (speechtokenizer_hubert_avg), first RVQ codebook (1024 entries), 50 Hz."""
name = "speechtokenizer-rvq_0"
sample_rate = 16_000
def __init__(self, device: torch.device):
from speechtokenizer import SpeechTokenizer
cfg = _hf_file(SPEECHTOKENIZER_REPO, "speechtokenizer_hubert_avg/config.json")
ckpt = _hf_file(SPEECHTOKENIZER_REPO, "speechtokenizer_hubert_avg/SpeechTokenizer.pt")
self.model = SpeechTokenizer.load_from_checkpoint(cfg, ckpt).eval().to(device)
assert self.model.sample_rate == self.sample_rate
self.device = device
@torch.inference_mode()
def encode(self, wav: torch.Tensor) -> list[int]:
x = wav.to(self.device, torch.float32).view(1, 1, -1)
codes = self.model.encode(x, n_q=1) # (n_q, B, T)
return codes[0, 0].cpu().tolist()
class MimiSRVQ0:
"""Kyutai Mimi (transformers MimiModel), split-RVQ level 0 (semantic codebook, 2048), 12.5 Hz."""
name = "mimi-srvq_0"
sample_rate = 24_000
def __init__(self, device: torch.device, resample: str = "torchaudio"):
from transformers import MimiModel
self.model = MimiModel.from_pretrained(MIMI_REPO).eval().to(device)
self.device = device
self.resample = resample
def _resample(self, wav: torch.Tensor) -> torch.Tensor:
if self.resample == "torchaudio":
return AF.resample(wav, INPUT_SR, self.sample_rate)
if self.resample.startswith("librosa"):
import librosa
res_type = self.resample.split(":", 1)[1] if ":" in self.resample else "soxr_hq"
y = librosa.resample(wav.numpy(), orig_sr=INPUT_SR, target_sr=self.sample_rate, res_type=res_type)
return torch.from_numpy(y)
raise ValueError(self.resample)
@torch.inference_mode()
def encode(self, wav: torch.Tensor) -> list[int]:
x = self._resample(wav.float().cpu()).to(self.device).view(1, 1, -1)
codes = self.model.encode(x, num_quantizers=8).audio_codes # (B, n_q, T)
return codes[0, 0].cpu().tolist()
class FocalCodec50Hz:
"""FocalCodec 50 Hz (single binary spherical quantizer codebook, 8192 entries)."""
name = "focalcodec"
sample_rate = 16_000
def __init__(self, device: torch.device, cpu_above_s: float = 40.0):
from focalcodec import FocalCodec
from safetensors.torch import load_file
# Same as FocalCodec.from_pretrained(FOCALCODEC_REPO) in focalcodec 0.0.1, but cache-aware
# (from_config calls list_repo_files, which fails with HF_HUB_OFFLINE=1)
with open(_hf_file(FOCALCODEC_REPO, "config.json", FOCALCODEC_REVISION)) as f:
model = FocalCodec(**json.load(f))
model.load_state_dict(load_file(_hf_file(FOCALCODEC_REPO, "model.safetensors", FOCALCODEC_REVISION)))
self.model = model.eval().requires_grad_(False).to(device)
# focalcodec 0.0.1 (pinned commit 68be6ce, the code current when the MLS tokens were made)
# exposes `sample_rate`; later versions renamed it to `sample_rate_input`
sr = getattr(self.model, "sample_rate_input", None) or self.model.sample_rate
assert sr == self.sample_rate, sr
self.device = device
self.cpu_above_s = cpu_above_s
self._cpu_model = None
@torch.inference_mode()
def encode(self, wav: torch.Tensor) -> list[int]:
# WavLM attention needs ~5 GiB extra GPU memory at 100 s, so long inputs go to a CPU copy of
# the model (CPU and GPU fp32 gave identical tokens in testing)
if self.device.type == "cuda" and wav.numel() > self.cpu_above_s * self.sample_rate:
if self._cpu_model is None:
self._cpu_model = copy.deepcopy(self.model).cpu()
model, device = self._cpu_model, torch.device("cpu")
else:
model, device = self.model, self.device
x = wav.to(device, torch.float32).view(1, -1)
toks = model.sig_to_toks(x) # (B, T)
return toks[0].cpu().tolist()
TOKENIZERS = {
cls.name: cls for cls in (HubertKMeansTokenizer, SpeechTokenizerRVQ0, MimiSRVQ0, FocalCodec50Hz)
}
def get_device() -> torch.device:
if torch.cuda.is_available():
visible = os.environ.get("CUDA_VISIBLE_DEVICES")
if visible != "3":
raise RuntimeError(f"Refusing to run on GPUs other than 3; CUDA_VISIBLE_DEVICES={visible!r}")
return torch.device("cuda:0")
return torch.device("cpu")