feat: add browser talking avatar pipeline
This commit is contained in:
1 parent
ebcb6e880a
commit
16c0bf7f2e
21 files changed
+1746
-22
No files matched your search
@@ -0,0 +1,143 @@
|
||||
"""Export JoyVASA's pinned Chinese HuBERT audio path to ONNX.
|
||||
|
||||
The graph accepts one already padded four-second 16 kHz waveform (64,080
|
||||
samples) and produces the 100 x 256 audio feature window consumed by the
|
||||
diffusion denoiser. Padding is kept outside the graph so the browser can apply
|
||||
JoyVASA's small reflect pad deterministically before inference.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import onnx
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from transformers import HubertConfig
|
||||
|
||||
|
||||
EXPECTED_CHECKPOINT_SHA256 = "9dd869329725caedf5f0c13dd383abec1e385f566d8afe2047b141f604844e80"
|
||||
EXPECTED_HUBERT_CONFIG_SHA256 = "f6bd1bdef239518d022edcef31243acf344a2afa33d5428e16f221cac09cbcd0"
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
class JoyVASAAudioFeatures(nn.Module):
|
||||
def __init__(self, encoder: nn.Module, projection: nn.Module):
|
||||
super().__init__()
|
||||
self.encoder = encoder
|
||||
self.projection = projection
|
||||
|
||||
def forward(self, audio_padded: torch.Tensor) -> torch.Tensor:
|
||||
# JoyVASA first asks HuBERT for 200 frames, then back-resamples to the
|
||||
# 100 motion frames used for a four-second, 25 fps diffusion window.
|
||||
hidden = self.encoder(audio_padded, 25, frame_num=200).last_hidden_state
|
||||
hidden = F.interpolate(
|
||||
hidden.transpose(1, 2), size=100, align_corners=False, mode="linear"
|
||||
).transpose(1, 2)
|
||||
return self.projection(hidden)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--source", type=Path, required=True)
|
||||
parser.add_argument("--checkpoint", type=Path, required=True)
|
||||
parser.add_argument("--hubert-config", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
checkpoint_hash = sha256(args.checkpoint)
|
||||
config_hash = sha256(args.hubert_config)
|
||||
if checkpoint_hash != EXPECTED_CHECKPOINT_SHA256:
|
||||
raise RuntimeError(f"Unexpected checkpoint SHA-256: {checkpoint_hash}")
|
||||
if config_hash != EXPECTED_HUBERT_CONFIG_SHA256:
|
||||
raise RuntimeError(f"Unexpected HuBERT config SHA-256: {config_hash}")
|
||||
|
||||
sys.path.insert(0, str(args.source))
|
||||
from src.modules.hubert import HubertModel
|
||||
|
||||
payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
|
||||
config = HubertConfig.from_json_file(str(args.hubert_config))
|
||||
encoder = HubertModel(config).eval()
|
||||
encoder_prefix = "audio_encoder."
|
||||
encoder_state = {
|
||||
key[len(encoder_prefix):]: value
|
||||
for key, value in payload["model"].items()
|
||||
if key.startswith(encoder_prefix)
|
||||
}
|
||||
missing, unexpected = encoder.load_state_dict(encoder_state, strict=True)
|
||||
if missing or unexpected:
|
||||
raise RuntimeError(f"Encoder state mismatch, missing={missing}, unexpected={unexpected}")
|
||||
|
||||
projection = nn.Linear(768, 256).eval()
|
||||
projection.load_state_dict(
|
||||
{
|
||||
"weight": payload["model"]["audio_feature_map.weight"],
|
||||
"bias": payload["model"]["audio_feature_map.bias"],
|
||||
},
|
||||
strict=True,
|
||||
)
|
||||
model = JoyVASAAudioFeatures(encoder, projection).eval()
|
||||
|
||||
torch.manual_seed(20260710)
|
||||
audio = torch.randn(1, 64_080)
|
||||
with torch.no_grad():
|
||||
reference = model(audio).cpu().numpy()
|
||||
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
torch.onnx.export(
|
||||
model,
|
||||
(audio,),
|
||||
args.output,
|
||||
input_names=["audio_padded"],
|
||||
output_names=["audio_features"],
|
||||
opset_version=17,
|
||||
do_constant_folding=True,
|
||||
export_params=True,
|
||||
)
|
||||
graph = onnx.load(args.output, load_external_data=False)
|
||||
onnx.checker.check_model(graph)
|
||||
np.savez_compressed(
|
||||
args.output.with_suffix(".reference.npz"),
|
||||
audio_padded=audio.numpy(),
|
||||
audio_features=reference,
|
||||
)
|
||||
np.savez_compressed(
|
||||
args.output.with_suffix(".conditioning.npz"),
|
||||
start_audio_feat=payload["model"]["start_audio_feat"].numpy(),
|
||||
start_motion_feat=payload["model"]["start_motion_feat"].numpy(),
|
||||
null_audio_feat=payload["model"]["null_audio_feat"].numpy(),
|
||||
)
|
||||
metadata = {
|
||||
"checkpoint_sha256": checkpoint_hash,
|
||||
"hubert_config_sha256": config_hash,
|
||||
"onnx_sha256": sha256(args.output),
|
||||
"onnx_bytes": args.output.stat().st_size,
|
||||
"opset": 17,
|
||||
"sample_rate": 16_000,
|
||||
"unpadded_samples": 64_000,
|
||||
"padded_samples": 64_080,
|
||||
"motion_fps": 25,
|
||||
"motion_frames": 100,
|
||||
"nodes": len(graph.graph.node),
|
||||
"inputs": {item.name: [dim.dim_value for dim in item.type.tensor_type.shape.dim] for item in graph.graph.input},
|
||||
"outputs": {item.name: [dim.dim_value for dim in item.type.tensor_type.shape.dim] for item in graph.graph.output},
|
||||
}
|
||||
args.output.with_suffix(".json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
|
||||
print(json.dumps(metadata, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Export the pinned JoyVASA diffusion denoiser to a browser-oriented ONNX graph.
|
||||
|
||||
The checkpoint pickle global list must be audited before running this script. The
|
||||
pinned checkpoint currently contains only argparse.Namespace, pathlib.PosixPath,
|
||||
collections.OrderedDict, and PyTorch tensor rebuild/storage globals.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import onnx
|
||||
import torch
|
||||
|
||||
|
||||
EXPECTED_CHECKPOINT_SHA256 = "9dd869329725caedf5f0c13dd383abec1e385f566d8afe2047b141f604844e80"
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--source", type=Path, required=True)
|
||||
parser.add_argument("--checkpoint", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
checkpoint_hash = sha256(args.checkpoint)
|
||||
if checkpoint_hash != EXPECTED_CHECKPOINT_SHA256:
|
||||
raise RuntimeError(f"Unexpected checkpoint SHA-256: {checkpoint_hash}")
|
||||
|
||||
sys.path.insert(0, str(args.source))
|
||||
import src.modules.dit_talking_head as dit_module
|
||||
|
||||
# JoyVASA's helper defaults this mask to CUDA even when the network itself
|
||||
# is constructed on CPU. Keep the upstream source untouched and make the
|
||||
# export-only call follow the tensors' actual device.
|
||||
upstream_enc_dec_mask = dit_module.enc_dec_mask
|
||||
|
||||
def cpu_enc_dec_mask(T, S, frame_width=2, expansion=0, device="cpu"):
|
||||
return upstream_enc_dec_mask(T, S, frame_width, expansion, device="cpu")
|
||||
|
||||
dit_module.enc_dec_mask = cpu_enc_dec_mask
|
||||
DenoisingNetwork = dit_module.DenoisingNetwork
|
||||
|
||||
payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
|
||||
checkpoint_args = payload["args"]
|
||||
checkpoint_expected = {
|
||||
"n_diff_steps": 50,
|
||||
"feature_dim": 256,
|
||||
"n_heads": 8,
|
||||
"n_layers": 6,
|
||||
"n_motions": 100,
|
||||
"n_prev_motions": 10,
|
||||
"motion_feat_dim": 73,
|
||||
"use_indicator": True,
|
||||
}
|
||||
checkpoint_actual = {key: getattr(checkpoint_args, key) for key in checkpoint_expected}
|
||||
if checkpoint_actual != checkpoint_expected:
|
||||
raise RuntimeError(f"Unexpected JoyVASA checkpoint config: {checkpoint_actual}")
|
||||
|
||||
# The pinned JoyVASA revision does not forward most training CLI fields into
|
||||
# DenoisingNetwork. Reproduce DitTalkingHead's real constructor call exactly:
|
||||
# checkpoint motion/feature dimensions plus DenoisingNetwork defaults. The
|
||||
# resulting state is 8 layers, a 501-step sinusoidal embedding, and no
|
||||
# indicator channel. Strict loading below is the final guard against drift.
|
||||
effective_architecture = {
|
||||
"motion_feat_dim": checkpoint_args.motion_feat_dim,
|
||||
"feature_dim": checkpoint_args.feature_dim,
|
||||
"n_heads": 8,
|
||||
"n_layers": 8,
|
||||
"n_motions": 100,
|
||||
"n_prev_motions": 10,
|
||||
"n_diff_steps_embedding": 500,
|
||||
"use_indicator": False,
|
||||
"learnable_pe": False,
|
||||
}
|
||||
|
||||
model = DenoisingNetwork(
|
||||
device="cpu",
|
||||
motion_feat_dim=checkpoint_args.motion_feat_dim,
|
||||
feature_dim=checkpoint_args.feature_dim,
|
||||
).eval()
|
||||
prefix = "denoising_net."
|
||||
state = {key[len(prefix):]: value for key, value in payload["model"].items() if key.startswith(prefix)}
|
||||
missing, unexpected = model.load_state_dict(state, strict=True)
|
||||
if missing or unexpected:
|
||||
raise RuntimeError(f"State mismatch, missing={missing}, unexpected={unexpected}")
|
||||
|
||||
torch.manual_seed(20260710)
|
||||
inputs = (
|
||||
torch.randn(2, 100, 73),
|
||||
torch.randn(2, 100, 256),
|
||||
torch.randn(2, 10, 73),
|
||||
torch.randn(2, 10, 256),
|
||||
torch.tensor([50, 50], dtype=torch.int64),
|
||||
)
|
||||
with torch.no_grad():
|
||||
reference = model(*inputs).cpu().numpy()
|
||||
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
torch.onnx.export(
|
||||
model,
|
||||
inputs,
|
||||
args.output,
|
||||
input_names=["motion", "audio", "previous_motion", "previous_audio", "step"],
|
||||
output_names=["motion_prediction"],
|
||||
opset_version=17,
|
||||
do_constant_folding=True,
|
||||
export_params=True,
|
||||
)
|
||||
graph = onnx.load(args.output, load_external_data=False)
|
||||
onnx.checker.check_model(graph)
|
||||
np.savez_compressed(
|
||||
args.output.with_suffix(".reference.npz"),
|
||||
motion=inputs[0].numpy(),
|
||||
audio=inputs[1].numpy(),
|
||||
previous_motion=inputs[2].numpy(),
|
||||
previous_audio=inputs[3].numpy(),
|
||||
step=inputs[4].numpy(),
|
||||
motion_prediction=reference,
|
||||
)
|
||||
metadata = {
|
||||
"checkpoint_sha256": checkpoint_hash,
|
||||
"onnx_sha256": sha256(args.output),
|
||||
"onnx_bytes": args.output.stat().st_size,
|
||||
"opset": 17,
|
||||
"checkpoint_config": checkpoint_actual,
|
||||
"effective_architecture": effective_architecture,
|
||||
"inputs": {item.name: [dim.dim_value for dim in item.type.tensor_type.shape.dim] for item in graph.graph.input},
|
||||
"outputs": {item.name: [dim.dim_value for dim in item.type.tensor_type.shape.dim] for item in graph.graph.output},
|
||||
"nodes": len(graph.graph.node),
|
||||
}
|
||||
args.output.with_suffix(".json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
|
||||
print(json.dumps(metadata, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Create deterministic browser runtime data for the pinned JoyVASA model."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import pickle
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
|
||||
EXPECTED_CHECKPOINT_SHA256 = "9dd869329725caedf5f0c13dd383abec1e385f566d8afe2047b141f604844e80"
|
||||
EXPECTED_TEMPLATE_SHA256 = "294ce67350b18031b375361756f654c76d5e14c8f1e319cf9ed07f759ef81a98"
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
return digest
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--checkpoint", type=Path, required=True)
|
||||
parser.add_argument("--template", type=Path, required=True)
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if sha256(args.checkpoint) != EXPECTED_CHECKPOINT_SHA256:
|
||||
raise RuntimeError("Unexpected JoyVASA checkpoint")
|
||||
if sha256(args.template) != EXPECTED_TEMPLATE_SHA256:
|
||||
raise RuntimeError("Unexpected JoyVASA motion template")
|
||||
|
||||
payload = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
|
||||
# The pinned 3.6KB pickle was audited before use and contains only a dict,
|
||||
# NumPy ndarray reconstruction, ndarray, and dtype globals.
|
||||
with args.template.open("rb") as handle:
|
||||
template = pickle.load(handle)
|
||||
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
conditioning_parts = [
|
||||
("start_audio_feat", payload["model"]["start_audio_feat"].numpy()),
|
||||
("start_motion_feat", payload["model"]["start_motion_feat"].numpy()),
|
||||
("null_audio_feat", payload["model"]["null_audio_feat"].numpy()),
|
||||
]
|
||||
conditioning = np.concatenate([value.reshape(-1) for _, value in conditioning_parts]).astype("<f4")
|
||||
conditioning_path = args.output_dir / "joyvasa-conditioning.bin"
|
||||
conditioning.tofile(conditioning_path)
|
||||
|
||||
steps = 51
|
||||
x = torch.linspace(0, 50, steps)
|
||||
alpha_bars_raw = torch.cos(((x / 50) + 0.008) / 1.008 * torch.pi * 0.5) ** 2
|
||||
alpha_bars_raw = alpha_bars_raw / alpha_bars_raw[0]
|
||||
betas = 1 - alpha_bars_raw[1:] / alpha_bars_raw[:-1]
|
||||
betas = torch.clip(betas, 0.0001, 0.999)
|
||||
betas = torch.cat([torch.zeros(1), betas])
|
||||
alphas = 1 - betas
|
||||
alpha_bars = torch.cumprod(alphas, dim=0)
|
||||
schedule = torch.stack([alphas, alpha_bars], dim=1).numpy().astype("<f4")
|
||||
schedule_path = args.output_dir / "joyvasa-schedule.bin"
|
||||
schedule.tofile(schedule_path)
|
||||
|
||||
template_json = {
|
||||
key: np.asarray(value, dtype=np.float32).reshape(-1).tolist()
|
||||
for key, value in template.items()
|
||||
}
|
||||
template_path = args.output_dir / "joyvasa-motion-template.json"
|
||||
template_path.write_text(json.dumps(template_json, separators=(",", ":")), encoding="utf-8")
|
||||
|
||||
offset = 0
|
||||
layout = {}
|
||||
for name, value in conditioning_parts:
|
||||
layout[name] = {"offset": offset, "length": int(value.size), "shape": list(value.shape)}
|
||||
offset += value.size
|
||||
metadata = {
|
||||
"conditioning": {"bytes": conditioning_path.stat().st_size, "sha256": sha256(conditioning_path), "layout": layout},
|
||||
"schedule": {"bytes": schedule_path.stat().st_size, "sha256": sha256(schedule_path), "shape": [51, 2], "columns": ["alpha", "alpha_bar"]},
|
||||
"template": {"bytes": template_path.stat().st_size, "sha256": sha256(template_path), "keys": sorted(template_json)},
|
||||
}
|
||||
(args.output_dir / "joyvasa-runtime.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
|
||||
print(json.dumps(metadata, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,191 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import * as ort from "onnxruntime-web";
|
||||
|
||||
const modelDir = process.argv[2] ?? "/private/tmp";
|
||||
const sourcePath = process.argv[3] ?? "/private/tmp/liveportrait-source-256.rgb";
|
||||
const outputDir = process.argv[4] ?? "/private/tmp/liveportrait-smoke";
|
||||
const renderSpecs = (process.argv[5] ?? "closed:0.05,open:0.35")
|
||||
.split(",")
|
||||
.map((entry) => {
|
||||
const [name, ratio] = entry.split(":");
|
||||
return [name, Number(ratio)];
|
||||
});
|
||||
|
||||
ort.env.wasm.numThreads = 1;
|
||||
ort.env.wasm.simd = true;
|
||||
|
||||
const modelPath = (name) => path.join(modelDir, `liveportrait-${name}.onnx`);
|
||||
const tensor = (data, dims) => new ort.Tensor("float32", data, dims);
|
||||
|
||||
function log(stage, detail = "") {
|
||||
process.stdout.write(`[liveportrait] ${stage}${detail ? `: ${detail}` : ""}\n`);
|
||||
}
|
||||
|
||||
function imageTensorFromRgb(bytes) {
|
||||
if (bytes.length !== 256 * 256 * 3) throw new Error(`Expected 256x256 RGB input, got ${bytes.length} bytes`);
|
||||
const data = new Float32Array(bytes.length);
|
||||
const plane = 256 * 256;
|
||||
for (let i = 0; i < plane; i += 1) {
|
||||
data[i] = bytes[i * 3] / 255;
|
||||
data[plane + i] = bytes[i * 3 + 1] / 255;
|
||||
data[plane * 2 + i] = bytes[i * 3 + 2] / 255;
|
||||
}
|
||||
return tensor(data, [1, 3, 256, 256]);
|
||||
}
|
||||
|
||||
function headposeDegree(logits) {
|
||||
let max = -Infinity;
|
||||
for (const value of logits) max = Math.max(max, value);
|
||||
let sum = 0;
|
||||
let weighted = 0;
|
||||
for (let i = 0; i < logits.length; i += 1) {
|
||||
const value = Math.exp(logits[i] - max);
|
||||
sum += value;
|
||||
weighted += value * i;
|
||||
}
|
||||
return (weighted / sum) * 3 - 97.5;
|
||||
}
|
||||
|
||||
function multiply3x3(a, b) {
|
||||
const out = new Float32Array(9);
|
||||
for (let row = 0; row < 3; row += 1) {
|
||||
for (let col = 0; col < 3; col += 1) {
|
||||
out[row * 3 + col] = a[row * 3] * b[col]
|
||||
+ a[row * 3 + 1] * b[3 + col]
|
||||
+ a[row * 3 + 2] * b[6 + col];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function rotationMatrix(pitchDegree, yawDegree, rollDegree) {
|
||||
const pitch = pitchDegree * Math.PI / 180;
|
||||
const yaw = yawDegree * Math.PI / 180;
|
||||
const roll = rollDegree * Math.PI / 180;
|
||||
const rx = new Float32Array([1, 0, 0, 0, Math.cos(pitch), -Math.sin(pitch), 0, Math.sin(pitch), Math.cos(pitch)]);
|
||||
const ry = new Float32Array([Math.cos(yaw), 0, Math.sin(yaw), 0, 1, 0, -Math.sin(yaw), 0, Math.cos(yaw)]);
|
||||
const rz = new Float32Array([Math.cos(roll), -Math.sin(roll), 0, Math.sin(roll), Math.cos(roll), 0, 0, 0, 1]);
|
||||
const product = multiply3x3(rz, multiply3x3(ry, rx));
|
||||
return new Float32Array([product[0], product[3], product[6], product[1], product[4], product[7], product[2], product[5], product[8]]);
|
||||
}
|
||||
|
||||
function transformKeypoints(motion) {
|
||||
const pitch = headposeDegree(motion.pitch.data);
|
||||
const yaw = headposeDegree(motion.yaw.data);
|
||||
const roll = headposeDegree(motion.roll.data);
|
||||
const rotation = rotationMatrix(pitch, yaw, roll);
|
||||
const kp = motion.kp.data;
|
||||
const exp = motion.exp.data;
|
||||
const translation = motion.t.data;
|
||||
const scale = motion.scale.data[0];
|
||||
const out = new Float32Array(63);
|
||||
for (let point = 0; point < 21; point += 1) {
|
||||
const offset = point * 3;
|
||||
for (let axis = 0; axis < 3; axis += 1) {
|
||||
out[offset + axis] = scale * (
|
||||
kp[offset] * rotation[axis]
|
||||
+ kp[offset + 1] * rotation[3 + axis]
|
||||
+ kp[offset + 2] * rotation[6 + axis]
|
||||
+ exp[offset + axis]
|
||||
);
|
||||
}
|
||||
out[offset] += translation[0];
|
||||
out[offset + 1] += translation[1];
|
||||
}
|
||||
return { data: out, pose: { pitch, yaw, roll, scale } };
|
||||
}
|
||||
|
||||
async function createSession(name) {
|
||||
const started = Date.now();
|
||||
const session = await ort.InferenceSession.create(fs.readFileSync(modelPath(name)), {
|
||||
executionProviders: ["wasm"],
|
||||
graphOptimizationLevel: "all",
|
||||
});
|
||||
log(`loaded ${name}`, `${Date.now() - started} ms`);
|
||||
return session;
|
||||
}
|
||||
|
||||
async function retargetLip(session, sourceKeypoints, targetRatio) {
|
||||
const input = new Float32Array(65);
|
||||
input.set(sourceKeypoints, 0);
|
||||
input[63] = 0.05;
|
||||
input[64] = targetRatio;
|
||||
const result = await session.run({ input: tensor(input, [1, 65]) });
|
||||
const keypoints = new Float32Array(63);
|
||||
for (let i = 0; i < 63; i += 1) keypoints[i] = sourceKeypoints[i] + result.output.data[i];
|
||||
return keypoints;
|
||||
}
|
||||
|
||||
async function stitch(session, source, driving) {
|
||||
const input = new Float32Array(126);
|
||||
input.set(source, 0);
|
||||
input.set(driving, 63);
|
||||
const result = await session.run({ input: tensor(input, [1, 126]) });
|
||||
const output = new Float32Array(driving);
|
||||
for (let i = 0; i < 63; i += 1) output[i] += result.output.data[i];
|
||||
for (let point = 0; point < 21; point += 1) {
|
||||
output[point * 3] += result.output.data[63];
|
||||
output[point * 3 + 1] += result.output.data[64];
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function writeRgbOutput(output, name) {
|
||||
const [batch, channels, height, width] = output.dims;
|
||||
if (batch !== 1 || channels !== 3) throw new Error(`Unexpected generator output ${output.dims.join("x")}`);
|
||||
const plane = height * width;
|
||||
const rgb = Buffer.alloc(plane * 3);
|
||||
for (let i = 0; i < plane; i += 1) {
|
||||
rgb[i * 3] = Math.round(Math.max(0, Math.min(1, output.data[i])) * 255);
|
||||
rgb[i * 3 + 1] = Math.round(Math.max(0, Math.min(1, output.data[plane + i])) * 255);
|
||||
rgb[i * 3 + 2] = Math.round(Math.max(0, Math.min(1, output.data[plane * 2 + i])) * 255);
|
||||
}
|
||||
fs.writeFileSync(path.join(outputDir, `${name}-${width}x${height}.rgb`), rgb);
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
const image = imageTensorFromRgb(fs.readFileSync(sourcePath));
|
||||
|
||||
const appearance = await createSession("appearance_feature_extractor");
|
||||
const appearanceOutput = await appearance.run({ img: image });
|
||||
const feature = appearanceOutput.output;
|
||||
log("appearance inference complete", feature.dims.join("x"));
|
||||
|
||||
const motionExtractor = await createSession("motion_extractor");
|
||||
const motion = await motionExtractor.run({ img: image });
|
||||
const transformed = transformKeypoints(motion);
|
||||
const source = transformed.data;
|
||||
log("motion inference complete", JSON.stringify(transformed.pose));
|
||||
|
||||
const lip = await createSession("stitching_lip");
|
||||
const stitching = await createSession("stitching");
|
||||
const drivingKeypoints = [];
|
||||
for (const [name, ratio] of renderSpecs) {
|
||||
if (!name || !Number.isFinite(ratio)) throw new Error(`Invalid render spec ${name}:${ratio}`);
|
||||
drivingKeypoints.push([name, await stitch(stitching, source, await retargetLip(lip, source, ratio))]);
|
||||
}
|
||||
|
||||
const warping = await createSession("warping");
|
||||
const spade = await createSession("spade_generator");
|
||||
|
||||
for (const [name, driving] of drivingKeypoints) {
|
||||
const started = Date.now();
|
||||
const warped = await warping.run({
|
||||
feature_3d: feature,
|
||||
kp_source: tensor(source, [1, 21, 3]),
|
||||
kp_driving: tensor(driving, [1, 21, 3]),
|
||||
});
|
||||
log(`${name} warping complete`, `${Date.now() - started} ms`);
|
||||
const generated = await spade.run({ input: warped["879"] });
|
||||
const dimensions = writeRgbOutput(generated.output, name);
|
||||
log(`${name} frame complete`, `${dimensions.width}x${dimensions.height}`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Rewrite static 5D ONNX GridSample nodes into WebGPU-friendly 4D sampling.
|
||||
|
||||
For trilinear sampling, XY bilinear sampling is batched across every input depth
|
||||
slice with one 4D GridSample. Linear Z weights are then applied and reduced.
|
||||
This preserves align_corners=0 and zeros padding without native 5D GridSample.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import onnx
|
||||
from onnx import TensorProto, helper, numpy_helper, shape_inference
|
||||
|
||||
|
||||
def tensor_shapes(model: onnx.ModelProto) -> dict[str, list[int]]:
|
||||
inferred = shape_inference.infer_shapes(model)
|
||||
values = list(inferred.graph.input) + list(inferred.graph.value_info) + list(inferred.graph.output)
|
||||
return {
|
||||
value.name: [dimension.dim_value for dimension in value.type.tensor_type.shape.dim]
|
||||
for value in values
|
||||
}
|
||||
|
||||
|
||||
def rewrite_node(node: onnx.NodeProto, input_shape: list[int], grid_shape: list[int], index: int):
|
||||
n, channels, depth, height, width = input_shape
|
||||
grid_n, out_depth, out_height, out_width, grid_coords = grid_shape
|
||||
if n != grid_n or grid_coords != 3 or not all(input_shape + grid_shape):
|
||||
raise RuntimeError(f"GridSample must have fully static 5D shapes: {input_shape}, {grid_shape}")
|
||||
attrs = {attribute.name: helper.get_attribute_value(attribute) for attribute in node.attribute}
|
||||
if attrs != {"align_corners": 0, "mode": b"linear", "padding_mode": b"zeros"}:
|
||||
raise RuntimeError(f"Unsupported GridSample attributes: {attrs}")
|
||||
|
||||
prefix = f"webgpu_grid5d_{index}"
|
||||
initializers = []
|
||||
|
||||
def const(name: str, values, dtype=np.int64):
|
||||
full_name = f"{prefix}_{name}"
|
||||
initializers.append(numpy_helper.from_array(np.asarray(values, dtype=dtype), full_name))
|
||||
return full_name
|
||||
|
||||
shape_volume = const("shape_volume", [n * depth, channels, height, width])
|
||||
slice_starts = const("slice_starts", [0])
|
||||
slice_ends = const("slice_ends", [2])
|
||||
slice_axes = const("slice_axes", [4])
|
||||
slice_steps = const("slice_steps", [1])
|
||||
unsqueeze_depth_axis = const("unsqueeze_depth_axis", [1])
|
||||
tile_repeats = const("tile_repeats", [1, depth, 1, 1, 1, 1])
|
||||
shape_grid2d = const("shape_grid2d", [n * depth, out_depth * out_height, out_width, 2])
|
||||
shape_sampled = const("shape_sampled", [n, depth, channels, out_depth, out_height, out_width])
|
||||
z_starts = const("z_starts", [2])
|
||||
z_ends = const("z_ends", [3])
|
||||
depth_values = const("depth_values", np.arange(depth).reshape(1, 1, 1, 1, depth), np.float32)
|
||||
z_scale = const("z_scale", [depth / 2], np.float32)
|
||||
z_offset = const("z_offset", [(depth - 1) / 2], np.float32)
|
||||
one = const("one", [1], np.float32)
|
||||
zero = const("zero", [0], np.float32)
|
||||
channel_axis = const("channel_axis", [1])
|
||||
reduce_axis = const("reduce_axis", [5])
|
||||
|
||||
names = {key: f"{prefix}_{key}" for key in [
|
||||
"volume_ndchw", "volume_4d", "grid_xy", "grid_xy_depth", "grid_xy_tiled", "grid_2d",
|
||||
"sampled_4d", "sampled_6d", "sampled_ordered", "grid_z", "z_scaled", "z_input",
|
||||
"z_delta", "z_distance", "z_weight_raw", "z_weights", "z_weights_channel", "weighted",
|
||||
]}
|
||||
nodes = [
|
||||
helper.make_node("Transpose", [node.input[0]], [names["volume_ndchw"]], perm=[0, 2, 1, 3, 4], name=f"{prefix}/volume_to_ndchw"),
|
||||
helper.make_node("Reshape", [names["volume_ndchw"], shape_volume], [names["volume_4d"]], name=f"{prefix}/volume_to_4d"),
|
||||
helper.make_node("Slice", [node.input[1], slice_starts, slice_ends, slice_axes, slice_steps], [names["grid_xy"]], name=f"{prefix}/slice_xy"),
|
||||
helper.make_node("Unsqueeze", [names["grid_xy"], unsqueeze_depth_axis], [names["grid_xy_depth"]], name=f"{prefix}/add_input_depth"),
|
||||
helper.make_node("Tile", [names["grid_xy_depth"], tile_repeats], [names["grid_xy_tiled"]], name=f"{prefix}/tile_xy"),
|
||||
helper.make_node("Reshape", [names["grid_xy_tiled"], shape_grid2d], [names["grid_2d"]], name=f"{prefix}/grid_to_2d"),
|
||||
helper.make_node("GridSample", [names["volume_4d"], names["grid_2d"]], [names["sampled_4d"]], align_corners=0, mode="linear", padding_mode="zeros", name=f"{prefix}/grid_sample_2d"),
|
||||
helper.make_node("Reshape", [names["sampled_4d"], shape_sampled], [names["sampled_6d"]], name=f"{prefix}/sampled_to_6d"),
|
||||
helper.make_node("Transpose", [names["sampled_6d"]], [names["sampled_ordered"]], perm=[0, 2, 3, 4, 5, 1], name=f"{prefix}/depth_last"),
|
||||
helper.make_node("Slice", [node.input[1], z_starts, z_ends, slice_axes, slice_steps], [names["grid_z"]], name=f"{prefix}/slice_z"),
|
||||
helper.make_node("Mul", [names["grid_z"], z_scale], [names["z_scaled"]], name=f"{prefix}/scale_z"),
|
||||
helper.make_node("Add", [names["z_scaled"], z_offset], [names["z_input"]], name=f"{prefix}/offset_z"),
|
||||
helper.make_node("Sub", [names["z_input"], depth_values], [names["z_delta"]], name=f"{prefix}/z_delta"),
|
||||
helper.make_node("Abs", [names["z_delta"]], [names["z_distance"]], name=f"{prefix}/z_distance"),
|
||||
helper.make_node("Sub", [one, names["z_distance"]], [names["z_weight_raw"]], name=f"{prefix}/z_weight_raw"),
|
||||
helper.make_node("Clip", [names["z_weight_raw"], zero, one], [names["z_weights"]], name=f"{prefix}/z_weight_clip"),
|
||||
helper.make_node("Unsqueeze", [names["z_weights"], channel_axis], [names["z_weights_channel"]], name=f"{prefix}/z_weight_channel"),
|
||||
helper.make_node("Mul", [names["sampled_ordered"], names["z_weights_channel"]], [names["weighted"]], name=f"{prefix}/apply_z_weights"),
|
||||
helper.make_node("ReduceSum", [names["weighted"], reduce_axis], [node.output[0]], keepdims=0, name=f"{prefix}/sum_z"),
|
||||
]
|
||||
return nodes, initializers
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("input", type=Path)
|
||||
parser.add_argument("output", type=Path)
|
||||
args = parser.parse_args()
|
||||
model = onnx.load(args.input, load_external_data=True)
|
||||
shapes = tensor_shapes(model)
|
||||
rewritten = []
|
||||
initializers = []
|
||||
count = 0
|
||||
for node in model.graph.node:
|
||||
if node.op_type == "GridSample" and len(shapes.get(node.input[0], [])) == 5:
|
||||
nodes, constants = rewrite_node(node, shapes[node.input[0]], shapes[node.input[1]], count)
|
||||
rewritten.extend(nodes)
|
||||
initializers.extend(constants)
|
||||
count += 1
|
||||
else:
|
||||
rewritten.append(node)
|
||||
if count == 0:
|
||||
raise RuntimeError("No static 5D GridSample nodes found")
|
||||
del model.graph.node[:]
|
||||
model.graph.node.extend(rewritten)
|
||||
model.graph.initializer.extend(initializers)
|
||||
model.producer_name = "Timeline Studio LivePortrait WebGPU rewrite"
|
||||
model.producer_version = "1"
|
||||
onnx.checker.check_model(model)
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
onnx.save(model, args.output)
|
||||
print(f"rewritten={count} nodes={len(model.graph.node)} bytes={args.output.stat().st_size}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,36 @@
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
|
||||
const root = process.argv[2] ?? "/private/tmp";
|
||||
const port = Number(process.argv[3] ?? 8788);
|
||||
|
||||
const server = http.createServer((request, response) => {
|
||||
const name = decodeURIComponent(new URL(request.url, `http://${request.headers.host}`).pathname).replace(/^\/+/, "");
|
||||
if (!/^[a-z0-9_.-]+\.(onnx|png|bin|json)$/i.test(name)) {
|
||||
response.writeHead(404, { "Access-Control-Allow-Origin": "*" });
|
||||
response.end("Not found");
|
||||
return;
|
||||
}
|
||||
const file = path.join(root, name.startsWith("joyvasa-") ? name : `liveportrait-${name}`);
|
||||
fs.stat(file, (error, stat) => {
|
||||
if (error || !stat.isFile()) {
|
||||
response.writeHead(404, { "Access-Control-Allow-Origin": "*" });
|
||||
response.end("Not found");
|
||||
return;
|
||||
}
|
||||
response.writeHead(200, {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
"Content-Length": stat.size,
|
||||
"Content-Type": name.endsWith(".png")
|
||||
? "image/png"
|
||||
: name.endsWith(".json") ? "application/json" : "application/octet-stream",
|
||||
});
|
||||
fs.createReadStream(file).pipe(response);
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(port, "127.0.0.1", () => {
|
||||
process.stdout.write(`LivePortrait model server: http://127.0.0.1:${port}/\n`);
|
||||
});
|
||||
Reference in new issue
Block a user