1import torch, json
2from huggingface_hub import hf_hub_download
3from transformers import Gemma4AudioModel, Gemma4AudioFeatureExtractor
4
5# Load RVQ
6cfg = json.load(open(hf_hub_download("REPO_ID", "config_stage1.json")))
7exec(open(hf_hub_download("REPO_ID", "rvq_wrapper.py")).read())
8rvq = RVQWrapper(cfg["rvq_dim"], cfg["rvq_num_quantizers"], cfg["rvq_codebook_size"])
9ckpt = torch.load(hf_hub_download("REPO_ID", "rvq_averaged.pt"), map_location="cpu")
10rvq.load_state_dict(ckpt["rvq"])
11rvq.eval()
12
13# Load Gemma 4 encoder
14encoder = Gemma4AudioModel.from_pretrained("rnagabh/gemma4-audio-encoder", torch_dtype=torch.bfloat16)
15feat_ext = Gemma4AudioFeatureExtractor.from_pretrained("rnagabh/gemma4-audio-encoder")
16
17# Encode audio → semantic tokens
18import numpy as np
19wav = np.random.randn(16000).astype(np.float32) # your audio here
20feats = feat_ext([wav], sampling_rate=16000, return_tensors="pt")
21
22hook_store = {}
23def hook(m, i, o): hook_store["h"] = i[0]
24handle = encoder.output_proj.register_forward_hook(hook)
25with torch.no_grad():
26 encoder(feats["input_features"].to(torch.bfloat16))
27 hs = hook_store["h"].float()
28 _, indices, _ = rvq(hs)
29handle.remove()
30
31print("Token indices:", indices.shape) # [1, Q, T]