mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
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).
517 lines
23 KiB
Python
517 lines
23 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate verified native 1080p, 900p, and 720p AMD FSR 4.1.2 Lite SPIR-V shaders
|
|
and zero-copy halo-aware QNN HTP v81 .wpack graphs.
|
|
|
|
Every generated SPIR-V shader is assembled with spirv-as and validated with
|
|
spirv-val --target-env vulkan1.1. Only exact audited geometry/scratch OpConstant
|
|
definitions are rewritten; all neural network weights, biases, and math stay
|
|
100% bit-for-bit identical to AMD FidelityFX SDK v2.4.0.
|
|
|
|
Zero-copy HTP graph layout (per tier):
|
|
- All 4 tensor offsets (slot 0 in/out, slot 1 in/out) are 4096-byte page-aligned
|
|
inside a single shared AHardwareBuffer backing scratch[0] and scratch[1].
|
|
- Input tensor: SFIXED_POINT_8 [1, Nh+2, Nw+2, 16] (scale=1.0, offset=0) at +0
|
|
- HTP Entry ops: StridedSlice [1:Nh+1, 1:Nw+1] -> Convert(S8 -> U8, offset=-128)
|
|
- Core network : Exact genuine AMD FSR 4.1.2 Lite INT8 U-Net
|
|
- HTP Exit ops : Pad [1,1],[1,1] (constant 0.0f) -> Convert(U8 -> S8, offset=0)
|
|
- Output tensor: SFIXED_POINT_8 [1, Nh+2, Nw+2, 16] (scale=2.0, offset=0) at +out_b_hi
|
|
-> Eliminates 0001.spv, lite_npu_pack.spv, and lite_npu_unpack.spv completely!
|
|
"""
|
|
import hashlib
|
|
import re
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
import numpy as np
|
|
|
|
# Import genuine weight loader from existing pack_fsr412_lite_weights.py
|
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
|
sys.path.insert(0, str(SCRIPT_DIR))
|
|
from pack_fsr412_lite_weights import load_all_weights, WPK_MAGIC, WPK_VERSION, PASS0_PAD
|
|
|
|
SPIRV_DIS = Path(r"C:\msys64\ucrt64\bin\spirv-dis.exe")
|
|
SPIRV_AS = Path(r"C:\msys64\ucrt64\bin\spirv-as.exe")
|
|
SPIRV_VAL = Path(r"C:\msys64\ucrt64\bin\spirv-val.exe")
|
|
|
|
ASSETS_LITE = Path(r"c:\Users\omeru\OneDrive\Desktop\print\Winlator-Ludashi-5.0\app\src\main\assets\fsr4\fsr412_lite")
|
|
|
|
# Extended WPK1 tensor kinds & op types (backwards-compatible with fsr4_v07_i8.wpack!)
|
|
TK_APP_WRITE = 0
|
|
TK_APP_READ = 1
|
|
TK_NATIVE = 2
|
|
TK_STATIC_U8 = 3
|
|
TK_STATIC_S32 = 4
|
|
TK_APP_WRITE_S8 = 5
|
|
TK_APP_READ_S8 = 6
|
|
TK_NATIVE_S8 = 7
|
|
TK_STATIC_S8 = 8
|
|
|
|
OP_CONV2D = 1
|
|
OP_RELU = 2
|
|
OP_ADD = 3
|
|
OP_CONCAT = 4
|
|
OP_SLICE_CH = 5
|
|
OP_DEPTH_TO_SPACE = 6
|
|
OP_CONVERT = 7
|
|
OP_SLICE_HW = 8
|
|
OP_PAD_HW = 9
|
|
|
|
|
|
def align_up(v: int, a: int) -> int:
|
|
return ((v + a - 1) // a) * a
|
|
|
|
|
|
def tier_geometry(name: str, out_w: int, out_h: int) -> dict:
|
|
assert out_w % 4 == 0 and out_h % 4 == 0
|
|
nw, nh = out_w // 2, out_h // 2
|
|
hw, hh = out_w // 4, out_h // 4
|
|
nw1, nh1 = nw + 1, nh + 1
|
|
nw2, nh2 = nw + 2, nh + 2
|
|
hw1, hh1 = hw + 1, hh + 1
|
|
hw2, hh2 = hw + 2, hh + 2
|
|
row_b_hi = nw2 * 16
|
|
plane_q_hi = nw2 * nh2
|
|
plane_b_hi = plane_q_hi * 16
|
|
# Page-align output buffer offset to 4096 B (and 16 B exact multiple!) for QNN zero-copy AHB
|
|
out_b_hi = align_up(2 * plane_b_hi, 4096)
|
|
assert out_b_hi % 16 == 0
|
|
out_q_hi = out_b_hi // 16
|
|
row_b_lo = hw2 * 16
|
|
plane_q_lo = hw2 * hh2
|
|
half_b_lo = plane_q_lo * 16
|
|
full_b_lo = plane_q_lo * 32
|
|
out_q_hi_plus_lo = out_q_hi + plane_q_lo
|
|
slot_stride = align_up(out_b_hi + plane_b_hi, 4096)
|
|
return dict(
|
|
name=name, out_w=out_w, out_h=out_h,
|
|
nw=nw, nh=nh, hw=hw, hh=hh,
|
|
nw1=nw1, nh1=nh1, nw2=nw2, nh2=nh2,
|
|
hw1=hw1, hh1=hh1, hw2=hw2, hh2=hh2,
|
|
row_b_hi=row_b_hi, plane_q_hi=plane_q_hi, plane_b_hi=plane_b_hi,
|
|
out_b_hi=out_b_hi, out_q_hi=out_q_hi,
|
|
row_b_lo=row_b_lo, plane_q_lo=plane_q_lo, half_b_lo=half_b_lo, full_b_lo=full_b_lo,
|
|
out_q_hi_plus_lo=out_q_hi_plus_lo, slot_stride=slot_stride,
|
|
)
|
|
|
|
|
|
def per_shader_const_map(shader_id: str, g: dict) -> dict:
|
|
"""Exact audited (type, old_val) -> new_val mapping per shader ID.
|
|
Only touches verified address/bounds OpConstant lines; never touches weights/biases."""
|
|
if shader_id == "0000":
|
|
return {
|
|
("%uint", 15392): g["row_b_hi"],
|
|
("%uint", 8342464): g["plane_b_hi"],
|
|
}
|
|
if shader_id == "0001":
|
|
return {
|
|
("%uint", 15392): g["row_b_hi"],
|
|
("%uint", 8342464): g["plane_b_hi"],
|
|
("%uint", 961): g["nw1"],
|
|
("%uint", 541): g["nh1"],
|
|
}
|
|
if shader_id == "0002":
|
|
return {
|
|
("%int", 960): g["nw"],
|
|
("%int", 540): g["nh"],
|
|
("%uint", 962): g["nw2"],
|
|
("%uint", 521404): g["plane_q_hi"],
|
|
("%uint", 7712): g["row_b_lo"],
|
|
("%uint", 2097664): g["half_b_lo"],
|
|
("%uint", 16684928): g["out_b_hi"],
|
|
}
|
|
if shader_id == "0003":
|
|
return {
|
|
("%uint", 15392): g["row_b_hi"],
|
|
("%uint", 8342464): g["plane_b_hi"],
|
|
("%uint", 961): g["nw1"],
|
|
("%uint", 541): g["nh1"],
|
|
}
|
|
if shader_id == "0004":
|
|
return {
|
|
("%uint", 7712): g["row_b_lo"],
|
|
("%uint", 2097664): g["half_b_lo"],
|
|
("%int", 2097664): g["half_b_lo"],
|
|
("%uint", 4195328): g["full_b_lo"],
|
|
("%uint", 16684928): g["out_b_hi"],
|
|
("%uint", 481): g["hw1"],
|
|
("%uint", 271): g["hh1"],
|
|
}
|
|
if shader_id == "0005":
|
|
return {
|
|
("%uint", 480): g["hw"],
|
|
("%uint", 270): g["hh"],
|
|
("%uint", 482): g["hw2"],
|
|
("%uint", 7712): g["row_b_lo"],
|
|
("%uint", 1042808): g["out_q_hi"],
|
|
("%uint", 1173912): g["out_q_hi_plus_lo"],
|
|
("%uint", 2097664): g["half_b_lo"],
|
|
("%uint", 2097668): g["half_b_lo"] + 4,
|
|
("%uint", 2097672): g["half_b_lo"] + 8,
|
|
("%uint", 2097676): g["half_b_lo"] + 12,
|
|
}
|
|
if shader_id == "0006":
|
|
return {
|
|
("%uint", 7712): g["row_b_lo"],
|
|
("%uint", 2097664): g["half_b_lo"],
|
|
("%int", 2097664): g["half_b_lo"],
|
|
("%uint", 4195328): g["full_b_lo"],
|
|
("%uint", 481): g["hw1"],
|
|
("%uint", 271): g["hh1"],
|
|
}
|
|
if shader_id == "0007":
|
|
return {
|
|
("%uint", 480): g["hw"],
|
|
("%uint", 270): g["hh"],
|
|
("%uint", 482): g["hw2"],
|
|
("%uint", 960): g["nw"],
|
|
("%uint", 540): g["nh"],
|
|
("%uint", 962): g["nw2"],
|
|
("%uint", 15392): g["row_b_hi"],
|
|
("%uint", 131104): g["plane_q_lo"],
|
|
("%uint", 521404): g["plane_q_hi"],
|
|
("%uint", 16684928): g["out_b_hi"],
|
|
}
|
|
if shader_id == "0008":
|
|
return {
|
|
("%uint", 15392): g["row_b_hi"],
|
|
("%uint", 8342464): g["plane_b_hi"],
|
|
("%uint", 16684928): g["out_b_hi"],
|
|
("%uint", 961): g["nw1"],
|
|
("%uint", 541): g["nh1"],
|
|
}
|
|
if shader_id == "0009":
|
|
return {
|
|
("%uint", 15392): g["row_b_hi"],
|
|
("%uint", 8342464): g["plane_b_hi"],
|
|
("%uint", 16684928): g["out_b_hi"],
|
|
("%uint", 960): g["nw"],
|
|
}
|
|
if shader_id == "0013":
|
|
return {
|
|
("%uint", 960): g["nw"],
|
|
}
|
|
raise ValueError(f"Unknown shader_id {shader_id}")
|
|
|
|
|
|
def patch_spirv(src_spv: Path, dst_spv: Path, shader_id: str, g: dict):
|
|
dis_txt = subprocess.check_output([str(SPIRV_DIS), str(src_spv)], text=True)
|
|
cmap = per_shader_const_map(shader_id, g)
|
|
matched = set()
|
|
out_lines = []
|
|
pat = re.compile(r"^(\s*%[\w]+\s*=\s*OpConstant\s+(%\w+)\s+)(-?\d+)(\s*)$")
|
|
for line in dis_txt.splitlines():
|
|
m = pat.match(line)
|
|
if m:
|
|
prefix, ty, val_s, suffix = m.group(1), m.group(2), m.group(3), m.group(4)
|
|
key = (ty, int(val_s))
|
|
if key in cmap:
|
|
matched.add(key)
|
|
line = f"{prefix}{cmap[key]}{suffix}"
|
|
out_lines.append(line)
|
|
missing = set(cmap.keys()) - matched
|
|
assert not missing, f"{shader_id} ({g['name']}): missing expected OpConstants {missing}"
|
|
|
|
dst_spv.parent.mkdir(parents=True, exist_ok=True)
|
|
asm_path = dst_spv.with_suffix(".spvasm")
|
|
asm_path.write_text("\n".join(out_lines) + "\n", encoding="utf-8")
|
|
try:
|
|
subprocess.check_call([str(SPIRV_AS), "--target-env", "vulkan1.3", str(asm_path), "-o", str(dst_spv)])
|
|
subprocess.check_call([str(SPIRV_VAL), "--target-env", "vulkan1.3", str(dst_spv)])
|
|
finally:
|
|
if asm_path.exists():
|
|
asm_path.unlink()
|
|
|
|
|
|
class ZcGraphPacker:
|
|
"""Packs FSR 4.1.2 Lite INT8 QNN HTP graph with halo-aware SFIXED_POINT_8 I/O."""
|
|
def __init__(self):
|
|
self.tensors = []
|
|
self.ops = []
|
|
self.payload = bytearray()
|
|
|
|
def _append_bytes(self, b: bytes):
|
|
pad = (-len(self.payload)) & 15
|
|
if pad:
|
|
self.payload.extend(b"\x00" * pad)
|
|
off = len(self.payload)
|
|
self.payload.extend(b)
|
|
return off, len(b)
|
|
|
|
def add_tensor(self, kind, dims, scale, offset, raw_bytes=None):
|
|
tid = len(self.tensors)
|
|
rank = len(dims)
|
|
d4 = list(dims) + [0] * (4 - rank)
|
|
off, sz = (0, 0)
|
|
if raw_bytes is not None:
|
|
off, sz = self._append_bytes(raw_bytes)
|
|
self.tensors.append(dict(
|
|
id=tid, kind=kind, dims=d4, rank=rank,
|
|
scale=float(scale), offset=int(offset),
|
|
data_offset=off, data_size=sz,
|
|
))
|
|
return tid
|
|
|
|
def add_act_u8(self, h, w, c, scale, kind=TK_NATIVE):
|
|
return self.add_tensor(kind, [1, h, w, c], scale, -128)
|
|
|
|
def add_act_s8(self, h, w, c, scale, kind=TK_NATIVE_S8):
|
|
return self.add_tensor(kind, [1, h, w, c], scale, 0)
|
|
|
|
def add_static_w_hwio(self, w_i8_hwio: np.ndarray, scale: float, use_s8: bool = False):
|
|
assert w_i8_hwio.dtype == np.int8 and w_i8_hwio.ndim == 4
|
|
if use_s8:
|
|
w_s8 = np.ascontiguousarray(w_i8_hwio, dtype=np.int8)
|
|
return self.add_tensor(TK_STATIC_S8, list(w_s8.shape), scale, 0, w_s8.tobytes())
|
|
w_u8 = np.ascontiguousarray(w_i8_hwio.astype(np.int16) + 128, dtype=np.uint8)
|
|
return self.add_tensor(TK_STATIC_U8, list(w_u8.shape), scale, -128, w_u8.tobytes())
|
|
|
|
def add_static_bias_s32_exact(self, b_i32: np.ndarray, s_in: float, s_w: float):
|
|
q = np.ascontiguousarray(b_i32.astype(np.int32))
|
|
return self.add_tensor(TK_STATIC_S32, [int(q.shape[0])], float(s_in) * float(s_w), 0, q.tobytes())
|
|
|
|
def emit_op(self, op_type, ins, out_id, p0=0, p1=0, p2=0, p3=0):
|
|
in3 = list(ins) + [0] * (3 - len(ins))
|
|
self.ops.append(dict(
|
|
op_type=op_type, in_ids=in3, num_ins=len(ins), out_id=out_id,
|
|
p0=int(p0), p1=int(p1), p2=int(p2), p3=int(p3),
|
|
))
|
|
return out_id
|
|
|
|
def slice_hw_s8(self, x_id, h0, h1, w0, w1):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
assert 0 <= h0 < h1 <= H and 0 <= w0 < w1 <= W
|
|
y_id = self.add_act_s8(h1 - h0, w1 - w0, C, xt["scale"], kind=TK_NATIVE_S8)
|
|
return self.emit_op(OP_SLICE_HW, [x_id], y_id, h0, h1, w0, w1)
|
|
|
|
def convert_s8_to_u8(self, x_id):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
y_id = self.add_act_u8(H, W, C, xt["scale"], kind=TK_NATIVE)
|
|
return self.emit_op(OP_CONVERT, [x_id], y_id)
|
|
|
|
def pad_hw_u8(self, x_id, pad_h0, pad_h1, pad_w0, pad_w1):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
y_id = self.add_act_u8(H + pad_h0 + pad_h1, W + pad_w0 + pad_w1, C, xt["scale"], kind=TK_NATIVE)
|
|
return self.emit_op(OP_PAD_HW, [x_id], y_id, pad_h0, pad_h1, pad_w0, pad_w1)
|
|
|
|
def pad_hw_s8(self, x_id, pad_h0, pad_h1, pad_w0, pad_w1, out_kind=TK_APP_READ_S8):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
y_id = self.add_act_s8(H + pad_h0 + pad_h1, W + pad_w0 + pad_w1, C, xt["scale"], kind=out_kind)
|
|
return self.emit_op(OP_PAD_HW, [x_id], y_id, pad_h0, pad_h1, pad_w0, pad_w1)
|
|
|
|
def convert_u8_to_s8(self, x_id, out_kind=TK_APP_READ_S8):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
y_id = self.add_act_s8(H, W, C, xt["scale"], kind=out_kind)
|
|
return self.emit_op(OP_CONVERT, [x_id], y_id)
|
|
|
|
def _add_act(self, h, w, c, scale, use_s8: bool, out_kind=None):
|
|
if use_s8:
|
|
return self.add_act_s8(h, w, c, scale, kind=TK_NATIVE_S8 if out_kind is None else out_kind)
|
|
return self.add_act_u8(h, w, c, scale, kind=TK_NATIVE if out_kind is None else out_kind)
|
|
|
|
def conv2d_exact(self, x_id, w_oihw: np.ndarray, b_i32: np.ndarray, s_w: float,
|
|
s_out: float, stride=1, pad=0, out_kind=None, use_s8: bool = False, group: int = 1):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, Cin = xt["dims"]
|
|
Co, Ci_w, kH, kW = w_oihw.shape
|
|
assert Ci_w * group == Cin, f"Conv2d Cin mismatch: {Ci_w}*{group} != {Cin}"
|
|
w_hwio = np.ascontiguousarray(w_oihw.transpose(2, 3, 1, 0), dtype=np.int8)
|
|
w_id = self.add_static_w_hwio(w_hwio, s_w, use_s8=use_s8)
|
|
b_id = self.add_static_bias_s32_exact(b_i32, xt["scale"], s_w)
|
|
Ho = (H + 2 * pad - kH) // stride + 1
|
|
Wo = (W + 2 * pad - kW) // stride + 1
|
|
y_id = self._add_act(Ho, Wo, Co, s_out, use_s8=use_s8, out_kind=out_kind)
|
|
return self.emit_op(OP_CONV2D, [x_id, w_id, b_id], y_id, stride, pad, group)
|
|
|
|
def relu(self, x_id, use_s8: bool = False):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
y_id = self._add_act(H, W, C, xt["scale"], use_s8=use_s8)
|
|
return self.emit_op(OP_RELU, [x_id], y_id)
|
|
|
|
def add(self, a_id, b_id, s_out, out_kind=None, use_s8: bool = False):
|
|
at = self.tensors[a_id]
|
|
bt = self.tensors[b_id]
|
|
assert at["dims"] == bt["dims"], f"Add mismatch {at['dims']} vs {bt['dims']}"
|
|
_, H, W, C = at["dims"]
|
|
y_id = self._add_act(H, W, C, s_out, use_s8=use_s8, out_kind=out_kind)
|
|
return self.emit_op(OP_ADD, [a_id, b_id], y_id)
|
|
|
|
def concat_c(self, a_id, b_id, s_out, use_s8: bool = False):
|
|
at = self.tensors[a_id]
|
|
bt = self.tensors[b_id]
|
|
assert at["dims"][:3] == bt["dims"][:3]
|
|
_, H, W, Ca = at["dims"]
|
|
Cb = bt["dims"][3]
|
|
y_id = self._add_act(H, W, Ca + Cb, s_out, use_s8=use_s8)
|
|
return self.emit_op(OP_CONCAT, [a_id, b_id], y_id, 3)
|
|
|
|
def slice_ch(self, x_id, c_start, c_end, use_s8: bool = False):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
y_id = self._add_act(H, W, c_end - c_start, xt["scale"], use_s8=use_s8)
|
|
return self.emit_op(OP_SLICE_CH, [x_id], y_id, c_start, c_end)
|
|
|
|
def depth_to_space(self, x_id, block=2, out_kind=None, use_s8: bool = False):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
y_id = self._add_act(H * block, W * block, C // (block * block), xt["scale"], use_s8=use_s8, out_kind=out_kind)
|
|
return self.emit_op(OP_DEPTH_TO_SPACE, [x_id], y_id, block, 0)
|
|
|
|
|
|
def build_zc_wpack(W_dict: dict, g: dict, out_path: Path, native_s8: bool = False):
|
|
gp = ZcGraphPacker()
|
|
nh, nw = g["nh"], g["nw"]
|
|
nh2, nw2 = g["nh2"], g["nw2"]
|
|
s8 = bool(native_s8)
|
|
|
|
# Zero-copy direct scratch+0 input: SFIXED_POINT_8 [1, Nh+2, Nw+2, 16] (scale=1.0, offset=0)
|
|
x_raw = gp.add_act_s8(nh2, nw2, 16, 1.0, kind=TK_APP_WRITE_S8)
|
|
# Strip 1-px halo border inside HTP (native_s8 skips the 8.34 MB Convert S8->U8 pass completely!)
|
|
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)
|
|
|
|
# ---- Block 1 (Nh x Nw) ----
|
|
h1 = gp.conv2d_exact(x0, W_dict["l1_c3"][0], W_dict["l1_c3"][1], s_w=2.0**-7, s_out=1.0, stride=1, pad=1, use_s8=s8)
|
|
m1 = gp.relu(gp.conv2d_exact(h1, W_dict["l1_e"][0], W_dict["l1_e"][1], s_w=2.0**-9, s_out=1.0, stride=1, pad=0, use_s8=s8), use_s8=s8)
|
|
f1 = gp.conv2d_exact(m1, W_dict["l1_f"][0], W_dict["l1_f"][1], s_w=2.0**-5, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
|
r = gp.add(f1, x0, s_out=2.0, use_s8=s8)
|
|
|
|
d0_lo = gp.conv2d_exact(r, W_dict["l1_d"][0][:16], W_dict["l1_d"][1][:16], s_w=2.0**-7, s_out=1.0, stride=2, pad=0, use_s8=s8)
|
|
d0_hi = gp.conv2d_exact(r, W_dict["l1_d"][0][16:], W_dict["l1_d"][1][16:], s_w=2.0**-8, s_out=1.0, stride=2, pad=0, use_s8=s8)
|
|
d0 = gp.concat_c(d0_lo, d0_hi, s_out=1.0, use_s8=s8)
|
|
|
|
# ---- Block 2 (Hh x Hw) ----
|
|
d0_s0 = gp.slice_ch(d0, 0, 16, use_s8=s8)
|
|
d0_s1 = gp.slice_ch(d0, 16, 32, use_s8=s8)
|
|
h2 = gp.conv2d_exact(d0_s0, W_dict["l2_c3"][0], W_dict["l2_c3"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=1, use_s8=s8)
|
|
c2 = gp.concat_c(h2, d0_s1, s_out=1.0, use_s8=s8)
|
|
m2 = gp.relu(gp.conv2d_exact(c2, W_dict["l2_e"][0], W_dict["l2_e"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=0, use_s8=s8), use_s8=s8)
|
|
f2_lo = gp.conv2d_exact(m2, W_dict["l2_f"][0][:16], W_dict["l2_f"][1][:16], s_w=2.0**-5, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
|
f2_hi = gp.conv2d_exact(m2, W_dict["l2_f"][0][16:], W_dict["l2_f"][1][16:], s_w=2.0**-6, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
|
e0_lo = gp.add(f2_lo, d0_s0, s_out=2.0, use_s8=s8)
|
|
e0_hi = gp.add(f2_hi, d0_s1, s_out=2.0, use_s8=s8)
|
|
|
|
# ---- Block 3 (Hh x Hw -> Nh x Nw) ----
|
|
h3 = gp.conv2d_exact(e0_lo, W_dict["l3_c3"][0], W_dict["l3_c3"][1], s_w=2.0**-8, s_out=2.0, stride=1, pad=1, use_s8=s8)
|
|
c3 = gp.concat_c(h3, e0_hi, s_out=2.0, use_s8=s8)
|
|
m3 = gp.relu(gp.conv2d_exact(c3, W_dict["l3_e"][0], W_dict["l3_e"][1], s_w=2.0**-8, s_out=1.0, stride=1, pad=0, use_s8=s8), use_s8=s8)
|
|
f3_lo = gp.conv2d_exact(m3, W_dict["l3_f"][0][:16], W_dict["l3_f"][1][:16], s_w=2.0**-5, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
|
z3_lo = gp.add(f3_lo, e0_lo, s_out=2.0, use_s8=s8)
|
|
f3_hi = gp.conv2d_exact(m3, W_dict["l3_f"][0][16:], W_dict["l3_f"][1][16:], s_w=2.0**-6, s_out=1.0, stride=1, pad=0, use_s8=s8)
|
|
z3_hi = gp.add(f3_hi, e0_hi, s_out=1.0, use_s8=s8)
|
|
|
|
up_lo = gp.conv2d_exact(z3_lo, W_dict["l3_up"][0][:, :16, :, :], W_dict["l3_up"][1], s_w=2.0**-8, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
|
up_hi = gp.conv2d_exact(z3_hi, W_dict["l3_up"][0][:, 16:, :, :], np.zeros(64, dtype=np.int32), s_w=2.0**-7, s_out=2.0, stride=1, pad=0, use_s8=s8)
|
|
up_sum = gp.add(up_lo, up_hi, s_out=2.0, use_s8=s8)
|
|
up_d2s = gp.depth_to_space(up_sum, block=2, use_s8=s8)
|
|
out_core = gp.add(up_d2s, r, s_out=2.0, use_s8=s8)
|
|
|
|
# Zero-pad 1-px halo border (native_s8 writes APP_READ_S8 directly — skips 8.34 MB Convert U8->S8!)
|
|
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)
|
|
|
|
hdr = struct.pack(
|
|
"<QIIIIIIIIIIffII",
|
|
WPK_MAGIC, WPK_VERSION,
|
|
nh2, nw2, 16,
|
|
nh2, nw2, 16,
|
|
len(gp.tensors), len(gp.ops),
|
|
x_raw, 1.0, 2.0,
|
|
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" wpack [{g['name']:5s}]: {out_path.name} ({len(buf)} B, in/out=[1,{nh2},{nw2},16] S8, "
|
|
f"{len(gp.tensors)} tensors, {len(gp.ops)} ops, sha256={hashlib.sha256(buf).hexdigest()[:12]})")
|
|
|
|
|
|
def main():
|
|
W_dict = load_all_weights()
|
|
if "--wpack-s8-only" in sys.argv:
|
|
g = tier_geometry("1080p", 1920, 1080)
|
|
build_zc_wpack(W_dict, g, ASSETS_LITE / "fsr412_lite_zc_s8.wpack", native_s8=True)
|
|
# Bit-exact verification of symmetric S8 conv + relu + add + pad vs U8(offset=-128)
|
|
rng = np.random.default_rng(123)
|
|
x_s8 = rng.integers(-128, 128, size=(1, 16, 16, 16), dtype=np.int8)
|
|
w_s8 = W_dict["l1_c3"][0].transpose(2, 3, 1, 0) # [3, 3, 16, 16] int8
|
|
b_i32 = W_dict["l1_c3"][1] # [16] int32
|
|
# Compare 1x1 inner slice conv in S8 vs U8(offset=-128)
|
|
x_u8 = (x_s8.astype(np.int16) + 128).astype(np.uint8)
|
|
w_u8 = (w_s8.astype(np.int16) + 128).astype(np.uint8)
|
|
acc_s8 = np.einsum("bhwc,co->bhwo", x_s8.astype(np.int32), w_s8[1, 1].astype(np.int32)) + b_i32
|
|
acc_u8 = np.einsum("bhwc,co->bhwo", x_u8.astype(np.int32) - 128, w_u8[1, 1].astype(np.int32) - 128) + b_i32
|
|
assert np.array_equal(acc_s8, acc_u8), "S8 vs U8 conv accumulator mismatch!"
|
|
y_s8 = np.clip(np.rint(acc_s8 * (2.0**-7)), -128, 127).astype(np.int8)
|
|
y_u8 = np.clip(np.rint(acc_u8 * (2.0**-7)) + 128, 0, 255).astype(np.uint8)
|
|
assert np.array_equal(y_s8, (y_u8.astype(np.int16) - 128).astype(np.int8)), "S8 vs U8 output mismatch!"
|
|
assert np.array_equal(np.maximum(y_s8, 0), (np.maximum(y_u8, 128).astype(np.int16) - 128).astype(np.int8)), "S8 vs U8 ReLU mismatch!"
|
|
print("Bit-exact symmetric SFIXED_POINT_8 vs UFIXED_POINT_8 verification PASSED!")
|
|
return
|
|
|
|
shader_ids = [f"{i:04d}" for i in range(10)] + ["0013"]
|
|
tiers = [
|
|
tier_geometry("1080p", 1920, 1080),
|
|
tier_geometry("900p", 1600, 900),
|
|
tier_geometry("720p", 1280, 720),
|
|
]
|
|
|
|
for g in tiers:
|
|
tdir = ASSETS_LITE / g["name"]
|
|
print(f"=== Building Tier {g['name']} ({g['out_w']}x{g['out_h']}, net {g['nw']}x{g['nh']}, "
|
|
f"plane_b={g['plane_b_hi']}, out_b={g['out_b_hi']}, slot_stride={g['slot_stride']}) ===")
|
|
for sid in shader_ids:
|
|
src = ASSETS_LITE / f"{sid}.spv"
|
|
dst = tdir / f"{sid}.spv"
|
|
patch_spirv(src, dst, sid, g)
|
|
print(f" SPIR-V [{g['name']:5s}]: all {len(shader_ids)} shaders assembled & spirv-val PASSED!")
|
|
build_zc_wpack(W_dict, g, tdir / "fsr412_lite_zc_i8.wpack")
|
|
|
|
# Sanity check: verify S8<->U8 halo math matches numpy reference bit-for-bit
|
|
rng = np.random.default_rng(42)
|
|
raw_s8 = rng.integers(-128, 128, size=(1, 362, 642, 16), dtype=np.int8)
|
|
cropped_s8 = raw_s8[:, 1:361, 1:641, :]
|
|
conv_u8 = (cropped_s8.astype(np.int16) + 128).astype(np.uint8)
|
|
old_pack = (cropped_s8.view(np.uint8) ^ np.uint8(0x80))
|
|
assert np.array_equal(conv_u8, old_pack), "S8->U8 bit mismatch!"
|
|
padded_u8 = np.pad(conv_u8, ((0,0),(1,1),(1,1),(0,0)), mode="constant", constant_values=128)
|
|
back_s8 = (padded_u8.astype(np.int16) - 128).astype(np.int8)
|
|
assert np.all(back_s8[:, 0, :, :] == 0) and np.all(back_s8[:, -1, :, :] == 0)
|
|
assert np.all(back_s8[:, :, 0, :] == 0) and np.all(back_s8[:, :, -1, :] == 0)
|
|
assert np.array_equal(back_s8[:, 1:361, 1:641, :], cropped_s8), "U8->S8 roundtrip mismatch!"
|
|
print("Bit-exact S8<->U8 halo verification PASSED!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|