roccoro 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- roccoro/__init__.py +49 -0
- roccoro/__main__.py +6 -0
- roccoro/build.py +74 -0
- roccoro/cli.py +155 -0
- roccoro/csrc/Makefile +48 -0
- roccoro/csrc/khip_loader.h +149 -0
- roccoro/csrc/kokoro_bench_hip.cpp +160 -0
- roccoro/csrc/kokoro_engine.cpp +1483 -0
- roccoro/csrc/kokoro_engine.h +265 -0
- roccoro/csrc/kokoro_hip_cli.cpp +147 -0
- roccoro/csrc/kokoro_kernels.h +303 -0
- roccoro/csrc/kokoro_kernels.hip +2095 -0
- roccoro/csrc/verify_fixture.cpp +119 -0
- roccoro/engine.py +558 -0
- roccoro/export.py +306 -0
- roccoro-0.1.1.dist-info/METADATA +155 -0
- roccoro-0.1.1.dist-info/RECORD +21 -0
- roccoro-0.1.1.dist-info/WHEEL +5 -0
- roccoro-0.1.1.dist-info/entry_points.txt +2 -0
- roccoro-0.1.1.dist-info/licenses/LICENSE +21 -0
- roccoro-0.1.1.dist-info/top_level.txt +1 -0
roccoro/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Roccoro — Native ROCm/HIP Kokoro-82M TTS engine."""
|
|
2
|
+
|
|
3
|
+
from .build import build_engine, detect_gpu_arch
|
|
4
|
+
from .engine import (
|
|
5
|
+
BUILTIN_KOKORO_VOCAB,
|
|
6
|
+
KOKORO_REPO,
|
|
7
|
+
MAGIC_READY,
|
|
8
|
+
MAGIC_REQ,
|
|
9
|
+
MAGIC_RESP,
|
|
10
|
+
SAMPLE_RATE,
|
|
11
|
+
KokoroEngine,
|
|
12
|
+
MisakiG2P,
|
|
13
|
+
cache_dir,
|
|
14
|
+
decode_response_frame,
|
|
15
|
+
encode_request_frame,
|
|
16
|
+
find_engine_binary,
|
|
17
|
+
find_weights,
|
|
18
|
+
is_available,
|
|
19
|
+
load_kokoro_vocab,
|
|
20
|
+
load_voice_pack,
|
|
21
|
+
phonemes_to_token_ids,
|
|
22
|
+
write_wav,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__version__ = "0.1.1"
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"__version__",
|
|
29
|
+
"BUILTIN_KOKORO_VOCAB",
|
|
30
|
+
"KOKORO_REPO",
|
|
31
|
+
"MAGIC_READY",
|
|
32
|
+
"MAGIC_REQ",
|
|
33
|
+
"MAGIC_RESP",
|
|
34
|
+
"SAMPLE_RATE",
|
|
35
|
+
"KokoroEngine",
|
|
36
|
+
"MisakiG2P",
|
|
37
|
+
"build_engine",
|
|
38
|
+
"cache_dir",
|
|
39
|
+
"decode_response_frame",
|
|
40
|
+
"detect_gpu_arch",
|
|
41
|
+
"encode_request_frame",
|
|
42
|
+
"find_engine_binary",
|
|
43
|
+
"find_weights",
|
|
44
|
+
"is_available",
|
|
45
|
+
"load_kokoro_vocab",
|
|
46
|
+
"load_voice_pack",
|
|
47
|
+
"phonemes_to_token_ids",
|
|
48
|
+
"write_wav",
|
|
49
|
+
]
|
roccoro/__main__.py
ADDED
roccoro/build.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Build helper for compiling the native ROCm/HIP `roccoro-engine` binary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
|
|
11
|
+
from .engine import _package_csrc_dir, cache_dir
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def detect_gpu_arch(rocm_path: str | Path = "/opt/rocm") -> str:
|
|
15
|
+
"""Auto-detect the active AMD GPU ISA (e.g. `gfx1151`, `gfx1100`) via `rocminfo`."""
|
|
16
|
+
rocminfo = Path(rocm_path) / "bin" / "rocminfo"
|
|
17
|
+
cmd = str(rocminfo) if rocminfo.is_file() else shutil.which("rocminfo")
|
|
18
|
+
if cmd:
|
|
19
|
+
try:
|
|
20
|
+
out = subprocess.check_output([cmd], text=True, stderr=subprocess.DEVNULL, timeout=10)
|
|
21
|
+
for match in re.findall(r"\bgfx[0-9a-f]+\b", out):
|
|
22
|
+
if match != "gfx000":
|
|
23
|
+
return match
|
|
24
|
+
except Exception:
|
|
25
|
+
pass
|
|
26
|
+
return "gfx1151"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def build_engine(
|
|
30
|
+
arch: str | None = None,
|
|
31
|
+
rocm_path: str | Path | None = None,
|
|
32
|
+
install_dir: str | Path | None = None,
|
|
33
|
+
targets: tuple[str, ...] = ("roccoro-engine",),
|
|
34
|
+
) -> Path:
|
|
35
|
+
"""Compile the HIP C++ sources into a writable cache build dir and install `roccoro-engine`."""
|
|
36
|
+
rocm = Path(rocm_path or os.environ.get("ROCM_PATH", "/opt/rocm"))
|
|
37
|
+
hipcc = rocm / "bin" / "hipcc"
|
|
38
|
+
if not hipcc.is_file():
|
|
39
|
+
found = shutil.which("hipcc")
|
|
40
|
+
if not found:
|
|
41
|
+
raise FileNotFoundError(
|
|
42
|
+
f"hipcc not found at {hipcc} or in PATH. Install ROCm or set ROCM_PATH."
|
|
43
|
+
)
|
|
44
|
+
hipcc = Path(found)
|
|
45
|
+
rocm = hipcc.parent.parent
|
|
46
|
+
|
|
47
|
+
gpu_arch = arch or detect_gpu_arch(rocm)
|
|
48
|
+
csrc = _package_csrc_dir()
|
|
49
|
+
if not (csrc / "kokoro_kernels.hip").is_file():
|
|
50
|
+
raise FileNotFoundError(f"Missing C++/HIP sources under {csrc}")
|
|
51
|
+
|
|
52
|
+
dest_dir = Path(install_dir).expanduser() if install_dir else cache_dir()
|
|
53
|
+
build_dir = dest_dir / "build"
|
|
54
|
+
build_dir.mkdir(parents=True, exist_ok=True)
|
|
55
|
+
dest_dir.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
|
|
57
|
+
for src_file in csrc.iterdir():
|
|
58
|
+
if src_file.is_file() and (
|
|
59
|
+
src_file.name == "Makefile" or src_file.suffix in (".h", ".cpp", ".hip")
|
|
60
|
+
):
|
|
61
|
+
shutil.copy2(src_file, build_dir / src_file.name)
|
|
62
|
+
|
|
63
|
+
cmd = [
|
|
64
|
+
"make",
|
|
65
|
+
"-C", str(build_dir),
|
|
66
|
+
f"ROCM_PATH={rocm}",
|
|
67
|
+
f"HIPCC={hipcc}",
|
|
68
|
+
f"ARCH={gpu_arch}",
|
|
69
|
+
f"INSTALL_DIR={dest_dir}",
|
|
70
|
+
*targets,
|
|
71
|
+
"install",
|
|
72
|
+
]
|
|
73
|
+
subprocess.run(cmd, check=True)
|
|
74
|
+
return dest_dir / "roccoro-engine"
|
roccoro/cli.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Command-line interface for Roccoro (native ROCm/HIP Kokoro-82M TTS)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .build import build_engine, detect_gpu_arch
|
|
12
|
+
from .engine import (
|
|
13
|
+
KokoroEngine,
|
|
14
|
+
cache_dir,
|
|
15
|
+
find_engine_binary,
|
|
16
|
+
find_weights,
|
|
17
|
+
is_available,
|
|
18
|
+
)
|
|
19
|
+
from .export import export_weights
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _cmd_info() -> int:
|
|
23
|
+
print(f"roccoro {__version__}")
|
|
24
|
+
print(f" /dev/kfd : {'present' if Path('/dev/kfd').exists() else 'missing'}")
|
|
25
|
+
print(f" GPU arch : {detect_gpu_arch()}")
|
|
26
|
+
print(f" cache dir : {cache_dir()}")
|
|
27
|
+
print(f" engine binary: {find_engine_binary() or 'NOT FOUND (run `roccoro build`)'}")
|
|
28
|
+
print(f" weights : {find_weights() or 'NOT FOUND (run `roccoro export-weights`)'}")
|
|
29
|
+
print(f" ready : {is_available()}")
|
|
30
|
+
return 0
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _cmd_build(argv: list[str]) -> int:
|
|
34
|
+
ap = argparse.ArgumentParser(prog="roccoro build", description="Compile the native ROCm/HIP engine binary.")
|
|
35
|
+
ap.add_argument("--arch", default=None, help="Target AMD GPU ISA (default: auto-detect via rocminfo, else gfx1151)")
|
|
36
|
+
ap.add_argument("--rocm-path", default=None, help="ROCm installation root (default: $ROCM_PATH or /opt/rocm)")
|
|
37
|
+
ap.add_argument("--install-dir", default=None, help="Where to install roccoro-engine (default: ~/.cache/roccoro)")
|
|
38
|
+
ap.add_argument("--all", action="store_true", help="Also build verify_fixture and kokoro_bench_hip")
|
|
39
|
+
args = ap.parse_args(argv)
|
|
40
|
+
targets = ("roccoro-engine", "verify_fixture", "kokoro_bench_hip") if args.all else ("roccoro-engine",)
|
|
41
|
+
out = build_engine(arch=args.arch, rocm_path=args.rocm_path, install_dir=args.install_dir, targets=targets)
|
|
42
|
+
print(f"Built and installed: {out}")
|
|
43
|
+
return 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _cmd_export(argv: list[str]) -> int:
|
|
47
|
+
ap = argparse.ArgumentParser(
|
|
48
|
+
prog="roccoro export-weights",
|
|
49
|
+
description="One-time export of Kokoro-82M FP32 folded weights into `.khip` format.",
|
|
50
|
+
)
|
|
51
|
+
ap.add_argument("--out", type=Path, default=None, help="Output .khip path (default: ~/.cache/roccoro/kokoro_v1_fp32.khip)")
|
|
52
|
+
ap.add_argument("--repo-id", default="hexgrad/Kokoro-82M", help="Hugging Face repo ID")
|
|
53
|
+
ap.add_argument("--voices-dir", type=Path, default=None, help="Optional directory to also export raw .bin voice packs")
|
|
54
|
+
ap.add_argument("--voices", nargs="*", default=["af_heart"], help="Voices to export with --voices-dir")
|
|
55
|
+
ap.add_argument("--dump-fixture", type=Path, default=None, help="Optional verification fixture .khip output path")
|
|
56
|
+
args = ap.parse_args(argv)
|
|
57
|
+
export_weights(
|
|
58
|
+
out_path=args.out,
|
|
59
|
+
repo_id=args.repo_id,
|
|
60
|
+
voices_dir=args.voices_dir,
|
|
61
|
+
voices=args.voices,
|
|
62
|
+
dump_fixture=args.dump_fixture,
|
|
63
|
+
)
|
|
64
|
+
return 0
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _cmd_synth(argv: list[str]) -> int:
|
|
68
|
+
ap = argparse.ArgumentParser(
|
|
69
|
+
prog="roccoro",
|
|
70
|
+
description="Native ROCm/HIP Kokoro-82M TTS (~245x RT on AMD Strix Halo / RDNA3+).",
|
|
71
|
+
)
|
|
72
|
+
ap.add_argument("text", nargs="?", help="Text to synthesize (or pass --text-file / pipe stdin)")
|
|
73
|
+
ap.add_argument("-f", "--text-file", type=Path, help="Read input text from a UTF-8 file")
|
|
74
|
+
ap.add_argument("-o", "--output", type=Path, default=Path("out.wav"), help="Output 24 kHz WAV path (default: out.wav)")
|
|
75
|
+
ap.add_argument("-v", "--voice", default="af_heart", help="Voice name, file path, or comma-blended voices (default: af_heart)")
|
|
76
|
+
ap.add_argument("--lang", default="a", help="Language code: 'a' (US English) or 'b' (UK English)")
|
|
77
|
+
ap.add_argument("--speed", type=float, default=1.0, help="Speech speed multiplier (default: 1.0)")
|
|
78
|
+
ap.add_argument("--pause", type=float, default=0.0, help="Optional silence gap in seconds between chunks")
|
|
79
|
+
ap.add_argument("--arena-mb", type=int, default=448, help="GPU scratch arena size in MiB (default: 448)")
|
|
80
|
+
ap.add_argument("--max-batch", type=int, default=32, help="Max dynamic batch size (default: 32)")
|
|
81
|
+
ap.add_argument("--binary", type=Path, default=None, help="Path to roccoro-engine binary")
|
|
82
|
+
ap.add_argument("--weights", type=Path, default=None, help="Path to kokoro_v1_fp32.khip weights")
|
|
83
|
+
ap.add_argument("-q", "--quiet", action="store_true", help="Disable progress bar")
|
|
84
|
+
args = ap.parse_args(argv)
|
|
85
|
+
|
|
86
|
+
if args.text_file:
|
|
87
|
+
text = args.text_file.read_text(encoding="utf-8")
|
|
88
|
+
elif args.text:
|
|
89
|
+
text = args.text
|
|
90
|
+
elif not sys.stdin.isatty():
|
|
91
|
+
text = sys.stdin.read()
|
|
92
|
+
else:
|
|
93
|
+
ap.error("Provide text as an argument, --text-file, or stdin (or run `roccoro --help`).")
|
|
94
|
+
return 2
|
|
95
|
+
|
|
96
|
+
t0 = time.perf_counter()
|
|
97
|
+
with KokoroEngine(
|
|
98
|
+
voice=args.voice,
|
|
99
|
+
lang_code=args.lang,
|
|
100
|
+
binary_path=args.binary,
|
|
101
|
+
weights_path=args.weights,
|
|
102
|
+
arena_mb=args.arena_mb,
|
|
103
|
+
max_batch=args.max_batch,
|
|
104
|
+
) as engine:
|
|
105
|
+
t_synth = time.perf_counter()
|
|
106
|
+
out_path, audio_s = engine.synthesize_to_file(
|
|
107
|
+
text,
|
|
108
|
+
args.output,
|
|
109
|
+
speed=args.speed,
|
|
110
|
+
pause_s=args.pause,
|
|
111
|
+
show_progress=not args.quiet,
|
|
112
|
+
)
|
|
113
|
+
synth_s = max(time.perf_counter() - t_synth, 1e-6)
|
|
114
|
+
total_s = max(time.perf_counter() - t0, 1e-6)
|
|
115
|
+
print(
|
|
116
|
+
f"Saved {out_path} ({audio_s:.2f}s audio in {synth_s:.2f}s synth / {total_s:.2f}s total, "
|
|
117
|
+
f"{audio_s / synth_s:.1f}x RT)"
|
|
118
|
+
)
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def main(argv: list[str] | None = None) -> int:
|
|
123
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
124
|
+
if not args or args[0] in ("-h", "--help"):
|
|
125
|
+
print(
|
|
126
|
+
"usage: roccoro <text | subcommand> [options]\n\n"
|
|
127
|
+
"Native ROCm/HIP Kokoro-82M TTS engine (~245x RT on AMD Strix Halo / RDNA3+).\n\n"
|
|
128
|
+
"subcommands:\n"
|
|
129
|
+
" build Compile and install the native HIP `roccoro-engine` binary\n"
|
|
130
|
+
" export-weights One-time export of Kokoro-82M weights into `.khip` format\n"
|
|
131
|
+
" info Show ROCm device, binary, weights, and cache status\n\n"
|
|
132
|
+
"synthesis:\n"
|
|
133
|
+
" roccoro \"Hello from Strix Halo!\" -o hello.wav [--voice af_heart]\n"
|
|
134
|
+
" roccoro --text-file chapter.txt -o chapter.wav\n\n"
|
|
135
|
+
"options:\n"
|
|
136
|
+
" -h, --help Show this help message and exit\n"
|
|
137
|
+
" -V, --version Show program version and exit"
|
|
138
|
+
)
|
|
139
|
+
return 0
|
|
140
|
+
if args[0] in ("-V", "--version"):
|
|
141
|
+
print(f"roccoro {__version__}")
|
|
142
|
+
return 0
|
|
143
|
+
|
|
144
|
+
cmd = args[0]
|
|
145
|
+
if cmd == "info":
|
|
146
|
+
return _cmd_info()
|
|
147
|
+
if cmd == "build":
|
|
148
|
+
return _cmd_build(args[1:])
|
|
149
|
+
if cmd == "export-weights":
|
|
150
|
+
return _cmd_export(args[1:])
|
|
151
|
+
return _cmd_synth(args)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
if __name__ == "__main__":
|
|
155
|
+
sys.exit(main())
|
roccoro/csrc/Makefile
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
ROCM_PATH ?= /opt/rocm
|
|
2
|
+
HIPCC ?= $(ROCM_PATH)/bin/hipcc
|
|
3
|
+
DETECTED_ARCH := $(shell $(ROCM_PATH)/bin/rocminfo 2>/dev/null | grep -oE 'gfx[0-9a-f]+' | grep -v 'gfx000' | head -n 1)
|
|
4
|
+
ARCH ?= $(if $(DETECTED_ARCH),$(DETECTED_ARCH),gfx1151)
|
|
5
|
+
INSTALL_DIR ?= $(HOME)/.cache/roccoro
|
|
6
|
+
|
|
7
|
+
HIPFLAGS := -O3 -std=c++17 --offload-arch=$(ARCH) -I$(ROCM_PATH)/include
|
|
8
|
+
CXXFLAGS := -O3 -std=c++17 -D__HIP_PLATFORM_AMD__ -I$(ROCM_PATH)/include
|
|
9
|
+
LDFLAGS := -L$(ROCM_PATH)/lib -lamdhip64 -lrocblas -Wl,-rpath,$(ROCM_PATH)/lib
|
|
10
|
+
|
|
11
|
+
.PHONY: all install clean
|
|
12
|
+
|
|
13
|
+
all: roccoro-engine verify_fixture kokoro_bench_hip
|
|
14
|
+
|
|
15
|
+
kokoro_kernels.o: kokoro_kernels.hip kokoro_kernels.h
|
|
16
|
+
$(HIPCC) $(HIPFLAGS) -c kokoro_kernels.hip -o kokoro_kernels.o
|
|
17
|
+
|
|
18
|
+
kokoro_engine.o: kokoro_engine.cpp kokoro_engine.h kokoro_kernels.h khip_loader.h
|
|
19
|
+
g++ $(CXXFLAGS) -c kokoro_engine.cpp -o kokoro_engine.o
|
|
20
|
+
|
|
21
|
+
verify_fixture.o: verify_fixture.cpp kokoro_engine.h khip_loader.h
|
|
22
|
+
g++ $(CXXFLAGS) -c verify_fixture.cpp -o verify_fixture.o
|
|
23
|
+
|
|
24
|
+
kokoro_bench_hip.o: kokoro_bench_hip.cpp kokoro_engine.h
|
|
25
|
+
g++ $(CXXFLAGS) -c kokoro_bench_hip.cpp -o kokoro_bench_hip.o
|
|
26
|
+
|
|
27
|
+
kokoro_hip_cli.o: kokoro_hip_cli.cpp kokoro_engine.h
|
|
28
|
+
g++ $(CXXFLAGS) -c kokoro_hip_cli.cpp -o kokoro_hip_cli.o
|
|
29
|
+
|
|
30
|
+
verify_fixture: verify_fixture.o kokoro_engine.o kokoro_kernels.o
|
|
31
|
+
$(HIPCC) --offload-arch=$(ARCH) verify_fixture.o kokoro_engine.o kokoro_kernels.o $(LDFLAGS) -o verify_fixture
|
|
32
|
+
|
|
33
|
+
kokoro_bench_hip: kokoro_bench_hip.o kokoro_engine.o kokoro_kernels.o
|
|
34
|
+
$(HIPCC) --offload-arch=$(ARCH) kokoro_bench_hip.o kokoro_engine.o kokoro_kernels.o $(LDFLAGS) -o kokoro_bench_hip
|
|
35
|
+
|
|
36
|
+
roccoro-engine: kokoro_hip_cli.o kokoro_engine.o kokoro_kernels.o
|
|
37
|
+
$(HIPCC) --offload-arch=$(ARCH) kokoro_hip_cli.o kokoro_engine.o kokoro_kernels.o $(LDFLAGS) -o roccoro-engine
|
|
38
|
+
|
|
39
|
+
kokoro_hip_cli: roccoro-engine
|
|
40
|
+
cp -f roccoro-engine kokoro_hip_cli
|
|
41
|
+
|
|
42
|
+
install: roccoro-engine
|
|
43
|
+
mkdir -p "$(INSTALL_DIR)"
|
|
44
|
+
install -m 0755 roccoro-engine "$(INSTALL_DIR)/roccoro-engine"
|
|
45
|
+
@echo "Installed roccoro-engine (ARCH=$(ARCH)) -> $(INSTALL_DIR)/roccoro-engine"
|
|
46
|
+
|
|
47
|
+
clean:
|
|
48
|
+
rm -f *.o roccoro-engine kokoro_hip_cli verify_fixture kokoro_bench_hip
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
#pragma once
|
|
2
|
+
|
|
3
|
+
#include <cstdint>
|
|
4
|
+
#include <cstring>
|
|
5
|
+
#include <fcntl.h>
|
|
6
|
+
#include <stdexcept>
|
|
7
|
+
#include <string>
|
|
8
|
+
#include <sys/mman.h>
|
|
9
|
+
#include <sys/stat.h>
|
|
10
|
+
#include <unistd.h>
|
|
11
|
+
#include <unordered_map>
|
|
12
|
+
#include <vector>
|
|
13
|
+
|
|
14
|
+
namespace kokoro_hip {
|
|
15
|
+
|
|
16
|
+
constexpr uint32_t KHIP_DTYPE_FP32 = 0;
|
|
17
|
+
constexpr uint32_t KHIP_DTYPE_FP16 = 1;
|
|
18
|
+
constexpr uint32_t KHIP_DTYPE_INT32 = 2;
|
|
19
|
+
|
|
20
|
+
struct KhipTensorMeta {
|
|
21
|
+
std::string name;
|
|
22
|
+
uint32_t dtype = 0;
|
|
23
|
+
uint32_t ndim = 0;
|
|
24
|
+
uint32_t shape[4] = {1, 1, 1, 1};
|
|
25
|
+
uint64_t offset = 0;
|
|
26
|
+
uint64_t nbytes = 0;
|
|
27
|
+
|
|
28
|
+
size_t numel() const {
|
|
29
|
+
size_t n = 1;
|
|
30
|
+
for (uint32_t i = 0; i < ndim; ++i) n *= shape[i];
|
|
31
|
+
return n;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
class KhipFile {
|
|
36
|
+
public:
|
|
37
|
+
KhipFile() = default;
|
|
38
|
+
~KhipFile() { close(); }
|
|
39
|
+
|
|
40
|
+
KhipFile(const KhipFile&) = delete;
|
|
41
|
+
KhipFile& operator=(const KhipFile&) = delete;
|
|
42
|
+
|
|
43
|
+
void open(const std::string& path) {
|
|
44
|
+
close();
|
|
45
|
+
fd_ = ::open(path.c_str(), O_RDONLY);
|
|
46
|
+
if (fd_ < 0) {
|
|
47
|
+
throw std::runtime_error("Failed to open .khip file: " + path);
|
|
48
|
+
}
|
|
49
|
+
struct stat st {};
|
|
50
|
+
if (fstat(fd_, &st) != 0) {
|
|
51
|
+
close();
|
|
52
|
+
throw std::runtime_error("Failed to stat .khip file: " + path);
|
|
53
|
+
}
|
|
54
|
+
size_ = static_cast<size_t>(st.st_size);
|
|
55
|
+
data_ = static_cast<const uint8_t*>(mmap(nullptr, size_, PROT_READ, MAP_PRIVATE, fd_, 0));
|
|
56
|
+
if (data_ == MAP_FAILED) {
|
|
57
|
+
data_ = nullptr;
|
|
58
|
+
close();
|
|
59
|
+
throw std::runtime_error("Failed to mmap .khip file: " + path);
|
|
60
|
+
}
|
|
61
|
+
if (size_ < 16 || std::memcmp(data_, "KHIP", 4) != 0) {
|
|
62
|
+
close();
|
|
63
|
+
throw std::runtime_error("Invalid .khip magic: " + path);
|
|
64
|
+
}
|
|
65
|
+
uint32_t version = 0, num_tensors = 0;
|
|
66
|
+
std::memcpy(&version, data_ + 4, 4);
|
|
67
|
+
std::memcpy(&num_tensors, data_ + 8, 4);
|
|
68
|
+
if (version != 1) {
|
|
69
|
+
close();
|
|
70
|
+
throw std::runtime_error("Unsupported .khip version: " + std::to_string(version));
|
|
71
|
+
}
|
|
72
|
+
constexpr size_t kEntrySize = 168;
|
|
73
|
+
if (size_ < 16 + static_cast<size_t>(num_tensors) * kEntrySize) {
|
|
74
|
+
close();
|
|
75
|
+
throw std::runtime_error("Truncated .khip directory: " + path);
|
|
76
|
+
}
|
|
77
|
+
const uint8_t* ptr = data_ + 16;
|
|
78
|
+
tensors_.reserve(num_tensors);
|
|
79
|
+
for (uint32_t i = 0; i < num_tensors; ++i, ptr += kEntrySize) {
|
|
80
|
+
KhipTensorMeta m;
|
|
81
|
+
char name_buf[129];
|
|
82
|
+
std::memcpy(name_buf, ptr, 128);
|
|
83
|
+
name_buf[128] = '\0';
|
|
84
|
+
m.name = name_buf;
|
|
85
|
+
std::memcpy(&m.dtype, ptr + 128, 4);
|
|
86
|
+
std::memcpy(&m.ndim, ptr + 132, 4);
|
|
87
|
+
std::memcpy(m.shape, ptr + 136, 16);
|
|
88
|
+
std::memcpy(&m.offset, ptr + 152, 8);
|
|
89
|
+
std::memcpy(&m.nbytes, ptr + 160, 8);
|
|
90
|
+
if (m.offset + m.nbytes > size_) {
|
|
91
|
+
close();
|
|
92
|
+
throw std::runtime_error("Out-of-bounds tensor in .khip: " + m.name);
|
|
93
|
+
}
|
|
94
|
+
tensors_.emplace(m.name, std::move(m));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
void close() {
|
|
99
|
+
if (data_) {
|
|
100
|
+
munmap(const_cast<uint8_t*>(data_), size_);
|
|
101
|
+
data_ = nullptr;
|
|
102
|
+
}
|
|
103
|
+
if (fd_ >= 0) {
|
|
104
|
+
::close(fd_);
|
|
105
|
+
fd_ = -1;
|
|
106
|
+
}
|
|
107
|
+
size_ = 0;
|
|
108
|
+
tensors_.clear();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
bool has(const std::string& name) const { return tensors_.find(name) != tensors_.end(); }
|
|
112
|
+
|
|
113
|
+
const KhipTensorMeta& meta(const std::string& name) const {
|
|
114
|
+
auto it = tensors_.find(name);
|
|
115
|
+
if (it == tensors_.end()) {
|
|
116
|
+
throw std::runtime_error("Missing tensor in .khip: " + name);
|
|
117
|
+
}
|
|
118
|
+
return it->second;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const void* raw_ptr(const std::string& name) const {
|
|
122
|
+
const auto& m = meta(name);
|
|
123
|
+
return data_ + m.offset;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const float* f32_ptr(const std::string& name) const {
|
|
127
|
+
const auto& m = meta(name);
|
|
128
|
+
if (m.dtype != KHIP_DTYPE_FP32) {
|
|
129
|
+
throw std::runtime_error("Expected FP32 tensor: " + name);
|
|
130
|
+
}
|
|
131
|
+
return reinterpret_cast<const float*>(data_ + m.offset);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const int32_t* i32_ptr(const std::string& name) const {
|
|
135
|
+
const auto& m = meta(name);
|
|
136
|
+
if (m.dtype != KHIP_DTYPE_INT32) {
|
|
137
|
+
throw std::runtime_error("Expected INT32 tensor: " + name);
|
|
138
|
+
}
|
|
139
|
+
return reinterpret_cast<const int32_t*>(data_ + m.offset);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
private:
|
|
143
|
+
int fd_ = -1;
|
|
144
|
+
const uint8_t* data_ = nullptr;
|
|
145
|
+
size_t size_ = 0;
|
|
146
|
+
std::unordered_map<std::string, KhipTensorMeta> tensors_;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
} // namespace kokoro_hip
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
#include "kokoro_engine.h"
|
|
2
|
+
|
|
3
|
+
#include <chrono>
|
|
4
|
+
#include <cstdint>
|
|
5
|
+
#include <cstdio>
|
|
6
|
+
#include <cstring>
|
|
7
|
+
#include <fstream>
|
|
8
|
+
#include <string>
|
|
9
|
+
#include <unordered_map>
|
|
10
|
+
#include <vector>
|
|
11
|
+
|
|
12
|
+
using namespace kokoro_hip;
|
|
13
|
+
|
|
14
|
+
// Exact Kokoro-82M vocab (from config.json)
|
|
15
|
+
static std::unordered_map<std::string, int32_t> make_kokoro_vocab() {
|
|
16
|
+
return {
|
|
17
|
+
{";", 1}, {":", 2}, {",", 3}, {".", 4}, {"!", 5}, {"?", 6},
|
|
18
|
+
{"\xE2\x80\x94", 9}, {"\xE2\x80\xA6", 10}, {"\"", 11}, {"(", 12}, {")", 13},
|
|
19
|
+
{"\xE2\x80\x9C", 14}, {"\xE2\x80\x9D", 15}, {" ", 16}, {"\xCC\x83", 17},
|
|
20
|
+
{"\xCA\xA3", 18}, {"\xCA\xA5", 19}, {"\xCA\xA6", 20}, {"\xCA\xA8", 21},
|
|
21
|
+
{"\xE1\xB5\x9D", 22}, {"\xEA\xAD\xA7", 23},
|
|
22
|
+
{"A", 24}, {"I", 25}, {"O", 31}, {"Q", 33}, {"S", 35}, {"T", 36},
|
|
23
|
+
{"W", 39}, {"Y", 41}, {"\xE1\xB5\x8A", 42},
|
|
24
|
+
{"a", 43}, {"b", 44}, {"c", 45}, {"d", 46}, {"e", 47}, {"f", 48},
|
|
25
|
+
{"h", 50}, {"i", 51}, {"j", 52}, {"k", 53}, {"l", 54}, {"m", 55},
|
|
26
|
+
{"n", 56}, {"o", 57}, {"p", 58}, {"q", 59}, {"r", 60}, {"s", 61},
|
|
27
|
+
{"t", 62}, {"u", 63}, {"v", 64}, {"w", 65}, {"x", 66}, {"y", 67}, {"z", 68},
|
|
28
|
+
{"\xC9\x91", 69}, {"\xC9\x90", 70}, {"\xC9\x92", 71}, {"\xC3\xA6", 72},
|
|
29
|
+
{"\xCE\xB2", 75}, {"\xC9\x94", 76}, {"\xC9\x95", 77}, {"\xC3\xA7", 78},
|
|
30
|
+
{"\xC9\x96", 80}, {"\xC3\xB0", 81}, {"\xCA\xA4", 82}, {"\xC9\x99", 83},
|
|
31
|
+
{"\xC9\x9A", 85}, {"\xC9\x9B", 86}, {"\xC9\x9C", 87}, {"\xC9\x9F", 90},
|
|
32
|
+
{"\xC9\xA1", 92}, {"\xC9\xA5", 99}, {"\xC9\xA8", 101}, {"\xC9\xAA", 102},
|
|
33
|
+
{"\xCA\x9D", 103}, {"\xC9\xAF", 110}, {"\xC9\xB0", 111}, {"\xC5\x8B", 112},
|
|
34
|
+
{"\xC9\xB3", 113}, {"\xC9\xB2", 114}, {"\xC9\xB4", 115}, {"\xC3\xB8", 116},
|
|
35
|
+
{"\xC9\xB8", 118}, {"\xCE\xB8", 119}, {"\xC5\x93", 120}, {"\xC9\xB9", 123},
|
|
36
|
+
{"\xC9\xBE", 125}, {"\xC9\xBB", 126}, {"\xCA\x81", 128}, {"\xC9\xBD", 129},
|
|
37
|
+
{"\xCA\x82", 130}, {"\xCA\x83", 131}, {"\xCA\x88", 132}, {"\xCA\xA7", 133},
|
|
38
|
+
{"\xCA\x8A", 135}, {"\xCA\x8B", 136}, {"\xCA\x8C", 138}, {"\xC9\xA3", 139},
|
|
39
|
+
{"\xC9\xA4", 140}, {"\xCF\x87", 142}, {"\xCA\x8E", 143}, {"\xCA\x92", 147},
|
|
40
|
+
{"\xCA\x94", 148}, {"\xCB\x88", 156}, {"\xCB\x8C", 157}, {"\xCB\x90", 158},
|
|
41
|
+
{"\xCA\xB0", 162}, {"\xCA\xB2", 164}, {"\xE2\x86\x93", 169},
|
|
42
|
+
{"\xE2\x86\x92", 171}, {"\xE2\x86\x97", 172}, {"\xE2\x86\x98", 173},
|
|
43
|
+
{"\xE1\xB5\xBB", 177},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
static std::vector<int32_t> tokenize_phonemes(
|
|
48
|
+
const std::string& ps, const std::unordered_map<std::string, int32_t>& vocab, int& n_codepoints) {
|
|
49
|
+
std::vector<int32_t> ids;
|
|
50
|
+
ids.push_back(0);
|
|
51
|
+
n_codepoints = 0;
|
|
52
|
+
for (size_t i = 0; i < ps.size();) {
|
|
53
|
+
unsigned char c = static_cast<unsigned char>(ps[i]);
|
|
54
|
+
size_t w = (c < 0x80) ? 1 : (c < 0xE0) ? 2 : (c < 0xF0) ? 3 : 4;
|
|
55
|
+
if (i + w > ps.size()) break;
|
|
56
|
+
++n_codepoints;
|
|
57
|
+
auto it = vocab.find(ps.substr(i, w));
|
|
58
|
+
if (it != vocab.end()) ids.push_back(it->second);
|
|
59
|
+
i += w;
|
|
60
|
+
}
|
|
61
|
+
ids.push_back(0);
|
|
62
|
+
return ids;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
static bool write_wav(const char* path, const float* samples, size_t n_samples, int sr = 24000) {
|
|
66
|
+
FILE* f = std::fopen(path, "wb");
|
|
67
|
+
if (!f) return false;
|
|
68
|
+
uint32_t data_size = static_cast<uint32_t>(n_samples * 2);
|
|
69
|
+
uint32_t riff_size = 36 + data_size;
|
|
70
|
+
uint16_t fmt = 1, ch = 1, bits = 16, align = 2;
|
|
71
|
+
uint32_t rate = sr, brate = sr * 2, fmtsz = 16;
|
|
72
|
+
std::fwrite("RIFF", 1, 4, f); std::fwrite(&riff_size, 4, 1, f); std::fwrite("WAVE", 1, 4, f);
|
|
73
|
+
std::fwrite("fmt ", 1, 4, f); std::fwrite(&fmtsz, 4, 1, f);
|
|
74
|
+
std::fwrite(&fmt, 2, 1, f); std::fwrite(&ch, 2, 1, f); std::fwrite(&rate, 4, 1, f);
|
|
75
|
+
std::fwrite(&brate, 4, 1, f); std::fwrite(&align, 2, 1, f); std::fwrite(&bits, 2, 1, f);
|
|
76
|
+
std::fwrite("data", 1, 4, f); std::fwrite(&data_size, 4, 1, f);
|
|
77
|
+
std::vector<int16_t> pcm(n_samples);
|
|
78
|
+
for (size_t i = 0; i < n_samples; ++i) {
|
|
79
|
+
float x = samples[i];
|
|
80
|
+
if (x > 1.0f) x = 1.0f;
|
|
81
|
+
if (x < -1.0f) x = -1.0f;
|
|
82
|
+
pcm[i] = static_cast<int16_t>(x * 32767.0f);
|
|
83
|
+
}
|
|
84
|
+
std::fwrite(pcm.data(), 2, n_samples, f);
|
|
85
|
+
std::fclose(f);
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
int main(int argc, char** argv) {
|
|
90
|
+
if (argc < 4) {
|
|
91
|
+
std::fprintf(stderr, "Usage: %s <weights.khip> <voice.bin> <phonemes.txt> [out.wav]\n", argv[0]);
|
|
92
|
+
return 1;
|
|
93
|
+
}
|
|
94
|
+
const char* out_wav = (argc >= 5) ? argv[4] : nullptr;
|
|
95
|
+
|
|
96
|
+
// Load voice pack [510, 256]
|
|
97
|
+
std::ifstream vf(argv[2], std::ios::binary | std::ios::ate);
|
|
98
|
+
if (!vf) { std::fprintf(stderr, "Failed to open voice: %s\n", argv[2]); return 2; }
|
|
99
|
+
size_t vbytes = static_cast<size_t>(vf.tellg());
|
|
100
|
+
vf.seekg(0);
|
|
101
|
+
std::vector<float> voice(vbytes / sizeof(float));
|
|
102
|
+
vf.read(reinterpret_cast<char*>(voice.data()), vbytes);
|
|
103
|
+
int max_voice_rows = static_cast<int>(voice.size() / 256);
|
|
104
|
+
|
|
105
|
+
auto vocab = make_kokoro_vocab();
|
|
106
|
+
std::vector<std::vector<int32_t>> all_ids;
|
|
107
|
+
std::vector<int> style_rows;
|
|
108
|
+
std::ifstream pf(argv[3]);
|
|
109
|
+
std::string line;
|
|
110
|
+
while (std::getline(pf, line)) {
|
|
111
|
+
if (line.empty()) continue;
|
|
112
|
+
int n_cp = 0;
|
|
113
|
+
auto ids = tokenize_phonemes(line, vocab, n_cp);
|
|
114
|
+
all_ids.push_back(std::move(ids));
|
|
115
|
+
int sr = std::max(0, std::min(n_cp - 1, max_voice_rows - 1));
|
|
116
|
+
style_rows.push_back(sr);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
KokoroHipEngine eng;
|
|
120
|
+
auto t0 = std::chrono::steady_clock::now();
|
|
121
|
+
eng.load(argv[1], 448);
|
|
122
|
+
auto t1 = std::chrono::steady_clock::now();
|
|
123
|
+
|
|
124
|
+
std::vector<SynthRequest> reqs;
|
|
125
|
+
reqs.reserve(all_ids.size());
|
|
126
|
+
for (size_t i = 0; i < all_ids.size(); ++i) {
|
|
127
|
+
SynthRequest r;
|
|
128
|
+
r.input_ids = all_ids[i];
|
|
129
|
+
r.style256 = &voice[static_cast<size_t>(style_rows[i]) * 256];
|
|
130
|
+
r.speed = 1.0f;
|
|
131
|
+
r.seed = 12345 + i;
|
|
132
|
+
reqs.push_back(std::move(r));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const char* batch_env = std::getenv("KOKORO_BATCH");
|
|
136
|
+
int max_batch = (batch_env && batch_env[0]) ? std::atoi(batch_env) : 32;
|
|
137
|
+
const char* prof_env = std::getenv("KOKORO_PROFILE");
|
|
138
|
+
bool do_prof = (prof_env && prof_env[0] && prof_env[0] != '0');
|
|
139
|
+
StageProfile prof;
|
|
140
|
+
|
|
141
|
+
auto ts0 = std::chrono::steady_clock::now();
|
|
142
|
+
auto chunks_audio = eng.synthesize_batch(reqs, max_batch, do_prof ? &prof : nullptr);
|
|
143
|
+
auto ts1 = std::chrono::steady_clock::now();
|
|
144
|
+
if (do_prof) prof.print();
|
|
145
|
+
|
|
146
|
+
std::vector<float> merged;
|
|
147
|
+
size_t total_samples = 0;
|
|
148
|
+
for (const auto& a : chunks_audio) total_samples += a.size();
|
|
149
|
+
merged.reserve(total_samples);
|
|
150
|
+
for (const auto& a : chunks_audio) merged.insert(merged.end(), a.begin(), a.end());
|
|
151
|
+
|
|
152
|
+
double init_s = std::chrono::duration<double>(t1 - t0).count();
|
|
153
|
+
double synth_s = std::chrono::duration<double>(ts1 - ts0).count();
|
|
154
|
+
double total_s = std::chrono::duration<double>(ts1 - t0).count();
|
|
155
|
+
double audio_s = static_cast<double>(merged.size()) / 24000.0;
|
|
156
|
+
if (out_wav) write_wav(out_wav, merged.data(), merged.size());
|
|
157
|
+
std::printf("kokoro-hip chunks=%zu batch=%d audio_s=%.3f init_s=%.3f synth_s=%.3f total_s=%.3f synth_xRT=%.2f total_xRT=%.2f\n",
|
|
158
|
+
all_ids.size(), max_batch, audio_s, init_s, synth_s, total_s, audio_s / synth_s, audio_s / total_s);
|
|
159
|
+
return 0;
|
|
160
|
+
}
|