Download scripts/pipeline/stage3_hubert.py from mistmlm/rvc-models: direct link, hf CLI and curl.
- Browser
- Download file 6.74 kB
-
https://huggingface.co/mistmlm/rvc-models/resolve/main/scripts/pipeline/stage3_hubert.py
- Command line
-
hf download hf://mistmlm/rvc-models/scripts/pipeline/stage3_hubert.py
-
curl -L -o stage3_hubert.py https://huggingface.co/mistmlm/rvc-models/resolve/main/scripts/pipeline/stage3_hubert.py
6.74 kB
| """ | |
| Stage 3: HuBERT ONNX export + qai-hub compile to Samsung Galaxy S23 (Family). | |
| HuBERT is the audio feature extractor (768-D output at 50 Hz, 320 ms window). | |
| For RVC the input is 16 kHz mono audio. We export from the .pt2 trace (which | |
| wraps the fairseq HuBERTBaseModel with all 12 CNN+Transformer layers), then | |
| submit to qai-hub for HTP compilation on sm8550 (8 Gen 2). | |
| Device choice rationale: | |
| - POCO F7 Ultra is sm8750 (8 Elite for Galaxy) — but qai-hub's "Samsung | |
| Galaxy S25 (Family)" compiles for sm8750-ac, and POCO is sm8750 too. | |
| - There is no S23 (sm8550) availability question, but compiling for the | |
| *earlier* Hexagon (v73) is forward-compatible to v79 (sm8750). QNN | |
| binaries compiled against v73 SHOULD run on v79 HTP. The reverse is | |
| not guaranteed. | |
| - So we target S23 (Family) so the .bin runs on BOTH S23/POCO F6 Pro | |
| (8 Gen 2) AND POCO F7 Ultra (8 Elite). | |
| Usage: | |
| /data/data/com.termux/files/home/tmp/rvc_ssh.sh ' | |
| cd ~/projects/rvc_npu && source .venv/bin/activate | |
| python stage3_hubert.py | |
| ' | |
| Outputs: | |
| models/hubert/hubert_320ms.onnx # ~360 MB | |
| qai-hub compile jobs (one per .bin variant) | |
| models/hubert/hubert_320ms_s23.bin # downloaded HTP binary | |
| """ | |
| import os | |
| import sys | |
| import types | |
| import shutil | |
| import numpy as np | |
| import torch | |
| # fairseq shim (needed for torch.jit.load to resolve HuBERTBaseModel) | |
| fake = types.ModuleType("fairseq") | |
| fake_fs_data = types.ModuleType("fairseq.data") | |
| class _Dict: | |
| def __init__(self, *a, **kw): pass | |
| fake_fs_data_dictionary = types.ModuleType("fairseq.data.dictionary") | |
| fake_fs_data_dictionary.Dictionary = _Dict | |
| sys.modules["fairseq"] = fake | |
| sys.modules["fairseq.data"] = fake_fs_data | |
| sys.modules["fairseq.data.dictionary"] = fake_fs_data_dictionary | |
| fake.data = fake_fs_data | |
| fake_fs_data.dictionary = fake_fs_data_dictionary | |
| PT2_PATH = "models/hubert/hubert_v2_320ms.pt2" | |
| ONNX_PATH = "models/hubert/hubert_320ms.onnx" | |
| OUT_BIN_DIR = "models/hubert" | |
| # 320 ms @ 16 kHz | |
| SAMPLE_RATE = 16000 | |
| WINDOW_SECS = 0.32 | |
| N_SAMPLES = int(SAMPLE_RATE * WINDOW_SECS) # 5120 | |
| BATCH = 1 | |
| def main(): | |
| os.makedirs(OUT_BIN_DIR, exist_ok=True) | |
| if not os.path.exists(PT2_PATH): | |
| print(f"FATAL: missing {PT2_PATH}") | |
| sys.exit(1) | |
| print(f"Loading torchscript module from {PT2_PATH}...") | |
| mod = torch.jit.load(PT2_PATH, map_location="cpu") | |
| mod.eval() | |
| print(f"Loaded: {mod}") | |
| # Inspect the graph for input signature | |
| print("\n--- Inspecting graph ---") | |
| for p in mod.parameters(): | |
| print(f" param: {p.shape}") | |
| break | |
| # We need to know the input tensor name + shape. JIT module may have multiple | |
| # forward inputs. Let us trace one invocation and check. | |
| audio = torch.randn(BATCH, N_SAMPLES, dtype=torch.float32) | |
| with torch.no_grad(): | |
| out = mod(audio) | |
| print(f"\nEager output: {type(out)}") | |
| if isinstance(out, (list, tuple)): | |
| print(f" tuple len {len(out)}; out[0]: {out[0].shape}") | |
| else: | |
| print(f" out: {out.shape}") | |
| # Export to ONNX | |
| print(f"\n--- Exporting to {ONNX_PATH} ---") | |
| if os.path.exists(ONNX_PATH): | |
| print(" already exists, skipping export") | |
| else: | |
| # torch 2.10's default torch.onnx.export uses torch.export which | |
| # refuses ScriptModule. Force the legacy TorchScript exporter. | |
| torch.onnx.export( | |
| mod, | |
| (audio,), | |
| ONNX_PATH, | |
| input_names=["audio_16k"], | |
| output_names=["hubert_features"], | |
| opset_version=14, # 14+ for scaled_dot_product_attention | |
| do_constant_folding=True, | |
| dynamic_axes=None, # fixed shape | |
| dynamo=False, | |
| ) | |
| print(f" saved {ONNX_PATH} ({os.path.getsize(ONNX_PATH)/1e6:.1f} MB)") | |
| # Sanity-check ONNX with onnxruntime (if installed) | |
| try: | |
| import onnx | |
| import onnxruntime as ort | |
| onnx_model = onnx.load(ONNX_PATH) | |
| onnx.checker.check_model(onnx_model) | |
| print(" onnx.checker: OK") | |
| sess = ort.InferenceSession(ONNX_PATH, providers=["CPUExecutionProvider"]) | |
| out_ort = sess.run(None, {"audio_16k": audio.numpy()}) | |
| print(f" onnxruntime output[0]: {out_ort[0].shape}, " | |
| f"max_diff_vs_eager: {np.abs(out_ort[0] - out[0].numpy()).max():.3e}") | |
| except ImportError: | |
| print(" (onnx/onnxruntime not installed — skipping verification)") | |
| # Submit qai-hub compile | |
| print("\n--- qai-hub compile ---") | |
| import qai_hub | |
| print(f" qai-hub: {qai_hub.__version__}") | |
| devs = qai_hub.get_devices() | |
| s23 = next(d for d in devs if d.name == "Samsung Galaxy S23 (Family)") | |
| print(f" target: {s23.name} attrs: {[a for a in s23.attributes if a.startswith('chipset') or a.startswith('hexagon')]}") | |
| import onnx | |
| onnx_model = onnx.load(ONNX_PATH) | |
| # Compile for HTP fp16 | |
| # qai-hub 0.55 Client.submit_compile_job signature: options: str | |
| # (NOT a kwarg 'target_runtime='). Pass via the options string. | |
| # "qnn_context_binary" produces a QNN .bin context loadable via | |
| # QnnInterpreter / libQnnHtp.so on-device (correct choice for a | |
| # single-context binary running on the HTP backend without an | |
| # on-device QNN compiler pass). | |
| print("\nSubmitting compile job (HTP fp16)...") | |
| compile_job = qai_hub.submit_compile_job( | |
| model=onnx_model, | |
| device=s23, | |
| input_specs={"audio_16k": (BATCH, N_SAMPLES)}, | |
| options="--target_runtime qnn_context_binary", | |
| ) | |
| print(f" job: {compile_job}") | |
| print(f" waiting...") | |
| compile_job.wait() | |
| status = compile_job.get_status() | |
| print(f" status: {status}") | |
| if str(status.state) != "State.SUCCESS": | |
| print(f" COMPILE FAILED: {status.state} / {status.message}") | |
| try: | |
| print(f" log: {compile_job.download_job_logs()}") | |
| except Exception as e: | |
| print(f" (could not fetch log: {e})") | |
| sys.exit(1) | |
| # Download the .bin | |
| target = compile_job.download_target_model() | |
| bin_path = os.path.join(OUT_BIN_DIR, "hubert_320ms_s23.bin") | |
| shutil.copy(target, bin_path) | |
| print(f"\n saved {bin_path} ({os.path.getsize(bin_path)/1e6:.1f} MB)") | |
| # Profile | |
| print("\n--- Profiling on-device ---") | |
| profile_job = qai_hub.submit_profile_job( | |
| model=onnx_model, | |
| device=s23, | |
| input_specs={"audio_16k": (BATCH, N_SAMPLES)}, | |
| ) | |
| print(f" profile job: {profile_job}") | |
| profile_job.wait() | |
| pstatus = profile_job.get_status() | |
| print(f" status: {pstatus.state}") | |
| if pstatus.state == "SUCCESS": | |
| results = profile_job.download_results() | |
| print(f" profile results: {results}") | |
| if __name__ == "__main__": | |
| main() | |