YuE2-3B-TensorRT / fp16 /pipeline.py
jennyxue's picture
fp16 build of YuE2-3B
3dfb5fc verified
Raw History Blame Contribute Delete
16.4 kB
"""YuE2-3B with ONNX Runtime: text-to-song (style + lyrics -> 48 kHz stereo). The AR tower (score + semantic codes),
the NAR flow-matching velocity and the VAE decoder as ONNX graphs; numpy around them, following the official
yue2_infer 0.1.5 pipeline:
- the prompt: the native instruction for the CoT mode, [Tags] style, [Lyrics] (the checkpoint's own tiktoken BPE);
- the ABC score (cot "full" / "melody") and then the semantic codes, sampled as the original samples them
(allowed tokens, minimum length, windowed repetition penalty, temperature, top-k, top-p);
- the acoustic latents: the codes' context chunks, the AR prefix cache, a 32-step midpoint ODE of the NAR velocity
from Gaussian noise (the original's ODE state is bf16; this runtime rounds it the same way);
- the VAE decoded in 512-frame tiles with a 16-frame halo (exact cores, no crossfade).
Needs numpy, onnxruntime (onnxruntime-gpu for CUDA), tiktoken; soundfile to write FLAC (else a 16-bit WAV).
python fp16/pipeline.py --style "Acoustic folk, warm male vocal" --lyrics lyrics.txt song.flac [--cuda]
"""
from __future__ import annotations
import base64
import math
import unicodedata
import wave
from pathlib import Path
import numpy as np
EOD = 151643
ABC_START, ABC_END = 151847, 151848
MUSIC_START, MUSIC_END = 151851, 151852
CODEC_OFFSET, CODEC_SIZE = 151853, 32768
VOCAB, CONTEXT = 184704, 24576
SAMPLE_RATE, RATIO = 48000, 1920
INSTRUCTIONS = {
"off": "Generate music with codec tokens from the given conditions.",
"melody": "Generate a melody-only ABC transcription without chord symbols, then generate music with codec tokens "
"from the given conditions.",
"full": "Generate a chord-annotated ABC transcription, then generate music with codec tokens from the given "
"conditions.",
}
ABC_SAMPLING = dict(temperature=0.7, top_p=0.9, top_k=30, repetition_penalty=1.005, penalty_window=100,
min_tokens=32, max_tokens=4096)
SEMANTIC_SAMPLING = dict(temperature=1.0, top_p=0.95, top_k=100, repetition_penalty=1.2, penalty_window=50,
min_tokens=200, max_tokens=9000)
ODE_STEPS = 32
PREFILL_CHUNK = 512
VAE_CORE, VAE_HALO = 512, 16
class Tokenizer:
"""yue2.tokenization_yue2.YuE2TextTokenizer: the checkpoint-native qwen.tiktoken BPE (ordinary tokens only)."""
PAT = (r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|"
r"\s+(?!\S)|\s+")
def __init__(self, path):
import tiktoken
ranks = {base64.b64decode(t): int(r) for t, r in
(line.split() for line in Path(path).read_bytes().splitlines() if line)}
specials = ["<|endoftext|>", "<|im_start|>", "<|im_end|>", "<R>", "<S>", "<X>", "<mask>", "<sep>"]
specials += [f"<extra_{i}>" for i in range(200)]
specials[204:206] = ["<abc>", "</abc>"]
self.enc = tiktoken.Encoding("YuE2", pat_str=self.PAT, mergeable_ranks=ranks,
special_tokens={s: i + len(ranks) for i, s in enumerate(specials)})
def encode(self, text):
return self.enc.encode_ordinary(unicodedata.normalize("NFC", text))
def decode(self, ids):
return self.enc.decode([int(i) for i in ids if 0 <= i < self.enc.n_vocab], errors="replace")
def request_text(style, lyrics, cot):
return f"{INSTRUCTIONS[cot]}\n[Tags]\n{style}\n[Lyrics]\n{lyrics}\n"
def prefixes(tok, style, lyrics, cot="full", abc_ids=None):
"""protocol.token_prefixes: the ABC-stage prefix (abc_ids None) or the semantic-stage prefix."""
base = [EOD] + tok.encode(request_text(style, lyrics, cot))
if cot == "off":
return base + [ABC_START, ABC_END, MUSIC_START]
if abc_ids is None:
return base + [ABC_START]
return base + [ABC_START] + list(abc_ids) + [ABC_END, MUSIC_START]
def distribution(logits, s, history, step, phase):
"""yue2.sampling.distribution (fp32): allowed tokens, minimum length, windowed repetition penalty, temperature,
top-k, top-p. Returns the scores (-inf where removed)."""
x = np.asarray(logits, np.float32).copy()
end = ABC_END if phase == "abc" else MUSIC_END
allowed = np.full(VOCAB, -np.inf, np.float32)
if phase == "abc":
allowed[:EOD] = 0
else:
allowed[CODEC_OFFSET:CODEC_OFFSET + CODEC_SIZE] = 0
allowed[end] = 0
x = x + allowed
if step < s["min_tokens"]:
x[end] = -np.inf
recent = history[-s["penalty_window"]:] if s["penalty_window"] else []
if s["repetition_penalty"] != 1.0 and len(recent):
ids, counts = np.unique(np.asarray(recent, np.int64), return_counts=True)
alpha = np.power(np.float32(s["repetition_penalty"]), counts.astype(np.float32)).astype(np.float32)
v = x[ids]
x[ids] = np.where(v < 0, v * alpha, v / alpha)
if s["temperature"] == 0:
return x
if s["temperature"] != 1:
x = x / np.float32(s["temperature"])
k = min(int(s["top_k"]), VOCAB)
kth = np.partition(x, VOCAB - k)[VOCAB - k]
x = np.where(x < kth, np.float32(-np.inf), x)
if s["top_p"] < 1:
order = np.argsort(-x, kind="stable")
v = x[order]
e = np.exp(v - v[0])
p = e / e.sum(dtype=np.float32)
removed = np.cumsum(p, dtype=np.float32) - p > np.float32(s["top_p"])
removed[:1] = False
v = np.where(removed, np.float32(-np.inf), v)
x = np.empty_like(x)
x[order] = v
return x
def softmax(x):
e = np.exp(x - x.max())
return (e / e.sum()).astype(np.float32)
def draw(probs, u):
c = np.cumsum(probs.astype(np.float64))
return min(int(np.searchsorted(c, u * c[-1], side="right")), len(probs) - 1)
def bf16(x):
"""Round float32 to the nearest bfloat16 (ties to even), as float32."""
b = np.asarray(x, np.float32).view(np.uint32)
b = (b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000
return b.astype(np.uint32).view(np.float32)
def shifted_t(raw):
"""YuE2ForCausalLM._shift_t_value with timestep_shift 1, in bf16 as the original computes it."""
t = float(bf16(np.float32(raw)))
return float(bf16(np.float32(1.0 / (1.0 + math.exp(-t)))))
def chunk_ranges(frames, prefix_tokens, context=CONTEXT):
size = min((context - prefix_tokens - 3) // 2, CONTEXT)
return [(a, min(a + size, frames)) for a in range(0, frames, size)]
class YuE2:
def __init__(self, folder, provider="cpu", emulate_bf16=True, low_memory=True):
import onnxruntime as ort
self.folder, self.ort = Path(folder), ort
self.tok = Tokenizer(self.folder / "qwen.tiktoken")
if provider != "cpu" and hasattr(ort, "preload_dlls"):
try:
ort.preload_dlls()
except Exception:
pass
self.dev = "cpu" if provider == "cpu" else "cuda"
self.pv = ["CPUExecutionProvider"] if provider == "cpu" else [
("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested", "use_tf32": "0"}),
"CPUExecutionProvider"]
self.ro = ort.RunOptions()
if provider != "cpu":
self.ro.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0")
self.s = {}
self.emulate_bf16 = emulate_bf16
self.low_memory = low_memory # one large graph at a time (AR, NAR, VAE)
def session(self, name):
"""Sessions on first use; the AR and NAR graphs keep their residual stream in fp32, which ONNX Runtime's
extended-level fusions would fold back to fp16: those two open at the basic level."""
if name not in self.s:
so = self.ort.SessionOptions()
so.log_severity_level = 3
if name in ("ar", "nar"):
so.graph_optimization_level = self.ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
self.s[name] = self.ort.InferenceSession(str(self.folder / f"{name}.onnx"), so, providers=self.pv)
if name == "ar":
ar = self.s["ar"]
self.past_names = [i.name for i in ar.get_inputs() if i.name.startswith("past_key_values.")]
self.present_names = [o.name for o in ar.get_outputs() if o.name.startswith("present.")]
pk = next(i for i in ar.get_inputs() if i.name == self.past_names[0])
self.kv_dt = np.float16 if pk.type == "tensor(float16)" else np.float32
return self.s[name]
def release(self, name):
self.s.pop(name, None)
# AR
def _ar(self, ids, cache):
ar = self.session("ar")
io = ar.io_binding()
io.bind_cpu_input("input_ids", np.asarray([ids], np.int64))
for n, v in zip(self.past_names, cache):
io.bind_ortvalue_input(n, v)
io.bind_output("logits", "cpu")
for n in self.present_names:
io.bind_output(n, self.dev)
ar.run_with_iobinding(io, self.ro)
o = io.get_outputs()
return o[0].numpy()[0], o[1:]
def prefill(self, ids):
self.session("ar")
cache = [self.ort.OrtValue.ortvalue_from_numpy(np.zeros((1, 8, 0, 128), self.kv_dt), self.dev, 0)
for _ in self.past_names]
logits = None
for a in range(0, len(ids), PREFILL_CHUNK):
logits, cache = self._ar(ids[a:a + PREFILL_CHUNK], cache)
return logits, cache
def generate(self, prefix, sampling, phase, uniforms=None, forced=None, seed=None, on_logits=None):
"""generate_tokens: returns (tokens without the end token, truncated, drawn tokens). uniforms: draws to
replay; forced: tokens to feed instead of the drawn ones (teacher forcing); on_logits(step, logits): each
step's raw logits."""
rng = np.random.default_rng(seed)
logits, cache = self.prefill(prefix)
end = ABC_END if phase == "abc" else MUSIC_END
history, drawn, eos = [], [], False
for step in range(sampling["max_tokens"]):
if on_logits is not None:
on_logits(step, logits)
sc = distribution(logits, sampling, history, step, phase)
u = uniforms[step] if uniforms is not None and step < len(uniforms) else rng.random()
t = int(np.argmax(sc)) if sampling["temperature"] == 0 else draw(softmax(sc), u)
drawn.append(t)
if forced is not None:
if step >= len(forced):
break
t = int(forced[step])
if t == end:
eos = True
break
history.append(t)
if step + 1 < sampling["max_tokens"]:
logits, cache = self._ar([t], cache)
return history, not eos, drawn
# NAR
def synthesize(self, prefix, codec, noise):
"""nar.synthesize: per context chunk, the AR cache of prefix + its codes + MUSIC_END, then the midpoint ODE
(t from 1 to 0, 32 steps) of the NAR velocity. noise [frames, 64] (the original draws it with torch's CPU
generator from the seed)."""
out = []
for a, b in chunk_ranges(len(codec), len(prefix)):
ar_tokens = list(prefix) + [int(v) + CODEC_OFFSET for v in codec[a:b]] + [MUSIC_END]
_, cache = self.prefill(ar_tokens)
if self.low_memory: # the AR and NAR graphs never resident together: the cache via system memory
host = [c.numpy() for c in cache]
cache = None
self.release("ar")
cache = [self.ort.OrtValue.ortvalue_from_numpy(h, self.dev, 0) for h in host]
host = None
out.append(self._ode(noise[a:b], cache))
if self.low_memory:
cache = None
self.release("nar")
return np.concatenate(out)
def _velocity(self, state, t, cache):
nar = self.session("nar")
io = nar.io_binding()
io.bind_cpu_input("x_t", np.ascontiguousarray(state, np.float32))
io.bind_cpu_input("t", np.asarray([t], np.float32))
for i, v in enumerate(cache):
io.bind_ortvalue_input(f"past.{i // 2}.{'key' if i % 2 == 0 else 'value'}", v)
io.bind_output("velocity", "cpu")
nar.run_with_iobinding(io, self.ro)
v = io.get_outputs()[0].numpy()
return bf16(v) if self.emulate_bf16 else v
def _ode(self, noise, cache):
r = bf16 if self.emulate_bf16 else (lambda z: np.asarray(z, np.float32))
state = r(noise)
dt = 1.0 / ODE_STEPS
for step in range(ODE_STEPS):
t = 1.0 - step * dt
raw = min(max(math.log(t / (1 - t)) if 0 < t < 1 else (20.0 if t >= 1 else -20.0), -20.0), 20.0)
first = self._velocity(state, shifted_t(raw), cache)
mid = r(state - r(first * np.float32(dt / 2)))
tm = t - dt / 2
raw_mid = min(max(math.log(tm / (1 - tm)), -20.0), 20.0)
state = r(state - r(self._velocity(mid, shifted_t(raw_mid), cache) * np.float32(dt)))
return state.astype(np.float32)
# VAE
def decode(self, latents):
"""YuE2VAE.decode_tiled (512-frame cores, 16-frame halo): [frames, 64] -> audio [samples, 2] in [-1, 1]."""
vae = self.session("vae")
z = np.ascontiguousarray(np.asarray(latents, np.float32).T[None])
frames = z.shape[-1]
total = RATIO * frames - 64
audio = np.empty((2, total), np.float32)
for start in range(0, frames, VAE_CORE):
end = min(frames, start + VAE_CORE)
left, right = max(0, start - VAE_HALO), min(frames, end + VAE_HALO)
tile = vae.run(None, {"latents": np.ascontiguousarray(z[..., left:right])}, self.ro)[0][0]
o0, o1 = start * RATIO, min(end * RATIO, total)
c0 = (start - left) * RATIO
audio[:, o0:o1] = tile[:, c0:c0 + o1 - o0]
return np.clip(audio, -1, 1).T.copy()
def __call__(self, style, lyrics, cot="full", seed=None, abc=None, abc_sampling=None, semantic_sampling=None):
rng = np.random.default_rng(seed)
abc_ids = self.tok.encode(abc) if abc is not None else None
if cot != "off" and abc_ids is None:
abc_ids, _, _ = self.generate(prefixes(self.tok, style, lyrics, cot), {**ABC_SAMPLING, **(abc_sampling or {})},
"abc", seed=int(rng.integers(2**63)))
prefix = prefixes(self.tok, style, lyrics, cot, abc_ids)
codes, _, _ = self.generate(prefix, {**SEMANTIC_SAMPLING, **(semantic_sampling or {})}, "semantic",
seed=int(rng.integers(2**63)))
codec = [t - CODEC_OFFSET for t in codes]
noise = rng.standard_normal((len(codec), 64)).astype(np.float32)
latents = self.synthesize(prefix, codec, noise)
self.release("ar")
self.release("nar")
audio = self.decode(latents)
self.release("vae")
return audio, {"abc": self.tok.decode(abc_ids) if abc_ids else None, "codec": codec}
def save_audio(path, audio):
try:
import soundfile as sf
sf.write(str(path), audio, SAMPLE_RATE)
except ImportError:
with wave.open(str(Path(path).with_suffix(".wav")), "wb") as w:
w.setnchannels(2)
w.setsampwidth(2)
w.setframerate(SAMPLE_RATE)
w.writeframes((np.clip(audio, -1, 1) * 32767).astype("<i2").tobytes())
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--style", required=True)
ap.add_argument("--lyrics", required=True, help="lyrics text or a file holding them")
ap.add_argument("out")
ap.add_argument("--cot", default="full", choices=list(INSTRUCTIONS))
ap.add_argument("--abc", help="an ABC score file to use instead of generating one")
ap.add_argument("--seed", type=int)
ap.add_argument("--dir", default=str(Path(__file__).resolve().parent))
ap.add_argument("--cuda", action="store_true")
a = ap.parse_args()
lyr = Path(a.lyrics).read_text(encoding="utf-8") if Path(a.lyrics).is_file() else a.lyrics
abc = Path(a.abc).read_text(encoding="utf-8") if a.abc else None
audio, info = YuE2(a.dir, "cuda" if a.cuda else "cpu")(a.style, lyr, a.cot, a.seed, abc)
save_audio(a.out, audio)
print(f"{len(audio) / SAMPLE_RATE:.1f} s written")