feat: enable LivePortrait WebGPU pipeline

This commit is contained in:
haixin.yang committed 2026-07-10 19:09:15 +08:00
1 parent 16c0bf7f2e
commit 32e8a0fbb4
10 files changed
+200 -81

No files matched your search

+15 -11
View File
@@ -6,25 +6,29 @@
- Revision: `e6c5d2407593a39f29c92ffd5ea3eaf5e59d52a1`
- Runtime: `onnxruntime-web@1.27.0`
- Minimum split pipeline: appearance extractor, motion extractor, lip retargeter, stitching, warping, and SPADE generator
- Combined generator SHA-256: `44effc5f2129c03353feb56bb8db7828346c36e81ffbacb4ab0622b3d91d2c77`
- Original combined generator SHA-256: `44effc5f2129c03353feb56bb8db7828346c36e81ffbacb4ab0622b3d91d2c77`
- WebGPU rewritten generator SHA-256: `03defe3d3a391a897ae4ed4059d19ff12c9a3f46f9c605471c365775388bc551`
- Audio driver: JoyVASA Chinese HuBERT checkpoint SHA-256 `9dd869329725caedf5f0c13dd383abec1e385f566d8afe2047b141f604844e80`
## Graph audit
The opset-20 combined generator has 277 nodes, including 13 rank-5 Conv nodes and 2 rank-5 GridSample nodes. The repository's Linux `.so` plugin cannot run in a browser. The browser correctness path therefore uses the split models and ONNX Runtime Web WASM for the 3D warping stage.
The opset-20 combined generator has 277 nodes, including 13 rank-5 Conv nodes and 2 rank-5 GridSample nodes. The repository's Linux `.so` plugin cannot run in a browser. Both 5D GridSample nodes are now equivalently rewritten as batched 4D GridSample plus linear depth interpolation. The sparse-motion grid additionally uses its verified shared-XY structure to remove redundant depth sampling. The rewritten graph has 316 nodes and runs with ONNX Runtime Web's WebGPU execution provider.
The full 512×512 output was compared against the original graph with fixed inputs: maximum absolute error `7.8976e-6`, mean absolute error `1.3853e-7`, and 99.9th-percentile error `1.7881e-6`.
## Acceptance result
- Test portrait: `老外戴眼镜中年人物肖像生成-modnet.png`, 819×1024 RGBA.
- Node smoke test: appearance, motion, lip retargeting, stitching, 3D warping, and 512×512 SPADE rendering passed.
- In-app browser test: model loading, real progress reporting, WASM inference, PNG creation, reusable media insertion, and visual-track replacement passed.
- Browser output: `liveportrait-browser-acceptance.png`, 512×512.
- Node smoke test: appearance, motion, stitching, rewritten 3D warping, and 512×512 SPADE rendering passed.
- JoyVASA HuBERT and diffusion denoiser ONNX exports match PyTorch numerically (`7.75e-6` and `6.44e-6` maximum absolute error respectively).
- In-app browser test: project-local 50MB model chunks, Asyncify WebGPU runtime, JoyVASA 50-step motion generation, LivePortrait frame rendering, WebM encoding, playback, media insertion, and visual-track replacement passed.
- Browser output: a playable 3.56-second WebM; inspected frames showed open and closed mouth states plus head/eye motion.
- Browser console errors after completion: 0.
The explicit bundled `ort-wasm-simd-threaded.wasm` path is required. Without it, Vite's HTML fallback produces the `expected magic word ... found 3c 21 64 6f` error.
The WebGPU workers must use the matching `ort-wasm-simd-threaded.asyncify.mjs` and `.wasm` pair. Loading the plain or JSEP glue produces `webgpuInit is not a function`. WebGPU sessions must also be created serially because ORT rejects concurrent EP session creation.
## Remaining gates
## Remaining optimization work
- Replace or accelerate the slow 3D WASM path with WebGPU.
- Select and validate a real audio-to-motion ONNX model.
- Generate temporally consistent frames from audio, then encode and replace the visual track with a video.
- Keep full talking-video generation/export locked until these gates pass; do not substitute handcrafted visemes or simulated mouth motion.
- Current 512×512 neural rendering takes roughly 25–60 seconds per frame on the tested browser/GPU, despite full WebGPU execution.
- Evaluate FP16 conversion, a lower-resolution preview tier, and motion-aware frame interpolation before describing the feature as real-time.
- Preserve the validated model path; do not substitute handcrafted visemes or simulated mouth motion.
Binary file not shown.
Binary file not shown.
+37 -8
View File
@@ -47,9 +47,21 @@ def rewrite_node(node: onnx.NodeProto, input_shape: list[int], grid_shape: list[
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])
shared_xy = index == 0
tile_repeats = const("tile_repeats", [1, depth, 1, 1, 1] if shared_xy else [1, depth, 1, 1, 1, 1])
shape_grid2d = const(
"shape_grid2d",
[n * depth, out_height, out_width, 2] if shared_xy else [n * depth, out_depth * out_height, out_width, 2],
)
shape_sampled = const(
"shape_sampled",
[n, depth, channels, out_height, out_width] if shared_xy else [n, depth, channels, out_depth, out_height, out_width],
)
first_depth_starts = const("first_depth_starts", [0])
first_depth_ends = const("first_depth_ends", [1])
first_depth_axes = const("first_depth_axes", [1])
squeeze_first_depth_axis = const("squeeze_first_depth_axis", [1])
add_output_depth_axis = const("add_output_depth_axis", [2])
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)
@@ -64,17 +76,34 @@ def rewrite_node(node: onnx.NodeProto, input_shape: list[int], grid_shape: list[
"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",
"grid_first_depth", "grid_first_depth_xy", "grid_xy_compact", "sampled_compact",
]}
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"),
]
if shared_xy:
nodes.extend([
helper.make_node("Slice", [node.input[1], first_depth_starts, first_depth_ends, first_depth_axes, slice_steps], [names["grid_first_depth"]], name=f"{prefix}/first_output_depth"),
helper.make_node("Slice", [names["grid_first_depth"], slice_starts, slice_ends, slice_axes, slice_steps], [names["grid_first_depth_xy"]], name=f"{prefix}/slice_shared_xy"),
helper.make_node("Squeeze", [names["grid_first_depth_xy"], squeeze_first_depth_axis], [names["grid_xy_compact"]], name=f"{prefix}/remove_output_depth"),
helper.make_node("Unsqueeze", [names["grid_xy_compact"], unsqueeze_depth_axis], [names["grid_xy_depth"]], name=f"{prefix}/add_input_depth"),
])
else:
nodes.extend([
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"),
])
nodes.extend([
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("Reshape", [names["sampled_4d"], shape_sampled], [names["sampled_6d"]], name=f"{prefix}/sampled_to_nd"),
helper.make_node("Transpose", [names["sampled_6d"]], [names["sampled_compact"] if shared_xy else names["sampled_ordered"]], perm=[0, 2, 3, 4, 1] if shared_xy else [0, 2, 3, 4, 5, 1], name=f"{prefix}/depth_last"),
])
if shared_xy:
nodes.append(helper.make_node("Unsqueeze", [names["sampled_compact"], add_output_depth_axis], [names["sampled_ordered"]], name=f"{prefix}/broadcast_output_depth"))
nodes.extend([
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"),
@@ -85,7 +114,7 @@ def rewrite_node(node: onnx.NodeProto, input_shape: list[int], grid_shape: list[
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
+23 -1
View File
@@ -83,6 +83,7 @@ import {
mapNormalizedBoxToFrame,
} from "./lib/visualGeometry.js";
import { JOYVASA_PROJECT_MODEL_BASE_URL } from "./config/joyVasa.js";
import { LIVE_PORTRAIT_WEBGPU_PROJECT_MODEL_BASE_URL } from "./config/livePortrait.js";
const PLAYBACK_UI_FRAME_MS = 50;
const DEFAULT_VISION_OPTIONS = Object.freeze({
@@ -364,6 +365,7 @@ export function App() {
const visionJobGenerationRef = useRef(0);
const avatarWorkerRef = useRef(null);
const avatarTestImportedRef = useRef(false);
const avatarTestAudioImportedRef = useRef(false);
const activeLanguage = uiLanguage || "zh";
const t = useMemo(() => createTranslator(activeLanguage), [activeLanguage]);
const trOption = (name, option) => {
@@ -467,7 +469,8 @@ export function App() {
type: "generateVideo", portraitBlob: sourceBlob, motionBuffer: event.data.motion,
modelBaseUrl: import.meta.env.VITE_LIVE_PORTRAIT_MODEL_BASE_URL || "",
joyVasaModelBaseUrl: JOYVASA_PROJECT_MODEL_BASE_URL,
renderFps: 8,
webGpuModelBaseUrl: LIVE_PORTRAIT_WEBGPU_PROJECT_MODEL_BASE_URL,
renderFps: Math.max(1, Number(import.meta.env.VITE_AVATAR_RENDER_FPS || 8)),
}, [event.data.motion]);
};
@@ -855,6 +858,25 @@ export function App() {
});
}, []);
useEffect(() => {
if (!import.meta.env.DEV || !import.meta.env.VITE_AVATAR_TEST_IMAGE_URL || avatarTestAudioImportedRef.current) return;
avatarTestAudioImportedRef.current = true;
fetch("/assets/avatar-e2e-16k.wav")
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.blob();
})
.then(async (blob) => {
const waveform = await decodeWaveform(blob);
replaceAudio(blob, waveform.duration, waveform.peaks, "端到端测试配音已载入");
notify("端到端测试配音已载入配音轨");
})
.catch((error) => {
avatarTestAudioImportedRef.current = false;
console.error("Avatar E2E test audio import failed", error);
});
}, []);
useEffect(() => {
const ratioSource = visualSegments.find((segment) => segment.width > 0 && segment.height > 0);
if (!ratioSource) {
+1 -1
View File
@@ -171,7 +171,7 @@ function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration
<div className="avatar-porting-stages" aria-label={t("avatarPortingStatus")}>
<div className="is-done"><span>1</span><strong>{t("avatarStagePinned")}</strong></div>
<div className="is-done"><span>2</span><strong>{t("avatarStageGrid")}</strong></div>
<div className="is-active"><span>3</span><strong>{t("avatarStageAudio")}</strong></div>
<div className="is-done"><span>3</span><strong>{t("avatarStageAudio")}</strong></div>
</div>
{probeResult ? (
<div className="avatar-probe-results">
+36
View File
@@ -16,6 +16,24 @@ export const LIVE_PORTRAIT_WEB_MODEL = Object.freeze({
stitching: "stitching.onnx",
stitchingLip: "stitching_lip.onnx",
stitchingRetargeting: "stitching_retargeting.onnx",
generatorWebGpu: Object.freeze([
"liveportrait-generator-webgpu.onnx.part-aa?v=03defe3d",
"liveportrait-generator-webgpu.onnx.part-ab?v=03defe3d",
"liveportrait-generator-webgpu.onnx.part-ac?v=03defe3d",
"liveportrait-generator-webgpu.onnx.part-ad?v=03defe3d",
"liveportrait-generator-webgpu.onnx.part-ae?v=03defe3d",
"liveportrait-generator-webgpu.onnx.part-af?v=03defe3d",
"liveportrait-generator-webgpu.onnx.part-ag?v=03defe3d",
"liveportrait-generator-webgpu.onnx.part-ah?v=03defe3d",
"liveportrait-generator-webgpu.onnx.part-ai?v=03defe3d",
]),
appearanceFeatureExtractorWebGpu: "liveportrait-appearance_feature_extractor.onnx",
motionExtractorWebGpu: Object.freeze([
"liveportrait-motion-extractor.onnx.part-aa",
"liveportrait-motion-extractor.onnx.part-ab",
"liveportrait-motion-extractor.onnx.part-ac",
]),
stitchingWebGpu: "liveportrait-stitching.onnx",
}),
knownArtifacts: Object.freeze({
appearanceFeatureExtractor: Object.freeze({
@@ -50,9 +68,27 @@ export const LIVE_PORTRAIT_WEB_MODEL = Object.freeze({
bytes: 150_609,
sha256: "33489d795915b78a8e96787c42c367cac23a0d5d3d2bd3efbb4af5ee758d42bb",
}),
generatorWebGpu: Object.freeze({
bytes: 421_246_756,
sha256: "03defe3d3a391a897ae4ed4059d19ff12c9a3f46f9c605471c365775388bc551",
}),
appearanceFeatureExtractorWebGpu: Object.freeze({
bytes: 3_355_896,
sha256: "e9cd2bd864a970f25bbe660e132778fc7f81a4f32945a97940a6225c8b2dafb0",
}),
motionExtractorWebGpu: Object.freeze({
bytes: 112_593_241,
sha256: "6be4dcb59827a5c9af587c8d7eb07bc9f5128ea01856e9b78cf7db316787cf86",
}),
stitchingWebGpu: Object.freeze({
bytes: 182_363,
sha256: "28b5fd0b97f3cee29b37b24937f2fa294d1548799b8a16d3cfe70fab1f49c785",
}),
}),
});
export const LIVE_PORTRAIT_WEBGPU_PROJECT_MODEL_BASE_URL = "/models/liveportrait-webgpu/";
export function getLivePortraitModelUrl(file) {
return `https://huggingface.co/${LIVE_PORTRAIT_WEB_MODEL.id}/resolve/${LIVE_PORTRAIT_WEB_MODEL.revision}/${file}`;
}
+18 -18
View File
@@ -145,25 +145,25 @@ export const UI_COPY = {
avatarSupported: "浏览器已就绪",
avatarDescription: "使用正脸照片与当前 AI 配音生成会说话的人像。首版采用浏览器端 ONNX 路径,模型将在首次生成时按需下载。",
avatarPortrait: "正脸照片",
avatarWebgpu: "WASM 稳定路径",
avatarWebgpu: "全链路 WebGPU",
avatarAudio: "当前配音",
avatarCheck: "检查浏览器支持",
avatarRecheck: "重新检查浏览器",
avatarOfficial: "完整模型路线",
avatarWebPort: "Web 移植中",
avatarWebPort: "WebGPU 已跑通",
avatarService: "官方推理服务",
avatarServiceNeeded: "LivePortrait Web 移植中",
avatarServiceHint: "浏览器单帧与画面轨替换已通过验收;3D 形变当前使用较慢的 WASM 正确性路径,下一阶段接入音频驱动 ONNX 并进行 WebGPU 加速。",
avatarPortingStatus: "模型工程 · 阶段 2/3",
avatarServiceHint: "JoyVASA 音频运动与 LivePortrait 神经渲染已完成全 WebGPU 端到端验收;5D GridSample 已等价改写为 WebGPU 支持的 4D 采样与深度插值。",
avatarPortingStatus: "模型工程 · 阶段 3/3",
avatarModelSource: "锁定模型",
avatarStagePinned: "模型版本已锁定",
avatarStageGrid: "3D 形变单帧已跑通",
avatarStageAudio: "音频驱动 ONNX",
avatarStageGrid: "5D 形变已改写验证",
avatarStageAudio: "音频驱动 + WebGPU",
avatarChecking: "正在检测浏览器…",
avatarPreparing: "准备肖像",
avatarGenerateAcceptance: "生成单帧并替换画面轨",
avatarAcceptanceDone: "单帧验收完成",
avatarTrackReplaced: "LivePortrait 单帧已替换到画面轨",
avatarAcceptanceDone: "口型视频已生成并替换画面轨",
avatarTrackReplaced: "LivePortrait 口型视频已替换到画面轨",
avatarGenerationFailed: "数字人生成失败",
avatarOpen: "打开数字人控制台",
avatarLipSyncTitle: "字幕口型同步",
@@ -176,7 +176,7 @@ export const UI_COPY = {
avatarNeedsCaptions: "请先生成或添加字幕",
avatarSyncMode: "同步方式",
avatarSyncModeCaption: "字幕 + 配音精确对齐",
avatarGenerationNote: "已锁定 Hugging Face 模型提交与生成器校验值;兼容性验证不会下载 421MB 生成器。",
avatarGenerationNote: "模型已随项目按 50MB 分片托管并由服务工作线程缓存;首次运行需要下载,后续直接复用本地缓存。",
avatarGenerate: "生成口型视频",
avatarGenerating: "正在生成数字人视频",
avatarGenerationHint: "首次运行会下载模型;请保持此页面打开。",
@@ -389,25 +389,25 @@ export const UI_COPY = {
avatarSupported: "Browser ready",
avatarDescription: "Generate a talking portrait from a front-facing photo and the current AI voiceover. The browser ONNX model will download on first use.",
avatarPortrait: "Front-facing photo",
avatarWebgpu: "Stable WASM path",
avatarWebgpu: "Full WebGPU pipeline",
avatarAudio: "Current voiceover",
avatarCheck: "Check browser support",
avatarRecheck: "Recheck browser",
avatarOfficial: "Full-model path",
avatarWebPort: "Web port in progress",
avatarWebPort: "WebGPU validated",
avatarService: "Official inference service",
avatarServiceNeeded: "LivePortrait Web port in progress",
avatarServiceHint: "Browser single-frame inference and visual-track replacement have passed. The 3D warping path currently uses the slower WASM correctness path; audio-driver ONNX and WebGPU acceleration are next.",
avatarPortingStatus: "Model engineering · Stage 2/3",
avatarServiceHint: "JoyVASA audio motion and LivePortrait neural rendering passed full WebGPU end-to-end acceptance. Native 5D GridSample was equivalently rewritten as supported 4D sampling plus depth interpolation.",
avatarPortingStatus: "Model engineering · Stage 3/3",
avatarModelSource: "Pinned model",
avatarStagePinned: "Model revision pinned",
avatarStageGrid: "3D browser frame passed",
avatarStageAudio: "Audio driver ONNX",
avatarStageGrid: "5D warping rewrite validated",
avatarStageAudio: "Audio driver + WebGPU",
avatarChecking: "Checking browser…",
avatarPreparing: "Preparing portrait",
avatarGenerateAcceptance: "Generate frame and replace visual track",
avatarAcceptanceDone: "Single-frame acceptance complete",
avatarTrackReplaced: "LivePortrait frame replaced the visual track",
avatarAcceptanceDone: "Lip-sync video generated and placed on the visual track",
avatarTrackReplaced: "LivePortrait lip-sync video replaced the visual track",
avatarGenerationFailed: "Avatar generation failed",
avatarOpen: "Open avatar controls",
avatarLipSyncTitle: "Caption lip sync",
@@ -420,7 +420,7 @@ export const UI_COPY = {
avatarNeedsCaptions: "Generate or add captions first",
avatarSyncMode: "Sync method",
avatarSyncModeCaption: "Captions + voiceover alignment",
avatarGenerationNote: "The Hugging Face revision and generator checksum are pinned. Compatibility diagnostics do not download the 421 MB generator.",
avatarGenerationNote: "Models ship with the project in 50 MB chunks and are cached by the service worker. First use downloads them; later runs reuse the local cache.",
avatarGenerate: "Generate lip-sync video",
avatarGenerating: "Generating avatar video",
avatarGenerationHint: "First use downloads models. Keep this page open.",
+14 -12
View File
@@ -1,6 +1,6 @@
import * as ort from "onnxruntime-web/wasm";
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.mjs?url";
import ortWasmUrl from "../assets/ort-wasm-simd-threaded.wasm?url";
import * as ort from "onnxruntime-web/webgpu";
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.mjs?url";
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.wasm?url";
import { JOYVASA_WEB_MODEL } from "../config/joyVasa.js";
@@ -63,10 +63,11 @@ async function fetchArtifact(key, baseUrl, start, span) {
}
async function createSession(key, bytes) {
// Use the deterministic WASM backend for the audio driver as well. The ORT
// WebGPU bundle currently fails during module initialization in some browsers,
// outside this session-level error boundary.
return ort.InferenceSession.create(bytes, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
if (!self.navigator?.gpu) throw new Error(`当前浏览器没有可用的 WebGPU,无法运行 JoyVASA ${key}`);
return ort.InferenceSession.create(bytes, {
executionProviders: [{ name: "webgpu", preferredLayout: "NHWC" }],
graphOptimizationLevel: "all",
});
}
function reflectPadOnce(input, amount) {
@@ -180,13 +181,13 @@ async function generate({ audioSamples, modelBaseUrl }) {
fetchArtifact("conditioning", modelBaseUrl, 61, 1),
fetchArtifact("schedule", modelBaseUrl, 62, 1),
]);
progress(63, "初始化 JoyVASA ONNX");
const [audioSession, denoiserSession] = await Promise.all([
createSession("audio", audioBytes),
createSession("denoiser", denoiserBytes),
]);
progress(63, "初始化 JoyVASA HuBERT WebGPU");
const audioSession = await createSession("audio", audioBytes);
const window = prepareWindow(new Float32Array(audioSamples));
const audioResult = await audioSession.run({ audio_padded: tensor(window, [1, 64_080]) });
await audioSession.release();
progress(65, "初始化 JoyVASA 运动 WebGPU");
const denoiserSession = await createSession("denoiser", denoiserBytes);
progress(66, "音频特征完成");
const motion = await sampleMotion(
denoiserSession,
@@ -194,6 +195,7 @@ async function generate({ audioSamples, modelBaseUrl }) {
new Float32Array(conditioningBytes),
new Float32Array(scheduleBytes),
);
await denoiserSession.release();
progress(100, "真实音频运动生成完成");
self.postMessage({ type: "motion", motion: motion.buffer, frames: 100, fps: 25 }, [motion.buffer]);
}
+56 -30
View File
@@ -1,6 +1,6 @@
import * as ort from "onnxruntime-web/wasm";
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.mjs?url";
import ortWasmUrl from "../assets/ort-wasm-simd-threaded.wasm?url";
import * as ort from "onnxruntime-web/webgpu";
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.mjs?url";
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.wasm?url";
import { LIVE_PORTRAIT_WEB_MODEL, getLivePortraitModelUrl } from "../config/livePortrait.js";
@@ -15,34 +15,45 @@ function postProgress(progress, phase) {
}
function resolveModelUrl(file, modelBaseUrl) {
return modelBaseUrl ? new URL(file, modelBaseUrl).href : getLivePortraitModelUrl(file);
return modelBaseUrl
? new URL(file, new URL(modelBaseUrl, self.location.origin)).href
: getLivePortraitModelUrl(file);
}
async function fetchModel(key, file, modelBaseUrl, completedBytes, totalBytes) {
const response = await fetch(resolveModelUrl(file, modelBaseUrl));
if (!response.ok) throw new Error(`${file} 下载失败(HTTP ${response.status})`);
if (!response.body) return response.arrayBuffer();
const files = Array.isArray(file) ? file : [file];
const parts = [];
let loaded = 0;
const stream = response.body.pipeThrough(new TransformStream({
transform(chunk, controller) {
loaded += chunk.byteLength;
postProgress(5 + ((completedBytes + loaded) / totalBytes) * 55, `下载 ${key}`);
controller.enqueue(chunk);
},
}));
return new Response(stream).arrayBuffer();
for (const partFile of files) {
const response = await fetch(resolveModelUrl(partFile, modelBaseUrl));
if (!response.ok) throw new Error(`${partFile} 下载失败(HTTP ${response.status})`);
const bytes = new Uint8Array(await response.arrayBuffer());
parts.push(bytes);
loaded += bytes.byteLength;
postProgress(5 + ((completedBytes + loaded) / totalBytes) * 55, `下载 ${key}`);
}
const combined = new Uint8Array(loaded);
let offset = 0;
for (const part of parts) {
combined.set(part, offset);
offset += part.byteLength;
}
return combined.buffer;
}
async function loadSession(key, modelBaseUrl, downloadState) {
async function loadSession(key, modelBaseUrl, downloadState, executionProvider = "wasm") {
const file = LIVE_PORTRAIT_WEB_MODEL.files[key];
const bytes = LIVE_PORTRAIT_WEB_MODEL.knownArtifacts[key]?.bytes ?? 0;
const model = await fetchModel(key, file, modelBaseUrl, downloadState.completed, downloadState.total);
downloadState.completed += bytes;
postProgress(5 + (downloadState.completed / downloadState.total) * 55, `初始化 ${key}`);
// Keep the accepted browser pipeline on WASM until the complete LivePortrait
// graph has been validated on WebGPU. Importing the WebGPU bundle can throw an
// asynchronous ORT-internal error before session fallback gets a chance to run.
return ort.InferenceSession.create(model, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
if (executionProvider === "webgpu" && !self.navigator?.gpu) {
throw new Error("当前浏览器没有可用的 WebGPU,无法运行全 GPU LivePortrait");
}
const provider = executionProvider === "webgpu" && key === "generatorWebGpu"
? { name: "webgpu", preferredLayout: "NHWC" }
: executionProvider;
return ort.InferenceSession.create(model, { executionProviders: [provider], graphOptimizationLevel: "all" });
}
function preprocessPortrait(blob) {
@@ -197,21 +208,28 @@ function buildDrivingKeypoints(motion, source, driving, initialDriving) {
return output;
}
async function generateVideo({ portraitBlob, motionBuffer, modelBaseUrl, joyVasaModelBaseUrl, renderFps = 8 }) {
async function generateVideo({ portraitBlob, motionBuffer, modelBaseUrl, joyVasaModelBaseUrl, webGpuModelBaseUrl, renderFps = 8 }) {
postProgress(2, "准备肖像与真实口型运动");
const image = await preprocessPortrait(portraitBlob);
const keys = ["appearanceFeatureExtractor", "motionExtractor", "stitching", "warping", "spadeGenerator"];
const keys = ["appearanceFeatureExtractorWebGpu", "motionExtractorWebGpu", "stitchingWebGpu", "generatorWebGpu"];
const downloadState = { completed: 0, total: keys.reduce((sum, key) => sum + (LIVE_PORTRAIT_WEB_MODEL.knownArtifacts[key]?.bytes ?? 0), 0) };
const sessions = {};
for (const key of keys) sessions[key] = await loadSession(key, modelBaseUrl, downloadState);
for (const key of keys) {
sessions[key] = await loadSession(
key,
webGpuModelBaseUrl,
downloadState,
"webgpu",
);
}
const templateResponse = await fetch(new URL("joyvasa-motion-template.json", new URL(joyVasaModelBaseUrl, self.location.origin)));
if (!templateResponse.ok) throw new Error(`JoyVASA 运动模板下载失败(HTTP ${templateResponse.status})`);
const template = await templateResponse.json();
const coefficients = new Float32Array(motionBuffer);
postProgress(63, "提取人物 3D 特征");
const feature = (await sessions.appearanceFeatureExtractor.run({ img: image })).output;
const sourceMotion = await sessions.motionExtractor.run({ img: image });
const feature = (await sessions.appearanceFeatureExtractorWebGpu.run({ img: image })).output;
const sourceMotion = await sessions.motionExtractorWebGpu.run({ img: image });
const source = transformKeypoints(sourceMotion);
const initialDriving = decodeJoyVasaFrame(coefficients, 0, template);
const frameCount = Math.ceil(4 * renderFps);
@@ -224,7 +242,7 @@ async function generateVideo({ portraitBlob, motionBuffer, modelBaseUrl, joyVasa
const input = new Float32Array(126);
input.set(source);
input.set(rawDriving, 63);
const result = await sessions.stitching.run({ input: tensor(input, [1, 126]) });
const result = await sessions.stitchingWebGpu.run({ input: tensor(input, [1, 126]) });
const value = new Float32Array(rawDriving);
for (let i = 0; i < 63; i += 1) value[i] += result.output.data[i];
for (let point = 0; point < 21; point += 1) {
@@ -233,10 +251,18 @@ async function generateVideo({ portraitBlob, motionBuffer, modelBaseUrl, joyVasa
}
return value;
})();
const warped = await sessions.warping.run({ feature_3d: feature, kp_source: tensor(source, [1, 21, 3]), kp_driving: tensor(stitched, [1, 21, 3]) });
const generated = await sessions.spadeGenerator.run({ input: warped["879"] });
blobs.push(await outputToBlob(generated.output));
postProgress(68 + ((outputFrame + 1) / frameCount) * 31, `渲染口型帧 ${outputFrame + 1}/${frameCount}`);
const inferenceStarted = performance.now();
const generated = await sessions.generatorWebGpu.run({
feature_3d: feature,
kp_source: tensor(source, [1, 21, 3]),
kp_driving: tensor(stitched, [1, 21, 3]),
});
const inferenceMs = performance.now() - inferenceStarted;
postProgress(68 + (outputFrame / frameCount) * 31, `WebGPU 帧 ${outputFrame + 1}/${frameCount} · ${(inferenceMs / 1000).toFixed(1)}s`);
const encodeStarted = performance.now();
blobs.push(await outputToBlob(generated.out));
const encodeMs = performance.now() - encodeStarted;
postProgress(68 + ((outputFrame + 1) / frameCount) * 31, `完成帧 ${outputFrame + 1}/${frameCount} · 编码 ${(encodeMs / 1000).toFixed(1)}s`);
}
postProgress(100, "真实口型帧生成完成");
self.postMessage({ type: "videoFrames", blobs, width: 512, height: 512, fps: renderFps, duration: 4 });