mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Port of the NeuralScale layer (previous commit) for DroidDeck: - Layer VK_LAYER_DROIDDECK_upscale, library libVkLayer_droiddeck_upscale.so, implicit manifest template (DROIDDECK_UPSCALE=1 / DROIDDECK_UPSCALE_DISABLE=1). - Settings read as DROIDDECK_UPSCALE_<KEY>, then WINLATOR_FSR4_<KEY>. - No hardcoded com.winlator.cmod data dir; without a dir frames get the blit fallback. - Compiled NPU graph caches go to <dir>/<htp arch>/ (v79/v81 from HTP_ARCH, the SoC properties or the mapped QNN stub) instead of <dir>/v81/. - The arch stub is loaded from the QNN library search list first, so NATIVELIB_DIR is enough without LD_LIBRARY_PATH. - driverID/driverName are only rewritten with GPU_SPOOF word "1"; SPOOF_DLSS=1 alone reports RTX vendor/device IDs. - APK build via app/src/main/cpp/CMakeLists.txt; glibc build for the PRoot guest (build-glibc.sh, DD_UPSCALE_NO_ANDROID: QNN stubs, stderr log) in the runtime recipe, installed to usr/local/lib/droiddeck-upscale-layer/. - -Bsymbolic so the exported vkGetInstanceProcAddr is not interposed by a libvulkan in the global scope. - Pack scripts take their paths as arguments. Seam protocol, buffer sizes, magic values and backend IDs are unchanged.
341 lines
15 KiB
Python
341 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""Pack AMD FSR 4.0.2 INT8 (fsr4_model_v07_i8_quality) weights & QNN HTP op graph
|
|
into a compact self-contained binary asset (fsr4_v07_i8.wpack) for on-device
|
|
compilation via Qualcomm libQnnHtpPrepare.so (HTP v81 / v79).
|
|
|
|
Every op uses standard QNN qti.aisw NHWC / HWIO layouts, group=1 Conv2d,
|
|
UFIXED_POINT_8 (offset=-128) weights/activations, SFIXED_POINT_32 biases,
|
|
and 1x1 Conv2d + DepthToSpace(DCR, 2x2) for exact 2x2 stride-2 ConvTranspose.
|
|
"""
|
|
import os
|
|
import sys
|
|
import struct
|
|
import hashlib
|
|
from pathlib import Path
|
|
import numpy as np
|
|
|
|
# Checkout of puzzled-pancake/fsr4-hexagon (provides model/sim/fsr4_sim.py).
|
|
FSR4_HEX_ROOT = Path(os.environ.get("FSR4_HEXAGON_ROOT", "fsr4-hexagon"))
|
|
sys.path.insert(0, str(FSR4_HEX_ROOT / "model/sim"))
|
|
import fsr4_sim as S
|
|
|
|
WPK_MAGIC = 0x314B505734525346 # "FSR4WPK1"
|
|
WPK_VERSION = 1
|
|
|
|
TK_APP_WRITE = 0
|
|
TK_APP_READ = 1
|
|
TK_NATIVE = 2
|
|
TK_STATIC_U8 = 3
|
|
TK_STATIC_S32 = 4
|
|
|
|
OP_CONV2D = 1
|
|
OP_RELU = 2
|
|
OP_ADD = 3
|
|
OP_CONCAT = 4
|
|
OP_SLICE_CH = 5
|
|
OP_DEPTH_TO_SPACE = 6
|
|
OP_CONVERT = 7
|
|
|
|
S_OUT = 0.303211569786 # Matches wv2a.comp / postA contract
|
|
|
|
|
|
class GraphPacker:
|
|
def __init__(self):
|
|
self.tensors = []
|
|
self.ops = []
|
|
self.payload = bytearray()
|
|
|
|
def _append_bytes(self, b: bytes):
|
|
# 16-byte align every static tensor in payload
|
|
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(self, h, w, c, scale, kind=TK_NATIVE):
|
|
return self.add_tensor(kind, [1, h, w, c], scale, -128)
|
|
|
|
def add_static_w_hwio(self, w_i8_hwio: np.ndarray, scale: float):
|
|
assert w_i8_hwio.dtype == np.int8 and w_i8_hwio.ndim == 4
|
|
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(self, b_f32: np.ndarray, s_in: float, s_w: float):
|
|
s_b = float(s_in) * float(s_w)
|
|
q = np.rint(b_f32.astype(np.float64) / s_b)
|
|
q = np.clip(q, -2147483648, 2147483647).astype(np.int32)
|
|
q = np.ascontiguousarray(q)
|
|
return self.add_tensor(TK_STATIC_S32, [int(q.shape[0])], s_b, 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 conv2d(self, x_id, w_oihw: np.ndarray, b_f32: np.ndarray, s_w: float,
|
|
s_out: float, stride=1, pad=0, out_kind=TK_NATIVE):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, Cin = xt["dims"]
|
|
Co, Ci_w, kH, kW = w_oihw.shape
|
|
assert Ci_w == Cin, f"Cin mismatch {Ci_w} vs {Cin}"
|
|
# OIHW -> HWIO
|
|
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)
|
|
b_id = self.add_static_bias_s32(b_f32, 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, kind=out_kind)
|
|
return self.emit_op(OP_CONV2D, [x_id, w_id, b_id], y_id, stride, pad)
|
|
|
|
def relu(self, x_id):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
y_id = self.add_act(H, W, C, xt["scale"])
|
|
return self.emit_op(OP_RELU, [x_id], y_id)
|
|
|
|
def add(self, a_id, b_id, s_out):
|
|
at = self.tensors[a_id]
|
|
bt = self.tensors[b_id]
|
|
assert at["dims"] == bt["dims"], f"Add shape mismatch {at['dims']} vs {bt['dims']}"
|
|
_, H, W, C = at["dims"]
|
|
y_id = self.add_act(H, W, C, s_out)
|
|
return self.emit_op(OP_ADD, [a_id, b_id], y_id)
|
|
|
|
def concat_c(self, a_id, b_id, s_out):
|
|
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]
|
|
# Rescale a/b to common s_out if scales differ (HTP Concat requires matching scales)
|
|
if abs(at["scale"] - s_out) > 1e-12:
|
|
a2 = self.add_act(H, W, Ca, s_out)
|
|
a_id = self.emit_op(OP_CONVERT, [a_id], a2)
|
|
if abs(bt["scale"] - s_out) > 1e-12:
|
|
b2 = self.add_act(H, W, Cb, s_out)
|
|
b_id = self.emit_op(OP_CONVERT, [b_id], b2)
|
|
y_id = self.add_act(H, W, Ca + Cb, s_out)
|
|
return self.emit_op(OP_CONCAT, [a_id, b_id], y_id, 3)
|
|
|
|
def slice_ch(self, x_id, c_start, c_end, s_out=None):
|
|
xt = self.tensors[x_id]
|
|
_, H, W, C = xt["dims"]
|
|
assert 0 <= c_start < c_end <= C
|
|
y_id = self.add_act(H, W, c_end - c_start, xt["scale"])
|
|
self.emit_op(OP_SLICE_CH, [x_id], y_id, c_start, c_end)
|
|
if s_out is not None and abs(xt["scale"] - s_out) > 1e-12:
|
|
y2 = self.add_act(H, W, c_end - c_start, s_out)
|
|
y_id = self.emit_op(OP_CONVERT, [y_id], y2)
|
|
return y_id
|
|
|
|
def conv_transpose_2x2(self, x_id, w_cio22: np.ndarray, b_f32: np.ndarray,
|
|
s_w: float, s_out: float, out_kind=TK_NATIVE):
|
|
"""Exact 2x2 stride-2 ConvTranspose via 1x1 Conv2d + DepthToSpace(DCR, 2)."""
|
|
xt = self.tensors[x_id]
|
|
_, H, W, Cin = xt["dims"]
|
|
Ci_w, Co, kH, kW = w_cio22.shape
|
|
assert Ci_w == Cin and kH == 2 and kW == 2
|
|
# DCR DepthToSpace: channel ((ky * 2 + kx) * Co + co) -> spatial (2y+ky, 2x+kx, co)
|
|
w_dcr = w_cio22.transpose(2, 3, 1, 0).reshape(4 * Co, Cin, 1, 1) # OIHW for 1x1 Conv2d
|
|
b_dcr = np.tile(b_f32, 4)
|
|
tmp_id = self.conv2d(x_id, w_dcr, b_dcr, s_w, s_out, stride=1, pad=0)
|
|
y_id = self.add_act(H * 2, W * 2, Co, s_out, kind=out_kind)
|
|
return self.emit_op(OP_DEPTH_TO_SPACE, [tmp_id], y_id, 2, 0)
|
|
|
|
|
|
def verify_ct2d_equivalence(L):
|
|
"""Prove 1x1 Conv2d + DepthToSpace(DCR) is bit-identical to fsr4_sim.convtranspose2x2_i8."""
|
|
w = L["dec2_ct_weight"] # [Cin, Cout, 2, 2]
|
|
rng = np.random.default_rng(42)
|
|
x = rng.integers(-60, 60, size=(4, 6, w.shape[0]), dtype=np.int8)
|
|
ref = S.convtranspose2x2_i8(x, w)
|
|
w_dcr = w.transpose(2, 3, 1, 0).reshape(4 * w.shape[1], w.shape[0]) # [4*Co, Cin]
|
|
tmp = np.einsum("hwc,oc->hwo", x.astype(np.int64), w_dcr.astype(np.int64))
|
|
# DCR DepthToSpace: [H, W, 2, 2, Co] -> [H, 2, W, 2, Co] -> [2H, 2W, Co]
|
|
Co = w.shape[1]
|
|
got = tmp.reshape(4, 6, 2, 2, Co).transpose(0, 2, 1, 3, 4).reshape(8, 12, Co)
|
|
assert np.array_equal(ref, got), "CT2D <-> 1x1+D2S mismatch!"
|
|
print("[PASS] 1x1 Conv2d + DepthToSpace(DCR) bit-exact match with fsr4_sim.convtranspose2x2_i8")
|
|
|
|
|
|
def expand_k2s2_to_k3s2p1(w_oihw: np.ndarray) -> np.ndarray:
|
|
"""Decompose k=2,s=2,p=0 conv into HTP-native k=3,s=2,p=1 conv (zero top/left taps)."""
|
|
O, I, kH, kW = w_oihw.shape
|
|
assert kH == 2 and kW == 2
|
|
w3 = np.zeros((O, I, 3, 3), dtype=np.int8)
|
|
w3[:, :, 1:3, 1:3] = w_oihw
|
|
return w3
|
|
|
|
|
|
def expand_group2_to_group1(w_oihw: np.ndarray) -> np.ndarray:
|
|
"""Decompose group=2 conv into HTP-native group=1 conv (zero cross-group weights)."""
|
|
O, Ci_g, kH, kW = w_oihw.shape
|
|
Og = O // 2
|
|
wfull = np.zeros((O, 2 * Ci_g, kH, kW), dtype=np.int8)
|
|
wfull[:Og, :Ci_g] = w_oihw[:Og]
|
|
wfull[Og:, Ci_g:2 * Ci_g] = w_oihw[Og:]
|
|
return wfull
|
|
|
|
|
|
def build_pack(out_path: Path, pass0_raw_path: Path):
|
|
L = S.load_layers()
|
|
L = S.load_with_pass0_scale(L)
|
|
verify_ct2d_equivalence(L)
|
|
|
|
pass0_wb = pass0_raw_path.read_bytes()
|
|
assert len(pass0_wb) == 1056
|
|
assert hashlib.md5(pass0_wb).hexdigest() == "0915f25de428aaeee396701e3abfd341"
|
|
|
|
p = GraphPacker()
|
|
calls = L["_calls"]
|
|
c = [calls[i]["args"] for i in range(len(calls))]
|
|
sc = lambda k: float(L[k])
|
|
|
|
x_in = p.add_act(540, 960, 16, S.S_IN, kind=TK_APP_WRITE)
|
|
|
|
def cnb(x_id, prefix, s_mid1, s_mid2, s_out):
|
|
y = p.conv2d(x_id, L[f"{prefix}_conv_dw_weight"], L[f"{prefix}_conv_dw_bias"],
|
|
sc(f"scale__{prefix}_conv_dw"), s_mid1, stride=1, pad=1)
|
|
y = p.conv2d(y, L[f"{prefix}_pw_expand_weight"], L[f"{prefix}_pw_expand_bias"],
|
|
sc(f"scale__{prefix}_pw_expand"), s_mid2, stride=1, pad=0)
|
|
y = p.relu(y)
|
|
y = p.conv2d(y, L[f"{prefix}_pw_contract_weight"], L[f"{prefix}_pw_contract_bias"],
|
|
sc(f"scale__{prefix}_pw_contract"), s_out, stride=1, pad=0)
|
|
return p.add(y, x_id, s_out)
|
|
|
|
def k2s2b(x_id, wkey, bkey, skey, q0, q1):
|
|
W = L[wkey]; b = L[bkey]; C = W.shape[0]
|
|
w0 = expand_k2s2_to_k3s2p1(W[:C // 2])
|
|
w1 = expand_k2s2_to_k3s2p1(W[C // 2:])
|
|
h0 = p.conv2d(x_id, w0, b[:C // 2], sc(skey), q0, stride=2, pad=1)
|
|
h1 = p.conv2d(x_id, w1, b[C // 2:], sc(skey), q1, stride=2, pad=1)
|
|
return (h0, h1)
|
|
|
|
def fnb(xg, prefix, q0, q1, act, variant, o0=None, o1=None, uniform_out=None):
|
|
h0, h1 = xg
|
|
Wsp = L[f"{prefix}_spatial_weight"]
|
|
if variant == "64":
|
|
Wsp = expand_group2_to_group1(Wsp)
|
|
y = p.conv2d(h0, Wsp, L[f"{prefix}_spatial_bias"],
|
|
sc(f"scale__{prefix}_spatial"), q1, stride=1, pad=1)
|
|
cat = p.concat_c(y, h1, q1)
|
|
y = p.conv2d(cat, L[f"{prefix}_pw_expand_weight"], L[f"{prefix}_pw_expand_bias"],
|
|
sc(f"scale__{prefix}_pw_expand"), act, stride=1, pad=0)
|
|
y = p.relu(y)
|
|
# Skip tensor at common scale
|
|
s_skip = max(q0, q1)
|
|
skip = p.concat_c(h0, h1, s_skip)
|
|
if uniform_out is not None:
|
|
y = p.conv2d(y, L[f"{prefix}_pw_contract_weight"], L[f"{prefix}_pw_contract_bias"],
|
|
sc(f"scale__{prefix}_pw_contract"), uniform_out, stride=1, pad=0)
|
|
return p.add(y, skip, uniform_out)
|
|
s_mid = max(o0, o1)
|
|
y = p.conv2d(y, L[f"{prefix}_pw_contract_weight"], L[f"{prefix}_pw_contract_bias"],
|
|
sc(f"scale__{prefix}_pw_contract"), s_mid, stride=1, pad=0)
|
|
y = p.add(y, skip, s_mid)
|
|
C = p.tensors[y]["dims"][3]
|
|
return (p.slice_ch(y, 0, C // 2, o0), p.slice_ch(y, C // 2, C, o1))
|
|
|
|
def fnb_ct2d(xg, prefix, skip_id, q0, q1, act, s_fnb, variant, wct, bct, sct,
|
|
o0=None, o1=None, uniform_out=None):
|
|
y = fnb(xg, prefix, q0, q1, act, variant, uniform_out=s_fnb)
|
|
s_ct = uniform_out if uniform_out is not None else max(o0, o1)
|
|
y = p.conv_transpose_2x2(y, L[wct], L[bct], sc(sct), s_ct)
|
|
y = p.add(y, skip_id, s_ct)
|
|
if uniform_out is not None:
|
|
return y
|
|
C = p.tensors[y]["dims"][3]
|
|
return (p.slice_ch(y, 0, C // 2, o0), p.slice_ch(y, C // 2, C, o1))
|
|
|
|
# Full 13-block FSR 4.0.2 INT8 U-Net (exact match to build_onnx.py / fsr4_sim.py)
|
|
y1 = cnb(x_in, "encoder2_RB0", c[0][1], c[0][3], 0.01933070458471775)
|
|
y2 = cnb(y1, "encoder2_RB1", c[1][1], c[1][3], 0.02335178479552269)
|
|
skip2 = y2
|
|
|
|
xg = k2s2b(y2, "enc2_ds_weight", "enc2_ds_bias", "scale__enc2_ds", c[2][0], c[2][1])
|
|
xg = fnb(xg, "encoder3_ResidualBlock_0", c[3][0], c[3][1], c[3][2], "32", o0=c[3][3], o1=c[3][4])
|
|
y5 = fnb(xg, "encoder3_ResidualBlock_1", c[4][0], c[4][1], c[4][2], "32", uniform_out=0.019347405061125755)
|
|
skip3 = y5
|
|
|
|
xg = k2s2b(y5, "enc3_ds_weight", "enc3_ds_bias", "scale__enc3_ds", c[5][0], c[5][1])
|
|
xg = fnb(xg, "bottleneck_ResidualBlock_0", c[6][0], c[6][1], c[6][2], "64", o0=c[6][3], o1=c[6][4])
|
|
xg = fnb(xg, "bottleneck_ResidualBlock_1", c[7][0], c[7][1], c[7][2], "64", o0=c[7][3], o1=c[7][4])
|
|
xg = fnb_ct2d(xg, "bottleneck_ResidualBlock_2", skip3, c[8][0], c[8][1], c[8][2], c[8][3], "64",
|
|
"bottleneck_ct_weight", "bottleneck_ct_bias", "scale__bottleneck_ct", o0=c[8][4], o1=c[8][5])
|
|
xg = fnb(xg, "decoder3_ResidualBlock_1", c[9][0], c[9][1], c[9][2], "32", o0=c[9][3], o1=c[9][4])
|
|
y11 = fnb_ct2d(xg, "decoder3_ResidualBlock_2", skip2, c[10][0], c[10][1], c[10][2], c[10][3], "32",
|
|
"dec3_ct_weight", "dec3_ct_bias", "scale__dec3_ct", uniform_out=0.027206305414438248)
|
|
y12 = cnb(y11, "decoder2_RB1", c[11][1], c[11][3], 0.035173576325178146)
|
|
y13 = cnb(y12, "decoder2_ResidualBlock_2", c[12][1], c[12][3], 0.06884194910526276)
|
|
y_out = p.conv_transpose_2x2(y13, L["dec2_ct_weight"], L["dec2_ct_bias"],
|
|
sc("scale__dec2_ct"), S_OUT, out_kind=TK_APP_READ)
|
|
|
|
assert p.tensors[x_in]["dims"] == [1, 540, 960, 16]
|
|
assert p.tensors[y_out]["dims"] == [1, 1080, 1920, 8]
|
|
|
|
# Serialize compact binary pack
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(out_path, "wb") as f:
|
|
# Header (64 bytes + 1056 bytes pass0_wb = 1120 bytes)
|
|
hdr = struct.pack(
|
|
"<QIIIIIIIIIIffII",
|
|
WPK_MAGIC, WPK_VERSION,
|
|
540, 960, 16,
|
|
1080, 1920, 8,
|
|
len(p.tensors), len(p.ops),
|
|
x_in,
|
|
S.S_IN, S_OUT,
|
|
y_out, len(p.payload),
|
|
)
|
|
assert len(hdr) == 64
|
|
f.write(hdr)
|
|
f.write(pass0_wb)
|
|
# Tensor table (44 bytes each)
|
|
for t in p.tensors:
|
|
f.write(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"],
|
|
))
|
|
# Op table (40 bytes each)
|
|
for o in p.ops:
|
|
f.write(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"],
|
|
))
|
|
# Static weight/bias payload
|
|
f.write(p.payload)
|
|
|
|
sz = out_path.stat().st_size
|
|
print(f"[PASS] Wrote {out_path} ({sz:,} bytes): {len(p.tensors)} tensors, {len(p.ops)} QNN ops, {len(p.payload):,} B weights/biases")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 3:
|
|
sys.exit("usage: FSR4_HEXAGON_ROOT=<fsr4-hexagon checkout> pack_fsr4_weights.py OUT.wpack PASS0_WB.raw")
|
|
build_pack(Path(sys.argv[1]), Path(sys.argv[2]))
|