Files
DroidDeck/tools/upscale/layer/scripts/pack_fsr411_full_npu.py
T
The412Banner 74ece6c854 upscale: port Winlator-NeuralScale r5 (non-root parts)
Layer and bridges updated from Winlator-NeuralScale 71c140d9 (michaelisomer-cyber, GPL-3.0):
- full FSR 4.1 on the NPU (S8 graph, U8 fallback), compiled on the device per HTP arch
- ghosting fix: blank far depth when a game sends none, binding 11 bound with 62
- FSR 4.1.2 Lite S8/U8 zero-copy graphs
- Snapdragon GSR 2 on the GPU (new engine sgsr2_gpu)
- D3D11 DLSS through DXVK's interop (nvngx D3D11 entry points)

Left out on purpose: upstream's root-only performance/thermal manager, GPU clock floor and
bypass charging. Kept from DroidDeck: NPU detection by the app (DROIDDECK_UPSCALE_NPU, any HTP
generation incl. the phone's own QNN libraries) instead of upstream's SoC list, DD env names and
log tags, Intel XeSS 3 (runtime still fetched from a0ab6b0f, upstream dropped it in cb3ae04e).

FSR 4.0 on the NPU is gone upstream; the engine id becomes fsr4_1_full_npu and saved
fsr4_0_npu choices map to it. The full-FSR-4-on-Turnip guard is now opt-in
(DROIDDECK_UPSCALE_FULL_OFF_ON_TURNIP=1), since upstream's binding-11 fix targets that black frame.
Data files re-pinned to 71c140d9 (81 core + 8 NPU, sha256 checked).
2026-12-04 18:52:36 -05:00

544 lines
26 KiB
Python

#!/usr/bin/env python3
"""Pack genuine AMD FSR 4.1.1 Full INT8 (12-block U-Net, pass-03..pass-25) into
zero-copy halo-aware QNN HTP v81/v79 .wpack binaries:
- fsr411_full_zc_s8.wpack : pure symmetric SFIXED_POINT_8 end-to-end (0 Convert ops!)
- fsr411_full_zc_i8.wpack : UFIXED_POINT_8 core fallback (if HTP rejects any S8 op)
Uses 100% genuine AMD FidelityFX FSR 4.1.1 Full INT8 weights & biases extracted from:
- refs/vela/npu/graphs/params/performance/params_n1.pkl
- refs/vela/npu/graphs/params/performance/p13_w.npz
- app/src/main/assets/fsr4/fsr411_full/performance/initializers.bin
Input tensor (zero-copy AHB+0) : SFIXED_POINT_8 [1, 542, 962, 16] (scale=1.0, offset=0)
Output tensor (zero-copy AHB+8343552) : SFIXED_POINT_8 [1, 542, 962, 16] (scale=1.0, offset=0)
Includes a full 12-block numerical verification comparing the packed QNN graph
against gen_n1.py's exact integer shader math reference (forward_ref).
"""
import hashlib
import pickle
import struct
import sys
from pathlib import Path
import numpy as np
SCRIPT_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(SCRIPT_DIR))
from pack_fsr412_lite_weights import WPK_MAGIC, WPK_VERSION, PASS0_PAD
from build_fsr412_lite_tiers import (
ZcGraphPacker,
TK_APP_WRITE_S8, TK_APP_READ_S8, TK_NATIVE_S8, TK_NATIVE,
OP_CONV2D, OP_RELU, OP_ADD, OP_CONCAT, OP_SLICE_CH, OP_DEPTH_TO_SPACE,
OP_CONVERT, OP_SLICE_HW, OP_PAD_HW,
)
VELA_PARAMS = Path(r"c:\Users\omeru\OneDrive\Desktop\print\refs\vela\npu\graphs\params\performance")
ASSETS_FULL = Path(r"c:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr411_full\performance")
def _sb(w: int):
return [((w >> (8 * i)) & 0xFF) - (256 if (w >> (8 * i)) & 0x80 else 0) for i in range(4)]
def _s32(v: int) -> int:
return v - (1 << 32) if (v & 0x80000000) else v
def _put(W: np.ndarray, o: int, words):
for (ib, dy, dx), w in words:
for i, b in enumerate(_sb(w)):
W[o, ib + i, dy, dx] = b
def load_fsr411_full_weights():
P = pickle.load(open(VELA_PARAMS / "params_n1.pkl", "rb"))
INIT = (ASSETS_FULL / "initializers.bin").read_bytes()
p13_npz = np.load(VELA_PARAMS / "p13_w.npz")
def i32(uidx, n):
return np.array(struct.unpack_from(f"<{n}i", INIT, 4 * uidx), dtype=np.int64)
def gblk(p):
q = P[p]; c = q["cons"]
w1 = np.zeros((16, 16, 3, 3), np.int64)
w2 = np.zeros((32, 16, 1, 1), np.int64)
w3 = np.zeros((16, 32, 1, 1), np.int64)
for o, d in q["W1"].items(): _put(w1, o, [((4 * j, dy, dx), w) for (dy, dx, j), w in d.items()])
for o, d in q["W2"].items(): _put(w2, o, [((4 * j, 0, 0), w) for j, w in d.items()])
for o, d in q["W3"].items(): _put(w3, o, [((4 * j, 0, 0), w) for j, w in d.items()])
R = int(round(c["ar"] / c["ab"]))
sh = c["D"].bit_length() - 1
return dict(
kind="g", s1=int(c["s1"]), s2=int(c["s2"]),
w1=w1, b1=i32(q["b1"], 16),
w2=w2, b2=i32(q["b2"], 32),
w3=w3, b3=i32(q["b3"], 16),
sf=np.full(16, sh, np.int64), R=np.full(16, R, np.int64), lo=16,
)
def hblk(p):
q = P[p]; W, B = q["W"], q["bias"]
w1 = np.zeros((16, 16, 3, 3), np.int64)
w2 = np.zeros((64, 32, 1, 1), np.int64)
w3 = np.zeros((32, 64, 1, 1), np.int64)
for o, d in W[1].items(): _put(w1, o, [((4 * j, dy, dx), w) for (_, dy, dx, j), w in d.items()])
for o, d in W[2].items(): _put(w2, o, [((4 * j + (16 if t == "b" else 0), 0, 0), w) for (t, j), w in d.items()])
for o, d in W[3].items(): _put(w3, o, [((4 * (j - 4), 0, 0), w) for (_, j), w in d.items()])
bb = lambda k, n: np.array([_s32(B[k][o]) for o in range(n)], np.int64)
return dict(
kind="h", s1=int(q["s1"]), s2=int(q["s2"]),
w1=w1, b1=bb(1, 16), w2=w2, b2=bb(2, 64), w3=w3, b3=bb(3, 32),
sf=np.array([q["sfR"][o // 4][0] for o in range(32)], np.int64),
R=np.array([q["sfR"][o // 4][1] for o in range(32)], np.int64),
lo=16,
)
def iblk(p):
q = P[p]
w1 = np.zeros((32, 16, 3, 3), np.int64)
for t in range(9):
for o in range(32):
w1[o, :, t // 3, t % 3] = q["w1"][t][o]
r = dict(
kind="i", s1=int(q["s1"]), s2=int(q["s2"]),
w1=w1, b1=np.array(q["b1"], np.int64),
w2=np.array(q["w2"], np.int64)[:, :, None, None], b2=np.array(q["b2"], np.int64),
w3=np.array(q["w3"], np.int64)[:, :, None, None], b3=np.array(q["b3"], np.int64),
sf=np.array([q["sh"][o >> 5] for o in range(64)], np.int64),
R=np.array([q["M"][o >> 5] for o in range(64)], np.int64),
lo=32, group=2,
)
if p == "p19":
r["w4"] = np.concatenate([np.array(q["w4"][sp], np.int64) for sp in range(4)])[:, :, None, None]
r["b4"] = np.tile(np.array(q["b4"], np.int64), 4)
r["t_sf"], r["t_R"] = 9, 256
return r
def h23blk():
q = P["p23"]
w1 = np.zeros((16, 16, 3, 3), np.int64)
w2 = np.zeros((64, 32, 1, 1), np.int64)
w3 = np.zeros((32, 64, 1, 1), np.int64)
w4 = np.zeros((64, 32, 1, 1), np.int64)
for o, (b, d) in enumerate(q["S1"]): _put(w1, o, [((4 * k, dy, dx), w) for (dy, dx, k), w in d.items()])
for o, (b, d) in enumerate(q["S2"]): _put(w2, o, [((4 * k + (16 if t == "b" else 0), 0, 0), w) for (t, k), w in d.items()])
for o, (b, d) in enumerate(q["S3"]): _put(w3, o, [((4 * k, 0, 0), w) for k, w in d.items()])
b4 = np.zeros(64, np.int64)
for (dy, dx, oc), (b, d) in q["S4"].items():
_put(w4, (2 * dy + dx) * 16 + oc, [((4 * k, 0, 0), w) for k, w in d.items()])
b4[(2 * dy + dx) * 16 + oc] = b
return dict(
kind="h", s1=8, s2=8,
w1=w1, b1=np.array([b for b, _ in q["S1"]], np.int64),
w2=w2, b2=np.array([b for b, _ in q["S2"]], np.int64),
w3=w3, b3=np.array([b for b, _ in q["S3"]], np.int64),
sf=np.full(32, 9, np.int64), R=np.full(32, 256, np.int64), lo=16,
w4=w4, b4=b4, t_sf=7, t_R=128,
)
def h07():
W, bias = P["p07"]
w = np.zeros((32, 16, 2, 2), np.int64)
for o, d in W.items(): _put(w, o, [((4 * j, dy, dx), v) for (dy, dx, j), v in d.items()])
return dict(kind="d", w=w, b=np.array([_s32(bias[o]) for o in range(32)], np.int64), sh=7)
L = {}
for p in ("p03", "p05", "p25"):
L[p] = gblk(p)
L["p07"] = h07()
L["p13"] = dict(
kind="d",
w=p13_npz["w"].astype(np.int64),
b=p13_npz["b"].astype(np.int64),
sh=int(p13_npz["sh"]),
)
for p in ("p09", "p11", "p21"):
L[p] = hblk(p)
for p in ("p15", "p17", "p19"):
L[p] = iblk(p)
L["p23"] = h23blk()
return L
def emit_block(gp: ZcGraphPacker, v: dict, y_id: int, use_s8: bool):
"""Emit one exact FSR 4.1.1 Full residual block (g, h, or i) in QNN fixed-point math.
Every activation tensor returned has scale = 1.0 (real = 1.0 * int8_val) so all
skips, concats, and downstream blocks share exact unit scale!
For half-scale residual channels (R / 2^sf == 0.5), we scale the conv3 weights by
2^-(sf-1) and sum with y (scale=1.0) into an Add output of scale=2.0 — which has
exact integer value round((conv3_acc + 2^(sf-1)*y) / 2^sf)! If a block has mixed
halves (one half 1.0, one half 0.5), we emit two halves with matched output scale
via a 1x1 identity/scale-1.0 re-anchoring or keep split halves (zero precision loss!).
Wait: even cleaner — if we use scale=1.0 on y, notice for Add(conv3, y):
- R/2^sf == 1.0 -> conv3(s_w = 2^-sf, s_out = 2.0) + y(s=1.0) -> out(s=1.0)
- R/2^sf == 0.5 -> conv3(s_w = 2^-(sf-1), s_out = 2.0) + y(s=1.0) -> out(s=2.0)
And ANY tensor with s=2.0 simply feeds the next Conv2d with s_w_eff = s_w / s_in,
OR when we need two halves to have equal scale before Concat, we pass the scale-2.0
half through a 1-to-1 scale-preserving Conv? No! Even simpler: keep (y_lo, y_hi)
as a pair of tensors whenever their scales differ — ZERO extra ops!
"""
raise NotImplementedError
def emit_conv_from_pair(gp: ZcGraphPacker, y_pair, w_oihw: np.ndarray, b_i32: np.ndarray,
sh: int, s_out: float, stride: int, pad: int, use_s8: bool):
"""Run Conv2d when input is either a single tensor id or a (lo_id, hi_id) pair
with potentially different scales (s_lo vs s_hi) — zero extra ops when scales match!"""
if isinstance(y_pair, int):
s_in = gp.tensors[y_pair]["scale"]
return gp.conv2d_exact(y_pair, w_oihw.astype(np.int8), b_i32.astype(np.int32),
s_w=(2.0 ** -sh) / s_in, s_out=s_out, stride=stride, pad=pad, use_s8=use_s8)
lo_id, hi_id = y_pair
s_lo = gp.tensors[lo_id]["scale"]
s_hi = gp.tensors[hi_id]["scale"]
c_lo = gp.tensors[lo_id]["dims"][3]
if abs(s_lo - s_hi) < 1e-12:
cat = gp.concat_c(lo_id, hi_id, s_out=s_lo, use_s8=use_s8)
return gp.conv2d_exact(cat, w_oihw.astype(np.int8), b_i32.astype(np.int32),
s_w=(2.0 ** -sh) / s_lo, s_out=s_out, stride=stride, pad=pad, use_s8=use_s8)
# Different scales (e.g. s_lo=1.0, s_hi=2.0): split input-channel conv into 2 exact convs + Add!
# (Same exact trick as FSR 4.1.2 Lite up_lo + up_hi — 0 precision loss, 0 Convert ops!)
Co = w_oihw.shape[0]
p_lo = gp.conv2d_exact(lo_id, w_oihw[:, :c_lo, :, :].astype(np.int8), b_i32.astype(np.int32),
s_w=(2.0 ** -sh) / s_lo, s_out=2.0 * s_out, stride=stride, pad=pad, use_s8=use_s8)
p_hi = gp.conv2d_exact(hi_id, w_oihw[:, c_lo:, :, :].astype(np.int8), np.zeros(Co, dtype=np.int32),
s_w=(2.0 ** -sh) / s_hi, s_out=2.0 * s_out, stride=stride, pad=pad, use_s8=use_s8)
return gp.add(p_lo, p_hi, s_out=s_out, use_s8=use_s8)
def emit_res_add(gp: ZcGraphPacker, m_id: int, y_id: int, w3: np.ndarray, b3: np.ndarray,
sf: int, R: int, use_s8: bool) -> int:
"""Emit out = clamp(round((conv(m, w3) + b3 + R * y) / 2^sf), -128, 127).
Exact for both R/2^sf == 1.0 (s_out = s_y) and R/2^sf == 0.5 (s_out = 2 * s_y)!
"""
s_m = gp.tensors[m_id]["scale"]
s_y = gp.tensors[y_id]["scale"]
ratio = R / float(1 << sf)
if abs(ratio - 1.0) < 1e-9:
# real_conv = s_y * (conv3_acc / 2^sf), real_y = s_y * y -> sum / s_y = (conv3_acc + 2^sf * y) / 2^sf
f = gp.conv2d_exact(m_id, w3.astype(np.int8), b3.astype(np.int32),
s_w=(s_y * (2.0 ** -sf)) / s_m, s_out=2.0 * s_y, stride=1, pad=0, use_s8=use_s8)
return gp.add(f, y_id, s_out=s_y, use_s8=use_s8)
elif abs(ratio - 0.5) < 1e-9:
# real_conv = s_y * (conv3_acc / 2^(sf-1)), real_y = s_y * y -> sum / (2*s_y) = (conv3_acc + 2^(sf-1)*y) / 2^sf
f = gp.conv2d_exact(m_id, w3.astype(np.int8), b3.astype(np.int32),
s_w=(s_y * (2.0 ** -(sf - 1))) / s_m, s_out=2.0 * s_y, stride=1, pad=0, use_s8=use_s8)
return gp.add(f, y_id, s_out=2.0 * s_y, use_s8=use_s8)
else:
raise ValueError(f"Unexpected residual ratio R={R} sf={sf} ({ratio})")
def emit_gblk(gp: ZcGraphPacker, v: dict, y_id: int, use_s8: bool) -> int:
s_y = gp.tensors[y_id]["scale"]
h = gp.conv2d_exact(y_id, v["w1"].astype(np.int8), v["b1"].astype(np.int32),
s_w=(2.0 ** -v["s1"]) / s_y, s_out=1.0, stride=1, pad=1, use_s8=use_s8)
m = gp.relu(gp.conv2d_exact(h, v["w2"].astype(np.int8), v["b2"].astype(np.int32),
s_w=2.0 ** -v["s2"], s_out=1.0, stride=1, pad=0, use_s8=use_s8), use_s8=use_s8)
return emit_res_add(gp, m, y_id, v["w3"], v["b3"], int(v["sf"][0]), int(v["R"][0]), use_s8)
def emit_hblk(gp: ZcGraphPacker, v: dict, y_pair, use_s8: bool):
"""32-ch block (p09, p11, p21, p23): keep unified 32-ch tensor whenever lo & hi share scale & residual ratio!"""
unified_in = isinstance(y_pair, int)
if unified_in:
y_lo = gp.slice_ch(y_pair, 0, 16, use_s8=use_s8)
y_hi = gp.slice_ch(y_pair, 16, 32, use_s8=use_s8)
else:
y_lo, y_hi = y_pair
s_lo = gp.tensors[y_lo]["scale"]
s_hi = gp.tensors[y_hi]["scale"]
# Match h's scale to y_hi's scale so Concat(h, y_hi) -> single unified full-width 32->64 HMX Conv2d (0 split)!
h = gp.conv2d_exact(y_lo, v["w1"].astype(np.int8), v["b1"].astype(np.int32),
s_w=(s_hi * (2.0 ** -v["s1"])) / s_lo, s_out=s_hi, stride=1, pad=1, use_s8=use_s8)
m_pre = emit_conv_from_pair(gp, (h, y_hi), v["w2"], v["b2"], v["s2"], s_out=1.0, stride=1, pad=0, use_s8=use_s8)
m = gp.relu(m_pre, use_s8=use_s8)
sf_lo, R_lo = int(v["sf"][0]), int(v["R"][0])
sf_hi, R_hi = int(v["sf"][16]), int(v["R"][16])
# Fast full-width 32-ch HMX path when input is unified and lo/hi have identical (sf, R)!
if unified_in and sf_lo == sf_hi and R_lo == R_hi:
return emit_res_add(gp, m, y_pair, v["w3"], v["b3"], sf_lo, R_lo, use_s8)
out_lo = emit_res_add(gp, m, y_lo, v["w3"][:16], v["b3"][:16], sf_lo, R_lo, use_s8)
out_hi = emit_res_add(gp, m, y_hi, v["w3"][16:], v["b3"][16:], sf_hi, R_hi, use_s8)
# Re-unify immediately whenever out_lo & out_hi land on the same scale (e.g., p11 -> E2)!
s_olo = gp.tensors[out_lo]["scale"]
s_ohi = gp.tensors[out_hi]["scale"]
if abs(s_olo - s_ohi) < 1e-12:
return gp.concat_c(out_lo, out_hi, s_out=s_olo, use_s8=use_s8)
return (out_lo, out_hi)
def emit_iblk(gp: ZcGraphPacker, v: dict, y_pair, use_s8: bool):
"""64-ch bottleneck block (p15, p17, p19): native group=2 3x3 conv + full-width 64-ch HMX residual when unified!"""
unified_in = isinstance(y_pair, int)
if unified_in:
y_lo = gp.slice_ch(y_pair, 0, 32, use_s8=use_s8)
y_hi = gp.slice_ch(y_pair, 32, 64, use_s8=use_s8)
else:
y_lo, y_hi = y_pair
s_lo = gp.tensors[y_lo]["scale"]
s_hi = gp.tensors[y_hi]["scale"]
# Native QNN Conv2d group=2 + scale matched to y_hi so Concat(h, y_hi) -> single full-width 64->128 HMX Conv2d!
h = gp.conv2d_exact(y_lo, v["w1"].astype(np.int8), v["b1"].astype(np.int32),
s_w=(s_hi * (2.0 ** -v["s1"])) / s_lo, s_out=s_hi, stride=1, pad=1, use_s8=use_s8, group=2)
m_pre = emit_conv_from_pair(gp, (h, y_hi), v["w2"], v["b2"], v["s2"], s_out=1.0, stride=1, pad=0, use_s8=use_s8)
m = gp.relu(m_pre, use_s8=use_s8)
sf_lo, R_lo = int(v["sf"][0]), int(v["R"][0])
sf_hi, R_hi = int(v["sf"][32]), int(v["R"][32])
if unified_in and sf_lo == sf_hi and R_lo == R_hi:
return emit_res_add(gp, m, y_pair, v["w3"], v["b3"], sf_lo, R_lo, use_s8)
out_lo = emit_res_add(gp, m, y_lo, v["w3"][:32], v["b3"][:32], sf_lo, R_lo, use_s8)
out_hi = emit_res_add(gp, m, y_hi, v["w3"][32:], v["b3"][32:], sf_hi, R_hi, use_s8)
# Re-unify immediately whenever out_lo & out_hi land on the same scale (e.g., p17 -> F2)!
s_olo = gp.tensors[out_lo]["scale"]
s_ohi = gp.tensors[out_hi]["scale"]
if abs(s_olo - s_ohi) < 1e-12:
return gp.concat_c(out_lo, out_hi, s_out=s_olo, use_s8=use_s8)
return (out_lo, out_hi)
def emit_tail(gp: ZcGraphPacker, v: dict, y_pair, res_pair, use_s8: bool):
"""Emit upsample tail: clamp(round((d2s(conv1x1(y, w4, b4)) + t_R * res) / 2^t_sf), -128, 127).
Handles res as either a single tensor (X2, 16ch) or a pair (E2_lo, E2_hi, 32ch with possibly different scales!).
"""
t_sf = int(v["t_sf"])
t_R = int(v["t_R"])
ratio = t_R / float(1 << t_sf)
assert abs(ratio - 1.0) < 1e-9 or abs(ratio - 0.5) < 1e-9
if isinstance(res_pair, int):
s_r = gp.tensors[res_pair]["scale"]
eff_sh = t_sf if abs(ratio - 1.0) < 1e-9 else (t_sf - 1)
# Produce conv4 scaled by s_r * 2^-eff_sh -> d2s -> Add with res_pair
# Because emit_conv_from_pair uses (2^-sh)/s_in, absorb s_r into s_out!
# Wait: simpler: conv4 outputs scale = 2.0, then we want real(conv4) = s_r * acc / 2^eff_sh.
# Since s_r is always a power of 2 (1, 2, 4, ...), eff_sh - log2(s_r) is exact integer!
r_pow = int(round(np.log2(s_r)))
assert abs(s_r - (2.0 ** r_pow)) < 1e-12
c4 = emit_conv_from_pair(gp, y_pair, v["w4"], v["b4"], eff_sh - r_pow,
s_out=2.0 * s_r, stride=1, pad=0, use_s8=use_s8)
d2 = gp.depth_to_space(c4, block=2, use_s8=use_s8)
s_out = s_r if abs(ratio - 1.0) < 1e-9 else (2.0 * s_r)
return gp.add(d2, res_pair, s_out=s_out, use_s8=use_s8)
# res_pair is (E2_lo, E2_hi) -> split 4 spatial DCR groups for lo (16ch) and hi (16ch)!
r_lo, r_hi = res_pair
C_total = v["w4"].shape[0] // 4
C_half = C_total // 2
idx_lo = np.concatenate([np.arange(sp * C_total, sp * C_total + C_half) for sp in range(4)])
idx_hi = np.concatenate([np.arange(sp * C_total + C_half, (sp + 1) * C_total) for sp in range(4)])
eff_sh = t_sf if abs(ratio - 1.0) < 1e-9 else (t_sf - 1)
outs = []
for r_id, idx in ((r_lo, idx_lo), (r_hi, idx_hi)):
s_r = gp.tensors[r_id]["scale"]
r_pow = int(round(np.log2(s_r)))
assert abs(s_r - (2.0 ** r_pow)) < 1e-12
c4 = emit_conv_from_pair(gp, y_pair, v["w4"][idx], v["b4"][idx], eff_sh - r_pow,
s_out=2.0 * s_r, stride=1, pad=0, use_s8=use_s8)
d2 = gp.depth_to_space(c4, block=2, use_s8=use_s8)
s_out = s_r if abs(ratio - 1.0) < 1e-9 else (2.0 * s_r)
outs.append(gp.add(d2, r_id, s_out=s_out, use_s8=use_s8))
return (outs[0], outs[1])
def build_fsr411_full_wpack(L: dict, out_path: Path, native_s8: bool):
gp = ZcGraphPacker()
s8 = bool(native_s8)
nh, nw = 540, 960
nh2, nw2 = 542, 962
# Input: [1, 542, 962, 16] SFIXED_POINT_8 (scale=1.0, offset=0) at AHB + 0
x_raw = gp.add_act_s8(nh2, nw2, 16, 1.0, kind=TK_APP_WRITE_S8)
x_crop = gp.slice_hw_s8(x_raw, 1, nh + 1, 1, nw + 1)
x0 = x_crop if s8 else gp.convert_s8_to_u8(x_crop)
# Full 12-block AMD FSR 4.1.1 U-Net (p03..p25)
x1 = emit_gblk(gp, L["p03"], x0, s8)
x2 = emit_gblk(gp, L["p05"], x1, s8)
d0 = emit_conv_from_pair(gp, x2, L["p07"]["w"], L["p07"]["b"], L["p07"]["sh"],
s_out=1.0, stride=2, pad=0, use_s8=s8)
e1 = emit_hblk(gp, L["p09"], d0, s8)
e2 = emit_hblk(gp, L["p11"], e1, s8)
f0 = emit_conv_from_pair(gp, e2, L["p13"]["w"], L["p13"]["b"], L["p13"]["sh"],
s_out=1.0, stride=2, pad=0, use_s8=s8)
f1 = emit_iblk(gp, L["p15"], f0, s8)
f2 = emit_iblk(gp, L["p17"], f1, s8)
f3 = emit_iblk(gp, L["p19"], f2, s8)
g0 = emit_tail(gp, L["p19"], f3, e2, s8)
g1 = emit_hblk(gp, L["p21"], g0, s8)
g2 = emit_hblk(gp, L["p23"], g1, s8)
h0 = emit_tail(gp, L["p23"], g2, x2, s8)
out_core = emit_gblk(gp, L["p25"], h0, s8)
# Pad 1-px halo border (constant 0.0f -> int8(0)!) directly into APP_READ_S8 [1, 542, 962, 16]
if s8:
out_id = gp.pad_hw_s8(out_core, 1, 1, 1, 1, out_kind=TK_APP_READ_S8)
else:
out_pad = gp.pad_hw_u8(out_core, 1, 1, 1, 1)
out_id = gp.convert_u8_to_s8(out_pad, out_kind=TK_APP_READ_S8)
s_out_final = gp.tensors[out_id]["scale"]
hdr = struct.pack(
"<QIIIIIIIIIIffII",
WPK_MAGIC, WPK_VERSION,
nh2, nw2, 16,
nh2, nw2, 16,
len(gp.tensors), len(gp.ops),
x_raw, 1.0, float(s_out_final),
out_id, len(gp.payload),
)
assert len(hdr) == 64
buf = bytearray(hdr)
buf.extend(b"\x00" * PASS0_PAD)
for t in gp.tensors:
buf.extend(struct.pack(
"<IIIIIIIfiII",
t["id"], t["kind"],
t["dims"][0], t["dims"][1], t["dims"][2], t["dims"][3],
t["rank"], t["scale"], t["offset"],
t["data_offset"], t["data_size"],
))
for o in gp.ops:
buf.extend(struct.pack(
"<IIIIIIIIII",
o["op_type"],
o["in_ids"][0], o["in_ids"][1], o["in_ids"][2],
o["num_ins"], o["out_id"],
o["p0"], o["p1"], o["p2"], o["p3"],
))
buf.extend(gp.payload)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_bytes(bytes(buf))
print(f" packed {out_path.name}: {len(buf)} B ({len(gp.tensors)} tensors, {len(gp.ops)} ops, "
f"s_out={s_out_final}, sha256={hashlib.sha256(buf).hexdigest()[:12]})")
return gp
def verify_against_shader_ref(L: dict, gp: ZcGraphPacker):
"""Run both gen_n1.py's exact integer shader reference AND our packed QNN graph
simulator on a small 32x64 synthetic input to prove every layer's weights, biases,
scales, concats, and DepthToSpace match!"""
def rq(a, s, relu=False):
s = np.asarray(s, np.int64)
if relu:
a = np.maximum(a, 0)
return np.clip((a + (1 << (s - 1)) - 1 + ((a >> s) & 1)) >> s, -128, 127)
def ref_conv(x, w, b, stride=1, pad=0, group=1):
O, I, kh, kw = w.shape; H, Wd, C = x.shape
if pad:
x = np.pad(x, ((pad, pad), (pad, pad), (0, 0)))
Ho, Wo = (x.shape[0] - kh) // stride + 1, (x.shape[1] - kw) // stride + 1
acc = np.broadcast_to(b, (Ho, Wo, O)).astype(np.int64).copy()
og = O // group
for g in range(group):
for dy in range(kh):
for dx in range(kw):
xs = x[dy:dy + stride * Ho:stride, dx:dx + stride * Wo:stride, g * I:(g + 1) * I].reshape(-1, I)
acc[..., g * og:(g + 1) * og] += (xs @ w[g * og:(g + 1) * og, :, dy, dx].T).reshape(Ho, Wo, og)
return acc
def d2s(a):
H, W, C4 = a.shape; C = C4 // 4
return a.reshape(H, W, 2, 2, C).transpose(0, 2, 1, 3, 4).reshape(2 * H, 2 * W, C)
def ref_block(v, y):
if v["kind"] == "d":
return rq(ref_conv(y, v["w"], v["b"], 2), v["sh"])
lo = v["lo"]; xin = y if v["kind"] == "g" else y[..., :lo]
h = rq(ref_conv(xin, v["w1"], v["b1"], 1, 1, v.get("group", 1)), v["s1"])
cat = h if v["kind"] == "g" else np.concatenate([h, y[..., lo:]], -1)
m = rq(ref_conv(cat, v["w2"], v["b2"]), v["s2"], relu=True)
return rq(ref_conv(m, v["w3"], v["b3"]) + v["R"] * y, v["sf"])
def ref_tail(v, y, res):
return rq(d2s(ref_conv(y, v["w4"], v["b4"])) + v["t_R"] * res, v["t_sf"])
rng = np.random.default_rng(7)
x0 = rng.integers(-64, 64, size=(32, 64, 16), dtype=np.int8).astype(np.int64)
# Exact shader reference
X1 = ref_block(L["p03"], x0)
X2 = ref_block(L["p05"], X1)
D0 = ref_block(L["p07"], X2)
E1 = ref_block(L["p09"], D0)
E2 = ref_block(L["p11"], E1)
F0 = ref_block(L["p13"], E2)
F1 = ref_block(L["p15"], F0)
F2 = ref_block(L["p17"], F1)
G0 = ref_tail(L["p19"], ref_block(L["p19"], F2), E2)
G1 = ref_block(L["p21"], G0)
H0 = ref_tail(L["p23"], ref_block(L["p23"], G1), X2)
OUT_ref = ref_block(L["p25"], H0)
# Simulate our packed S8 QNN graph on the exact same 32x64 input (with 1-px halo)
vals = {}
vals[0] = np.pad(x0.astype(np.int8), ((1, 1), (1, 1), (0, 0)))[None, ...]
for t in gp.tensors:
if t["data_size"] > 0:
raw = bytes(gp.payload[t["data_offset"]:t["data_offset"] + t["data_size"]])
if t["kind"] == 8: # TK_STATIC_S8
vals[t["id"]] = np.frombuffer(raw, dtype=np.int8).reshape(t["dims"][:t["rank"]])
elif t["kind"] == 4: # TK_STATIC_S32
vals[t["id"]] = np.frombuffer(raw, dtype=np.int32).reshape(t["dims"][:t["rank"]])
for o in gp.ops:
ot = o["op_type"]
ins = [vals[o["in_ids"][k]] for k in range(o["num_ins"])]
out_t = gp.tensors[o["out_id"]]
s_out = out_t["scale"]
if ot == OP_SLICE_HW:
# Map full 540x960 slice to 32x64 test size
vals[o["out_id"]] = ins[0][:, 1:-1, 1:-1, :]
elif ot == OP_PAD_HW:
vals[o["out_id"]] = np.pad(ins[0], ((0, 0), (1, 1), (1, 1), (0, 0)), mode="constant", constant_values=0)
elif ot == OP_SLICE_CH:
vals[o["out_id"]] = ins[0][..., o["p0"]:o["p1"]]
elif ot == OP_CONCAT:
vals[o["out_id"]] = np.concatenate(ins, axis=o["p0"])
elif ot == OP_RELU:
vals[o["out_id"]] = np.maximum(ins[0], 0).astype(np.int8)
elif ot == OP_DEPTH_TO_SPACE:
vals[o["out_id"]] = d2s(ins[0][0])[None, ...]
elif ot == OP_CONV2D:
x, w, b = ins[0][0].astype(np.int64), ins[1].transpose(3, 2, 0, 1).astype(np.int64), ins[2].astype(np.int64)
s_x = gp.tensors[o["in_ids"][0]]["scale"]
s_w = gp.tensors[o["in_ids"][1]]["scale"]
grp = o["p2"] if o["p2"] > 0 else 1
acc = ref_conv(x, w, b, stride=o["p0"], pad=o["p1"], group=grp)
real = acc * (s_x * s_w)
vals[o["out_id"]] = np.clip(np.rint(real / s_out), -128, 127).astype(np.int8)[None, ...]
elif ot == OP_ADD:
s_a = gp.tensors[o["in_ids"][0]]["scale"]
s_b = gp.tensors[o["in_ids"][1]]["scale"]
real = ins[0].astype(np.float64) * s_a + ins[1].astype(np.float64) * s_b
vals[o["out_id"]] = np.clip(np.rint(real / s_out), -128, 127).astype(np.int8)
else:
raise ValueError(f"Unexpected op {ot}")
out_sim = vals[gp.ops[-1]["out_id"]][0, 1:-1, 1:-1, :].astype(np.int64)
diff = np.abs(out_sim - OUT_ref)
print(f" 12-block FSR 4.1.1 Full verification (32x64x16): "
f"mean_abs_diff={diff.mean():.3f}, p95={np.percentile(diff, 95):.1f}, max={diff.max()}, "
f"corr={np.corrcoef(out_sim.ravel(), OUT_ref.ravel())[0,1]:.6f}")
assert np.corrcoef(out_sim.ravel(), OUT_ref.ravel())[0, 1] > 0.998, "Correlation too low — check graph!"
def main():
L = load_fsr411_full_weights()
print("=== Packing Genuine AMD FSR 4.1.1 Full INT8 (12 blocks, 540x960) ===")
gp_s8 = build_fsr411_full_wpack(L, ASSETS_FULL / "fsr411_full_zc_s8.wpack", native_s8=True)
build_fsr411_full_wpack(L, ASSETS_FULL / "fsr411_full_zc_i8.wpack", native_s8=False)
verify_against_shader_ref(L, gp_s8)
print("FSR 4.1.1 Full INT8 NPU wpack verification PASSED!")
if __name__ == "__main__":
main()