Spaces:
Running
Running
File size: 3,768 Bytes
9cb73e8 | 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 | """Convert an RVC training checkpoint (.pth) to an ONNX voice model.
The RVC decoder architecture lives in the official RVC-WebUI repository, so
this script needs a local checkout of
https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI
plus PyTorch (CPU build is enough) and onnxsim:
pip install torch onnx onnxsim
git clone --depth 1 https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git
Usage:
python scripts/convert_model.py --model voice.pth \
--rvc-root ../Retrieval-based-Voice-Conversion-WebUI \
--output models/rvc/voices/my-voice.onnx
"""
import argparse
import json
import sys
from pathlib import Path
def _require(module: str, hint: str):
try:
return __import__(module, fromlist=[""])
except ImportError:
raise SystemExit(f"missing dependency: {module}. {hint}")
def main() -> int:
parser = argparse.ArgumentParser(description="Convert RVC .pth to .onnx")
parser.add_argument("--model", required=True, help="path to the RVC checkpoint (.pth)")
parser.add_argument("--output", default="model.onnx", help="output .onnx path")
parser.add_argument("--rvc-root", required=True, help="path to RVC-WebUI checkout")
parser.add_argument("--opset", type=int, default=18)
args = parser.parse_args()
torch = _require("torch", "pip install torch (CPU build is enough)")
onnx = _require("onnx", "pip install onnx")
try:
onnxsim = _require("onnxsim", "pip install onnxsim")
except SystemExit:
onnxsim = None
sys.path.insert(0, args.rvc_root)
try:
from infer.lib.infer_pack.models_onnx import SynthesizerTrnMsNSFsidM
except ImportError:
raise SystemExit(
"could not import RVC model code. Point --rvc-root to a checkout of "
"RVC-Project/Retrieval-based-Voice-Conversion-WebUI"
)
rvc_root = Path(args.rvc_root)
if (rvc_root / "assets" / "pretrained").exists():
sys.path.insert(0, str(rvc_root))
cpt = torch.load(args.model, map_location="cpu")
cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0]
vec_channels = 256 if cpt.get("version", "v1") == "v1" else 768
is_v2 = cpt.get("version", "v1") == "v2"
dummy_args = (
torch.rand(1, 200, vec_channels).to("cpu"),
torch.tensor([200], dtype=torch.long),
torch.randint(size=(1, 200), low=5, high=255, dtype=torch.long),
torch.rand(1, 200),
torch.tensor([0], dtype=torch.long),
torch.rand(1, 192, 200),
)
net_g = SynthesizerTrnMsNSFsidM(*cpt["config"], is_half=False, version="v2" if is_v2 else "v1")
net_g.load_state_dict(cpt["weight"], strict=False)
net_g.eval()
torch.onnx.export(
net_g,
dummy_args,
args.output,
input_names=["phone", "phone_lengths", "pitch", "pitchf", "ds", "rnd"],
output_names=["audio"],
dynamic_axes={
"phone": [1],
"phone_lengths": [0],
"pitch": [1],
"pitchf": [1],
"rnd": [2],
},
do_constant_folding=False,
opset_version=args.opset,
verbose=False,
)
if onnxsim is not None:
print("Simplifying with onnxsim...")
model, check = onnxsim.simplify(args.output)
if not check:
raise SystemExit("onnxsim verification failed")
onnx.save(model, args.output)
else:
print("onnxsim not installed, skipping simplification")
sample_rate = int(cpt["config"][-1])
print("Done.")
print(f"config (sr={sample_rate}, version={'v2' if is_v2 else 'v1'}):")
print(json.dumps(cpt["config"], indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main()) |