Make repo self-contained: inference wrapper code and arena_entry.yaml
Browse filesFiles changed (5)
- _net.py+23-3
- arena_entry.yamlAdded+7
- sweep.pyAdded+43
- trt_xlsr_mamba_df.py+15-2
- xlsr2_300m_model_cfg.jsonAdded+51
42 unmodified lines43444546474831 unmodified lines8081828384858687888942 unmodified linesWINDOW = 66800 # authors' training/eval cut (4.175 s @ 16 kHz)_XLSR_PATH = os.path.join(_HERE, "xlsr2_300m.pt") # symlink to W2V2-AASIST's base XLS-Rdef pad_repeat(x: np.ndarray, max_len: int = WINDOW) -> np.ndarray:"""Source utils.pad: first max_len samples; shorter clips tiled to max_len."""31 unmodified linesimport fairseqfrom fairseq.dataclass.utils import merge_with_parentfrom fairseq.models.wav2vec.wav2vec2 import Wav2Vec2Config, Wav2Vec2Modelstate = fairseq.checkpoint_utils.load_checkpoint_to_cpu(cp_path)cfg = merge_with_parent(Wav2Vec2Config(), state["cfg"]["model"], remove_missing=True)ssl = Wav2Vec2Model.build_model(cfg, task=None)ssl.load_state_dict(state["model"], strict=True)self.model = sslself.out_dim = 102442 unmodified lines4344454647484950515253545556575859606162636465666731 unmodified lines9910010110210310410510610710810942 unmodified linesWINDOW = 66800 # authors' training/eval cut (4.175 s @ 16 kHz)_XLSR_PATH = os.path.join(_HERE, "xlsr2_300m.pt") # symlink to W2V2-AASIST's base XLS-R# xlsr2_300m.pt (fairseq XLS-R 300M, 3.8 GB) is NOT shipped with this repo: only its model cfg is needed to build# the architecture, vendored as xlsr2_300m_model_cfg.json (identical to xlsr2_300m.pt["cfg"]["model"]); every SSL# weight is overwritten by the strict load of the fine-tuned checkpoint, so scores are unchanged. If xlsr2_300m.pt# is placed at the path above it is used exactly as before._XLSR_CFG = os.path.join(_HERE, "xlsr2_300m_model_cfg.json")def _xlsr_model_cfg_and_state(cp_path):"""(model cfg, pre-trained state dict or None) of the XLS-R 300M base checkpoint."""if os.path.exists(cp_path):import fairseqstate = fairseq.checkpoint_utils.load_checkpoint_to_cpu(cp_path)return state["cfg"]["model"], state["model"]import jsonfrom omegaconf import OmegaConfwith open(_XLSR_CFG) as f:return OmegaConf.create(json.load(f)), Nonedef pad_repeat(x: np.ndarray, max_len: int = WINDOW) -> np.ndarray:"""Source utils.pad: first max_len samples; shorter clips tiled to max_len."""31 unmodified linesimport fairseqfrom fairseq.dataclass.utils import merge_with_parentfrom fairseq.models.wav2vec.wav2vec2 import Wav2Vec2Config, Wav2Vec2Modelmodel_cfg, model_sd = _xlsr_model_cfg_and_state(cp_path)cfg = merge_with_parent(Wav2Vec2Config(), model_cfg, remove_missing=True)ssl = Wav2Vec2Model.build_model(cfg, task=None)if model_sd is not None:ssl.load_state_dict(model_sd, strict=True)self.model = sslself.out_dim = 1024
1234567# How Arena drivers load this model (discovered from the repo; no central registry needed)module: xlsr_mamba_dfclass: XLSRMambaDFtrt_module: trt_xlsr_mamba_dftrt_class: XLSRMambaDFTRTsample_rate: 16000devices: 112345678910111213141516171819202122232425262728293031323334353637383940414243# sweep.pyfrom __future__ import annotationsimport timefrom statistics import medianimport numpy as npimport torchimport xlsr_mamba_df
_CUT = 66800
def time_batch_sizes(): print("device", torch.cuda.get_device_name(0)) m = xlsr_mamba_df.XLSRMambaDF() m.load() cuda = getattr(m, "device", "cpu") == "cuda" results = {} print("=== batch-size sweep ===") for bs in [1, 2, 4, 8, 16, 24, 32]: audios = [np.random.randn(_CUT).astype(np.float32) for _ in range(bs)] srs = [16000] * bs try: m.score_batch(audios, srs) # warm-up if cuda: torch.cuda.synchronize() reps = [] for _ in range(5): if cuda: torch.cuda.synchronize() t0 = time.perf_counter() m.score_batch(audios, srs) if cuda: torch.cuda.synchronize() reps.append(time.perf_counter() - t0) med = median(reps); ups = bs / med results[bs] = ups print(f"bs={bs:3d} median={med*1000:8.3f} ms utt/s={ups:8.2f}") except torch.cuda.OutOfMemoryError: print(f"bs={bs:3d} OOM (skipped)") if cuda: torch.cuda.empty_cache() m.unload() best = max(results, key=results.get) print(f"best batch_size = {best} (utt/s={results[best]:.2f})") return best, results
if __name__ == "__main__": time_batch_sizes()64 unmodified lines656667686970713 unmodified lines7576777879808182838485868764 unmodified lines# helpers# ----------------------------------------------------------------------------def gpu_slug() -> str:name = torch.cuda.get_device_name(0)return name.replace("NVIDIA ", "").replace("GeForce ", "").strip().replace(" ", "_")3 unmodified linesreturn mdef real_audio(n=64):"""Decode up to n real 16 kHz mono utterances from PARITY_DATASET/data/*.parquet."""import pyarrow.parquet as pqimport soundfile as sfimport torchaudio.functional as AFdata_dir = HERE.parent / PARITY_DATASET / "data"files = sorted(data_dir.glob("test-*.parquet")) or sorted(data_dir.glob("*.parquet"))out = []for f in files:64 unmodified lines656667686970713 unmodified lines7576777879808182838485868788899091929394959697989910064 unmodified lines# helpers# ----------------------------------------------------------------------------def gpu_slug() -> str:name = torch.cuda.get_device_name() # current device (multi-GPU drivers set_device first)return name.replace("NVIDIA ", "").replace("GeForce ", "").strip().replace(" ", "_")3 unmodified linesreturn mdef _parity_data_dir() -> Path:"""Dir with the parity clips (<PARITY_DATASET> data/*.parquet; the clips used are unchanged).$ARENA_PARITY_DIR if set, else $ARENA_DATASETS/arena/<PARITY_DATASET>/data if ARENA_DATASETS is set,else the legacy sibling layout <repo>/../<PARITY_DATASET>/data."""if os.environ.get("ARENA_PARITY_DIR"):return Path(os.environ["ARENA_PARITY_DIR"])if os.environ.get("ARENA_DATASETS"):return Path(os.environ["ARENA_DATASETS"]) / "arena" / PARITY_DATASET / "data"return HERE.parent / PARITY_DATASET / "data"def real_audio(n=64):"""Decode up to n real 16 kHz mono utterances from PARITY_DATASET/data/*.parquet."""import pyarrow.parquet as pqimport soundfile as sfimport torchaudio.functional as AFdata_dir = _parity_data_dir()files = sorted(data_dir.glob("test-*.parquet")) or sorted(data_dir.glob("*.parquet"))out = []for f in files:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051{ "_name": "wav2vec2", "activation_dropout": 0.0, "activation_fn": "gelu", "attention_dropout": 0.0, "codebook_negatives": 0, "conv_bias": true, "conv_feature_layers": "[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512,2,2)] + [(512,2,2)]", "conv_pos": 128, "conv_pos_groups": 16, "cross_sample_negatives": 0, "dropout": 0.0, "dropout_features": 0.0, "dropout_input": 0.0, "encoder_attention_heads": 16, "encoder_embed_dim": 1024, "encoder_ffn_embed_dim": 4096, "encoder_layerdrop": 0.0, "encoder_layers": 24, "extractor_mode": "layer_norm", "feature_grad_mult": 1.0, "final_dim": 768, "latent_dim": 0, "latent_groups": 2, "latent_temp": [ 2.0, 0.1, 0.999995 ], "latent_vars": 320, "layer_norm_first": true, "logit_temp": 0.1, "mask_channel_length": 10, "mask_channel_min_space": 1, "mask_channel_other": 0.0, "mask_channel_prob": 0.0, "mask_channel_selection": "static", "mask_length": 10, "mask_min_space": 1, "mask_other": 0.0, "mask_prob": 0.65, "mask_selection": "static", "negatives_from_everywhere": false, "no_mask_channel_overlap": false, "no_mask_overlap": false, "num_negatives": 100, "quantize_input": false, "quantize_targets": true, "same_quantizer": false, "target_glu": false}_net.py+23-3
arena_entry.yamlAdded+7
sweep.pyAdded+43
trt_xlsr_mamba_df.py+15-2
xlsr2_300m_model_cfg.jsonAdded+51