Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
WIP (unbuilt, not wired into CMake): YuNet GPU face detector sources and build script
Veyra Goal Agent902ea4e78f7f
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.mdindex 001edacc..57e35554 100644--- a/docs/WORKLOG.md+++ b/docs/WORKLOG.md@@ -9721,3 +9721,9 @@ final-audit.py pre已通过82旧树/94旧分支/509脏文件与main b571a44不- 基线:本地 main `26c0d61`,分支 `claude/beauty-20261017`,工作树 `E:/项目/Veyra/worktrees/beauty-20261017`。存档:tag `checkpoint/pre-claude-beauty-20261017`,`E:/项目/Veyra/archives/claude-beauty-20261017/all-refs-26c0d61.bundle`(`git bundle verify` 通过,complete history)。- 产物目录:`E:/项目/Veyra/{build,tests,logs,tmp,reports,archives,downloads,deps}/claude-beauty-20261017`。- 计划:P0(推理路线对照 / SkinSoft D3D12 原型 / 同帧原画与 HDR 合同)→ 写 `docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md`;`claude/effects-infra-20261017` 出现后再做 P1–P4。E0 范围(链容量、计时掩码、插入槽、格式版本)不自行改动。++### 2026-10-17 美颜 P0 中段(用量上限中断,Claude)+- 已完成:构建脚本 `scripts/acceptance/claude-beauty-build.py`(基线 configure+build 69 秒通过);YuNet 两个 fp32 权重(2023mar / 2026may)下载到 `E:/项目/Veyra/deps/claude-beauty-20261017/yunet-47534e27`,SHA256 与 Git LFS 指针 oid 一致;SkinSoft fd5690f、GPUPixel ef552bf、公共测试人像已取到同目录下各自独立子目录;用 OpenCV 5.0.0 复现了 FaceDetectorYN 的预处理与解码(4 张图结果一致)。+- 已写未验证:`include/veyra/beauty/{OnnxLite,YuNetGpu}.h`、`src/beauty/{OnnxLite,YuNetGpu}.cpp`、`shaders/BeautyYuNet*.hlsl`。**尚未接入 CMake、尚未编译、尚未运行**,不能当作已通过;不影响现有目标构建。+- 未做:WinML / ORT-DML 实测对照、SkinSoft HLSL 原型、P0.3 合同测试、`docs/BEAUTY_IMPLEMENTATION_PLAN_2026-10-17.md`。`claude/effects-infra-20261017` 尚未出现(E0 未交付),P1–P4 未开始。+- 详细发现与下一步:`C:/Users/123/AppData/Roaming/Claude/side-session-notes/local_089fcd60-31dd-4fd0-aac7-c63d8dc7d88a/beauty-20261017-handover.md`。diff --git a/include/veyra/beauty/OnnxLite.h b/include/veyra/beauty/OnnxLite.hnew file mode 100644index 00000000..2b343abc--- /dev/null+++ b/include/veyra/beauty/OnnxLite.h@@ -0,0 +1,59 @@+#pragma once+#include <cstdint>+#include <filesystem>+#include <map>+#include <string>+#include <unordered_map>+#include <vector>++namespace veyra::beauty {++// A deliberately small ONNX reader: just enough protobuf to read the graph of a+// compact CNN (nodes, attributes, float/int64 initializers, graph inputs and+// outputs). It is not a general ONNX implementation: anything it does not+// understand is rejected with a message, never guessed. Used by the face+// detector to read the model file that ships next to the program (the model is+// never part of the source tree).+struct OnnxTensor {+ std::string name;+ std::vector<int64_t> dims;+ int32_t dataType = 0; // ONNX TensorProto.DataType (1 = float, 7 = int64)+ std::vector<float> floats; // filled for float tensors+ std::vector<int64_t> ints; // filled for int64 tensors+ size_t elementCount() const {+ size_t n = 1;+ for (const auto d : dims) n *= size_t(d < 0 ? 0 : d);+ return n;+ }+};++struct OnnxNode {+ std::string op, name;+ std::vector<std::string> inputs, outputs;+ std::map<std::string, std::vector<int64_t>> ints; // INT and INTS attributes+ std::map<std::string, std::vector<float>> floats; // FLOAT and FLOATS attributes+ std::map<std::string, std::string> strings;+ int64_t intOr(const std::string& key, int64_t fallback) const {+ const auto it = ints.find(key);+ return it == ints.end() || it->second.empty() ? fallback : it->second.front();+ }+};++struct OnnxValueInfo {+ std::string name;+ std::vector<int64_t> dims; // -1 for symbolic dimensions+ std::vector<std::string> symbolicDims; // "" for fixed dimensions+};++struct OnnxModel {+ int64_t opset = 0; // default-domain opset+ std::string producer;+ std::vector<OnnxNode> nodes;+ std::unordered_map<std::string, OnnxTensor> initializers;+ std::vector<OnnxValueInfo> inputs, outputs;+};++bool parseOnnx(const std::vector<uint8_t>& bytes, OnnxModel& model, std::string& error);+bool readFileBytes(const std::filesystem::path& path, std::vector<uint8_t>& bytes, std::string& error);++} // namespace veyra::beautydiff --git a/include/veyra/beauty/YuNetGpu.h b/include/veyra/beauty/YuNetGpu.hnew file mode 100644index 00000000..0c91dea1--- /dev/null+++ b/include/veyra/beauty/YuNetGpu.h@@ -0,0 +1,91 @@+#pragma once+#include <d3d12.h>+#include <wrl/client.h>++#include <array>+#include <cstdint>+#include <filesystem>+#include <memory>+#include <string>+#include <vector>++namespace veyra::beauty {++// One detected face, in detector-input pixels (top-left origin, before any+// mapping back to the frame).+struct FaceBox {+ float x = 0, y = 0, w = 0, h = 0;+ // right eye, left eye, nose tip, right mouth corner, left mouth corner (x, y).+ std::array<float, 10> landmarks{};+ float score = 0;+ uint32_t id = 0; // scale << 24 | anchor index: deterministic tie-break only+};++struct YuNetConfig {+ uint32_t maxWidth = 640; // largest padded detector input (multiple of 32)+ uint32_t maxHeight = 640;+ uint32_t ringSlots = 3; // detections that may be in flight at once+ uint32_t candidateCapacity = 1024;+ float scoreThreshold = 0.6f;+ float nmsThreshold = 0.3f;+};++// YuNet (OpenCV Zoo / libfacedetection, MIT) face detector as D3D12 compute+// kernels. The network is read from the ONNX file at run time and compiled into+// a short list of layers (stem, 1x1, depthwise 3x3, max-pool, upsample+add and a+// per-stride decode); nothing is rendered or read back except a bounded list of+// candidate faces. Dispatches are recorded into the caller's command list, so the+// caller decides which queue runs them and when the result may be collected.+class YuNetGpu {+public:+ struct Source {+ ID3D12Resource* texture = nullptr; // RGBA16F, readable as a non-pixel SRV+ uint32_t width = 0, height = 0; // full texture size+ bool hdr = false; // scRGB (1.0 = 80 nits) instead of linear SDR+ uint32_t originX = 0, originY = 0; // optional crop; 0 size = whole texture+ uint32_t regionWidth = 0, regionHeight = 0;+ };++ YuNetGpu();+ ~YuNetGpu();+ YuNetGpu(const YuNetGpu&) = delete;+ YuNetGpu& operator=(const YuNetGpu&) = delete;++ bool initialize(ID3D12Device* device, const std::filesystem::path& modelPath,+ const YuNetConfig& config, std::string& error);+ void shutdown();+ bool ready() const;++ // Whole detection: prep (resample + encode the source), network, decode and+ // the copy of the candidate list into this slot's readback buffer.+ // detWidth/detHeight are the content size (<= padded maximum, any size, the+ // model input is padded up to a multiple of 32).+ bool record(ID3D12GraphicsCommandList* list, uint32_t slot, const Source& source,+ uint32_t detWidth, uint32_t detHeight);+ // Network + decode + readback copy only; the caller filled inputBuffer().+ bool recordNetwork(ID3D12GraphicsCommandList* list, uint32_t slot, uint32_t detWidth, uint32_t detHeight);++ // After the fence for `slot` completed: candidates -> NMS -> faces sorted by+ // score. Returns false when the readback is not available.+ bool collect(uint32_t slot, std::vector<FaceBox>& faces, uint32_t* rawCandidates = nullptr);+ static void nonMaxSuppression(std::vector<FaceBox>& boxes, float iouThreshold);++ // Test and tooling hooks.+ ID3D12Resource* inputBuffer() const; // padded BGR0 float4 grid, UAV state+ ID3D12Resource* headBuffer(uint32_t scale) const; // merged 16-channel head, UAV state+ uint32_t paddedExtent(uint32_t value) const { return (value + 31u) / 32u * 32u; }+ uint32_t layerCount() const;+ const char* layerName(uint32_t index) const;+ // Per-layer timestamps: EndQuery at base (start) and base + 1 + i after layer i.+ void setProfiler(ID3D12QueryHeap* heap, uint32_t baseIndex);+ uint64_t weightBytes() const;+ uint64_t workingSetBytes() const; // all tensor buffers at the maximum size+ uint64_t multiplyAccumulates(uint32_t detWidth, uint32_t detHeight) const;+ const std::string& modelDescription() const;++private:+ struct Impl;+ std::unique_ptr<Impl> impl_;+};++} // namespace veyra::beautydiff --git a/scripts/acceptance/claude-beauty-build.py b/scripts/acceptance/claude-beauty-build.pynew file mode 100644index 00000000..f8bc0652--- /dev/null+++ b/scripts/acceptance/claude-beauty-build.py@@ -0,0 +1,98 @@+"""Configure (once) and build selected targets for the claude/beauty-20261017 branch.++Mirrors scripts/acceptance/test-2.0.8-build.py: dependency paths are taken from the most recent accepted+CMake cache, FFmpeg import libraries are generated from the pinned DEF files inside this build tree, and+nothing outside E:/项目/Veyra/{build,logs,tmp}/<task> is written. No downloads, no packaging.++usage (run from a console whose output code page is 65001, see memory build-console-codepage):+ chcp.com 65001 >/dev/null && py -3.11 -B scripts/acceptance/claude-beauty-build.py --target veyra_beauty_p0_tests+"""+from pathlib import Path+import argparse, hashlib, json, os, re, subprocess, time++parser = argparse.ArgumentParser()+parser.add_argument('--task', default='claude-beauty-20261017')+parser.add_argument('--label', default='2.0.9-beauty')+parser.add_argument('--target', action='append', default=[])+parser.add_argument('--template-cache', default='E:/项目/Veyra/build/pr57-capture-window-20261017/CMakeCache.txt')+parser.add_argument('--reconfigure', action='store_true')+parser.add_argument('--parallel', default='8')+args = parser.parse_args()+assert re.fullmatch(r'[a-z0-9][a-z0-9.-]{0,79}', args.task)+assert args.target, 'pass at least one --target'+assert all(re.fullmatch(r'veyra_[a-z0-9_]+', t) for t in args.target)+ROOT = Path(__file__).resolve().parents[2]+BASE = Path('E:/项目/Veyra')+TASK = args.task+BUILD = BASE / 'build' / TASK+TMP = BASE / 'tmp' / TASK / 'build'+LOG = BASE / 'logs' / TASK / ('build-' + time.strftime('%Y%m%d-%H%M%S'))+for p in (BUILD, TMP, LOG):+ p.mkdir(parents=True, exist_ok=True)+++def sha(p):+ with Path(p).open('rb') as f:+ return hashlib.file_digest(f, 'sha256').hexdigest()+++text = Path(args.template_cache).read_text('utf8')+options = {k: v for k, t, v in re.findall(r'^(VEYRA_[^:]+|CMAKE_MAKE_PROGRAM|CMAKE_PREFIX_PATH):([^=]+)=(.*)$', text, re.M)+ if t not in ('INTERNAL', 'STATIC')}+for k in ('PROTOC', 'PKG_CONFIG_EXECUTABLE', 'SDL3_DIR', 'LibDataChannel_DIR', 'Opus_DIR', 'nlohmann_json_DIR'):+ options[k] = re.search(r'^' + k + r':[^=]+=(.*)$', text, re.M).group(1)+options.update(VEYRA_DECKLINK_SDK_DIR=str(BASE / 'deps/decklink-sdk-obs31-20261009'),+ VEYRA_AMD_NR_TEST_GRAPH_SOURCE=str(ROOT / 'src/pipeline/EnhanceGraph.cpp'),+ VEYRA_FFMPEG_ROOT=str(BASE / 'deps/ffmpeg-filter-issues41-45-20261016'),+ VEYRA_DISPLAY_VERSION=args.label, Python3_EXECUTABLE=os.sys.executable)+env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_', 'QML_'))}+env.update(TEMP=str(TMP), TMP=str(TMP), VSLANG='1033', PYTHONDONTWRITEBYTECODE='1')+setup = subprocess.run(['cmd.exe', '/u', '/d', '/c', r'call C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Auxiliary\Build\vcvars64.bat >nul && set'],+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding='utf-16-le', errors='replace', env=env, check=True)+for line in setup.stdout.splitlines():+ if '=' in line:+ k, v = line.split('=', 1)+ if k and not k.startswith('='):+ env[k] = v+env.update(TEMP=str(TMP), TMP=str(TMP), PYTHONDONTWRITEBYTECODE='1')++importdir = BUILD / 'ffmpeg-imports'+importdir.mkdir(exist_ok=True)+lib = r'C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/VC/Tools/MSVC/14.44.35207/bin/Hostx64/x64/lib.exe'+for short, dll in [('avformat', 'avformat-63'), ('avcodec', 'avcodec-63'), ('swresample', 'swresample-7'), ('swscale', 'swscale-10'), ('avutil', 'avutil-61')]:+ definition = Path(options['VEYRA_FFMPEG_ROOT']) / 'lib' / (dll + '.def')+ target = importdir / (short + '.lib')+ if not target.exists():+ with (LOG / ('import-' + short + '.log')).open('wb') as stream:+ subprocess.run([lib, '/nologo', '/machine:x64', '/def:' + str(definition), '/name:' + dll + '.dll', '/out:' + str(target)],+ cwd=TMP, env=env, stdout=stream, stderr=subprocess.STDOUT, check=True, timeout=30)+ options['FFMPEG_lib' + short + '_LIBRARY'] = str(target)+ options['FFMPEG_lib' + short + '_LIBRARY_RELEASE'] = str(target)+ options['FFMPEG_lib' + short + '_LIBRARY_RELEASE_DIR'] = str(importdir)++cmake = r'C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/bin/cmake.exe'+configure = [cmake, '-S', str(ROOT), '-B', str(BUILD), '-G', 'Ninja', '-DCMAKE_BUILD_TYPE=Release'] + ['-D' + k + '=' + v for k, v in options.items()]+build = [cmake, '--build', str(BUILD), '--parallel', args.parallel, '--target', *args.target]+steps = []+if args.reconfigure or not (BUILD / 'build.ninja').exists():+ steps.append(('configure', configure))+steps.append(('compile', build))+start = time.monotonic()+results = []+for name, command in steps:+ with (LOG / (name + '.log')).open('wb') as stream:+ try:+ rc = subprocess.run(command, cwd=TMP, env=env, stdout=stream, stderr=subprocess.STDOUT,+ timeout=max(1, 890 - (time.monotonic() - start))).returncode+ except subprocess.TimeoutExpired:+ rc = 124+ results.append(dict(step=name, exit=rc, seconds=round(time.monotonic() - start, 1)))+ print(name, rc, LOG / (name + '.log'), flush=True)+ if rc:+ print((LOG / (name + '.log')).read_text('utf8', errors='replace')[-9000:], flush=True)+ (LOG / 'failure.json').write_text(json.dumps(dict(results=results, commands=[c for _, c in steps]), ensure_ascii=False, indent=2), 'utf8')+ raise SystemExit(rc)+exes = {t: sha(BUILD / (t + '.exe')) for t in args.target if (BUILD / (t + '.exe')).exists()}+(LOG / 'receipt.json').write_text(json.dumps(dict(passed=True, results=results, targets=args.target, executables=exes,+ seconds=round(time.monotonic() - start, 1)), ensure_ascii=False, indent=2), 'utf8')+print('PASS', args.target, round(time.monotonic() - start, 1), 'seconds', flush=True)diff --git a/shaders/BeautyYuNet.hlsli b/shaders/BeautyYuNet.hlslinew file mode 100644index 00000000..a645d37a--- /dev/null+++ b/shaders/BeautyYuNet.hlsli@@ -0,0 +1,24 @@+// Shared declarations for the YuNet face detector kernels.+//+// Tensors are float4 buffers, channel-last: element index = pixel * quads + quad,+// quad k holding channels 4k..4k+3. Weights and biases of every layer live in one+// float4 buffer; the host writes the offsets (in float4 units) into the root+// constants. Layouts (host side packing is in YuNetGpu.cpp):+// pointwise : W[wOff + g * (inQuads * 4) + c] = (w[4g+0][c], .., w[4g+3][c])+// depthwise : W[wOff + q * 9 + (ky * 3 + kx)] = (w[4q+0], .., w[4q+3]) of that tap+// stem 3x3/s2: W[wOff + (q * 9 + tap) * 3 + c] = (w[4q+0][c][tap], .., w[4q+3][c][tap])+// bias : W[bOff + q] = (b[4q+0], .., b[4q+3])+cbuffer Params : register(b0) {+ uint inW; uint inH; uint inQ;+ uint outW; uint outH; uint outQ;+ uint wOff; uint bOff;+ uint flags; // bit 0: ReLU on the result+ uint arg0; uint arg1; uint arg2; uint arg3; uint arg4; uint arg5; uint arg6;+};+StructuredBuffer<float4> Weights : register(t0);++static const uint kFlagRelu = 1u;++float4 finishLayer(float4 value) {+ return (flags & kFlagRelu) ? max(value, 0.0) : value;+}diff --git a/shaders/BeautyYuNetDecode.hlsl b/shaders/BeautyYuNetDecode.hlslnew file mode 100644index 00000000..35e802e8--- /dev/null+++ b/shaders/BeautyYuNetDecode.hlsl@@ -0,0 +1,37 @@+// YuNet head decode for one stride. The merged head tensor holds 16 channels per+// anchor: 0 cls, 1 obj, 2..5 box, 6..15 five landmarks (x,y pairs). Anchors whose+// sqrt(sigmoid(cls) * sigmoid(obj)) reaches the threshold are appended to a+// bounded candidate list (atomic counter in the first 16 bytes, then 64-byte+// records); the host reads the list back after the fence and runs NMS.+// arg0 stride | arg1 capacity | arg2 threshold (float bits) | arg3 scale index+// Record: x, y, w, h, 5 x (lx, ly), score, id (scale << 24 | anchor).+#include "BeautyYuNet.hlsli"+RWStructuredBuffer<float4> Head : register(u0);+RWByteAddressBuffer Candidates : register(u2);++float sigmoid(float x) { return 1.0 / (1.0 + exp(-x)); }++[numthreads(64,1,1)]+void main(uint3 id : SV_DispatchThreadID) {+ const uint total = outW * outH;+ if (id.x >= total) return;+ const uint pixel = id.x;+ const float4 a = Head[pixel * 4 + 0];+ const float score = sqrt(saturate(sigmoid(a.x)) * saturate(sigmoid(a.y)));+ if (!(score >= asfloat(arg2))) return;+ const float4 b = Head[pixel * 4 + 1];+ const float4 c = Head[pixel * 4 + 2];+ const float4 d = Head[pixel * 4 + 3];+ const float stride = float(arg0);+ const float col = float(pixel % outW), row = float(pixel / outW);+ const float cx = (col + a.z) * stride, cy = (row + a.w) * stride;+ const float w = exp(b.x) * stride, h = exp(b.y) * stride;+ uint slot;+ Candidates.InterlockedAdd(0, 1, slot);+ if (slot >= arg1) return;+ const uint o = 16 + slot * 64;+ Candidates.Store4(o, asuint(float4(cx - w * 0.5, cy - h * 0.5, w, h)));+ Candidates.Store4(o + 16, asuint(float4((b.z + col) * stride, (b.w + row) * stride, (c.x + col) * stride, (c.y + row) * stride)));+ Candidates.Store4(o + 32, asuint(float4((c.z + col) * stride, (c.w + row) * stride, (d.x + col) * stride, (d.y + row) * stride)));+ Candidates.Store4(o + 48, uint4(asuint((d.z + col) * stride), asuint((d.w + row) * stride), asuint(score), (arg3 << 24) | pixel));+}diff --git a/shaders/BeautyYuNetDepthwise.hlsl b/shaders/BeautyYuNetDepthwise.hlslnew file mode 100644index 00000000..9015c158--- /dev/null+++ b/shaders/BeautyYuNetDepthwise.hlsl@@ -0,0 +1,21 @@+// 3x3 depthwise convolution, stride 1, padding 1, one 3x3 kernel per channel.+#include "BeautyYuNet.hlsli"+RWStructuredBuffer<float4> Input : register(u0);+RWStructuredBuffer<float4> Out : register(u2);++[numthreads(64,1,1)]+void main(uint3 id : SV_DispatchThreadID) {+ const uint total = outW * outH * outQ;+ if (id.x >= total) return;+ const uint q = id.x % outQ, pixel = id.x / outQ;+ const int x = int(pixel % outW), y = int(pixel / outW);+ float4 acc = Weights[bOff + q];+ [unroll] for (int ky = 0; ky < 3; ++ky) {+ [unroll] for (int kx = 0; kx < 3; ++kx) {+ const int ix = x + kx - 1, iy = y + ky - 1;+ if (ix < 0 || iy < 0 || ix >= int(inW) || iy >= int(inH)) continue;+ acc += Weights[wOff + q * 9 + uint(ky * 3 + kx)] * Input[(uint(iy) * inW + uint(ix)) * inQ + q];+ }+ }+ Out[id.x] = finishLayer(acc);+}diff --git a/shaders/BeautyYuNetPointwise.hlsl b/shaders/BeautyYuNetPointwise.hlslnew file mode 100644index 00000000..22b69fd8--- /dev/null+++ b/shaders/BeautyYuNetPointwise.hlsl@@ -0,0 +1,19 @@+// 1x1 convolution (groups = 1) over a channel-last quad tensor.+#include "BeautyYuNet.hlsli"+RWStructuredBuffer<float4> Input : register(u0);+RWStructuredBuffer<float4> Out : register(u2);++[numthreads(64,1,1)]+void main(uint3 id : SV_DispatchThreadID) {+ const uint total = outW * outH * outQ;+ if (id.x >= total) return;+ const uint g = id.x % outQ, pixel = id.x / outQ;+ float4 acc = Weights[bOff + g];+ const uint weightBase = wOff + g * inQ * 4;+ for (uint q = 0; q < inQ; ++q) {+ const float4 v = Input[pixel * inQ + q];+ const uint base = weightBase + q * 4;+ acc += Weights[base] * v.x + Weights[base + 1] * v.y + Weights[base + 2] * v.z + Weights[base + 3] * v.w;+ }+ Out[id.x] = finishLayer(acc);+}diff --git a/shaders/BeautyYuNetPool.hlsl b/shaders/BeautyYuNetPool.hlslnew file mode 100644index 00000000..39834934--- /dev/null+++ b/shaders/BeautyYuNetPool.hlsl@@ -0,0 +1,17 @@+// 2x2 max pooling, stride 2.+#include "BeautyYuNet.hlsli"+RWStructuredBuffer<float4> Input : register(u0);+RWStructuredBuffer<float4> Out : register(u2);++[numthreads(64,1,1)]+void main(uint3 id : SV_DispatchThreadID) {+ const uint total = outW * outH * outQ;+ if (id.x >= total) return;+ const uint q = id.x % outQ, pixel = id.x / outQ;+ const uint x = (pixel % outW) * 2, y = (pixel / outW) * 2;+ float4 m = Input[(y * inW + x) * inQ + q];+ m = max(m, Input[(y * inW + min(x + 1, inW - 1)) * inQ + q]);+ m = max(m, Input[(min(y + 1, inH - 1) * inW + x) * inQ + q]);+ m = max(m, Input[(min(y + 1, inH - 1) * inW + min(x + 1, inW - 1)) * inQ + q]);+ Out[id.x] = m;+}diff --git a/shaders/BeautyYuNetPrep.hlsl b/shaders/BeautyYuNetPrep.hlslnew file mode 100644index 00000000..88edfd01--- /dev/null+++ b/shaders/BeautyYuNetPrep.hlsl@@ -0,0 +1,45 @@+// Face detector input: area-averaged, sRGB-coded, BGR 0..255 copy of the frame+// (what the model was trained on: an 8-bit display-referred picture). The model+// input is padded with zeros to a multiple of 32 on the right and bottom.+//+// Source: the linear working texture of the graph (RGBA16F). SDR frames are+// encoded with the sRGB curve; HDR (scRGB, 1 = 80 nits) frames first go through+// the fixed 203-nit proxy used by the other HDR-aware effects, so highlights+// compress instead of clipping and negative wide-gamut components clamp at zero+// in this analysis copy only (the picture itself is never touched here).+#include "BeautyYuNet.hlsli"+#include "HdrColor.hlsli"++Texture2D<float4> Source : register(t1);+RWStructuredBuffer<float4> Out : register(u2);++float3 srgbEncode(float3 linearValue) {+ const float3 c = saturate(linearValue);+ return select(c <= 0.0031308, c * 12.92, 1.055 * pow(c, 1.0 / 2.4) - 0.055);+}++// outW/outH = padded size; arg0/arg1 = source size; arg2/arg3 = content size+// inside the padded grid; arg4 = HDR flag; arg5 = taps per axis (1..8);+// arg6 = region origin x | y << 16 in source pixels (whole frame: 0).+[numthreads(64,1,1)]+void main(uint3 id : SV_DispatchThreadID) {+ const uint total = outW * outH;+ if (id.x >= total) return;+ const uint x = id.x % outW, y = id.x / outW;+ if (x >= arg2 || y >= arg3) { Out[id.x] = float4(0, 0, 0, 0); return; }+ const uint2 origin = uint2(arg6 & 0xffffu, arg6 >> 16);+ const float2 scale = float2(arg0, arg1) / float2(arg2, arg3);+ const uint taps = max(arg5, 1u);+ float3 sum = 0;+ for (uint j = 0; j < taps; ++j) {+ for (uint i = 0; i < taps; ++i) {+ const float2 p = (float2(x, y) + (float2(i, j) + 0.5) / taps) * scale;+ const uint2 pixel = origin + min(uint2(p), uint2(arg0 - 1, arg1 - 1));+ float3 c = Source.Load(int3(pixel, 0)).rgb;+ c = arg4 ? HdrProxy(c) : c;+ sum += srgbEncode(c);+ }+ }+ const float3 rgb = sum / float(taps * taps) * 255.0;+ Out[id.x] = float4(rgb.b, rgb.g, rgb.r, 0.0);+}diff --git a/shaders/BeautyYuNetStem.hlsl b/shaders/BeautyYuNetStem.hlslnew file mode 100644index 00000000..7685b8b4--- /dev/null+++ b/shaders/BeautyYuNetStem.hlsl@@ -0,0 +1,23 @@+// YuNet stem: 3x3 convolution, stride 2, padding 1, 3 -> 16 channels, then ReLU.+#include "BeautyYuNet.hlsli"+RWStructuredBuffer<float4> Input : register(u0);+RWStructuredBuffer<float4> Out : register(u2);++[numthreads(64,1,1)]+void main(uint3 id : SV_DispatchThreadID) {+ const uint total = outW * outH * outQ;+ if (id.x >= total) return;+ const uint q = id.x % outQ, pixel = id.x / outQ;+ const int x = int(pixel % outW), y = int(pixel / outW);+ float4 acc = Weights[bOff + q];+ [unroll] for (int ky = 0; ky < 3; ++ky) {+ [unroll] for (int kx = 0; kx < 3; ++kx) {+ const int ix = x * 2 + kx - 1, iy = y * 2 + ky - 1;+ if (ix < 0 || iy < 0 || ix >= int(inW) || iy >= int(inH)) continue;+ const float4 v = Input[uint(iy) * inW + uint(ix)];+ const uint base = wOff + (q * 9 + uint(ky * 3 + kx)) * 3;+ acc += Weights[base] * v.x + Weights[base + 1] * v.y + Weights[base + 2] * v.z;+ }+ }+ Out[id.x] = finishLayer(acc);+}diff --git a/shaders/BeautyYuNetUpAdd.hlsl b/shaders/BeautyYuNetUpAdd.hlslnew file mode 100644index 00000000..40d38fdd--- /dev/null+++ b/shaders/BeautyYuNetUpAdd.hlsl@@ -0,0 +1,15 @@+// Neck merge: nearest-neighbour 2x upsample of the coarser map (u0) added to the+// skip connection (u1). ONNX Resize(nearest, asymmetric, floor) == source index x / 2.+#include "BeautyYuNet.hlsli"+RWStructuredBuffer<float4> Coarse : register(u0);+RWStructuredBuffer<float4> Skip : register(u1);+RWStructuredBuffer<float4> Out : register(u2);++[numthreads(64,1,1)]+void main(uint3 id : SV_DispatchThreadID) {+ const uint total = outW * outH * outQ;+ if (id.x >= total) return;+ const uint q = id.x % outQ, pixel = id.x / outQ;+ const uint x = pixel % outW, y = pixel / outW;+ Out[id.x] = Skip[id.x] + Coarse[((y >> 1) * inW + (x >> 1)) * inQ + q];+}diff --git a/src/beauty/OnnxLite.cpp b/src/beauty/OnnxLite.cppnew file mode 100644index 00000000..1191d18f--- /dev/null+++ b/src/beauty/OnnxLite.cpp@@ -0,0 +1,271 @@+#include "veyra/beauty/OnnxLite.h"++#include <cstring>+#include <fstream>++namespace veyra::beauty {+namespace {++// Wire-level protobuf cursor. Every read is bounds checked; a malformed or+// truncated file turns into a clean error instead of an out-of-range access.+struct Reader {+ const uint8_t* p = nullptr;+ const uint8_t* end = nullptr;+ bool bad = false;+ bool more() const { return !bad && p < end; }+ uint64_t varint() {+ uint64_t value = 0;+ for (unsigned shift = 0; shift < 70; shift += 7) {+ if (p >= end) { bad = true; return 0; }+ const uint8_t byte = *p++;+ value |= uint64_t(byte & 0x7f) << shift;+ if (!(byte & 0x80)) return value;+ }+ bad = true;+ return 0;+ }+ Reader bytes() {+ const uint64_t length = varint();+ if (bad || length > uint64_t(end - p)) { bad = true; return {}; }+ Reader sub{p, p + length, false};+ p += length;+ return sub;+ }+ bool skip(uint32_t wire) {+ switch (wire) {+ case 0: varint(); break;+ case 1: if (end - p < 8) { bad = true; } else p += 8; break;+ case 2: (void)bytes(); break;+ case 5: if (end - p < 4) { bad = true; } else p += 4; break;+ default: bad = true;+ }+ return !bad;+ }+ std::string text() {+ const Reader sub = bytes();+ return std::string(reinterpret_cast<const char*>(sub.p), size_t(sub.end - sub.p));+ }+};++int64_t signedValue(uint64_t v) { return int64_t(v); }++// Repeated scalar fields come either packed (one length-delimited blob) or as+// individual varints; both encodings are valid in the ONNX schema.+void readInts(Reader& r, uint32_t wire, std::vector<int64_t>& out)+{+ if (wire == 2) {+ Reader sub = r.bytes();+ while (sub.more()) out.push_back(signedValue(sub.varint()));+ r.bad = r.bad || sub.bad;+ } else if (wire == 0) {+ out.push_back(signedValue(r.varint()));+ } else r.bad = true;+}++void readFloats(Reader& r, uint32_t wire, std::vector<float>& out)+{+ if (wire == 2) {+ Reader sub = r.bytes();+ if (sub.bad || ((sub.end - sub.p) % 4) != 0) { r.bad = true; return; }+ while (sub.p < sub.end) { float f; std::memcpy(&f, sub.p, 4); sub.p += 4; out.push_back(f); }+ } else if (wire == 5) {+ if (r.end - r.p < 4) { r.bad = true; return; }+ float f; std::memcpy(&f, r.p, 4); r.p += 4; out.push_back(f);+ } else r.bad = true;+}++bool parseTensor(Reader r, OnnxTensor& t, std::string& error)+{+ std::vector<uint8_t> raw;+ bool hasRaw = false;+ while (r.more()) {+ const uint64_t key = r.varint();+ const uint32_t field = uint32_t(key >> 3), wire = uint32_t(key & 7);+ if (field == 1) readInts(r, wire, t.dims);+ else if (field == 2 && wire == 0) t.dataType = int32_t(r.varint());+ else if (field == 4) readFloats(r, wire, t.floats);+ else if (field == 7) readInts(r, wire, t.ints);+ else if (field == 8 && wire == 2) t.name = r.text();+ else if (field == 9 && wire == 2) {+ const Reader sub = r.bytes();+ raw.assign(sub.p, sub.end);+ hasRaw = true;+ } else if (field == 13) { error = "tensor uses external data"; return false; }+ else if (!r.skip(wire)) break;+ }+ if (r.bad) { error = "malformed tensor"; return false; }+ if (hasRaw) {+ if (t.dataType == 1) {+ if (raw.size() % 4) { error = "float tensor raw_data size"; return false; }+ t.floats.resize(raw.size() / 4);+ std::memcpy(t.floats.data(), raw.data(), raw.size());+ } else if (t.dataType == 7) {+ if (raw.size() % 8) { error = "int64 tensor raw_data size"; return false; }+ t.ints.resize(raw.size() / 8);+ std::memcpy(t.ints.data(), raw.data(), raw.size());+ }+ }+ return true;+}++bool parseAttribute(Reader r, OnnxNode& node, std::string& error)+{+ std::string name, text;+ std::vector<int64_t> ints;+ std::vector<float> floats;+ bool isInt = false, isFloat = false, isString = false;+ while (r.more()) {+ const uint64_t key = r.varint();+ const uint32_t field = uint32_t(key >> 3), wire = uint32_t(key & 7);+ if (field == 1 && wire == 2) name = r.text();+ else if (field == 2) { readFloats(r, wire, floats); isFloat = true; }+ else if (field == 3) { readInts(r, wire, ints); isInt = true; }+ else if (field == 4 && wire == 2) { text = r.text(); isString = true; }+ else if (field == 7) { readFloats(r, wire, floats); isFloat = true; }+ else if (field == 8) { readInts(r, wire, ints); isInt = true; }+ else if (!r.skip(wire)) break; // tensor/graph/type fields are not needed for this model family+ }+ if (r.bad) { error = "malformed attribute"; return false; }+ if (isInt) node.ints[name] = std::move(ints);+ if (isFloat) node.floats[name] = std::move(floats);+ if (isString) node.strings[name] = std::move(text);+ return true;+}++bool parseNode(Reader r, OnnxNode& node, std::string& error)+{+ while (r.more()) {+ const uint64_t key = r.varint();+ const uint32_t field = uint32_t(key >> 3), wire = uint32_t(key & 7);+ if (field == 1 && wire == 2) node.inputs.push_back(r.text());+ else if (field == 2 && wire == 2) node.outputs.push_back(r.text());+ else if (field == 3 && wire == 2) node.name = r.text();+ else if (field == 4 && wire == 2) node.op = r.text();+ else if (field == 5 && wire == 2) { if (!parseAttribute(r.bytes(), node, error)) return false; }+ else if (!r.skip(wire)) break;+ }+ if (r.bad) { error = "malformed node"; return false; }+ return true;+}++bool parseValueInfo(Reader r, OnnxValueInfo& info, std::string& error)+{+ while (r.more()) {+ const uint64_t key = r.varint();+ const uint32_t field = uint32_t(key >> 3), wire = uint32_t(key & 7);+ if (field == 1 && wire == 2) info.name = r.text();+ else if (field == 2 && wire == 2) { // TypeProto+ Reader type = r.bytes();+ while (type.more()) {+ const uint64_t k2 = type.varint();+ const uint32_t f2 = uint32_t(k2 >> 3), w2 = uint32_t(k2 & 7);+ if (f2 == 1 && w2 == 2) { // tensor_type+ Reader tensor = type.bytes();+ while (tensor.more()) {+ const uint64_t k3 = tensor.varint();+ const uint32_t f3 = uint32_t(k3 >> 3), w3 = uint32_t(k3 & 7);+ if (f3 == 2 && w3 == 2) { // shape+ Reader shape = tensor.bytes();+ while (shape.more()) {+ const uint64_t k4 = shape.varint();+ const uint32_t f4 = uint32_t(k4 >> 3), w4 = uint32_t(k4 & 7);+ if (f4 == 1 && w4 == 2) { // dim+ Reader dim = shape.bytes();+ int64_t value = -1;+ std::string symbol;+ while (dim.more()) {+ const uint64_t k5 = dim.varint();+ const uint32_t f5 = uint32_t(k5 >> 3), w5 = uint32_t(k5 & 7);+ if (f5 == 1 && w5 == 0) value = signedValue(dim.varint());+ else if (f5 == 2 && w5 == 2) symbol = dim.text();+ else if (!dim.skip(w5)) break;+ }+ info.dims.push_back(value);+ info.symbolicDims.push_back(symbol);+ } else if (!shape.skip(w4)) break;+ }+ } else if (!tensor.skip(w3)) break;+ }+ } else if (!type.skip(w2)) break;+ }+ } else if (!r.skip(wire)) break;+ }+ if (r.bad) { error = "malformed value info"; return false; }+ return true;+}++bool parseGraph(Reader r, OnnxModel& model, std::string& error)+{+ while (r.more()) {+ const uint64_t key = r.varint();+ const uint32_t field = uint32_t(key >> 3), wire = uint32_t(key & 7);+ if (field == 1 && wire == 2) {+ OnnxNode node;+ if (!parseNode(r.bytes(), node, error)) return false;+ model.nodes.push_back(std::move(node));+ } else if (field == 5 && wire == 2) {+ OnnxTensor tensor;+ if (!parseTensor(r.bytes(), tensor, error)) return false;+ const std::string name = tensor.name;+ model.initializers[name] = std::move(tensor);+ } else if (field == 11 && wire == 2) {+ OnnxValueInfo info;+ if (!parseValueInfo(r.bytes(), info, error)) return false;+ model.inputs.push_back(std::move(info));+ } else if (field == 12 && wire == 2) {+ OnnxValueInfo info;+ if (!parseValueInfo(r.bytes(), info, error)) return false;+ model.outputs.push_back(std::move(info));+ } else if (!r.skip(wire)) break;+ }+ if (r.bad) { error = "malformed graph"; return false; }+ return true;+}++} // namespace++bool parseOnnx(const std::vector<uint8_t>& bytes, OnnxModel& model, std::string& error)+{+ model = {};+ if (bytes.size() < 16) { error = "file too small to be an ONNX model"; return false; }+ Reader r{bytes.data(), bytes.data() + bytes.size(), false};+ bool sawGraph = false;+ while (r.more()) {+ const uint64_t key = r.varint();+ const uint32_t field = uint32_t(key >> 3), wire = uint32_t(key & 7);+ if (field == 2 && wire == 2) model.producer = r.text();+ else if (field == 7 && wire == 2) {+ if (!parseGraph(r.bytes(), model, error)) return false;+ sawGraph = true;+ } else if (field == 8 && wire == 2) {+ Reader opset = r.bytes();+ std::string domain;+ int64_t version = 0;+ while (opset.more()) {+ const uint64_t k2 = opset.varint();+ const uint32_t f2 = uint32_t(k2 >> 3), w2 = uint32_t(k2 & 7);+ if (f2 == 1 && w2 == 2) domain = opset.text();+ else if (f2 == 2 && w2 == 0) version = signedValue(opset.varint());+ else if (!opset.skip(w2)) break;+ }+ if (domain.empty() || domain == "ai.onnx") model.opset = version;+ } else if (!r.skip(wire)) break;+ }+ if (r.bad) { error = "malformed model (truncated or not protobuf)"; return false; }+ if (!sawGraph || model.nodes.empty()) { error = "model has no graph"; return false; }+ return true;+}++bool readFileBytes(const std::filesystem::path& path, std::vector<uint8_t>& bytes, std::string& error)+{+ std::ifstream file(path, std::ios::binary | std::ios::ate);+ if (!file) { error = "cannot open " + path.string(); return false; }+ const std::streamsize size = file.tellg();+ if (size <= 0 || size > (256ll << 20)) { error = "unexpected model size"; return false; }+ bytes.resize(size_t(size));+ file.seekg(0);+ if (!file.read(reinterpret_cast<char*>(bytes.data()), size)) { error = "read failed"; return false; }+ return true;+}++} // namespace veyra::beautydiff --git a/src/beauty/YuNetGpu.cpp b/src/beauty/YuNetGpu.cppnew file mode 100644index 00000000..9975c91f--- /dev/null+++ b/src/beauty/YuNetGpu.cpp@@ -0,0 +1,799 @@+#include "veyra/beauty/YuNetGpu.h"++#include <algorithm>+#include <cmath>+#include <cstring>+#include <format>+#include <map>+#include <set>+#include <unordered_map>++#include "veyra/Log.h"+#include "veyra/RuntimePaths.h"+#include "veyra/beauty/OnnxLite.h"++namespace veyra::beauty {+namespace {++template <typename T> using ComPtr = Microsoft::WRL::ComPtr<T>;++constexpr uint32_t kConstantDwords = 16;+constexpr uint32_t kSrvPerSlot = 2; // t0 weights, t1 source frame+constexpr uint32_t kUavPerLayer = 3; // u0 first input, u1 second input, u2 output+constexpr uint32_t kMaxTaps = 8;++enum class Kind : uint8_t { Prep, Stem, Pointwise, Depthwise, Pool, UpAdd, Decode, Count };+constexpr const char* kShaderFile[] = {"BeautyYuNetPrep.dxil", "BeautyYuNetStem.dxil", "BeautyYuNetPointwise.dxil",+ "BeautyYuNetDepthwise.dxil", "BeautyYuNetPool.dxil", "BeautyYuNetUpAdd.dxil", "BeautyYuNetDecode.dxil"};+constexpr const char* kKindName[] = {"prep", "stem", "pointwise", "depthwise", "pool", "upadd", "decode"};++struct TensorDesc {+ std::string name;+ uint32_t quads = 0; // channels / 4+ uint32_t shift = 0; // log2 of the stride relative to the padded input+ int firstWrite = -1, lastRead = -1;+ int buffer = -1;+ bool pinned = false; // never shared with other tensors+};++struct LayerDesc {+ Kind kind = Kind::Stem;+ int in0 = -1, in1 = -1, out = -1; // tensor ids; Decode writes the candidate buffer instead+ uint32_t wOff = 0, bOff = 0;+ bool relu = false;+ int scale = -1; // Decode: 0/1/2 -> stride 8/16/32+ std::string name;+};++uint32_t bits(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; }++D3D12_RESOURCE_DESC bufferDesc(uint64_t bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE)+{+ D3D12_RESOURCE_DESC d{};+ d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;+ d.Width = bytes; d.Height = 1; d.DepthOrArraySize = 1; d.MipLevels = 1;+ d.SampleDesc.Count = 1; d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Flags = flags;+ return d;+}++ComPtr<ID3D12Resource> createBuffer(ID3D12Device* device, uint64_t bytes, D3D12_HEAP_TYPE heap,+ D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state)+{+ D3D12_HEAP_PROPERTIES hp{};+ hp.Type = heap;+ const auto desc = bufferDesc(bytes, flags);+ ComPtr<ID3D12Resource> r;+ if (FAILED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&r))))+ return nullptr;+ return r;+}++bool loadDxil(const char* name, std::vector<uint8_t>& bytes)+{+ const auto path = runtime::shaderDirectory() / name;+ FILE* f = nullptr;+ if (_wfopen_s(&f, path.c_str(), L"rb") != 0 || !f) {+ log::error("beauty-detect", std::format("shader missing: {}", path.string()));+ return false;+ }+ fseek(f, 0, SEEK_END);+ const long size = ftell(f);+ fseek(f, 0, SEEK_SET);+ bytes.resize(size_t(size > 0 ? size : 0));+ const size_t read = bytes.empty() ? 0 : fread(bytes.data(), 1, bytes.size(), f);+ fclose(f);+ return !bytes.empty() && read == bytes.size();+}++} // namespace++struct YuNetGpu::Impl {+ ID3D12Device* device = nullptr;+ YuNetConfig cfg;+ std::string description;+ std::vector<TensorDesc> tensors;+ std::vector<LayerDesc> layers;+ std::vector<float> weights; // float4-aligned+ std::vector<ComPtr<ID3D12Resource>> buffers;+ std::vector<uint64_t> bufferBytes;+ ComPtr<ID3D12Resource> weightBuffer;+ ComPtr<ID3D12RootSignature> rootSignature;+ ComPtr<ID3D12PipelineState> pipelines[size_t(Kind::Count)];+ ComPtr<ID3D12DescriptorHeap> heap, stagingHeap;+ UINT increment = 0;+ std::vector<ComPtr<ID3D12Resource>> candidates, readbacks;+ ComPtr<ID3D12Resource> zeroUpload;+ uint64_t candidateBytes = 0;+ uint32_t uavBase = 0; // first UAV descriptor in the heap+ std::vector<uint32_t> layerUav; // per layer: base index; Decode: base of slot 0+ int headTensor[3] = {-1, -1, -1};+ int inputTensor = -1;+ ID3D12QueryHeap* profileHeap = nullptr;+ uint32_t profileBase = 0;+ uint64_t workingSet = 0;+ bool ready = false;++ // ------------------------------------------------------------------ plan+ uint32_t allocate(size_t float4Count)+ {+ const size_t offset = weights.size() / 4;+ weights.resize(weights.size() + float4Count * 4, 0.0f);+ return uint32_t(offset);+ }++ int newTensor(const std::string& name, uint32_t quads, uint32_t shift, bool pinned = false)+ {+ TensorDesc t;+ t.name = name; t.quads = quads; t.shift = shift; t.pinned = pinned;+ tensors.push_back(std::move(t));+ return int(tensors.size()) - 1;+ }++ // Packs one convolution into the shared weight array; returns false for a+ // shape the kernels do not implement.+ bool packStem(const OnnxTensor& w, const OnnxTensor& b, LayerDesc& layer, std::string& error)+ {+ if (w.dims.size() != 4 || w.dims[1] != 3 || w.dims[2] != 3 || w.dims[3] != 3 || w.dims[0] % 4 || b.floats.size() != size_t(w.dims[0])) {+ error = "stem convolution shape"; return false;+ }+ const size_t cout = size_t(w.dims[0]), quads = cout / 4;+ layer.wOff = allocate(quads * 9 * 3);+ layer.bOff = allocate(quads);+ for (size_t q = 0; q < quads; ++q) {+ for (size_t t = 0; t < 9; ++t) for (size_t c = 0; c < 3; ++c) for (size_t k = 0; k < 4; ++k)+ weights[(layer.wOff + (q * 9 + t) * 3 + c) * 4 + k] = w.floats[((4 * q + k) * 3 + c) * 9 + t];+ for (size_t k = 0; k < 4; ++k) weights[(layer.bOff + q) * 4 + k] = b.floats[4 * q + k];+ }+ return true;+ }++ bool packPointwise(const std::vector<float>& w, const std::vector<float>& b, size_t cout, size_t cin, LayerDesc& layer, std::string& error)+ {+ if (cout % 4 || cin % 4 || w.size() != cout * cin || b.size() != cout) { error = "pointwise convolution shape"; return false; }+ layer.wOff = allocate(cout / 4 * cin);+ layer.bOff = allocate(cout / 4);+ for (size_t g = 0; g < cout / 4; ++g) {+ for (size_t c = 0; c < cin; ++c) for (size_t k = 0; k < 4; ++k)+ weights[(layer.wOff + g * cin + c) * 4 + k] = w[(4 * g + k) * cin + c];+ for (size_t k = 0; k < 4; ++k) weights[(layer.bOff + g) * 4 + k] = b[4 * g + k];+ }+ return true;+ }++ bool packDepthwise(const std::vector<float>& w, const std::vector<float>& b, size_t channels, LayerDesc& layer, std::string& error)+ {+ if (channels % 4 || w.size() != channels * 9 || b.size() != channels) { error = "depthwise convolution shape"; return false; }+ layer.wOff = allocate(channels / 4 * 9);+ layer.bOff = allocate(channels / 4);+ for (size_t q = 0; q < channels / 4; ++q) {+ for (size_t t = 0; t < 9; ++t) for (size_t k = 0; k < 4; ++k)+ weights[(layer.wOff + q * 9 + t) * 4 + k] = w[(4 * q + k) * 9 + t];+ for (size_t k = 0; k < 4; ++k) weights[(layer.bOff + q) * 4 + k] = b[4 * q + k];+ }+ return true;+ }++ bool buildPlan(const OnnxModel& model, std::string& error)+ {+ static const std::set<std::string> allowed = {"Conv", "Relu", "MaxPool", "Resize", "Add", "Transpose", "Reshape", "Sigmoid"};+ for (const auto& n : model.nodes) if (!allowed.count(n.op)) { error = "unsupported operator " + n.op; return false; }+ if (model.opset < 9 || model.opset > 21) { error = std::format("unexpected opset {}", model.opset); return false; }+ if (model.inputs.size() != 1 || model.inputs[0].dims.size() != 4 || model.inputs[0].dims[1] != 3) {+ error = "model input is not a single NCHW RGB tensor"; return false;+ }+ std::unordered_map<std::string, int> producer, consumers;+ for (size_t i = 0; i < model.nodes.size(); ++i) {+ for (const auto& o : model.nodes[i].outputs) producer[o] = int(i);+ for (const auto& in : model.nodes[i].inputs) ++consumers[in];+ }+ const auto init = [&](const std::string& name) -> const OnnxTensor* {+ const auto it = model.initializers.find(name);+ return it == model.initializers.end() ? nullptr : &it->second;+ };+ const auto convTensors = [&](const OnnxNode& n, const OnnxTensor*& w, const OnnxTensor*& b) {+ w = n.inputs.size() > 1 ? init(n.inputs[1]) : nullptr;+ b = n.inputs.size() > 2 ? init(n.inputs[2]) : nullptr;+ return w && b && w->dataType == 1 && b->dataType == 1 && w->floats.size() == w->elementCount() && b->floats.size() == b->elementCount();+ };++ // 1. The twelve head outputs: trace each back to its (1x1, depthwise 3x3) pair.+ struct HeadChain { int pw = -1, dw = -1; std::string feature; };+ static const char* kTypeName[4] = {"cls", "obj", "bbox", "kps"};+ static const size_t kTypeChannels[4] = {1, 1, 4, 10};+ static const uint32_t kStrides[3] = {8, 16, 32};+ HeadChain heads[4][3];+ std::vector<bool> headNode(model.nodes.size(), false);+ for (int t = 0; t < 4; ++t) for (int s = 0; s < 3; ++s) {+ const std::string output = std::format("{}_{}", kTypeName[t], kStrides[s]);+ if (std::none_of(model.outputs.begin(), model.outputs.end(), [&](const OnnxValueInfo& o) { return o.name == output; })) {+ error = "missing model output " + output; return false;+ }+ const auto at = producer.find(output);+ int n = at == producer.end() ? -1 : at->second;+ const auto step = [&](const char* op) -> bool {+ if (n < 0 || model.nodes[size_t(n)].op != op || model.nodes[size_t(n)].inputs.empty()) { error = std::format("head {} does not match the expected {} chain", output, op); return false; }+ headNode[size_t(n)] = true;+ return true;+ };+ const auto advance = [&]() { const auto it = producer.find(model.nodes[size_t(n)].inputs[0]); n = it == producer.end() ? -1 : it->second; };+ if (t < 2) { if (!step("Sigmoid")) return false; advance(); }+ if (!step("Reshape")) return false; advance();+ if (!step("Transpose")) return false; advance();+ if (!step("Conv")) return false;+ heads[t][s].dw = n; advance();+ if (!step("Conv")) return false;+ heads[t][s].pw = n;+ heads[t][s].feature = model.nodes[size_t(n)].inputs[0];+ const auto& pw = model.nodes[size_t(heads[t][s].pw)];+ const auto& dw = model.nodes[size_t(heads[t][s].dw)];+ const OnnxTensor *pww, *pwb, *dww, *dwb;+ if (!convTensors(pw, pww, pwb) || !convTensors(dw, dww, dwb)) { error = "head convolution weights"; return false; }+ const size_t c = kTypeChannels[t];+ if (pww->dims.size() != 4 || size_t(pww->dims[0]) != c || pww->dims[1] != 64 || pww->dims[2] != 1 || pww->dims[3] != 1 ||+ dww->dims.size() != 4 || size_t(dww->dims[0]) != c || dww->dims[1] != 1 || dww->dims[2] != 3 || dww->dims[3] != 3 ||+ pw.intOr("group", 1) != 1 || dw.intOr("group", 1) != int64_t(c)) {+ error = "head convolution shapes"; return false;+ }+ }+ for (int s = 0; s < 3; ++s) for (int t = 1; t < 4; ++t)+ if (heads[t][s].feature != heads[0][s].feature) { error = "head branches use different features"; return false; }++ // 2. Backbone and neck: everything that is not part of a head.+ inputTensor = newTensor(model.inputs[0].name, 1, 0, true);+ std::unordered_map<std::string, int> tensorOf;+ tensorOf[model.inputs[0].name] = inputTensor;+ std::unordered_map<std::string, std::string> upsampled; // Resize output -> its input+ for (size_t i = 0; i < model.nodes.size(); ++i) {+ if (headNode[i]) continue;+ const OnnxNode& node = model.nodes[i];+ LayerDesc layer;+ layer.name = node.name.empty() ? node.outputs[0] : node.name;+ if (node.op == "Conv") {+ const OnnxTensor *w, *b;+ if (!convTensors(node, w, b) || w->dims.size() != 4) { error = "convolution weights in " + layer.name; return false; }+ const auto in = tensorOf.find(node.inputs[0]);+ if (in == tensorOf.end()) { error = "convolution input is not available: " + node.inputs[0]; return false; }+ const TensorDesc inDesc = tensors[size_t(in->second)];+ const int64_t group = node.intOr("group", 1), stride = node.intOr("strides", 1);+ const int64_t cout = w->dims[0], cinPerGroup = w->dims[1], kh = w->dims[2], kw = w->dims[3];+ uint32_t outShift = inDesc.shift;+ if (kh == 3 && kw == 3 && group == 1 && stride == 2 && cinPerGroup == 3 && inDesc.quads == 1) {+ layer.kind = Kind::Stem; outShift += 1;+ if (!packStem(*w, *b, layer, error)) return false;+ } else if (kh == 1 && kw == 1 && group == 1 && stride == 1 && size_t(cinPerGroup) == size_t(inDesc.quads) * 4) {+ layer.kind = Kind::Pointwise;+ if (!packPointwise(w->floats, b->floats, size_t(cout), size_t(cinPerGroup), layer, error)) return false;+ } else if (kh == 3 && kw == 3 && group == cout && cinPerGroup == 1 && stride == 1 && size_t(cout) == size_t(inDesc.quads) * 4) {+ layer.kind = Kind::Depthwise;+ if (!packDepthwise(w->floats, b->floats, size_t(cout), layer, error)) return false;+ } else { error = "unsupported convolution configuration in " + layer.name; return false; }+ std::string outName = node.outputs[0];+ if (i + 1 < model.nodes.size() && !headNode[i + 1] && model.nodes[i + 1].op == "Relu" &&+ model.nodes[i + 1].inputs[0] == node.outputs[0] && consumers[node.outputs[0]] == 1) {+ layer.relu = true;+ outName = model.nodes[i + 1].outputs[0];+ ++i;+ }+ layer.in0 = in->second;+ layer.out = newTensor(outName, uint32_t(cout / 4), outShift);+ tensorOf[outName] = layer.out;+ } else if (node.op == "MaxPool") {+ const auto in = tensorOf.find(node.inputs[0]);+ const auto& k = node.ints.find("kernel_shape");+ if (in == tensorOf.end() || k == node.ints.end() || k->second != std::vector<int64_t>{2, 2} || node.intOr("strides", 0) != 2) { error = "unsupported pooling in " + layer.name; return false; }+ layer.kind = Kind::Pool;+ layer.in0 = in->second;+ layer.out = newTensor(node.outputs[0], tensors[size_t(in->second)].quads, tensors[size_t(in->second)].shift + 1);+ tensorOf[node.outputs[0]] = layer.out;+ } else if (node.op == "Resize") {+ const OnnxTensor* scales = node.inputs.size() > 2 ? init(node.inputs[2]) : nullptr;+ const auto mode = node.strings.find("mode");+ if (!scales || scales->floats != std::vector<float>{1, 1, 2, 2} || mode == node.strings.end() || mode->second != "nearest") {+ error = "unsupported resize in " + layer.name; return false;+ }+ upsampled[node.outputs[0]] = node.inputs[0];+ continue; // fused into the Add that consumes it+ } else if (node.op == "Add") {+ std::string coarseName, skipName;+ if (upsampled.count(node.inputs[1])) { coarseName = upsampled[node.inputs[1]]; skipName = node.inputs[0]; }+ else if (upsampled.count(node.inputs[0])) { coarseName = upsampled[node.inputs[0]]; skipName = node.inputs[1]; }+ else { error = "unsupported add in " + layer.name; return false; }+ const auto coarse = tensorOf.find(coarseName), skip = tensorOf.find(skipName);+ if (coarse == tensorOf.end() || skip == tensorOf.end()) { error = "add inputs are not available in " + layer.name; return false; }+ const TensorDesc& c = tensors[size_t(coarse->second)];+ const TensorDesc& s = tensors[size_t(skip->second)];+ if (c.quads != s.quads || c.shift != s.shift + 1) { error = "add operand shapes differ in " + layer.name; return false; }+ layer.kind = Kind::UpAdd;+ layer.in0 = coarse->second; layer.in1 = skip->second;+ layer.out = newTensor(node.outputs[0], s.quads, s.shift);+ tensorOf[node.outputs[0]] = layer.out;+ } else { error = "unexpected operator " + node.op + " outside the heads"; return false; }+ layers.push_back(std::move(layer));+ }++ // 3. Heads: the four branches of a stride share their input, so their 1x1+ // convolutions and depthwise 3x3 convolutions are concatenated channel-wise+ // (cls, obj, box x4, landmarks x10) into one 16-channel pair per stride.+ for (int s = 0; s < 3; ++s) {+ const auto feature = tensorOf.find(heads[0][s].feature);+ if (feature == tensorOf.end() || tensors[size_t(feature->second)].shift != 3 + uint32_t(s) || tensors[size_t(feature->second)].quads != 16) {+ error = std::format("head feature for stride {} has an unexpected shape", kStrides[s]); return false;+ }+ std::vector<float> pw, pwBias, dw, dwBias;+ for (int t : {0, 1, 2, 3}) {+ const OnnxTensor *w, *b;+ (void)convTensors(model.nodes[size_t(heads[t][s].pw)], w, b);+ pw.insert(pw.end(), w->floats.begin(), w->floats.end());+ pwBias.insert(pwBias.end(), b->floats.begin(), b->floats.end());+ (void)convTensors(model.nodes[size_t(heads[t][s].dw)], w, b);+ dw.insert(dw.end(), w->floats.begin(), w->floats.end());+ dwBias.insert(dwBias.end(), b->floats.begin(), b->floats.end());+ }+ LayerDesc first, second;+ first.kind = Kind::Pointwise; first.name = std::format("head{}-pw", kStrides[s]);+ second.kind = Kind::Depthwise; second.name = std::format("head{}-dw", kStrides[s]);+ if (!packPointwise(pw, pwBias, 16, 64, first, error) || !packDepthwise(dw, dwBias, 16, second, error)) return false;+ first.in0 = feature->second;+ first.out = newTensor(std::format("head{}-pre", kStrides[s]), 4, 3 + uint32_t(s));+ second.in0 = first.out;+ second.out = newTensor(std::format("head{}", kStrides[s]), 4, 3 + uint32_t(s), true);+ headTensor[s] = second.out;+ layers.push_back(std::move(first));+ layers.push_back(std::move(second));+ }+ for (int s = 0; s < 3; ++s) {+ LayerDesc decode;+ decode.kind = Kind::Decode; decode.scale = s; decode.in0 = headTensor[s];+ decode.name = std::format("decode{}", kStrides[s]);+ layers.push_back(std::move(decode));+ }++ // The prep layer is layer 0 conceptually: it writes the input tensor.+ LayerDesc prep;+ prep.kind = Kind::Prep; prep.out = inputTensor; prep.name = "prep";+ layers.insert(layers.begin(), std::move(prep));++ // Liveness (first write / last read) for buffer sharing.+ for (size_t i = 0; i < layers.size(); ++i) {+ const LayerDesc& l = layers[i];+ for (const int t : {l.in0, l.in1}) if (t >= 0) tensors[size_t(t)].lastRead = std::max(tensors[size_t(t)].lastRead, int(i));+ if (l.out >= 0 && tensors[size_t(l.out)].firstWrite < 0) tensors[size_t(l.out)].firstWrite = int(i);+ }+ description = std::format("YuNet-compatible CNN: opset {}, {} nodes, {} GPU layers, {} weights, input {} (producer {})",+ model.opset, model.nodes.size(), layers.size(), weights.size(), model.inputs[0].name, model.producer);+ return true;+ }++ // ------------------------------------------------------------- resources+ uint64_t tensorBytes(const TensorDesc& t) const+ {+ const uint64_t w = std::max<uint64_t>(1, cfg.maxWidth >> t.shift), h = std::max<uint64_t>(1, cfg.maxHeight >> t.shift);+ return w * h * t.quads * 16;+ }++ bool createBuffers(std::string& error)+ {+ // Greedy buffer sharing: a tensor may reuse a buffer once every earlier+ // tensor that lives in it has been read for the last time.+ std::vector<int> owner; // per buffer: tensor currently held, -1 when free+ for (size_t i = 0; i < layers.size(); ++i) {+ for (size_t b = 0; b < owner.size(); ++b)+ if (owner[b] >= 0 && !tensors[size_t(owner[b])].pinned && tensors[size_t(owner[b])].lastRead < int(i)) owner[b] = -1;+ const int out = layers[i].out;+ if (out < 0 || tensors[size_t(out)].buffer >= 0) continue;+ TensorDesc& t = tensors[size_t(out)];+ const uint64_t need = tensorBytes(t);+ int pick = -1;+ if (!t.pinned) for (size_t b = 0; b < owner.size(); ++b)+ if (owner[b] < 0 && bufferBytes[b] >= need && (pick < 0 || bufferBytes[b] < bufferBytes[size_t(pick)])) pick = int(b);+ if (pick < 0) {+ auto buffer = createBuffer(device, need, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ if (!buffer) { error = std::format("tensor buffer allocation failed ({} bytes)", need); return false; }+ buffers.push_back(buffer); bufferBytes.push_back(need); owner.push_back(-1);+ workingSet += need;+ pick = int(buffers.size()) - 1;+ }+ t.buffer = pick;+ owner[size_t(pick)] = out;+ }+ // Weights: upload once, then readable as a structured SRV.+ const uint64_t bytes = uint64_t(weights.size()) * 4;+ weightBuffer = createBuffer(device, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST);+ auto upload = createBuffer(device, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ);+ if (!weightBuffer || !upload) { error = "weight buffer allocation failed"; return false; }+ void* mapped = nullptr;+ if (FAILED(upload->Map(0, nullptr, &mapped))) { error = "weight upload map failed"; return false; }+ std::memcpy(mapped, weights.data(), size_t(bytes));+ upload->Unmap(0, nullptr);+ // One-shot copy on a private queue so initialize() stays self-contained.+ ComPtr<ID3D12CommandQueue> queue;+ D3D12_COMMAND_QUEUE_DESC qd{};+ qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;+ ComPtr<ID3D12CommandAllocator> allocator;+ ComPtr<ID3D12GraphicsCommandList> list;+ ComPtr<ID3D12Fence> fence;+ if (FAILED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue))) ||+ FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) ||+ FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) ||+ FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) { error = "weight upload queue creation failed"; return false; }+ list->CopyBufferRegion(weightBuffer.Get(), 0, upload.Get(), 0, bytes);+ D3D12_RESOURCE_BARRIER barrier{};+ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ barrier.Transition.pResource = weightBuffer.Get();+ barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;+ barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;+ barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;+ list->ResourceBarrier(1, &barrier);+ list->Close();+ ID3D12CommandList* lists[] = {list.Get()};+ queue->ExecuteCommandLists(1, lists);+ HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);+ queue->Signal(fence.Get(), 1);+ fence->SetEventOnCompletion(1, event);+ WaitForSingleObject(event, 10000);+ CloseHandle(event);+ if (fence->GetCompletedValue() < 1) { error = "weight upload timed out"; return false; }++ candidateBytes = 16 + uint64_t(cfg.candidateCapacity) * 64;+ zeroUpload = createBuffer(device, 16, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ);+ if (!zeroUpload) { error = "zero buffer allocation failed"; return false; }+ void* zero = nullptr;+ if (SUCCEEDED(zeroUpload->Map(0, nullptr, &zero))) { std::memset(zero, 0, 16); zeroUpload->Unmap(0, nullptr); }+ for (uint32_t s = 0; s < cfg.ringSlots; ++s) {+ candidates.push_back(createBuffer(device, candidateBytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS));+ readbacks.push_back(createBuffer(device, candidateBytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST));+ if (!candidates.back() || !readbacks.back()) { error = "candidate buffer allocation failed"; return false; }+ }+ return true;+ }++ bool createPipelines(std::string& error)+ {+ D3D12_DESCRIPTOR_RANGE1 srv{};+ srv.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;+ srv.NumDescriptors = kSrvPerSlot;+ srv.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE;+ D3D12_DESCRIPTOR_RANGE1 uav{};+ uav.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;+ uav.NumDescriptors = kUavPerLayer;+ uav.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE;+ D3D12_ROOT_PARAMETER1 rp[3]{};+ rp[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;+ rp[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;+ rp[0].Constants.Num32BitValues = kConstantDwords;+ rp[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;+ rp[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;+ rp[1].DescriptorTable.NumDescriptorRanges = 1;+ rp[1].DescriptorTable.pDescriptorRanges = &srv;+ rp[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;+ rp[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;+ rp[2].DescriptorTable.NumDescriptorRanges = 1;+ rp[2].DescriptorTable.pDescriptorRanges = &uav;+ D3D12_VERSIONED_ROOT_SIGNATURE_DESC rd{};+ rd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;+ rd.Desc_1_1.NumParameters = 3;+ rd.Desc_1_1.pParameters = rp;+ ComPtr<ID3DBlob> blob, message;+ if (FAILED(D3D12SerializeVersionedRootSignature(&rd, &blob, &message)) ||+ FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&rootSignature)))) {+ error = "root signature creation failed"; return false;+ }+ for (size_t k = 0; k < size_t(Kind::Count); ++k) {+ std::vector<uint8_t> code;+ if (!loadDxil(kShaderFile[k], code)) { error = std::string("shader missing: ") + kShaderFile[k]; return false; }+ D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};+ pd.pRootSignature = rootSignature.Get();+ pd.CS = {code.data(), code.size()};+ const HRESULT hr = device->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pipelines[k]));+ if (FAILED(hr)) { error = std::format("pipeline {} failed hr=0x{:08X}", kKindName[k], unsigned(hr)); return false; }+ }+ return true;+ }++ void structuredUav(ID3D12Resource* resource, uint64_t bytes, D3D12_CPU_DESCRIPTOR_HANDLE at) const+ {+ D3D12_UNORDERED_ACCESS_VIEW_DESC d{};+ d.Format = DXGI_FORMAT_UNKNOWN;+ d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;+ d.Buffer.NumElements = UINT(bytes / 16);+ d.Buffer.StructureByteStride = 16;+ device->CreateUnorderedAccessView(resource, nullptr, &d, at);+ }++ bool createDescriptors(std::string& error)+ {+ uint32_t decodeLayers = 0;+ for (const auto& l : layers) decodeLayers += l.kind == Kind::Decode;+ uavBase = kSrvPerSlot * cfg.ringSlots;+ const uint32_t total = uavBase + kUavPerLayer * (uint32_t(layers.size()) - decodeLayers + decodeLayers * cfg.ringSlots);+ D3D12_DESCRIPTOR_HEAP_DESC hd{};+ hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;+ hd.NumDescriptors = total;+ hd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;+ D3D12_DESCRIPTOR_HEAP_DESC sd = hd;+ sd.NumDescriptors = cfg.ringSlots;+ sd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;+ if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap))) || FAILED(device->CreateDescriptorHeap(&sd, IID_PPV_ARGS(&stagingHeap)))) {+ error = "descriptor heap creation failed"; return false;+ }+ increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);+ const auto cpuAt = [&](uint32_t index) { auto h = heap->GetCPUDescriptorHandleForHeapStart(); h.ptr += SIZE_T(index) * increment; return h; };+ // t0 weights in every slot pair; t1 (source frame) is written per detection.+ D3D12_SHADER_RESOURCE_VIEW_DESC wd{};+ wd.Format = DXGI_FORMAT_UNKNOWN;+ wd.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;+ wd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;+ wd.Buffer.NumElements = UINT(weights.size() / 4);+ wd.Buffer.StructureByteStride = 16;+ for (uint32_t s = 0; s < cfg.ringSlots; ++s) {+ device->CreateShaderResourceView(weightBuffer.Get(), &wd, cpuAt(s * kSrvPerSlot));+ // Slot t1 starts as a null texture view so the pair is always valid.+ D3D12_SHADER_RESOURCE_VIEW_DESC nd{};+ nd.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;+ nd.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;+ nd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;+ nd.Texture2D.MipLevels = 1;+ device->CreateShaderResourceView(nullptr, &nd, cpuAt(s * kSrvPerSlot + 1));+ }+ layerUav.assign(layers.size(), 0);+ uint32_t next = uavBase;+ for (size_t i = 0; i < layers.size(); ++i) {+ const LayerDesc& l = layers[i];+ layerUav[i] = next;+ const auto bufferOf = [&](int t) { return t < 0 ? nullptr : buffers[size_t(tensors[size_t(t)].buffer)].Get(); };+ const auto bytesOf = [&](int t) { return bufferBytes[size_t(tensors[size_t(t)].buffer)]; };+ if (l.kind == Kind::Decode) {+ for (uint32_t s = 0; s < cfg.ringSlots; ++s) {+ structuredUav(bufferOf(l.in0), bytesOf(l.in0), cpuAt(next));+ structuredUav(bufferOf(l.in0), bytesOf(l.in0), cpuAt(next + 1));+ D3D12_UNORDERED_ACCESS_VIEW_DESC raw{};+ raw.Format = DXGI_FORMAT_R32_TYPELESS;+ raw.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;+ raw.Buffer.NumElements = UINT(candidateBytes / 4);+ raw.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;+ device->CreateUnorderedAccessView(candidates[s].Get(), nullptr, &raw, cpuAt(next + 2));+ next += kUavPerLayer;+ }+ continue;+ }+ const int in0 = l.in0 >= 0 ? l.in0 : l.out;+ const int in1 = l.in1 >= 0 ? l.in1 : in0;+ structuredUav(bufferOf(in0), bytesOf(in0), cpuAt(next));+ structuredUav(bufferOf(in1), bytesOf(in1), cpuAt(next + 1));+ structuredUav(bufferOf(l.out), bytesOf(l.out), cpuAt(next + 2));+ next += kUavPerLayer;+ }+ return true;+ }++ // ----------------------------------------------------------------- record+ D3D12_GPU_DESCRIPTOR_HANDLE gpuAt(uint32_t index) const+ {+ auto h = heap->GetGPUDescriptorHandleForHeapStart();+ h.ptr += UINT64(index) * increment;+ return h;+ }++ void uavBarrier(ID3D12GraphicsCommandList* list) const+ {+ D3D12_RESOURCE_BARRIER b{};+ b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;+ list->ResourceBarrier(1, &b);+ }++ void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* r, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) const+ {+ D3D12_RESOURCE_BARRIER b{};+ b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;+ b.Transition.pResource = r;+ b.Transition.StateBefore = from;+ b.Transition.StateAfter = to;+ b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;+ list->ResourceBarrier(1, &b);+ }++ bool recordLayers(ID3D12GraphicsCommandList* list, uint32_t slot, const Source* source, uint32_t detWidth, uint32_t detHeight)+ {+ const uint32_t padW = (detWidth + 31) / 32 * 32, padH = (detHeight + 31) / 32 * 32;+ if (!ready || slot >= cfg.ringSlots || detWidth < 32 || detHeight < 32 || padW > cfg.maxWidth || padH > cfg.maxHeight) return false;+ if (source && (!source->texture || !source->width || !source->height)) return false;++ ID3D12DescriptorHeap* heaps[] = {heap.Get()};+ list->SetDescriptorHeaps(1, heaps);+ list->SetComputeRootSignature(rootSignature.Get());+ if (source) {+ D3D12_SHADER_RESOURCE_VIEW_DESC sd{};+ sd.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;+ sd.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;+ sd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;+ sd.Texture2D.MipLevels = 1;+ auto staging = stagingHeap->GetCPUDescriptorHandleForHeapStart();+ staging.ptr += SIZE_T(slot) * increment;+ device->CreateShaderResourceView(source->texture, &sd, staging);+ auto visible = heap->GetCPUDescriptorHandleForHeapStart();+ visible.ptr += SIZE_T(slot * kSrvPerSlot + 1) * increment;+ device->CopyDescriptorsSimple(1, visible, staging, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);+ }+ // Empty the candidate list of this slot.+ transition(list, candidates[slot].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST);+ list->CopyBufferRegion(candidates[slot].Get(), 0, zeroUpload.Get(), 0, 16);+ transition(list, candidates[slot].Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ uavBarrier(list);++ if (profileHeap) list->EndQuery(profileHeap, D3D12_QUERY_TYPE_TIMESTAMP, profileBase);+ for (size_t i = source ? 0 : 1; i < layers.size(); ++i) {+ const LayerDesc& l = layers[i];+ uint32_t c[kConstantDwords] = {};+ const auto dims = [&](int t, uint32_t& w, uint32_t& h, uint32_t& q) {+ const TensorDesc& d = tensors[size_t(t)];+ w = std::max(1u, padW >> d.shift); h = std::max(1u, padH >> d.shift); q = d.quads;+ };+ if (l.in0 >= 0) dims(l.in0, c[0], c[1], c[2]);+ if (l.out >= 0) dims(l.out, c[3], c[4], c[5]);+ c[6] = l.wOff; c[7] = l.bOff; c[8] = l.relu ? 1u : 0u;+ uint32_t groupsOf = 0;+ switch (l.kind) {+ case Kind::Prep: {+ uint32_t rw = source->regionWidth ? source->regionWidth : source->width, rh = source->regionHeight ? source->regionHeight : source->height;+ rw = std::min(rw, source->width - std::min(source->originX, source->width - 1));+ rh = std::min(rh, source->height - std::min(source->originY, source->height - 1));+ const float scale = std::max(float(rw) / float(detWidth), float(rh) / float(detHeight));+ const uint32_t taps = std::clamp(uint32_t(std::ceil(scale)), 1u, kMaxTaps);+ c[3] = padW; c[4] = padH;+ c[9] = rw; c[10] = rh; c[11] = detWidth; c[12] = detHeight; c[13] = source->hdr ? 1u : 0u; c[14] = taps;+ c[15] = (source->originX & 0xffffu) | (source->originY << 16);+ groupsOf = padW * padH;+ break;+ }+ case Kind::Stem: case Kind::Pointwise: case Kind::Depthwise: case Kind::Pool: case Kind::UpAdd:+ groupsOf = c[3] * c[4] * c[5];+ break;+ case Kind::Decode:+ c[3] = padW >> (3 + l.scale); c[4] = padH >> (3 + l.scale);+ c[9] = 8u << l.scale; c[10] = cfg.candidateCapacity; c[11] = bits(cfg.scoreThreshold); c[12] = uint32_t(l.scale);+ groupsOf = c[3] * c[4];+ break;+ default: return false;+ }+ list->SetPipelineState(pipelines[size_t(l.kind)].Get());+ list->SetComputeRoot32BitConstants(0, kConstantDwords, c, 0);+ list->SetComputeRootDescriptorTable(1, gpuAt(slot * kSrvPerSlot));+ list->SetComputeRootDescriptorTable(2, gpuAt(layerUav[i] + (l.kind == Kind::Decode ? slot * kUavPerLayer : 0)));+ list->Dispatch((groupsOf + 63) / 64, 1, 1);+ uavBarrier(list);+ if (profileHeap) list->EndQuery(profileHeap, D3D12_QUERY_TYPE_TIMESTAMP, profileBase + 1 + uint32_t(i));+ }+ transition(list, candidates[slot].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);+ list->CopyBufferRegion(readbacks[slot].Get(), 0, candidates[slot].Get(), 0, candidateBytes);+ transition(list, candidates[slot].Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);+ return true;+ }++ uint64_t macs(uint32_t detWidth, uint32_t detHeight) const+ {+ const uint32_t padW = (detWidth + 31) / 32 * 32, padH = (detHeight + 31) / 32 * 32;+ uint64_t total = 0;+ for (const auto& l : layers) {+ if (l.out < 0) continue;+ const TensorDesc& o = tensors[size_t(l.out)];+ const uint64_t pixels = uint64_t(std::max(1u, padW >> o.shift)) * std::max(1u, padH >> o.shift);+ const uint64_t cout = uint64_t(o.quads) * 4;+ if (l.kind == Kind::Stem) total += pixels * cout * 27;+ else if (l.kind == Kind::Pointwise) total += pixels * cout * uint64_t(tensors[size_t(l.in0)].quads) * 4;+ else if (l.kind == Kind::Depthwise) total += pixels * cout * 9;+ }+ return total;+ }+};++YuNetGpu::YuNetGpu() : impl_(std::make_unique<Impl>()) {}+YuNetGpu::~YuNetGpu() = default;++bool YuNetGpu::ready() const { return impl_ && impl_->ready; }+const std::string& YuNetGpu::modelDescription() const { return impl_->description; }+uint32_t YuNetGpu::layerCount() const { return uint32_t(impl_->layers.size()); }+const char* YuNetGpu::layerName(uint32_t index) const { return index < impl_->layers.size() ? impl_->layers[index].name.c_str() : ""; }+void YuNetGpu::setProfiler(ID3D12QueryHeap* heap, uint32_t baseIndex) { impl_->profileHeap = heap; impl_->profileBase = baseIndex; }+uint64_t YuNetGpu::weightBytes() const { return uint64_t(impl_->weights.size()) * 4; }+uint64_t YuNetGpu::workingSetBytes() const { return impl_->workingSet; }+uint64_t YuNetGpu::multiplyAccumulates(uint32_t w, uint32_t h) const { return impl_->macs(w, h); }+ID3D12Resource* YuNetGpu::inputBuffer() const+{+ return impl_->ready ? impl_->buffers[size_t(impl_->tensors[size_t(impl_->inputTensor)].buffer)].Get() : nullptr;+}+ID3D12Resource* YuNetGpu::headBuffer(uint32_t scale) const+{+ return impl_->ready && scale < 3 ? impl_->buffers[size_t(impl_->tensors[size_t(impl_->headTensor[scale])].buffer)].Get() : nullptr;+}++bool YuNetGpu::initialize(ID3D12Device* device, const std::filesystem::path& modelPath, const YuNetConfig& config, std::string& error)+{+ shutdown();+ Impl& m = *impl_;+ m.device = device;+ m.cfg = config;+ if (!device || config.maxWidth < 32 || config.maxHeight < 32 || config.maxWidth % 32 || config.maxHeight % 32 || config.ringSlots == 0 || config.candidateCapacity == 0) {+ error = "invalid detector configuration"; return false;+ }+ std::vector<uint8_t> bytes;+ OnnxModel model;+ if (!readFileBytes(modelPath, bytes, error) || !parseOnnx(bytes, model, error)) return false;+ if (!m.buildPlan(model, error) || !m.createBuffers(error) || !m.createPipelines(error) || !m.createDescriptors(error)) {+ const std::string reason = error;+ shutdown();+ error = reason;+ log::error("beauty-detect", "face detector initialisation failed: " + reason);+ return false;+ }+ m.ready = true;+ log::info("beauty-detect", std::format("{}; weights {} KiB; working set {:.1f} MiB at {}x{}", m.description, weightBytes() / 1024,+ double(m.workingSet) / (1024.0 * 1024.0), config.maxWidth, config.maxHeight));+ return true;+}++void YuNetGpu::shutdown()+{+ Impl& m = *impl_;+ const YuNetConfig keep = m.cfg;+ m = Impl{};+ m.cfg = keep;+}++bool YuNetGpu::record(ID3D12GraphicsCommandList* list, uint32_t slot, const Source& source, uint32_t detWidth, uint32_t detHeight)+{+ return impl_->recordLayers(list, slot, &source, detWidth, detHeight);+}++bool YuNetGpu::recordNetwork(ID3D12GraphicsCommandList* list, uint32_t slot, uint32_t detWidth, uint32_t detHeight)+{+ return impl_->recordLayers(list, slot, nullptr, detWidth, detHeight);+}++void YuNetGpu::nonMaxSuppression(std::vector<FaceBox>& boxes, float iouThreshold)+{+ std::sort(boxes.begin(), boxes.end(), [](const FaceBox& a, const FaceBox& b) { return a.score != b.score ? a.score > b.score : a.id < b.id; });+ std::vector<FaceBox> kept;+ for (const FaceBox& b : boxes) {+ bool suppressed = false;+ for (const FaceBox& k : kept) {+ const float x1 = std::max(b.x, k.x), y1 = std::max(b.y, k.y);+ const float x2 = std::min(b.x + b.w, k.x + k.w), y2 = std::min(b.y + b.h, k.y + k.h);+ const float inter = std::max(0.0f, x2 - x1) * std::max(0.0f, y2 - y1);+ const float uni = b.w * b.h + k.w * k.h - inter;+ if (uni > 0 && inter / uni > iouThreshold) { suppressed = true; break; }+ }+ if (!suppressed) kept.push_back(b);+ }+ boxes = std::move(kept);+}++bool YuNetGpu::collect(uint32_t slot, std::vector<FaceBox>& faces, uint32_t* rawCandidates)+{+ Impl& m = *impl_;+ faces.clear();+ if (!m.ready || slot >= m.cfg.ringSlots) return false;+ void* mapped = nullptr;+ D3D12_RANGE range{0, size_t(m.candidateBytes)};+ if (FAILED(m.readbacks[slot]->Map(0, &range, &mapped)) || !mapped) return false;+ const auto* base = static_cast<const uint8_t*>(mapped);+ uint32_t count = 0;+ std::memcpy(&count, base, 4);+ if (rawCandidates) *rawCandidates = count;+ count = std::min(count, m.cfg.candidateCapacity);+ for (uint32_t i = 0; i < count; ++i) {+ float f[16];+ std::memcpy(f, base + 16 + size_t(i) * 64, 64);+ FaceBox b;+ b.x = f[0]; b.y = f[1]; b.w = f[2]; b.h = f[3];+ for (int k = 0; k < 10; ++k) b.landmarks[size_t(k)] = f[4 + k];+ b.score = f[14];+ std::memcpy(&b.id, &f[15], 4);+ if (std::isfinite(b.x + b.y + b.w + b.h + b.score) && b.w > 0 && b.h > 0) faces.push_back(b);+ }+ D3D12_RANGE none{0, 0};+ m.readbacks[slot]->Unmap(0, &none);+ nonMaxSuppression(faces, m.cfg.nmsThreshold);+ return true;+}++} // namespace veyra::beauty