Avatar Forcing portrait encoder + renderer, ONNX (fp16/fp32) for WebGPU
Browse filesFiles changed (8)
- README.mdAdded+48
- convert/fold_casts.pyAdded+27
- convert/fp16_export.pyAdded+51
- decoder_fp16.onnxAdded+3
- decoder_fp32.onnxAdded+3
- encoder_fp16.onnxAdded+3
- encoder_fp32.onnxAdded+3
- motion_basis_512x20.f32Added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748---license: cc-by-nc-4.0library_name: onnxruntimebase_model: TaekyungKi/AvatarForcingtags: - webgpu - onnx - onnxruntime-web - talking-head - avatar - avatar-forcing---
# Avatar Forcing, portrait encoder and renderer, ONNX for the browser (WebGPU)
The two image-side networks of [Avatar Forcing](https://github.com/TaekyungKi/AvatarForcing) (Ki et al., KAIST, CVPR 2026, [arXiv 2601.00664](https://arxiv.org/abs/2601.00664)),converted to ONNX from the authors' `motion_autoencoder.pth` for [onnxruntime-web](https://github.com/microsoft/onnxruntime) on WebGPU.Demo: [WeReCooking/AvatarForcing-WebGPU](https://huggingface.co/spaces/WeReCooking/AvatarForcing-WebGPU).
**Licence: CC BY-NC 4.0, inherited from the original weights. Non-commercial use, with attribution to the authors.**
| File | What | Size ||---|---|---|| `encoder_fp16.onnx` / `encoder_fp32.onnx` | portrait (1×3×512×512, values in [-1,1]) → identity style `x_r` (512) + 7 feature maps; run once per portrait | 44 / 87 MB || `decoder_fp16.onnx` / `decoder_fp32.onnx` | style `wa` (512) + the 7 feature maps → one 512×512 frame; run per frame (batch 1) | 49 / 94 MB || `motion_basis_512x20.f32` | the 512×20 orthonormal motion basis (float32, row-major): `wa = x_r + basis @ lambda` for a 20-number motion vector `lambda` | 41 KB |
Not included: the speech-to-motion flow transformer, wav2vec2, and the voice/chat parts of the original pipeline.
## Conversion notes (what mattered)- The decoder's per-sample modulated convolution is rewritten as `conv(x · style) · demod` (the same algebra as `mlx_port/decoder_fast_torch.py` in [AvatarVoice](https://github.com/johnrobinsn/AvatarVoice)); the original grouped form does not export cleanly.- **fp16 keeps the image warp (`grid_sample`) in fp32.** A fully fp16 decoder breaks the picture (about 4 dB PSNR); with the warp in fp32 it is visually lossless.- Float→float `Cast` nodes on constants are folded away (`convert/fold_casts.py`): ONNX Runtime Web's WebGPU backend otherwise refuses to build the session ("Provider type for Cast node is not set").- Exported with the dynamo exporter, opset 19 (`GridSample` is available for opset 16–19), single-file (no external data).
## Verification (CPU/software reference, real weights, one portrait)| Check | Result ||---|---|| decoder fp32 ONNX (ORT CPU) vs original PyTorch | max abs error 1.3e-5 (pixels in [-1,1]) || decoder fp32 through ORT-Web **WebGPU** (software adapter) | max abs 5.5e-5, 124.8 dB PSNR || decoder fp16 ONNX (ORT CPU) vs fp32 original | max abs 0.007, mean abs 0.0003 || fp16 encoder → fp16 decoder chain (PyTorch) vs fp32 | 66.2 dB PSNR (8-bit display rounding alone is 58.6 dB) || encoder fp32 ONNX vs original | max abs 1e-5 |
Not verified here: speed or fp16 behaviour on a physical GPU (no GPU was available). The demo page measures that on the visitor's machine and falls back to fp32 automatically if fp16 is rejected.
## CreditsOriginal model and weights: Taekyung Ki, Sangwon Jang, Jaehyeong Jo, Jaehong Yoon, Sung Ju Hwang (KAIST / NTU / DeepAuto.ai). Streaming and engineering ideas: [johnrobinsn/AvatarVoice](https://github.com/johnrobinsn/AvatarVoice).123456789101112131415161718192021222324252627import sys, onnx, numpy as npfrom onnx import numpy_helper, TensorProto, helperdef fold(path): m = onnx.load(path); g = m.graph inits = {i.name: i for i in g.initializer} types = {} for i in g.initializer: types[i.name] = i.data_type for v in list(g.input) + list(g.value_info): types[v.name] = v.type.tensor_type.elem_type removed = 0; keep = []; rename = {} for n in g.node: for k, x in enumerate(n.input): if x in rename: n.input[k] = rename[x] if n.op_type == "Cast": to = [a.i for a in n.attribute if a.name == "to"][0]; src = n.input[0] if src in inits: # Cast of a constant: fold into a new constant arr = numpy_helper.to_array(inits[src]); dt = helper.tensor_dtype_to_np_dtype(to) t = numpy_helper.from_array(arr.astype(dt), n.output[0]); g.initializer.append(t); inits[n.output[0]] = t; types[n.output[0]] = to; removed += 1; continue if types.get(src) == to: # same-type Cast: bypass rename[n.output[0]] = src; removed += 1; continue keep.append(n) del g.node[:]; g.node.extend(keep) for o in g.output: if o.name in rename: raise SystemExit("graph output renamed; unsupported") used = {x for n in g.node for x in n.input}; used |= {o.name for o in g.output} keep_i = [i for i in g.initializer if i.name in used]; pruned = len(g.initializer) - len(keep_i); del g.initializer[:]; g.initializer.extend(keep_i) onnx.save(m, path); return f'{removed} (pruned {pruned} unused constants)'for p in sys.argv[1:]: print(p, "folded/removed", fold(p))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import sys, time, numpy as np, torch, torch.nn.functional as F, onnx, onnxruntime as ort, ossys.path.insert(0, "/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad/res2/s")from common import *from PIL import ImageR = "/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad/res2/"torch.set_num_threads(4)E = enc.Encoder(512, 512, 20).eval(); D = sd.Synthesis(512, 512, 20).eval()sdict = torch.load(R + "w/motion_autoencoder.pth", map_location="cpu", weights_only=True)E.load_state_dict({k[len("motion_autoencoder.enc."):]: v for k, v in sdict.items() if k.startswith("motion_autoencoder.enc.")}, strict=True)D.load_state_dict({k[len("motion_autoencoder.dec."):]: v for k, v in sdict.items() if k.startswith("motion_autoencoder.dec.")}, strict=True)def modconv(self, input, style): batch, in_channel, h, w = input.shape style = self.modulation(style); weight = self.scale * self.weight[0] xx = input * style.view(batch, in_channel, 1, 1) if self.upsample: out = F.conv_transpose2d(xx, weight.transpose(0, 1), padding=0, stride=2) elif self.downsample: out = F.conv2d(self.blur(xx), weight, padding=0, stride=2) else: out = F.conv2d(xx, weight, padding=self.padding) if self.demodulate: w2 = weight.pow(2).sum([2, 3]); demod = torch.rsqrt(style.pow(2) @ w2.t() + 1e-8); out = out * demod.view(batch, self.out_channel, 1, 1) if self.upsample: out = self.blur(out) return outsd.ModulatedConv2d.forward = modconv_gs = F.grid_sampleF.grid_sample = lambda inp, g, **k: _gs(inp.float(), g.float(), **k).to(inp.dtype) # the warp stays fp32img = Image.open("/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad/av/repo/data/rumi.jpg").convert("RGB").resize((512, 512))x = (torch.from_numpy(np.array(img)).float().permute(2, 0, 1)[None] / 255 - 0.5) / 0.5z = np.load(R + "out/dec_in.npz"); ref = torch.from_numpy(z["ref_mv"]); r_d = torch.from_numpy(z["wa_mv"]) - E(x, input_target=None)[0].detach()class WE(torch.nn.Module): def __init__(s, e): super().__init__(); s.e = e def forward(s, x): x_r, _, f = s.e(x, input_target=None); return (x_r, *f)class WD(torch.nn.Module): def __init__(s, d): super().__init__(); s.d = d def forward(s, wa, *f): return s.d(wa, None, list(f))[0]Eh = WE(E).half().eval(); Dh = WD(D).half().eval()with torch.no_grad(): outs = Eh(x.half()); x_r = outs[0]; feats = list(outs[1:]) img16 = Dh((x_r + r_d.half()), *feats).float()d = (img16 - ref).abs()mse = float(((img16 - ref) ** 2).mean()); print("fp16 encoder -> fp16 decoder chain vs fp32: max abs %.3f mean abs %.5f PSNR %.1f dB" % (d.max(), d.mean(), 10 * np.log10(4 / mse)))Image.fromarray(((img16[0].clamp(-1, 1) * 0.5 + 0.5) * 255).byte().permute(1, 2, 0).numpy()).save(R + "out/fp16_chain.png")names_d = ["wa"] + [f"f{i}" for i in range(7)]t = time.time()with torch.no_grad(): torch.onnx.export(Eh, (x.half(),), R + "pub/encoder_fp16.onnx", opset_version=19, dynamo=True, input_names=["img"], output_names=["x_r"] + [f"f{i}" for i in range(7)]) torch.onnx.export(Dh, ((x_r + r_d.half()), *feats), R + "pub/decoder_fp16.onnx", opset_version=19, dynamo=True, input_names=names_d, output_names=["img"])print("export %.1fs" % (time.time() - t))for n in ["encoder_fp16", "decoder_fp16"]: m = onnx.load(R + f"pub/{n}.onnx", load_external_data=False) import collections; print(n, sorted(collections.Counter(nd.op_type for nd in m.graph.node).items()))np.savez(R + "out/chain_in.npz", img=x.numpy(), xr_rd=(x_r + r_d.half()).numpy(), ref=ref.numpy())print({f: round(os.path.getsize(R + "pub/" + f) / 1e6, 1) for f in os.listdir(R + "pub")})123version https://git-lfs.github.com/spec/v1oid sha256:ad1771e04550ed8a87f4791d9d5b7201a17806a9ecd3a84d73f4bb0f01b3d2b1size 48767839123version https://git-lfs.github.com/spec/v1oid sha256:7d3a1517da2ffe5ac98993a6af03a54cba5944ab460c50adbd5aafd8f894ff35size 93696744123version https://git-lfs.github.com/spec/v1oid sha256:ae9fd075b51e7b7410a0a85647b879472177e802805d1b6edc3488f2def4a654size 43761689123version https://git-lfs.github.com/spec/v1oid sha256:781474c822bdae58b7ad5712f3672262113ccd8667064b09beae4177609c4155size 87090622README.mdAdded+48
convert/fold_casts.pyAdded+27
convert/fp16_export.pyAdded+51
decoder_fp16.onnxAdded+3
decoder_fp32.onnxAdded+3
encoder_fp16.onnxAdded+3
encoder_fp32.onnxAdded+3
motion_basis_512x20.f32Added