File size: 6,742 Bytes
bda6de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""
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()