diff --git a/CMakeLists.txt b/CMakeLists.txt index 89e47fb7..5b4f4fad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is the server release that /version reports. The plugin ABI version is separate and is # read from abi/rad_abi.h below. -project(radiance VERSION 1.15.1 LANGUAGES C CXX) +project(radiance VERSION 1.16.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -299,8 +299,9 @@ if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt) endif() # libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP # toolchain. It declares itself for `^gfx11` and returns without a target when the build's -# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it. A card -# with no kernel library of its own refuses device-only ops (docs/PLUGIN.md §10). +# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it, and +# declines every machine without a gfx11 card (rad_plugin_open). A card with no kernel library of +# its own refuses device-only ops (docs/PLUGIN.md §10). if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt) add_subdirectory(libr3d) endif() diff --git a/Dockerfile b/Dockerfile index 8963f833..8f27542c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,10 +28,12 @@ # and refuses a compressed bundle. # # GPU_TARGETS must be named: a build container has no card to detect, unlike a bare-metal -# ./build.sh. They are the targets of the shipped kernel libraries; libr4d serves RDNA4 only and -# drops every architecture outside gfx12. The engine's own kernels carry the generic family -# targets and run on every AMD GPU family, so a kernel library for another card is added by -# mounting it on the search path: +# ./build.sh. They are the targets of the shipped kernel libraries, each of which keeps only its own +# family: libr4d takes gfx1201 (RDNA4), libr3d gfx11-generic (every RDNA3 chip) and gfx1151, and +# libhalo gfx1151 (Strix Halo), where the loader prefers it over libr3d. On any one card the other +# libraries decline or are left out, so the default image serves all three. The engine's own +# kernels carry the generic family targets and run on every AMD GPU family, so a kernel library for +# another card is added by mounting it on the search path: # docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance # # The image's ROCm userspace must be supported by the host's amdgpu kernel driver; it is pinned to @@ -131,7 +133,7 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ # ------------------------------------------------------------------------------------------ build FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build -ARG GPU_TARGETS=gfx1201 +ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151" # Parallel compile jobs; empty means one per core. A device-kernel translation unit takes 2-3 GB # of RAM under hipcc, so lower it on a host that is also serving. ARG JOBS= @@ -227,11 +229,12 @@ ARG TEST_EXCLUDE= # perf_event_open, so the tests that bound work count CPU time rather than instructions # (tests/work_counter.h). The `oot` suite (every shipped plugin rebuilt against the installed # package) repeats this stage's whole compile, so it runs from the development tree instead -# (tests/oot_plugins.sh). +# (tests/oot_plugins.sh). The `parity` entry (halo_parity: libhalo's tables against libr4d's) is +# left out until libhalo has ported the ops libr4d added after it (the test names each one). RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ bash /src/docker/llvm-check.sh /build \ && RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \ - ctest --test-dir /build -LE 'gpu|oot' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \ + ctest --test-dir /build -LE 'gpu|oot|parity' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \ -j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \ && touch /build/host-tests-passed @@ -283,7 +286,7 @@ RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \ # ---------------------------------------------------------------------------------------- runtime FROM scratch AS runtime -ARG GPU_TARGETS=gfx1201 +ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151" ARG VERSION=dev ARG REVISION=unknown diff --git a/NOTICE b/NOTICE index 4fbf1c61..378474a8 100644 --- a/NOTICE +++ b/NOTICE @@ -19,7 +19,10 @@ Written by Deadcode, with contributions from: Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights - through w4a16_asym, and the Ornith-1.5-122B compose files + through w4a16_asym, the Ornith-1.5-122B compose files, the Gemma 4 31B's asymmetric int5 + linears (w5a8i8 and w5a16), the junctions at quant_act_i8g's grid (rmsnorm_quant_i8g, + gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g) with the prefill overlap on the i8a8, a4 and w5 + grids, and the 31B's i8g, heretic-ara-i8g and w5 compose files - mechkbfan: the token embedding in the pinned host pool - Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft coupling with its cooperative verify (--draft-coupling), the W4A8 prefill's tail scale read, the @@ -85,7 +88,8 @@ Written by Deadcode, with contributions from: split by depth, the delta net's out-projection read beside its decode recurrent update, the MXFP4 feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6 - paged prefill, and the preempted-prefill gate past a KV group that holds no blocks + paged prefill, the preempted-prefill gate past a KV group that holds no blocks, and the norms' + lane sum issuing its reads eight at a time - eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8 linears' operands directly @@ -118,7 +122,8 @@ Written by Deadcode, with contributions from: - farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix - gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode - (the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds) + (the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds), + and the head-256 prefill softmax rescaled by row rather than by wave - launch80_assets: tuning collectives as the exchange they serve at the served configuration, the per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch - hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2 @@ -134,7 +139,9 @@ Written by Deadcode, with contributions from: - Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS and its gated three-tile form at 8 waves -- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library +- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library, and its wave-matrix rewrite: the GEMMs + retiled to 16x128 blocks, the grouped MoE GEMMs, the norms and quantisers, and the QSA and MoE + router rows - fl0l0u: every request entry point bounded, gated and sanitised (JSON parses bounded in depth, errors safe on invalid UTF-8, control bytes kept off the log, the dashboard's CSP, cross-origin browsers refused on the loopback-only routes, method-scoped API-key exemptions), prompt ids that diff --git a/README.md b/README.md index f1895a36..2dbeaab9 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,8 @@ APIs, Anthropic's Messages API and llama-server's native one, so their clients a unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)). -The bundled device kernels (`libr4d`) target AMD RDNA4 (`gfx1200`, `gfx1201`). The serve flags +The bundled device kernels target AMD RDNA4 (`libr4d`: `gfx1200`, `gfx1201`), RDNA3 (`libr3d`: +`gfx11xx`) and Strix Halo (`libhalo`: `gfx1151`). The serve flags below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family; another card needs a kernel library for it. A machine with no GPU builds the host backend, whose AVX-512/AVX2 kernels (`libavx`) serve every model here: the small ones (EmbeddingGemma 2, @@ -150,8 +151,8 @@ card works best with Resizable BAR on (Above 4G Decoding and Resizable BAR in th without it the engine keeps kernel arguments in pinned host memory, and every dispatch reads them over the link. The image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels -built for `gfx1201`. Pull it, clone this repository for its compose files, then start a model from -one of them: +built for `gfx1201` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix Halo). Pull it, clone +this repository for its compose files, then start a model from one of them: ```sh docker pull stilldeadcode/radiance diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 7492d326..8a28681c 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -19,7 +19,7 @@ extern "C" { * version is refused at load with both versions printed. Each also exports the layout's fingerprint * (rad_abi_layout.h), so two layouts given one number are refused as well. A new optional export * (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 32u +#define RAD_ABI_VERSION 33u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_abi_layout_rows.h b/abi/rad_abi_layout_rows.h index ae806135..8966469e 100644 --- a/abi/rad_abi_layout_rows.h +++ b/abi/rad_abi_layout_rows.h @@ -26,6 +26,7 @@ ABI_FIELD(RadArchProbe, state_f16_ok) ABI_FIELD(RadArchProbe, tree_pays) ABI_FIELD(RadArchProbe, gen_max_pixels) ABI_FIELD(RadArchProbe, gen_max_refs) +ABI_FIELD(RadArchProbe, gen_shape) ABI_STRUCT(RadArgs) ABI_FIELD(RadArgs, t) ABI_FIELD(RadArgs, n_t) @@ -93,6 +94,7 @@ ABI_FIELD(RadBatch, plugin_words) ABI_FIELD(RadBatch, plugin_cu) ABI_FIELD(RadBatch, plugin_words_h) ABI_FIELD(RadBatch, plugin_cu_h) +ABI_FIELD(RadBatch, sgen_b) ABI_STRUCT(RadBufDecl) ABI_FIELD(RadBufDecl, dtype) ABI_FIELD(RadBufDecl, rank) @@ -699,6 +701,44 @@ ABI_FIELD(RadSampleParams, hist_len) ABI_FIELD(RadSampleParams, mask_row) ABI_FIELD(RadSampleParams, flags) ABI_FIELD(RadSampleParams, dry_rep_limit) +ABI_STRUCT(RadShapeGenBatch) +ABI_FIELD(RadShapeGenBatch, lane) +ABI_FIELD(RadShapeGenBatch, patches) +ABI_FIELD(RadShapeGenBatch, step) +ABI_FIELD(RadShapeGenBatch, n_steps) +ABI_FIELD(RadShapeGenBatch, sigma) +ABI_FIELD(RadShapeGenBatch, sigma_next) +ABI_FIELD(RadShapeGenBatch, cfg) +ABI_FIELD(RadShapeGenBatch, pair) +ABI_FIELD(RadShapeGenBatch, lanes) +ABI_FIELD(RadShapeGenBatch, flags) +ABI_FIELD(RadShapeGenBatch, seed) +ABI_FIELD(RadShapeGenBatch, lat_cu) +ABI_FIELD(RadShapeGenBatch, n_query) +ABI_FIELD(RadShapeGenBatch, query) +ABI_FIELD(RadShapeGenBatch, query_cu) +ABI_STRUCT(RadShapeGenDecl) +ABI_FIELD(RadShapeGenDecl, name) +ABI_FIELD(RadShapeGenDecl, canvas) +ABI_FIELD(RadShapeGenDecl, border_ratio) +ABI_FIELD(RadShapeGenDecl, enc_size) +ABI_FIELD(RadShapeGenDecl, enc_patch) +ABI_FIELD(RadShapeGenDecl, pix_mean) +ABI_FIELD(RadShapeGenDecl, pix_std) +ABI_FIELD(RadShapeGenDecl, latent_rows) +ABI_FIELD(RadShapeGenDecl, latent_channels) +ABI_FIELD(RadShapeGenDecl, step_rows) +ABI_FIELD(RadShapeGenDecl, default_steps) +ABI_FIELD(RadShapeGenDecl, max_steps) +ABI_FIELD(RadShapeGenDecl, default_guidance) +ABI_FIELD(RadShapeGenDecl, bounds) +ABI_FIELD(RadShapeGenDecl, level) +ABI_FIELD(RadShapeGenDecl, default_resolution) +ABI_FIELD(RadShapeGenDecl, min_resolution) +ABI_FIELD(RadShapeGenDecl, max_resolution) +ABI_FIELD(RadShapeGenDecl, max_lanes) +ABI_FIELD(RadShapeGenDecl, max_query) +ABI_FIELD(RadShapeGenDecl, field_out) ABI_STRUCT(RadTensor) ABI_FIELD(RadTensor, data) ABI_FIELD(RadTensor, dtype) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 08ae1c62..f1911886 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -1471,6 +1471,87 @@ typedef struct RadVideoGenDecl { int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d); +/* ================================================================== the shape generator */ +/* A program that makes a 3-D shape from one picture: an image encoder reads the picture, a + * denoiser steps a set of latent rows by flow matching, guided against an unconditioned branch, + * and a decoder turns the latent into an occupancy field that the core samples at points of its + * choosing and meshes. The core drives the passes (RadBatch::gen, RadShapeGenBatch), one request + * a pass: + * + * RAD_GEN_PASS_SCOND the request's picture through the image encoder into the request's + * lane: what the denoiser reads of it at every step, for both branches + * (the picture's and the unconditioned one). + * RAD_GEN_PASS_SSTEP one denoising step of one lane over both branches, `step_rows` rows: + * each branch's conditioning and latent, laid out as the plugin likes, the + * latents two entries of `latent_rows` (the conditioned first) for the + * image generator's sampler ops. The first step draws the lane's noise. + * RAD_GEN_PASS_SLATENT the lane's final latent through the decoder's network, into the lane: + * what every query pass of the request reads. Runs once, after the last + * step. + * RAD_GEN_PASS_SQUERY the field at `n_query` points (RadShapeGenBatch::query, at most + * `max_query`), one f32 a point in `field_out`, which the core reads + * back. + * + * The picture. The core decodes it with its alpha (opaque without one) and prepares it as + * Hunyuan3D-2's ImageProcessorV2 and image encoder do: the alpha's bounding box (its last row and + * column left out, as the reference's slice leaves them) scaled with OpenCV's INTER_AREA to + * (1 - border_ratio) of the longer side of the square that holds the picture, centred on it and + * flattened onto white; that square resized to `canvas` x `canvas` with INTER_CUBIC; then as 0..1 + * values bilinearly resized to `enc_size` x `enc_size` (half-pixel centres, torchvision's), each + * channel normalised by `pix_mean` and `pix_std`, and cut into (enc_size / enc_patch)^2 patches of + * enc_patch x enc_patch pixels, row-major, each patch's values channel-major then row-major (a + * convolution's weight order). An SCOND pass carries those patches. + * + * The sampler: a request's `steps` are sigma grid points, sigma_i = i / (steps - 1) for i in + * [0, steps), numpy's linspace(0, 1) taken to f32; the latent starts as noise at sigma 0 and an + * evaluation at each sigma but the last steps it to the next (the reference evaluates at the + * last too, against itself, a step of zero). The model's timestep is sigma, the guided velocity + * neg + cfg (pos - neg), and the step x + (sigma_next - sigma) v. + * + * The field: the decoder's logit at a point, inside the shape above `level`. The core samples the + * cube [-bounds, bounds]^3 on a grid of `resolution` cells a side ((resolution + 1)^3 points, + * numpy's linspace in f32 along each axis), coarse to fine as FlashVDM's hierarchical decoding + * does: the whole grid at the coarsest level (resolution halved while it stays at least 63), then + * at each finer level only the points near where the coarser one crosses `level` or is within + * 0.95 of it. The surface is marching cubes over the finest grid, a vertex at grid index g placed + * at g 2 bounds / (resolution + 1) - bounds, as the reference places it. + * + * A program declares exactly one of this, the other generators, logits or pooled vectors. */ +enum { RAD_GEN_PASS_SCOND = 15, RAD_GEN_PASS_SSTEP = 16, RAD_GEN_PASS_SLATENT = 17, + RAD_GEN_PASS_SQUERY = 18 }; + +typedef struct RadShapeGenDecl { + const char* name; /* "hunyuan3d-2" -- the served model id and messages */ + + /* The picture (above). */ + int64_t canvas; + double border_ratio; + int64_t enc_size, enc_patch; + double pix_mean[3], pix_std[3]; + + /* The latent: `latent_rows` rows of `latent_channels` a branch; a step's rows, both branches + * with their conditioning. */ + int64_t latent_rows, latent_channels, step_rows; + + /* The sampler (above) and the guidance a request that names none runs at. */ + int64_t default_steps, max_steps; + double default_guidance; + + /* The field (above): the cube's half side, the iso value, and the grid's resolution a request + * that names none is sampled at, with the range a request may name. */ + double bounds; + double level; + int64_t default_resolution, min_resolution, max_resolution; + + /* `max_lanes` requests may hold state at once. `field_out` is a device f32 buffer of at least + * `max_query` elements. */ + int64_t max_lanes; + int64_t max_query; + rad_buf field_out; +} RadShapeGenDecl; + +int rad_declare_shape_generator(RadBuilder* b, const RadShapeGenDecl* d); + /* ================================================================== diagnostics */ /* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */ void rad_note(RadBuilder* b, const char* fmt, ...); @@ -1605,6 +1686,12 @@ typedef struct RadArchProbe { * gen_patches answer for them. */ int64_t gen_max_pixels; int64_t gen_max_refs; + + /* ---- appended in ABI 33 (the shape generator) */ + /* Nonzero for a shape generator, which the engine sizes as it does a video generator from + * `gen_rows` (its largest pass: a step's two branches, or a query pass's points). It keeps no + * KV. */ + int32_t gen_shape; } RadArchProbe; int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 034c3642..3019c8ba 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -325,6 +325,11 @@ typedef struct RadBatch { const int32_t* plugin_cu; /* [n_seq + 1] device */ const int32_t* plugin_words_h; const int32_t* plugin_cu_h; + + /* ---- appended in ABI 33 (the shape generator) */ + /* A shape generator's pass (rad_declare_shape_generator; `gen` is one of its + * RAD_GEN_PASS_S*): its payload. Null on every other step. */ + const struct RadShapeGenBatch* sgen_b; } RadBatch; /* What a generator pass carries beside the step batch's own fields, which keep their meanings: @@ -712,6 +717,44 @@ typedef struct RadVideoGenBatch { enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1 }; +/* What a shape generator's pass carries beside the step batch's own fields (rad_builder.h, + * RadShapeGenDecl, describes the passes). Every pass is one request's, in lane `lane`: + * + * SCOND `n_tok` is the picture's patches, `patches` [n_tok, 3 enc_patch^2] f32. + * SSTEP `n_tok` is step_rows. The two branches' latents are entries 0 (the picture's) and 1 + * (the unconditioned one) of the image generator's sampler ops (`randn_lanes`, + * `lane_gather`, `flow_euler`): `lat_cu` bounds them and the per-entry arrays are + * theirs, entry 0 guided against entry 1 (`pair` {1, -2}) at the request's scale. + * SLATENT `n_tok` is latent_rows; nothing of the pass's own. + * SQUERY `n_tok` is n_query, `query` [n_query, 3] f32: x, y, z a point, and `query_cu` + * {0, n_query}. + * + * `lanes` and `lat_cu` are staged on every pass; the latent's rows are lat_cu[0..1]. Every + * pointer is device memory. */ +typedef struct RadShapeGenBatch { + int32_t lane; + + /* ---- SCOND */ + const float* patches; + + /* ---- SSTEP: the step (from 0) of the request's `n_steps` evaluations, then the two + * entries' sampler operands, [2] each but `seed` [2, 2] (low word first) and `lat_cu` [3]. */ + int32_t step, n_steps; + const float* sigma; + const float* sigma_next; + const float* cfg; + const int32_t* pair; + const int32_t* lanes; + const int32_t* flags; /* RAD_GEN_F_FIRST on entry 0 of the first step */ + const uint32_t* seed; + const int32_t* lat_cu; + + /* ---- SQUERY */ + int64_t n_query; + const float* query; + const int32_t* query_cu; +} RadShapeGenBatch; + /* RadVideoGenBatch::enc_kind: the media an encode pass carries, numbered from 1 within a kind. A * keyframe is 1 for the first frame and 2 for the last. */ enum { diff --git a/arch/hunyuan3d2/CMakeLists.txt b/arch/hunyuan3d2/CMakeLists.txt new file mode 100644 index 00000000..bc41bf6a --- /dev/null +++ b/arch/hunyuan3d2/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/hunyuan3d2 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(hunyuan3d2 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(hunyuan3d2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hunyuan3d2.cpp) diff --git a/arch/hunyuan3d2/hunyuan3d2.cpp b/arch/hunyuan3d2/hunyuan3d2.cpp new file mode 100644 index 00000000..645cf203 --- /dev/null +++ b/arch/hunyuan3d2/hunyuan3d2.cpp @@ -0,0 +1,1231 @@ +/* hunyuan3d2 -- Hunyuan3D-2's shape model (tencent/Hunyuan3D-2, hunyuan3d-dit-v2-0): one picture + * to an untextured 3-D shape. + * + * ============================== THE MODEL ============================== + * + * Three networks in one checkpoint (hy3dgen's Hunyuan3DDiTFlowMatchingPipeline): + * + * Image encoder: DINOv2-giant (40 layers of 1536, 24 heads, SwiGLU feed-forward and layer + * scales) over the prepared picture, 518 x 518 in 14 x 14 patches and the class token, 1370 rows. + * Its last hidden state, after the final LayerNorm, is the conditioning; the unconditioned + * branch's is zeros. + * + * Denoiser: a FLUX-shaped transformer of width 1024 (16 heads of 64) over a set of 3072 latent + * rows of 64 values. The conditioning goes in through `cond_in`, the latent through + * `latent_in`; 16 double-stream blocks keep the two streams' weights apart and attend over both + * together, then 32 single-stream blocks run [conditioning | latent] as one. Each block's + * LayerNorms (no affine) are modulated by shift, scale and gate projected from the timestep + * embedding, and q and k are RMS-normed per head. Nothing is positional: the latent is a set. The + * output layer maps the latent rows to a velocity. + * + * Decoder: the shape VAE's latent network (64 -> 1024, then 16 self-attention blocks with + * per-head LayerNorms on q and k) turns the latent into 3072 rows the geometry decoder reads. + * The geometry decoder embeds a query point (x, sin and cos at 8 octaves, 51 values), projects + * it to 1024, attends once over those rows (one cross-attention block with its MLP), and maps + * the result to the occupancy logit there. + * + * Sampling is flow matching from sigma 0 (noise) to 1 (the shape), Euler steps, guided at 5 + * against the unconditioned branch (abi/rad_builder.h, RadShapeGenDecl). Both branches run in one + * step: rows [txt | latent] for the picture's branch, then [latent | txt] for the unconditioned + * one, so each branch is one run for the attention and the two latents are one run for every + * latent-stream op: + * + * rows [0, C) the picture's conditioning (C = 1370) + * rows [C, C + L) the picture's latent (L = 3072) + * rows [C + L, C + 2L) the unconditioned latent + * rows [C + 2L, 2C + 2L) the unconditioned conditioning + * + * ============================== PRECISION ============================== + * + * The reference runs in fp16; here every weight and activation is bf16, rounded where the + * reference stores a tensor, except the picture's patches and the query points' embedding, which + * stay f32 into their projections, and the timestep, which the embedding reads in f32. + * + * One card: the model is 2.2B parameters (4.4 GB in bf16), and every pass is one request's. + */ +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace hunyuan3d2 { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* DINOv2's picture: 518 x 518 in 14 x 14 patches, and its normalisation. */ +enum { kEncSize = 518, kPatch = 14, kGrid = kEncSize / kPatch, kNPatch = kGrid * kGrid, + kCond = kNPatch + 1, kPatchDim = 3 * kPatch * kPatch }; +static const double kMean[3] = { 0.485, 0.456, 0.406 }; +static const double kStd[3] = { 0.229, 0.224, 0.225 }; +/* ImageProcessorV2's canvas and border. */ +enum { kCanvas = 512 }; +/* Requests in flight; a pass is one request's. */ +enum { kLanes = 2 }; +/* The query points a pass carries. */ +enum { kMaxQuery = 32768 }; +/* The query embedding: x, then sin and cos at kFreqs octaves (1, 2, 4, ..., without pi). */ +enum { kFreqs = 8 }; +/* The grid: the reference's default bounds, and the resolutions served (Hunyuan3D-2's own app + * offers 16..512, 256 by default). */ +static const double kBounds = 1.01; +enum { kResDef = 256, kResMin = 16, kResMax = 512 }; + +enum : int { + kGrpDino = 1000, /* the encoder's layers kGrpDino + 1.. */ + kGrpDit = 2000, /* the double blocks kGrpDit + 1.., the single blocks kGrpSingle + 1.. */ + kGrpSingle = 2100, + kGrpVae = 3000, +}; + +/* ================================================================== the model */ +/* A bf16 linear: weight, bias, and its op. */ +struct Lin { + rad_weight w = 0, b = 0; + rad_op op = 0; +}; + +struct DinoLayer { + rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0, ls1 = 0, ls2 = 0; + Lin qkv, o, up, down; + rad_op op_n1 = 0, op_attn = 0, op_ls1 = 0, op_add1 = 0, op_n2 = 0, op_gu = 0, op_ls2 = 0, + op_add2 = 0; +}; + +/* One stream of a double block. */ +struct Stream { + rad_weight qn = 0, kn = 0; + Lin mod, qkv, proj, mlp1, mlp2; + rad_op op_n1 = 0, op_qk = 0, op_n2 = 0; +}; + +struct Double { + Stream s[2]; /* kImg, kTxt */ + rad_op op_attn = 0; +}; +enum { kImg = 0, kTxt = 1 }; + +struct Single { + rad_weight qn = 0, kn = 0; + Lin mod, l1, l2; + rad_op op_n = 0, op_qk = 0, op_attn = 0, op_act = 0; +}; + +struct VaeLayer { + rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0, qnw = 0, qnb = 0, knw = 0, knb = 0; + Lin q, k, v, proj, fc, out; + rad_op op_n1 = 0, op_qn = 0, op_kn = 0, op_attn = 0, op_n2 = 0; +}; + +struct Model { + Names nm{""}; + /* Parameter strings longer than Names keeps (its names are at most 255 characters). */ + std::deque strs; + /* Dimensions, from config.yaml (the importer's metadata). */ + int64_t D = 1024, H = 16, hd = 64, ff = 4096, C = 64, L = 3072; + int64_t E = 1536, EH = 24, Eff = 4096; + int64_t n_double = 16, n_single = 32, n_vae = 16, n_dino = 40; + double scale_factor = 1.0; + int64_t rows = 0; /* a step's: 2 (kCond + L) */ + int64_t lanes = kLanes; + + /* ---- the image encoder */ + rad_weight w_patch = 0, b_patchw = 0, w_cls = 0, w_pos = 0, w_lnw = 0, w_lnb = 0; + rad_op op_ids = 0, op_pos = 0, op_cls = 0, op_cls_add = 0, op_patch = 0, op_dcu = 0, + op_dln = 0; + std::vector dino; + rad_buf b_ids = 0, b_pos = 0, b_cls = 0, b_dx = 0, b_dh = 0, b_dqkv = 0, b_datt = 0, + b_do = 0, b_dgu = 0, b_dact = 0, b_dcu = 0, b_dout = 0; + /* ---- cond_in, both branches, into the lane's store */ + Lin cond_in; + rad_op op_zero = 0; + rad_buf b_zero = 0, b_cstore = 0; + + /* ---- the denoiser */ + Lin latent_in, t_in1, t_out, fin_mod, fin; + rad_op op_randn = 0, op_lgather = 0, op_ccopy = 0, op_temb = 0, op_tsilu = 0, op_vsilu = 0, + op_cu_txt = 0, op_cu_img = 0, op_cu_all = 0, op_cu_ent = 0, op_gate_img = 0, + op_gate_txt = 0, op_fin_n = 0, op_euler = 0; + std::vector dbl; + std::vector sgl; + rad_buf b_lat = 0, b_lx = 0, b_temb = 0, b_t1 = 0, b_t1s = 0, b_vec = 0, b_svec = 0, + b_mods = 0, b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_o = 0, b_ff = 0, b_f = 0, + b_l1 = 0, b_cat = 0, b_v = 0, b_cu_txt = 0, b_cu_img = 0, b_cu_all = 0, b_cu_ent = 0; + int64_t mods_w = 0; + std::vector mod_dbl[2], mod_sgl; /* each block's columns in b_mods */ + int64_t mod_fin = 0; + + /* ---- the decoder's latent network, then the geometry decoder's keys and values */ + Lin post_kl; + rad_op op_unscale = 0, op_vcu = 0; + std::vector vae; + rad_weight g_n2w = 0, g_n2b = 0, g_knw = 0, g_knb = 0; + Lin g_k, g_v; + rad_op op_gn2 = 0, op_gkn = 0; + rad_buf b_vl = 0, b_vx = 0, b_vh = 0, b_vq = 0, b_vk = 0, b_vv = 0, b_vqn = 0, b_vkn = 0, + b_vatt = 0, b_vff = 0, b_vcu = 0, b_gk = 0, b_gv = 0; + + /* ---- the geometry decoder at the query points */ + rad_weight q_n1w = 0, q_n1b = 0, q_n3w = 0, q_n3b = 0, q_qnw = 0, q_qnb = 0, q_pw = 0, + q_pb = 0; + Lin q_proj, q_q, q_o, q_fc, q_out, q_head; + rad_op op_four = 0, op_qn1 = 0, op_qqn = 0, op_qattn = 0, op_qn3 = 0, op_qpost = 0, + op_qcast = 0; + rad_buf b_feat = 0, b_qx = 0, b_qh = 0, b_qq = 0, b_qqn = 0, b_qatt = 0, b_qff = 0, + b_qlogit = 0, b_field = 0; +}; + +static Model g_model; + +/* ================================================================== declare helpers */ +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A biased linear [N, K] (bias absent with `bias` false), read whole, over at most `rows` rows, + * its activation and residual in the epilogue. The weight is mapped by the caller (`mapped`) or + * copied from `src`.weight. `adt` is the activation's dtype ("bf16", or "f32" with an f32 + * weight). */ +static int linear(RadBuilder* b, Names& nm, Lin& l, const char* dn, const char* src, int64_t N, + int64_t K, int64_t rows, rad_buf in, rad_buf out, int access, int group, + bool bias = true, const char* act = "none", rad_buf res = 0, bool mapped = false, + const char* adt = "bf16") { + const uint32_t wdt = std::strcmp(adt, "f32") == 0 ? RAD_F32 : RAD_BF16; + const char* wn = nm.f("%s.weight", dn); + if (!mapped && map_copy(b, wn, nm.ckpt("%s.weight", src)) < 0) return RAD_E_INVAL; + l.w = decl_w(b, wn, wdt, { N, K }, access, RAD_SHARD_NONE, grp_layer(group)); + if (!l.w) return RAD_E_INVAL; + if (bias) { + l.b = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), wdt, { N }, access, group); + if (!l.b) return RAD_E_INVAL; + l.op = RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", adt), RAD_STR("act", act)), + RAD_WEIGHTS(l.w, l.b)); + } else { + l.op = RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", adt)), + RAD_WEIGHTS(l.w)); + } + if (!l.op) return RAD_E_INVAL; + /* An input read from the batch (`in` 0) has no buffer to name. */ + const rad_buf reads[2] = { in, res }; + for (rad_buf r : reads) + if (r) rad_op_reads(b, l.op, &r, 1); + rad_op_writes(b, l.op, &out, 1); + return RAD_OK; +} + +/* Issue a linear over `n` rows: `in` -> `out`, the residual `res` added (RAD_NONE for none). */ +static void lin_issue(RadCtx* c, const Lin& l, int64_t n, RadOperand in, RadOperand out, + RadOperand res = RAD_NONE) { + if (l.b) RAD_ISSUE_N(c, l.op, n, in, RAD_W(l.w), RAD_W(l.b), res, out); + else RAD_ISSUE_N(c, l.op, n, in, RAD_W(l.w), out); +} + +/* A cu_seqlens of `n` + 1 entries, every run `step` rows: iota's constant runs. */ +static rad_op cu_op(RadBuilder* b, int64_t n, int64_t step, rad_buf y) { + return rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, n + 1), RAD_INT("start", 0), + RAD_INT("step", step)), + RAD_NOWEIGHTS), + {}, { y }); +} + +static rad_op attn_op(RadBuilder* b, const char* kind, int64_t rows, int64_t hd, rad_buf q, + rad_buf cu, rad_buf out) { + return rw(b, RAD_OP(b, kind, + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { q, cu }, { out }); +} + +/* norm(x) (1 + scale) + shift, a LayerNorm with no affine, after the gated branch before it. */ +static rad_op mod_norm(RadBuilder* b, int64_t rows, int64_t n, bool gated, rad_buf x, rad_buf y, + rad_buf mods, rad_buf cu, rad_buf z) { + rad_op op = RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", 1e-6), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS); + if (!op) return op; + if (gated) rw(b, op, { x, y, mods, cu }, { x, z }); + else rw(b, op, { x, mods, cu }, { z }); + return op; +} + +/* `n` copies of `v` as chan_affine's list, f32 digits (the op keeps the list in f32 at round 0). */ +static const char* list_of(Model& m, int64_t n, double v) { + std::string s; + char one[40]; + std::snprintf(one, sizeof one, "%.9g", v); + for (int64_t i = 0; i < n; ++i) { if (i) s += ' '; s += one; } + m.strs.push_back(std::move(s)); + return m.strs.back().c_str(); +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta) { + const char* dit = rad_meta_gets(meta, "model.target", ""); + const char* vae = rad_meta_gets(meta, "vae.target", ""); + const char* enc = rad_meta_gets(meta, "conditioner.params.main_image_encoder.type", ""); + if (std::strcmp(dit, "hy3dgen.shapegen.models.Hunyuan3DDiT") != 0 || + std::strcmp(vae, "hy3dgen.shapegen.models.ShapeVAE") != 0 || + std::strcmp(enc, "DinoImageEncoder") != 0) { + fprintf(stderr, "radiance: hunyuan3d2: the checkpoint is '%s' with '%s' and '%s'; this " + "plugin serves Hunyuan3DDiT with ShapeVAE and DINOv2 " + "(hunyuan3d-dit-v2-0)\n", + dit, vae, enc); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "model.params.guidance_embed", 0) != 0) { + fprintf(stderr, "radiance: hunyuan3d2: a guidance-distilled DiT (guidance_embed) is not " + "served yet\n"); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "model.params.depth", 16) <= 0 || + rad_meta_geti(meta, "vae.params.num_freqs", kFreqs) != kFreqs || + rad_meta_geti(meta, "vae.params.include_pi", 0) != 0 || + rad_meta_geti(meta, "conditioner.params.main_image_encoder.kwargs.image_size", kEncSize) != + kEncSize || + rad_meta_geti(meta, "conditioner.params.main_image_encoder.kwargs.config.patch_size", + kPatch) != kPatch || + rad_meta_geti(meta, "conditioner.params.main_image_encoder.kwargs.config.use_swiglu_ffn", + 1) != 1) { + fprintf(stderr, "radiance: hunyuan3d2: the checkpoint's geometry (query embedding, " + "encoder picture or feed-forward) is not hunyuan3d-dit-v2-0's\n"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== declare */ +static int declare_dino(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t R = kCond, E = m.E; + const char* P = "conditioner.main_image_encoder.model"; + const int g0 = kGrpDino; + const int acc = RAD_ACCESS_PER_REQUEST; + m.b_ids = decl_b(b, nm.f("dino.ids"), RAD_I32, { R }); + m.b_pos = decl_b(b, nm.f("dino.pos"), RAD_BF16, { R, E }); + m.b_cls = decl_b(b, nm.f("dino.cls"), RAD_BF16, { 1, E }); + m.b_dx = decl_b(b, nm.f("dino.x"), RAD_BF16, { R, E }); + m.b_dh = decl_b(b, nm.f("dino.h"), RAD_BF16, { R, E }); + m.b_dqkv = decl_b(b, nm.f("dino.qkv"), RAD_BF16, { R, 3 * E }); + m.b_datt = decl_b(b, nm.f("dino.att"), RAD_BF16, { R, E }); + m.b_do = decl_b(b, nm.f("dino.o"), RAD_BF16, { R, E }); + m.b_dgu = decl_b(b, nm.f("dino.gate_up"), RAD_BF16, { R, 2 * m.Eff }); + m.b_dact = decl_b(b, nm.f("dino.act"), RAD_BF16, { R, m.Eff }); + m.b_dcu = decl_b(b, nm.f("dino.cu"), RAD_I32, { 2 }); + m.b_dout = decl_b(b, nm.f("dino.out"), RAD_BF16, { R, E }); + + m.op_ids = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("start", 0), + RAD_INT("step", 1)), + RAD_NOWEIGHTS), + {}, { m.b_ids }); + m.op_dcu = cu_op(b, 1, R, m.b_dcu); + /* The position table and the class token as rows of the stream: embedding lookups of + * the table's own rows. */ + m.w_pos = wcopy(b, nm.f("dino.pos_embed"), nm.ckpt("%s.embeddings.position_embeddings", P), + RAD_BF16, { R, E }, RAD_ACCESS_VOCAB, g0); + m.w_cls = wcopy(b, nm.f("dino.cls_token"), nm.ckpt("%s.embeddings.cls_token", P), RAD_BF16, + { 1, E }, RAD_ACCESS_VOCAB, g0); + if (!m.w_pos || !m.w_cls) return RAD_E_INVAL; + auto lookup = [&](int64_t rows, int64_t vocab, rad_weight w, rad_buf out) { + return rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_embd", E), + RAD_INT("n_vocab", vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(w)), + { m.b_ids }, { out }); + }; + m.op_pos = lookup(R, R, m.w_pos, m.b_pos); + m.op_cls = lookup(1, 1, m.w_cls, m.b_cls); + m.op_cls_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_cls, m.b_pos }, { m.b_dx }); + /* The 14 x 14 patch convolution as a linear over the f32 patches (its kernel read as + * [1536, 3 x 14 x 14]), the position rows added. */ + Lin patch; + RAD_ARCH_TRY(linear(b, nm, patch, "dino.patch", + nm.ckpt("%s.embeddings.patch_embeddings.projection", P), E, kPatchDim, + kNPatch, 0, m.b_dx, acc, g0, true, "none", m.b_pos, false, "f32")); + m.w_patch = patch.w; + m.b_patchw = patch.b; + m.op_patch = patch.op; + m.dino.resize((size_t)m.n_dino); + for (int64_t l = 0; l < m.n_dino; ++l) { + DinoLayer& Y = m.dino[(size_t)l]; + const int g = g0 + 1 + (int)l; + const char* lp = nm.ckpt("%s.encoder.layer.%lld", P, (long long)l); + auto W = [&](const char* dn, const char* src, std::initializer_list sh) { + return wcopy(b, nm.f("dino.blk.%lld.%s", (long long)l, dn), nm.ckpt("%s.%s", lp, src), + RAD_BF16, sh, acc, g); + }; + Y.n1w = W("norm1.weight", "norm1.weight", { E }); + Y.n1b = W("norm1.bias", "norm1.bias", { E }); + Y.n2w = W("norm2.weight", "norm2.weight", { E }); + Y.n2b = W("norm2.bias", "norm2.bias", { E }); + Y.ls1 = W("ls1", "layer_scale1.lambda1", { E }); + Y.ls2 = W("ls2", "layer_scale2.lambda1", { E }); + if (!Y.n1w || !Y.n1b || !Y.n2w || !Y.n2b || !Y.ls1 || !Y.ls2) return RAD_E_INVAL; + Y.op_n1 = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", E), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(Y.n1w, Y.n1b)), + { m.b_dx }, { m.b_dh }); + const char* qn = nm.f("dino.blk.%lld.qkv", (long long)l); + if (map_concat(b, nm.f("%s.weight", qn), + { nm.ckpt("%s.attention.attention.query.weight", lp), + nm.ckpt("%s.attention.attention.key.weight", lp), + nm.ckpt("%s.attention.attention.value.weight", lp) }) < 0 || + map_concat(b, nm.f("%s.bias", qn), + { nm.ckpt("%s.attention.attention.query.bias", lp), + nm.ckpt("%s.attention.attention.key.bias", lp), + nm.ckpt("%s.attention.attention.value.bias", lp) }) < 0) + return RAD_E_INVAL; + /* map_concat named both; the linear declares them without copying again. */ + Y.qkv.w = decl_w(b, nm.f("%s.weight", qn), RAD_BF16, { 3 * E, E }, acc, RAD_SHARD_NONE, + grp_layer(g)); + Y.qkv.b = decl_w(b, nm.f("%s.bias", qn), RAD_BF16, { 3 * E }, acc, RAD_SHARD_NONE, + grp_layer(g)); + if (!Y.qkv.w || !Y.qkv.b) return RAD_E_INVAL; + Y.qkv.op = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", 3 * E), + RAD_INT("K", E), RAD_STR("dtype", "bf16"), + RAD_STR("act", "none")), + RAD_WEIGHTS(Y.qkv.w, Y.qkv.b)), + { m.b_dh }, { m.b_dqkv }); + Y.op_attn = attn_op(b, "attn_dense", R, 64, m.b_dqkv, m.b_dcu, m.b_datt); + RAD_ARCH_TRY(linear(b, nm, Y.o, nm.f("dino.blk.%lld.attn_out", (long long)l), + nm.ckpt("%s.attention.output.dense", lp), E, E, R, m.b_datt, m.b_do, + acc, g)); + auto ls = [&](rad_weight w) { + return rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { m.b_do }, { m.b_do }); + }; + auto add = [&]() { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_do, m.b_dx }, { m.b_dx }); + }; + Y.op_ls1 = ls(Y.ls1); + Y.op_add1 = add(); + Y.op_n2 = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", E), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(Y.n2w, Y.n2b)), + { m.b_dx }, { m.b_dh }); + RAD_ARCH_TRY(linear(b, nm, Y.up, nm.f("dino.blk.%lld.ffn_in", (long long)l), + nm.ckpt("%s.mlp.weights_in", lp), 2 * m.Eff, E, R, m.b_dh, m.b_dgu, + acc, g)); + Y.op_gu = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", m.Eff), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dgu }, { m.b_dact }); + RAD_ARCH_TRY(linear(b, nm, Y.down, nm.f("dino.blk.%lld.ffn_out", (long long)l), + nm.ckpt("%s.mlp.weights_out", lp), E, m.Eff, R, m.b_dact, m.b_do, + acc, g)); + Y.op_ls2 = ls(Y.ls2); + Y.op_add2 = add(); + if (!Y.op_n1 || !Y.qkv.op || !Y.op_attn || !Y.op_ls1 || !Y.op_add1 || !Y.op_n2 || + !Y.op_gu || !Y.op_ls2 || !Y.op_add2) + return RAD_E_INVAL; + } + m.w_lnw = wcopy(b, nm.f("dino.norm.weight"), nm.ckpt("%s.layernorm.weight", P), RAD_BF16, + { E }, acc, g0); + m.w_lnb = wcopy(b, nm.f("dino.norm.bias"), nm.ckpt("%s.layernorm.bias", P), RAD_BF16, { E }, + acc, g0); + if (!m.w_lnw || !m.w_lnb) return RAD_E_INVAL; + m.op_dln = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", E), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_lnw, m.w_lnb)), + { m.b_dx }, { m.b_dout }); + + /* ---- cond_in for both branches: the picture's rows, and the unconditioned branch's zeros + * (whose rows are cond_in's bias), into the lane's store */ + m.b_zero = decl_b(b, nm.f("cond.zero"), RAD_BF16, { R, E }); + m.op_zero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", E), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_zero }); + RAD_ARCH_TRY(linear(b, nm, m.cond_in, "dit.cond_in", "model.cond_in", m.D, E, R, m.b_dout, + m.b_cstore, acc, kGrpDit)); + rw(b, m.cond_in.op, { m.b_dout, m.b_zero }, { m.b_cstore }); + return m.op_ids && m.op_dcu && m.op_pos && m.op_cls && m.op_cls_add && m.op_patch && + m.op_dln && m.op_zero + ? RAD_OK : RAD_E_INVAL; +} + +/* One stream of a double block over `rows` rows. */ +static int declare_stream(RadBuilder* b, Model& m, Stream& S, int64_t l, int which, int64_t rows, + int g) { + Names& nm = m.nm; + const char* nmS = which == kImg ? "img" : "txt"; + const char* src = nm.ckpt("model.double_blocks.%lld", (long long)l); + const int acc = RAD_ACCESS_PER_TOKEN; + const char* dn = nm.f("dit.dbl.%lld.%s", (long long)l, nmS); + S.qn = wcopy(b, nm.f("%s.q_norm", dn), nm.ckpt("%s.%s_attn.norm.query_norm.scale", src, nmS), + RAD_F32, { m.hd }, acc, g); + S.kn = wcopy(b, nm.f("%s.k_norm", dn), nm.ckpt("%s.%s_attn.norm.key_norm.scale", src, nmS), + RAD_F32, { m.hd }, acc, g); + if (!S.qn || !S.kn) return RAD_E_INVAL; + RAD_ARCH_TRY(linear(b, nm, S.mod, nm.f("%s.mod", dn), nm.ckpt("%s.%s_mod.lin", src, nmS), + 6 * m.D, m.D, 1, m.b_svec, m.b_mods, acc, g)); + const rad_buf cu = which == kImg ? m.b_cu_img : m.b_cu_txt; + S.op_n1 = mod_norm(b, rows, m.D, l > 0, m.b_x, m.b_f, m.b_mods, cu, m.b_h); + RAD_ARCH_TRY(linear(b, nm, S.qkv, nm.f("%s.qkv", dn), nm.ckpt("%s.%s_attn.qkv", src, nmS), + 3 * m.D, m.D, rows, m.b_h, m.b_qkv, acc, g)); + S.op_qk = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", m.hd), + RAD_INT("n_head", m.H), RAD_INT("n_head_kv", m.H), + RAD_F64("theta", 10000.0), RAD_F64("eps", 1e-6), + RAD_INT("rotary_dim", 0)), + RAD_WEIGHTS(S.qn, S.kn)), + { m.b_qkv }, { m.b_qkv }); + return S.op_n1 && S.op_qk ? RAD_OK : RAD_E_INVAL; +} + +static int declare_stream_out(RadBuilder* b, Model& m, Stream& S, int64_t l, int which, + int64_t rows, int g) { + Names& nm = m.nm; + const char* nmS = which == kImg ? "img" : "txt"; + const char* src = nm.ckpt("model.double_blocks.%lld", (long long)l); + const int acc = RAD_ACCESS_PER_TOKEN; + const char* dn = nm.f("dit.dbl.%lld.%s", (long long)l, nmS); + RAD_ARCH_TRY(linear(b, nm, S.proj, nm.f("%s.proj", dn), nm.ckpt("%s.%s_attn.proj", src, nmS), + m.D, m.D, rows, m.b_att, m.b_o, acc, g)); + S.op_n2 = mod_norm(b, rows, m.D, true, m.b_x, m.b_o, m.b_mods, + which == kImg ? m.b_cu_img : m.b_cu_txt, m.b_h); + RAD_ARCH_TRY(linear(b, nm, S.mlp1, nm.f("%s.mlp_in", dn), nm.ckpt("%s.%s_mlp.0", src, nmS), + m.ff, m.D, rows, m.b_h, m.b_ff, acc, g, true, "gelu_tanh")); + RAD_ARCH_TRY(linear(b, nm, S.mlp2, nm.f("%s.mlp_out", dn), nm.ckpt("%s.%s_mlp.2", src, nmS), + m.D, m.ff, rows, m.b_ff, m.b_f, acc, g)); + return S.op_n2 ? RAD_OK : RAD_E_INVAL; +} + +static int declare_dit(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t N = m.rows, D = m.D, L2 = 2 * m.L; + const int acc = RAD_ACCESS_PER_TOKEN; + const int gx = kGrpDit; + m.b_lx = decl_b(b, nm.f("dit.lat"), RAD_BF16, { L2, m.C }); + m.b_temb = decl_b(b, nm.f("dit.temb"), RAD_BF16, { 1, 256 }); + m.b_t1 = decl_b(b, nm.f("dit.t1"), RAD_BF16, { 1, D }); + m.b_t1s = decl_b(b, nm.f("dit.t1s"), RAD_BF16, { 1, D }); + m.b_vec = decl_b(b, nm.f("dit.vec"), RAD_BF16, { 1, D }); + m.b_svec = decl_b(b, nm.f("dit.svec"), RAD_BF16, { 1, D }); + /* Every block's modulation, one row: each double block's two streams (6 D each), each single + * block's (3 D) and the output layer's (2 D). */ + for (int s = 0; s < 2; ++s) m.mod_dbl[s].clear(); + m.mod_sgl.clear(); + int64_t col = 0; + for (int64_t l = 0; l < m.n_double; ++l) + for (int s = 0; s < 2; ++s) { m.mod_dbl[s].push_back(col); col += 6 * D; } + for (int64_t l = 0; l < m.n_single; ++l) { m.mod_sgl.push_back(col); col += 3 * D; } + m.mod_fin = col; + col += 2 * D; + m.mods_w = col; + m.b_mods = decl_b(b, nm.f("dit.mods"), RAD_BF16, { 1, m.mods_w }); + m.b_x = decl_b(b, nm.f("dit.x"), RAD_BF16, { N, D }); + m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { N, D }); + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { N, 3 * D }); + m.b_att = decl_b(b, nm.f("dit.att"), RAD_BF16, { N, D }); + m.b_o = decl_b(b, nm.f("dit.o"), RAD_BF16, { N, D }); + m.b_ff = decl_b(b, nm.f("dit.ff"), RAD_BF16, { N, m.ff }); + m.b_f = decl_b(b, nm.f("dit.f"), RAD_BF16, { N, D }); + m.b_l1 = decl_b(b, nm.f("dit.l1"), RAD_BF16, { N, 3 * D + m.ff }); + m.b_cat = decl_b(b, nm.f("dit.cat"), RAD_BF16, { N, D + m.ff }); + m.b_v = decl_b(b, nm.f("dit.v"), RAD_BF16, { L2, m.C }); + m.b_cu_txt = decl_b(b, nm.f("dit.cu_txt"), RAD_I32, { 2 }); + m.b_cu_img = decl_b(b, nm.f("dit.cu_img"), RAD_I32, { 2 }); + m.b_cu_all = decl_b(b, nm.f("dit.cu_all"), RAD_I32, { 2 }); + m.b_cu_ent = decl_b(b, nm.f("dit.cu_ent"), RAD_I32, { 3 }); + + /* ---- the latents: the first step's noise, both entries' rows of the lane, latent_in */ + m.op_randn = rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, L2), RAD_INT("n", m.C), + RAD_INT("stride", m.L), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_lat }, { m.b_lat }); + m.op_lgather = rw(b, RAD_OP(b, "lane_gather", + RAD_PARAMS(RAD_RANGE("M", 1, L2), RAD_INT("n", m.C), + RAD_INT("stride", m.L), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_lat }, { m.b_lx }); + RAD_ARCH_TRY(linear(b, nm, m.latent_in, "dit.latent_in", "model.latent_in", D, m.C, L2, + m.b_lx, m.b_x, acc, gx)); + /* The conditioning rows from the lane's store. */ + m.op_ccopy = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, kCond), RAD_INT("n", D), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_cstore }, { m.b_x }); + /* ---- the timestep: the sinusoid of 1000 sigma, time_in, silu. The reference passes its + * time_factor (1000) where timestep_embedding takes max_period, so the model was trained on + * a period of 1000, and the time is scaled by the default factor, also 1000. */ + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 256), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 1000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_temb }); + RAD_ARCH_TRY(linear(b, nm, m.t_in1, "dit.time_in.in", "model.time_in.in_layer", D, 256, 1, + m.b_temb, m.b_t1, acc, gx)); + m.op_tsilu = rw(b, RAD_OP(b, "silu", RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_t1 }, { m.b_t1s }); + RAD_ARCH_TRY(linear(b, nm, m.t_out, "dit.time_in.out", "model.time_in.out_layer", D, D, 1, + m.b_t1s, m.b_vec, acc, gx)); + m.op_vsilu = rw(b, RAD_OP(b, "silu", RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vec }, { m.b_svec }); + m.op_cu_txt = cu_op(b, 1, kCond, m.b_cu_txt); + m.op_cu_img = cu_op(b, 1, L2, m.b_cu_img); + m.op_cu_all = cu_op(b, 1, N, m.b_cu_all); + m.op_cu_ent = cu_op(b, 2, N / 2, m.b_cu_ent); + + /* ---- the double blocks: each stream's norm, qkv and q/k norm, the joint attention, then + * each stream's projection, second norm and MLP, in the order the step issues them */ + m.dbl.resize((size_t)m.n_double); + for (int64_t l = 0; l < m.n_double; ++l) { + Double& B = m.dbl[(size_t)l]; + const int g = gx + 1 + (int)l; + RAD_ARCH_TRY(declare_stream(b, m, B.s[kImg], l, kImg, L2, g)); + RAD_ARCH_TRY(declare_stream(b, m, B.s[kTxt], l, kTxt, kCond, g)); + B.op_attn = attn_op(b, "attn_dense", N, m.hd, m.b_qkv, m.b_cu_ent, m.b_att); + RAD_ARCH_TRY(declare_stream_out(b, m, B.s[kImg], l, kImg, L2, g)); + RAD_ARCH_TRY(declare_stream_out(b, m, B.s[kTxt], l, kTxt, kCond, g)); + if (!B.op_attn) return RAD_E_INVAL; + } + auto gate_op = [&](int64_t rows, rad_buf cu) { + return rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { m.b_f, m.b_mods, cu, m.b_x }, { m.b_x }); + }; + m.op_gate_img = gate_op(L2, m.b_cu_img); + m.op_gate_txt = gate_op(kCond, m.b_cu_txt); + + /* ---- the single blocks over every row */ + m.sgl.resize((size_t)m.n_single); + for (int64_t l = 0; l < m.n_single; ++l) { + Single& S = m.sgl[(size_t)l]; + const int g = kGrpSingle + 1 + (int)l; + const char* src = nm.ckpt("model.single_blocks.%lld", (long long)l); + const char* dn = nm.f("dit.sgl.%lld", (long long)l); + S.qn = wcopy(b, nm.f("%s.q_norm", dn), nm.ckpt("%s.norm.query_norm.scale", src), RAD_F32, + { m.hd }, acc, g); + S.kn = wcopy(b, nm.f("%s.k_norm", dn), nm.ckpt("%s.norm.key_norm.scale", src), RAD_F32, + { m.hd }, acc, g); + if (!S.qn || !S.kn) return RAD_E_INVAL; + RAD_ARCH_TRY(linear(b, nm, S.mod, nm.f("%s.mod", dn), nm.ckpt("%s.modulation.lin", src), + 3 * D, D, 1, m.b_svec, m.b_mods, acc, g)); + S.op_n = mod_norm(b, N, D, l > 0, m.b_x, m.b_f, m.b_mods, m.b_cu_all, m.b_h); + RAD_ARCH_TRY(linear(b, nm, S.l1, nm.f("%s.linear1", dn), nm.ckpt("%s.linear1", src), + 3 * D + m.ff, D, N, m.b_h, m.b_l1, acc, g)); + S.op_qk = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, N), RAD_INT("head_dim", m.hd), + RAD_INT("n_head", m.H), RAD_INT("n_head_kv", m.H), + RAD_F64("theta", 10000.0), RAD_F64("eps", 1e-6), + RAD_INT("rotary_dim", 0)), + RAD_WEIGHTS(S.qn, S.kn)), + { m.b_l1 }, { m.b_l1 }); + S.op_attn = attn_op(b, "attn_dense", N, m.hd, m.b_l1, m.b_cu_ent, m.b_cat); + S.op_act = rw(b, RAD_OP(b, "gelu_tanh", + RAD_PARAMS(RAD_RANGE("M", 1, N), RAD_INT("n", m.ff), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_l1 }, { m.b_cat }); + RAD_ARCH_TRY(linear(b, nm, S.l2, nm.f("%s.linear2", dn), nm.ckpt("%s.linear2", src), D, + D + m.ff, N, m.b_cat, m.b_f, acc, g)); + if (!S.op_n || !S.op_qk || !S.op_attn || !S.op_act) return RAD_E_INVAL; + } + + /* ---- the output layer over the latent rows, and the guided step */ + RAD_ARCH_TRY(linear(b, nm, m.fin_mod, "dit.final.mod", "model.final_layer.adaLN_modulation.1", + 2 * D, D, 1, m.b_svec, m.b_mods, acc, gx)); + m.op_fin_n = mod_norm(b, L2, D, true, m.b_x, m.b_f, m.b_mods, m.b_cu_img, m.b_h); + RAD_ARCH_TRY(linear(b, nm, m.fin, "dit.final.linear", "model.final_layer.linear", m.C, D, L2, + m.b_h, m.b_v, acc, gx)); + m.op_euler = rw(b, RAD_OP(b, "flow_euler", + RAD_PARAMS(RAD_RANGE("M", 1, L2), RAD_INT("n", m.C), + RAD_INT("stride", m.L), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_v, m.b_lat }, { m.b_lat }); + return m.op_randn && m.op_lgather && m.op_ccopy && m.op_temb && m.op_tsilu && m.op_vsilu && + m.op_cu_txt && m.op_cu_img && m.op_cu_all && m.op_cu_ent && m.op_gate_img && + m.op_gate_txt && m.op_fin_n && m.op_euler + ? RAD_OK : RAD_E_INVAL; +} + +/* Rows of a head-interleaved projection: for every head h of `heads`, rows + * [h * per + first, h * per + first + width) of `src`, joined (RAD_MAP_ROWS, eight a map). */ +static int map_heads(RadBuilder* b, const char* declared, const char* src, int64_t heads, + int64_t per, int64_t first, int64_t width) { + for (int64_t h0 = 0; h0 < heads; h0 += 8) { + RadNameMap mp = map_base(declared, RAD_MAP_ROWS); + for (int64_t h = h0; h < std::min(heads, h0 + 8); ++h) { + mp.src[mp.n_src] = src; + mp.src_index[mp.n_src] = (int)(h * per + first); + mp.src_rows[mp.n_src] = width; + ++mp.n_src; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mp)); + } + return RAD_OK; +} + +/* A per-head LayerNorm (gain and bias of head_dim) over [rows x heads] heads in place of rows. */ +static rad_op head_norm(RadBuilder* b, const Model& m, int64_t rows, rad_weight w, rad_weight bb, + rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows * m.H), RAD_INT("n", m.hd), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)), + { in }, { out }); +} + +static rad_op affine_norm(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, + rad_weight bb, rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)), + { in }, { out }); +} + +static int declare_vae(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t L = m.L, D = m.D; + const int acc = RAD_ACCESS_PER_REQUEST; + m.b_vl = decl_b(b, nm.f("vae.lat"), RAD_BF16, { L, m.C }); + m.b_vx = decl_b(b, nm.f("vae.x"), RAD_BF16, { L, D }); + m.b_vh = decl_b(b, nm.f("vae.h"), RAD_BF16, { L, D }); + m.b_vq = decl_b(b, nm.f("vae.q"), RAD_BF16, { L, D }); + m.b_vk = decl_b(b, nm.f("vae.k"), RAD_BF16, { L, D }); + m.b_vv = decl_b(b, nm.f("vae.v"), RAD_BF16, { L, D }); + m.b_vqn = decl_b(b, nm.f("vae.qn"), RAD_BF16, { L, D }); + m.b_vkn = decl_b(b, nm.f("vae.kn"), RAD_BF16, { L, D }); + m.b_vatt = decl_b(b, nm.f("vae.att"), RAD_BF16, { L, D }); + m.b_vff = decl_b(b, nm.f("vae.ff"), RAD_BF16, { L, 4 * D }); + m.b_vcu = decl_b(b, nm.f("vae.cu"), RAD_I32, { 2 }); + m.op_vcu = cu_op(b, 1, L, m.b_vcu); + /* 1 / scale_factor times the latent, in f32 and rounded once. */ + m.op_unscale = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, L), RAD_INT("n", m.C), + RAD_STR("mul", list_of(m, m.C, 1.0 / m.scale_factor)), + RAD_STR("add", list_of(m, m.C, 0.0)), + RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"), + RAD_INT("round", 0)), + RAD_NOWEIGHTS), + { m.b_lat }, { m.b_vl }); + RAD_ARCH_TRY(linear(b, nm, m.post_kl, "vae.post_kl", "vae.post_kl", D, m.C, L, m.b_vl, m.b_vx, + acc, kGrpVae)); + m.vae.resize((size_t)m.n_vae); + for (int64_t l = 0; l < m.n_vae; ++l) { + VaeLayer& V = m.vae[(size_t)l]; + const int g = kGrpVae + 1 + (int)l; + const char* src = nm.ckpt("vae.transformer.resblocks.%lld", (long long)l); + const char* dn = nm.f("vae.blk.%lld", (long long)l); + auto W = [&](const char* d, const char* s, int64_t n) { + return wcopy(b, nm.f("%s.%s", dn, d), nm.ckpt("%s.%s", src, s), RAD_BF16, { n }, acc, + g); + }; + V.n1w = W("ln_1.weight", "ln_1.weight", D); + V.n1b = W("ln_1.bias", "ln_1.bias", D); + V.n2w = W("ln_2.weight", "ln_2.weight", D); + V.n2b = W("ln_2.bias", "ln_2.bias", D); + V.qnw = W("q_norm.weight", "attn.attention.q_norm.weight", m.hd); + V.qnb = W("q_norm.bias", "attn.attention.q_norm.bias", m.hd); + V.knw = W("k_norm.weight", "attn.attention.k_norm.weight", m.hd); + V.knb = W("k_norm.bias", "attn.attention.k_norm.bias", m.hd); + if (!V.n1w || !V.n1b || !V.n2w || !V.n2b || !V.qnw || !V.qnb || !V.knw || !V.knb) + return RAD_E_INVAL; + V.op_n1 = affine_norm(b, L, D, 1e-6, V.n1w, V.n1b, m.b_vx, m.b_vh); + /* c_qkv holds each head's q, k and v side by side (192 rows a head). */ + const char* qkv = nm.ckpt("%s.attn.c_qkv.weight", src); + const char* part[3] = { "q", "k", "v" }; + Lin* lin3[3] = { &V.q, &V.k, &V.v }; + const rad_buf out3[3] = { m.b_vq, m.b_vk, m.b_vv }; + for (int p = 0; p < 3; ++p) { + const char* pn = nm.f("%s.attn_%s", dn, part[p]); + RAD_ARCH_TRY(map_heads(b, nm.f("%s.weight", pn), qkv, m.H, 3 * m.hd, p * m.hd, m.hd)); + RAD_ARCH_TRY(linear(b, nm, *lin3[p], pn, nullptr, D, D, L, m.b_vh, out3[p], acc, g, + false, "none", 0, true)); + } + V.op_qn = head_norm(b, m, L, V.qnw, V.qnb, m.b_vq, m.b_vqn); + V.op_kn = head_norm(b, m, L, V.knw, V.knb, m.b_vk, m.b_vkn); + V.op_attn = attn_op(b, "attn_dense", L, m.hd, m.b_vqn, m.b_vcu, m.b_vatt); + rw(b, V.op_attn, { m.b_vqn, m.b_vkn, m.b_vv }, { m.b_vatt }); + RAD_ARCH_TRY(linear(b, nm, V.proj, nm.f("%s.attn_out", dn), nm.ckpt("%s.attn.c_proj", src), + D, D, L, m.b_vatt, m.b_vx, acc, g, true, "none", m.b_vx)); + V.op_n2 = affine_norm(b, L, D, 1e-6, V.n2w, V.n2b, m.b_vx, m.b_vh); + RAD_ARCH_TRY(linear(b, nm, V.fc, nm.f("%s.mlp_in", dn), nm.ckpt("%s.mlp.c_fc", src), + 4 * D, D, L, m.b_vh, m.b_vff, acc, g, true, "gelu")); + RAD_ARCH_TRY(linear(b, nm, V.out, nm.f("%s.mlp_out", dn), nm.ckpt("%s.mlp.c_proj", src), + D, 4 * D, L, m.b_vff, m.b_vx, acc, g, true, "none", m.b_vx)); + if (!V.op_n1 || !V.op_qn || !V.op_kn || !V.op_attn || !V.op_n2) return RAD_E_INVAL; + } + /* ---- the geometry decoder's keys and values over the latent network's rows, normed and + * kept in the lane (c_kv holds each head's k and v side by side, 128 rows a head) */ + const char* gd = "vae.geo_decoder.cross_attn_decoder"; + const int g = kGrpVae + 100; + auto GW = [&](const char* dn, const char* pre, const char* src, int64_t n) { + return wcopy(b, nm.f("%s", dn), nm.ckpt("%s.%s", pre, src), RAD_BF16, { n }, acc, g); + }; + m.g_n2w = GW("geo.ln_2.weight", gd, "ln_2.weight", D); + m.g_n2b = GW("geo.ln_2.bias", gd, "ln_2.bias", D); + m.g_knw = wcopy(b, nm.f("geo.k_norm.weight"), nm.ckpt("%s.attn.attention.k_norm.weight", gd), + RAD_BF16, { m.hd }, acc, g); + m.g_knb = wcopy(b, nm.f("geo.k_norm.bias"), nm.ckpt("%s.attn.attention.k_norm.bias", gd), + RAD_BF16, { m.hd }, acc, g); + if (!m.g_n2w || !m.g_n2b || !m.g_knw || !m.g_knb) return RAD_E_INVAL; + m.op_gn2 = affine_norm(b, L, D, 1e-6, m.g_n2w, m.g_n2b, m.b_vx, m.b_vh); + const char* kv = nm.ckpt("%s.attn.c_kv.weight", gd); + RAD_ARCH_TRY(map_heads(b, nm.f("geo.attn_k.weight"), kv, m.H, 2 * m.hd, 0, m.hd)); + RAD_ARCH_TRY(map_heads(b, nm.f("geo.attn_v.weight"), kv, m.H, 2 * m.hd, m.hd, m.hd)); + RAD_ARCH_TRY(linear(b, nm, m.g_k, "geo.attn_k", nullptr, D, D, L, m.b_vh, m.b_vk, acc, g, + false, "none", 0, true)); + RAD_ARCH_TRY(linear(b, nm, m.g_v, "geo.attn_v", nullptr, D, D, L, m.b_vh, m.b_gv, acc, g, + false, "none", 0, true)); + m.op_gkn = head_norm(b, m, L, m.g_knw, m.g_knb, m.b_vk, m.b_gk); + return m.op_vcu && m.op_unscale && m.op_gn2 && m.op_gkn ? RAD_OK : RAD_E_INVAL; +} + +static int declare_query(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t Q = kMaxQuery, D = m.D, F = 3 * (2 * kFreqs + 1); + const int acc = RAD_ACCESS_PER_REQUEST; + const int g = kGrpVae + 101; + const char* gd = "vae.geo_decoder"; + m.b_feat = decl_b(b, nm.f("geo.feat"), RAD_F32, { Q, F }); + m.b_qx = decl_b(b, nm.f("geo.x"), RAD_BF16, { Q, D }); + m.b_qh = decl_b(b, nm.f("geo.h"), RAD_BF16, { Q, D }); + m.b_qq = decl_b(b, nm.f("geo.q"), RAD_BF16, { Q, D }); + m.b_qqn = decl_b(b, nm.f("geo.qn"), RAD_BF16, { Q, D }); + m.b_qatt = decl_b(b, nm.f("geo.att"), RAD_BF16, { Q, D }); + m.b_qff = decl_b(b, nm.f("geo.ff"), RAD_BF16, { Q, 4 * D }); + m.b_qlogit = decl_b(b, nm.f("geo.logit"), RAD_BF16, { Q, 1 }); + m.b_field = decl_b(b, nm.f("geo.field"), RAD_F32, { Q }); + m.op_four = rw(b, RAD_OP(b, "point_fourier", + RAD_PARAMS(RAD_RANGE("M", 1, Q), RAD_INT("n", 3), + RAD_INT("freqs", kFreqs), RAD_INT("pi", 0), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_feat }); + RAD_ARCH_TRY(linear(b, nm, m.q_proj, "geo.query_proj", "vae.geo_decoder.query_proj", D, F, Q, + m.b_feat, m.b_qx, acc, g, true, "none", 0, false, "f32")); + const char* cb = "vae.geo_decoder.cross_attn_decoder"; + auto GW = [&](const char* dn, const char* pre, const char* src, int64_t n) { + return wcopy(b, nm.f("%s", dn), nm.ckpt("%s.%s", pre, src), RAD_BF16, { n }, acc, g); + }; + m.q_n1w = GW("geo.ln_1.weight", cb, "ln_1.weight", D); + m.q_n1b = GW("geo.ln_1.bias", cb, "ln_1.bias", D); + m.q_n3w = GW("geo.ln_3.weight", cb, "ln_3.weight", D); + m.q_n3b = GW("geo.ln_3.bias", cb, "ln_3.bias", D); + m.q_qnw = wcopy(b, nm.f("geo.q_norm.weight"), nm.ckpt("%s.attn.attention.q_norm.weight", cb), + RAD_BF16, { m.hd }, acc, g); + m.q_qnb = wcopy(b, nm.f("geo.q_norm.bias"), nm.ckpt("%s.attn.attention.q_norm.bias", cb), + RAD_BF16, { m.hd }, acc, g); + m.q_pw = GW("geo.ln_post.weight", gd, "ln_post.weight", D); + m.q_pb = GW("geo.ln_post.bias", gd, "ln_post.bias", D); + if (!m.q_n1w || !m.q_n1b || !m.q_n3w || !m.q_n3b || !m.q_qnw || !m.q_qnb || !m.q_pw || !m.q_pb) + return RAD_E_INVAL; + m.op_qn1 = affine_norm(b, Q, D, 1e-6, m.q_n1w, m.q_n1b, m.b_qx, m.b_qh); + RAD_ARCH_TRY(linear(b, nm, m.q_q, "geo.attn_q", nm.ckpt("%s.attn.c_q", cb), D, D, Q, m.b_qh, + m.b_qq, acc, g, false)); + m.op_qqn = head_norm(b, m, Q, m.q_qnw, m.q_qnb, m.b_qq, m.b_qqn); + m.op_qattn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, Q), RAD_INT("head_dim", m.hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)m.hd))), + RAD_NOWEIGHTS), + { m.b_qqn, m.b_gk, m.b_gv }, { m.b_qatt }); + RAD_ARCH_TRY(linear(b, nm, m.q_o, "geo.attn_out", nm.ckpt("%s.attn.c_proj", cb), D, D, Q, + m.b_qatt, m.b_qx, acc, g, true, "none", m.b_qx)); + m.op_qn3 = affine_norm(b, Q, D, 1e-6, m.q_n3w, m.q_n3b, m.b_qx, m.b_qh); + RAD_ARCH_TRY(linear(b, nm, m.q_fc, "geo.mlp_in", nm.ckpt("%s.mlp.c_fc", cb), 4 * D, D, Q, + m.b_qh, m.b_qff, acc, g, true, "gelu")); + RAD_ARCH_TRY(linear(b, nm, m.q_out, "geo.mlp_out", nm.ckpt("%s.mlp.c_proj", cb), D, 4 * D, Q, + m.b_qff, m.b_qx, acc, g, true, "none", m.b_qx)); + /* torch's LayerNorm default eps, 1e-5, unlike the blocks' 1e-6. */ + m.op_qpost = affine_norm(b, Q, D, 1e-5, m.q_pw, m.q_pb, m.b_qx, m.b_qh); + RAD_ARCH_TRY(linear(b, nm, m.q_head, "geo.output_proj", "vae.geo_decoder.output_proj", 1, D, Q, + m.b_qh, m.b_qlogit, acc, g)); + m.op_qcast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, Q), RAD_INT("n", 1), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_qlogit }, { m.b_field }); + return m.op_four && m.op_qn1 && m.op_qqn && m.op_qattn && m.op_qn3 && m.op_qpost && + m.op_qcast + ? RAD_OK : RAD_E_INVAL; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + Model& m = g_model; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + if (ctx->world_size > 1) { + fprintf(stderr, "radiance: hunyuan3d2 runs on one card (--tp 1): the model is 2.2B and a " + "pass is one request's\n"); + return RAD_E_UNSUPPORTED; + } + const char* dc = "conditioner.params.main_image_encoder.kwargs.config"; + char key[160]; + auto ci = [&](const char* k, long long d) { + std::snprintf(key, sizeof key, "%s.%s", dc, k); + return (int64_t)rad_meta_geti(meta, key, d); + }; + m.D = rad_meta_geti(meta, "model.params.hidden_size", 1024); + m.H = rad_meta_geti(meta, "model.params.num_heads", 16); + m.hd = m.D / std::max(m.H, 1); + m.ff = (int64_t)(m.D * rad_meta_getf(meta, "model.params.mlp_ratio", 4.0)); + m.C = rad_meta_geti(meta, "model.params.in_channels", 64); + m.n_double = rad_meta_geti(meta, "model.params.depth", 16); + m.n_single = rad_meta_geti(meta, "model.params.depth_single_blocks", 32); + m.L = rad_meta_geti(meta, "vae.params.num_latents", 3072); + m.n_vae = rad_meta_geti(meta, "vae.params.num_decoder_layers", 16); + m.scale_factor = rad_meta_getf(meta, "vae.params.scale_factor", 1.0); + m.E = ci("hidden_size", 1536); + m.EH = ci("num_attention_heads", 24); + m.n_dino = ci("num_hidden_layers", 40); + /* DINOv2's SwiGLU width: 2/3 of mlp_ratio times the width, rounded up to 8. */ + m.Eff = ((int64_t)(m.E * ci("mlp_ratio", 4) * 2 / 3) + 7) / 8 * 8; + if (m.hd != 64 || m.E / std::max(m.EH, 1) != 64 || + rad_meta_geti(meta, "vae.params.width", m.D) != m.D || + rad_meta_geti(meta, "vae.params.heads", m.H) != m.H || + rad_meta_geti(meta, "vae.params.embed_dim", m.C) != m.C || + rad_meta_geti(meta, "model.params.context_in_dim", m.E) != m.E || + !(m.scale_factor > 0.0)) { + fprintf(stderr, "radiance: hunyuan3d2: the networks' widths disagree (DiT %lld x %lld, " + "encoder %lld x %lld, VAE scale %g); every attention here is 64 wide\n", + (long long)m.H, (long long)m.hd, (long long)m.EH, (long long)m.E, m.scale_factor); + return RAD_E_UNSUPPORTED; + } + /* Lanes are requests holding state, not a pass's sequences (a pass is one request's, and + * --max-num-seqs is 1): one denoising or decoding while the next is conditioned. */ + m.rows = 2 * (kCond + m.L); + m.lanes = kLanes; + Names& nm = m.nm; + m.b_lat = decl_b(b, nm.f("lat_state"), RAD_BF16, { m.lanes * m.L, m.C }, RAD_BUF_PERSIST); + m.b_cstore = decl_b(b, nm.f("cond_store"), RAD_BF16, { m.lanes * 2 * kCond, m.D }, + RAD_BUF_PERSIST); + m.b_gk = decl_b(b, nm.f("geo_k"), RAD_BF16, { m.lanes * m.L, m.D }, RAD_BUF_PERSIST); + m.b_gv = decl_b(b, nm.f("geo_v"), RAD_BF16, { m.lanes * m.L, m.D }, RAD_BUF_PERSIST); + RAD_ARCH_TRY(declare_dino(b, m)); + RAD_ARCH_TRY(declare_dit(b, m)); + RAD_ARCH_TRY(declare_vae(b, m)); + RAD_ARCH_TRY(declare_query(b, m)); + + RadShapeGenDecl d{}; + d.name = "hunyuan3d-2"; + d.canvas = rad_meta_geti(meta, "image_processor.params.size", kCanvas); + d.border_ratio = rad_meta_getf(meta, "image_processor.params.border_ratio", 0.15); + d.enc_size = kEncSize; + d.enc_patch = kPatch; + for (int c = 0; c < 3; ++c) { d.pix_mean[c] = kMean[c]; d.pix_std[c] = kStd[c]; } + d.latent_rows = m.L; + d.latent_channels = m.C; + d.step_rows = m.rows; + d.default_steps = 50; + d.max_steps = 200; + d.default_guidance = 5.0; + d.bounds = kBounds; + d.level = 0.0; + d.default_resolution = kResDef; + d.min_resolution = kResMin; + d.max_resolution = kResMax; + d.max_lanes = m.lanes; + d.max_query = kMaxQuery; + d.field_out = m.b_field; + RAD_ARCH_TRY(rad_declare_shape_generator(b, &d)); + rad_note(b, "Hunyuan3D-2 shape: DINOv2 %lld x %lld, DiT %lld double + %lld single blocks of " + "%lld, VAE %lld blocks over %lld latents; %lld lanes, %d query points a pass", + (long long)m.n_dino, (long long)m.E, (long long)m.n_double, (long long)m.n_single, + (long long)m.D, (long long)m.n_vae, (long long)m.L, (long long)m.lanes, kMaxQuery); + return RAD_OK; +} + +/* ================================================================== step */ +static void step_cond(RadCtx* c, const RadShapeGenBatch* S, const Model& m) { + const int64_t R = kCond, E = m.E, D = m.D; + RAD_ISSUE_N(c, m.op_ids, R, brows(m.b_ids, R)); + RAD_ISSUE_N(c, m.op_dcu, 2, brows(m.b_dcu, 2)); + RAD_ISSUE_N(c, m.op_pos, R, brows(m.b_ids, R), RAD_W(m.w_pos), brows(m.b_pos, R)); + RAD_ISSUE_N(c, m.op_cls, 1, brows(m.b_ids, 1), RAD_W(m.w_cls), brows(m.b_cls, 1)); + RAD_ISSUE_N(c, m.op_cls_add, 1, brows(m.b_cls, 1), brows(m.b_pos, 1), brows(m.b_dx, 1)); + RAD_ISSUE_N(c, m.op_patch, kNPatch, praw2(S->patches, RAD_F32, kNPatch, kPatchDim), + RAD_W(m.w_patch), RAD_W(m.b_patchw), brow_slice(m.b_pos, 1, kNPatch, E), + brow_slice(m.b_dx, 1, kNPatch, E)); + const RadOperand cu = brows(m.b_dcu, 2); + for (const DinoLayer& Y : m.dino) { + RAD_ISSUE_N(c, Y.op_n1, R, brows(m.b_dx, R), RAD_W(Y.n1w), RAD_W(Y.n1b), brows(m.b_dh, R)); + lin_issue(c, Y.qkv, R, brows(m.b_dh, R), brows(m.b_dqkv, R)); + RAD_ISSUE_N(c, Y.op_attn, R, bcol(m.b_dqkv, 0, E, R), bcol(m.b_dqkv, E, E, R), + bcol(m.b_dqkv, 2 * E, E, R), cu, brows(m.b_datt, R)); + lin_issue(c, Y.o, R, brows(m.b_datt, R), brows(m.b_do, R)); + RAD_ISSUE_N(c, Y.op_ls1, R, brows(m.b_do, R), RAD_W(Y.ls1), brows(m.b_do, R)); + RAD_ISSUE_N(c, Y.op_add1, R, brows(m.b_do, R), brows(m.b_dx, R), brows(m.b_dx, R)); + RAD_ISSUE_N(c, Y.op_n2, R, brows(m.b_dx, R), RAD_W(Y.n2w), RAD_W(Y.n2b), brows(m.b_dh, R)); + lin_issue(c, Y.up, R, brows(m.b_dh, R), brows(m.b_dgu, R)); + RAD_ISSUE_N(c, Y.op_gu, R, brows(m.b_dgu, R), brows(m.b_dact, R)); + lin_issue(c, Y.down, R, brows(m.b_dact, R), brows(m.b_do, R)); + RAD_ISSUE_N(c, Y.op_ls2, R, brows(m.b_do, R), RAD_W(Y.ls2), brows(m.b_do, R)); + RAD_ISSUE_N(c, Y.op_add2, R, brows(m.b_do, R), brows(m.b_dx, R), brows(m.b_dx, R)); + } + RAD_ISSUE_N(c, m.op_dln, R, brows(m.b_dx, R), RAD_W(m.w_lnw), RAD_W(m.w_lnb), + brows(m.b_dout, R)); + /* The lane's store: the picture's branch, then the unconditioned one. */ + const int64_t base = (int64_t)S->lane * 2 * R; + RAD_ISSUE_N(c, m.op_zero, R, brows(m.b_zero, R)); + lin_issue(c, m.cond_in, R, brows(m.b_dout, R), brow_slice(m.b_cstore, base, R, D)); + lin_issue(c, m.cond_in, R, brows(m.b_zero, R), brow_slice(m.b_cstore, base + R, R, D)); +} + +/* One stream's rows of a step: the latents' one run, or the conditioning's two. */ +template static void each_run(int which, const Model& m, F&& f) { + if (which == kImg) { f((int64_t)kCond, 2 * m.L); return; } + f(0, (int64_t)kCond); + f((int64_t)kCond + 2 * m.L, (int64_t)kCond); +} + +static void step_dit(RadCtx* c, const RadShapeGenBatch* S, const Model& m) { + const int64_t N = m.rows, D = m.D, L2 = 2 * m.L, Cn = kCond; + const RadOperand lat_cu = praw(S->lat_cu, RAD_I32, 3); + const RadOperand lanes = praw(S->lanes, RAD_I32, 2); + const int64_t LR = m.lanes * m.L; + /* ---- the latent rows: noise on the first step, both entries from the lane, latent_in */ + RAD_ISSUE_N(c, m.op_randn, L2, praw(S->flags, RAD_I32, 2), praw(S->seed, RAD_U32, 4), lanes, + lat_cu, brows(m.b_lat, LR)); + RAD_ISSUE_N(c, m.op_lgather, L2, brows(m.b_lat, LR), lanes, lat_cu, brows(m.b_lx, L2)); + lin_issue(c, m.latent_in, L2, brows(m.b_lx, L2), brow_slice(m.b_x, Cn, L2, D)); + /* ---- the conditioning rows from the lane's store */ + const int64_t base = (int64_t)S->lane * 2 * Cn; + RAD_ISSUE_N(c, m.op_ccopy, Cn, brow_slice(m.b_cstore, base, Cn, D), + brow_slice(m.b_x, 0, Cn, D)); + RAD_ISSUE_N(c, m.op_ccopy, Cn, brow_slice(m.b_cstore, base + Cn, Cn, D), + brow_slice(m.b_x, Cn + L2, Cn, D)); + /* ---- the timestep and every modulation */ + RAD_ISSUE_N(c, m.op_temb, 1, praw(S->sigma, RAD_F32, 1), brows(m.b_temb, 1)); + lin_issue(c, m.t_in1, 1, brows(m.b_temb, 1), brows(m.b_t1, 1)); + RAD_ISSUE_N(c, m.op_tsilu, 1, brows(m.b_t1, 1), brows(m.b_t1s, 1)); + lin_issue(c, m.t_out, 1, brows(m.b_t1s, 1), brows(m.b_vec, 1)); + RAD_ISSUE_N(c, m.op_vsilu, 1, brows(m.b_vec, 1), brows(m.b_svec, 1)); + for (int64_t l = 0; l < m.n_double; ++l) + for (int s = 0; s < 2; ++s) + lin_issue(c, m.dbl[(size_t)l].s[s].mod, 1, brows(m.b_svec, 1), + bcol(m.b_mods, m.mod_dbl[s][(size_t)l], 6 * D, 1)); + for (int64_t l = 0; l < m.n_single; ++l) + lin_issue(c, m.sgl[(size_t)l].mod, 1, brows(m.b_svec, 1), + bcol(m.b_mods, m.mod_sgl[(size_t)l], 3 * D, 1)); + lin_issue(c, m.fin_mod, 1, brows(m.b_svec, 1), bcol(m.b_mods, m.mod_fin, 2 * D, 1)); + RAD_ISSUE_N(c, m.op_cu_txt, 2, brows(m.b_cu_txt, 2)); + RAD_ISSUE_N(c, m.op_cu_img, 2, brows(m.b_cu_img, 2)); + RAD_ISSUE_N(c, m.op_cu_all, 2, brows(m.b_cu_all, 2)); + RAD_ISSUE_N(c, m.op_cu_ent, 3, brows(m.b_cu_ent, 3)); + auto mod = [&](int64_t col, int64_t off, int64_t w) { + return bcol(m.b_mods, col + off * D, w, 1); + }; + auto rcu = [&](int64_t n) { return n == L2 ? brows(m.b_cu_img, 2) : brows(m.b_cu_txt, 2); }; + + /* ---- the double blocks */ + for (int64_t l = 0; l < m.n_double; ++l) { + const Double& B = m.dbl[(size_t)l]; + for (int s = 0; s < 2; ++s) { + const Stream& T = B.s[s]; + const int64_t col = m.mod_dbl[s][(size_t)l]; + const int64_t pcol = l > 0 ? m.mod_dbl[s][(size_t)(l - 1)] : 0; + each_run(s, m, [&](int64_t r0, int64_t n) { + const RadOperand x = brow_slice(m.b_x, r0, n, D); + if (l > 0) + RAD_ISSUE_N(c, T.op_n1, n, brow_slice(m.b_f, r0, n, D), mod(pcol, 5, D), + mod(col, 0, 2 * D), RAD_NONE, rcu(n), x, + brow_slice(m.b_h, r0, n, D)); + else + RAD_ISSUE_N(c, T.op_n1, n, RAD_NONE, RAD_NONE, mod(col, 0, 2 * D), RAD_NONE, + rcu(n), x, brow_slice(m.b_h, r0, n, D)); + lin_issue(c, T.qkv, n, brow_slice(m.b_h, r0, n, D), + brow_slice(m.b_qkv, r0, n, 3 * D)); + RAD_ISSUE_N(c, T.op_qk, n, brow_slice(m.b_qkv, r0, n, 3 * D), RAD_NONE, + RAD_W(T.qn), RAD_W(T.kn)); + }); + } + RAD_ISSUE_N(c, B.op_attn, N, bcol(m.b_qkv, 0, D, N), bcol(m.b_qkv, D, D, N), + bcol(m.b_qkv, 2 * D, D, N), brows(m.b_cu_ent, 3), brows(m.b_att, N)); + for (int s = 0; s < 2; ++s) { + const Stream& T = B.s[s]; + const int64_t col = m.mod_dbl[s][(size_t)l]; + each_run(s, m, [&](int64_t r0, int64_t n) { + lin_issue(c, T.proj, n, brow_slice(m.b_att, r0, n, D), brow_slice(m.b_o, r0, n, D)); + RAD_ISSUE_N(c, T.op_n2, n, brow_slice(m.b_o, r0, n, D), mod(col, 2, D), + mod(col, 3, 2 * D), RAD_NONE, rcu(n), brow_slice(m.b_x, r0, n, D), + brow_slice(m.b_h, r0, n, D)); + lin_issue(c, T.mlp1, n, brow_slice(m.b_h, r0, n, D), + brow_slice(m.b_ff, r0, n, m.ff)); + lin_issue(c, T.mlp2, n, brow_slice(m.b_ff, r0, n, m.ff), + brow_slice(m.b_f, r0, n, D)); + }); + } + } + /* The last double block's MLP, gated in, each stream by its own gate. */ + { + const int64_t l = m.n_double - 1; + for (int s = 0; s < 2; ++s) { + const int64_t col = m.mod_dbl[s][(size_t)l]; + each_run(s, m, [&](int64_t r0, int64_t n) { + RAD_ISSUE_N(c, s == kImg ? m.op_gate_img : m.op_gate_txt, n, + brow_slice(m.b_f, r0, n, D), mod(col, 5, D), rcu(n), + brow_slice(m.b_x, r0, n, D)); + }); + } + } + /* ---- the single blocks */ + for (int64_t l = 0; l < m.n_single; ++l) { + const Single& T = m.sgl[(size_t)l]; + const int64_t col = m.mod_sgl[(size_t)l]; + if (l > 0) + RAD_ISSUE_N(c, T.op_n, N, brows(m.b_f, N), mod(m.mod_sgl[(size_t)(l - 1)], 2, D), + mod(col, 0, 2 * D), RAD_NONE, brows(m.b_cu_all, 2), brows(m.b_x, N), + brows(m.b_h, N)); + else + RAD_ISSUE_N(c, T.op_n, N, RAD_NONE, RAD_NONE, mod(col, 0, 2 * D), RAD_NONE, + brows(m.b_cu_all, 2), brows(m.b_x, N), brows(m.b_h, N)); + lin_issue(c, T.l1, N, brows(m.b_h, N), brows(m.b_l1, N)); + RAD_ISSUE_N(c, T.op_qk, N, bcol(m.b_l1, 0, 3 * D, N), RAD_NONE, RAD_W(T.qn), RAD_W(T.kn)); + RAD_ISSUE_N(c, T.op_attn, N, bcol(m.b_l1, 0, D, N), bcol(m.b_l1, D, D, N), + bcol(m.b_l1, 2 * D, D, N), brows(m.b_cu_ent, 3), bcol(m.b_cat, 0, D, N)); + RAD_ISSUE_N(c, T.op_act, N, bcol(m.b_l1, 3 * D, m.ff, N), bcol(m.b_cat, D, m.ff, N)); + lin_issue(c, T.l2, N, brows(m.b_cat, N), brows(m.b_f, N)); + } + /* ---- the output layer over the latent rows (the last single block gated in), the step */ + const int64_t lcol = m.mod_sgl.back(); + RAD_ISSUE_N(c, m.op_fin_n, L2, brow_slice(m.b_f, Cn, L2, D), mod(lcol, 2, D), + mod(m.mod_fin, 0, 2 * D), RAD_NONE, brows(m.b_cu_img, 2), + brow_slice(m.b_x, Cn, L2, D), brow_slice(m.b_h, Cn, L2, D)); + lin_issue(c, m.fin, L2, brow_slice(m.b_h, Cn, L2, D), brows(m.b_v, L2)); + RAD_ISSUE_N(c, m.op_euler, L2, brows(m.b_v, L2), praw(S->sigma, RAD_F32, 2), + praw(S->sigma_next, RAD_F32, 2), praw(S->cfg, RAD_F32, 2), + praw(S->pair, RAD_I32, 2), lanes, praw(S->flags, RAD_I32, 2), + praw(S->seed, RAD_U32, 4), lat_cu, RAD_NONE, RAD_NONE, brows(m.b_lat, LR), + RAD_NONE); +} + +/* A per-head view of rows [first_row, first_row + rows) of a [*, H hd] bf16 buffer: the same + * bytes as [rows H, hd], one head a row (the buffer's liveness is declared on the op). */ +static RadOperand heads(RadCtx* c, rad_buf h, int64_t first_row, int64_t rows, const Model& m) { + const char* p = (const char*)rad_buf_ptr(c, h) + first_row * m.D * 2; + return RAD_P_T2(p, RAD_BF16, rows * m.H, m.hd); +} + +static void step_latent(RadCtx* c, const RadShapeGenBatch* S, const Model& m) { + const int64_t L = m.L, D = m.D; + const int64_t base = (int64_t)S->lane * L; + RAD_ISSUE_N(c, m.op_vcu, 2, brows(m.b_vcu, 2)); + RAD_ISSUE_N(c, m.op_unscale, L, brow_slice(m.b_lat, base, L, m.C), brows(m.b_vl, L)); + lin_issue(c, m.post_kl, L, brows(m.b_vl, L), brows(m.b_vx, L)); + for (const VaeLayer& V : m.vae) { + RAD_ISSUE_N(c, V.op_n1, L, brows(m.b_vx, L), RAD_W(V.n1w), RAD_W(V.n1b), brows(m.b_vh, L)); + lin_issue(c, V.q, L, brows(m.b_vh, L), brows(m.b_vq, L)); + lin_issue(c, V.k, L, brows(m.b_vh, L), brows(m.b_vk, L)); + lin_issue(c, V.v, L, brows(m.b_vh, L), brows(m.b_vv, L)); + RAD_ISSUE_N(c, V.op_qn, L * m.H, heads(c, m.b_vq, 0, L, m), RAD_W(V.qnw), RAD_W(V.qnb), + heads(c, m.b_vqn, 0, L, m)); + RAD_ISSUE_N(c, V.op_kn, L * m.H, heads(c, m.b_vk, 0, L, m), RAD_W(V.knw), RAD_W(V.knb), + heads(c, m.b_vkn, 0, L, m)); + RAD_ISSUE_N(c, V.op_attn, L, brows(m.b_vqn, L), brows(m.b_vkn, L), brows(m.b_vv, L), + brows(m.b_vcu, 2), brows(m.b_vatt, L)); + lin_issue(c, V.proj, L, brows(m.b_vatt, L), brows(m.b_vx, L), brows(m.b_vx, L)); + RAD_ISSUE_N(c, V.op_n2, L, brows(m.b_vx, L), RAD_W(V.n2w), RAD_W(V.n2b), brows(m.b_vh, L)); + lin_issue(c, V.fc, L, brows(m.b_vh, L), brows(m.b_vff, L)); + lin_issue(c, V.out, L, brows(m.b_vff, L), brows(m.b_vx, L), brows(m.b_vx, L)); + } + RAD_ISSUE_N(c, m.op_gn2, L, brows(m.b_vx, L), RAD_W(m.g_n2w), RAD_W(m.g_n2b), brows(m.b_vh, L)); + lin_issue(c, m.g_k, L, brows(m.b_vh, L), brows(m.b_vk, L)); + lin_issue(c, m.g_v, L, brows(m.b_vh, L), brow_slice(m.b_gv, base, L, D)); + RAD_ISSUE_N(c, m.op_gkn, L * m.H, heads(c, m.b_vk, 0, L, m), RAD_W(m.g_knw), RAD_W(m.g_knb), + heads(c, m.b_gk, base, L, m)); +} + +static void step_query(RadCtx* c, const RadShapeGenBatch* S, const Model& m) { + const int64_t n = S->n_query, D = m.D, L = m.L; + const int64_t base = (int64_t)S->lane * L; + RAD_ISSUE_N(c, m.op_four, n, praw2(S->query, RAD_F32, n, 3), brows(m.b_feat, n)); + lin_issue(c, m.q_proj, n, brows(m.b_feat, n), brows(m.b_qx, n)); + RAD_ISSUE_N(c, m.op_qn1, n, brows(m.b_qx, n), RAD_W(m.q_n1w), RAD_W(m.q_n1b), brows(m.b_qh, n)); + lin_issue(c, m.q_q, n, brows(m.b_qh, n), brows(m.b_qq, n)); + RAD_ISSUE_N(c, m.op_qqn, n * m.H, heads(c, m.b_qq, 0, n, m), RAD_W(m.q_qnw), RAD_W(m.q_qnb), + heads(c, m.b_qqn, 0, n, m)); + RAD_ISSUE_N(c, m.op_qattn, n, brows(m.b_qqn, n), brow_slice(m.b_gk, base, L, D), + brow_slice(m.b_gv, base, L, D), praw(S->query_cu, RAD_I32, 2), + praw(S->lat_cu, RAD_I32, 2), brows(m.b_qatt, n)); + lin_issue(c, m.q_o, n, brows(m.b_qatt, n), brows(m.b_qx, n), brows(m.b_qx, n)); + RAD_ISSUE_N(c, m.op_qn3, n, brows(m.b_qx, n), RAD_W(m.q_n3w), RAD_W(m.q_n3b), brows(m.b_qh, n)); + lin_issue(c, m.q_fc, n, brows(m.b_qh, n), brows(m.b_qff, n)); + lin_issue(c, m.q_out, n, brows(m.b_qff, n), brows(m.b_qx, n), brows(m.b_qx, n)); + RAD_ISSUE_N(c, m.op_qpost, n, brows(m.b_qx, n), RAD_W(m.q_pw), RAD_W(m.q_pb), brows(m.b_qh, n)); + lin_issue(c, m.q_head, n, brows(m.b_qh, n), brows(m.b_qlogit, n)); + RAD_ISSUE_N(c, m.op_qcast, n, brows(m.b_qlogit, n), brows(m.b_field, n)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model; + const RadShapeGenBatch* S = batch->sgen_b; + if (!batch->gen || !S) { + rad_step_fail(c, "hunyuan3d2 is a shape generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_SCOND: step_cond(c, S, m); return; + case RAD_GEN_PASS_SSTEP: step_dit(c, S, m); return; + case RAD_GEN_PASS_SLATENT: step_latent(c, S, m); return; + case RAD_GEN_PASS_SQUERY: step_query(c, S, m); return; + default: rad_step_fail(c, "hunyuan3d2: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows of the largest pass: a query pass's points, against a step's two branches. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + const int64_t L = rad_meta_geti(meta, "vae.params.num_latents", 3072); + out->gen_rows = std::max(kMaxQuery, 2 * (kCond + L)); + out->gen_shape = 1; + return RAD_OK; +} + +} /* namespace hunyuan3d2 */ + +RAD_ARCH_PROBE(hunyuan3d2) +RAD_ARCH_PLUGIN(hunyuan3d2, "hunyuan3d2", "", "0.1.0", + "Hunyuan3D-2's shape model: DINOv2-giant over the picture, a flow-matching DiT of " + "16 double and 32 single blocks over 3072 latents, and the shape VAE's geometry " + "decoder sampled at the core's grid points; bf16") diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 4c5ad87a..120d6c60 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -137,6 +137,7 @@ public: int declare_generator(const RadGeneratorDecl* d); int declare_audio_generator(const RadAudioGenDecl* d); int declare_video_generator(const RadVideoGenDecl* d); + int declare_shape_generator(const RadShapeGenDecl* d); void note_v (const char* f, va_list ap); /* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 9aebb1ea..4c4cfb94 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1201,6 +1201,11 @@ int Builder::declare_logits(rad_buf b) { prog_.vgen_str.name.c_str()); return RAD_E_STATE; } + if (prog_.is_shape_generator()) { + err(RAD_E_STATE, "declare_logits: this program already declared the shape generator '%s'", + prog_.sgen_name.c_str()); + return RAD_E_STATE; + } prog_.logits_buf = b; return RAD_OK; } @@ -1241,6 +1246,11 @@ int Builder::declare_pooled(rad_buf b) { prog_.vgen_str.name.c_str()); return RAD_E_STATE; } + if (prog_.is_shape_generator()) { + err(RAD_E_STATE, "declare_pooled: this program already declared the shape generator '%s'", + prog_.sgen_name.c_str()); + return RAD_E_STATE; + } const RadBufDecl& d = prog_.buffers[b].decl; if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 || d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) { @@ -1348,12 +1358,13 @@ int Builder::declare_generator(const RadGeneratorDecl* d) { return RAD_E_STATE; } if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || - prog_.is_audio_generator() || prog_.is_video_generator()) { + prog_.is_audio_generator() || prog_.is_video_generator() || prog_.is_shape_generator()) { err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program " - "generates text, embeds, makes images, audio or video -- one of the five", - nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits" + "generates text, embeds, makes images, audio, video or shapes -- one of " + "the six", nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits" : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" - : prog_.is_audio_generator() ? "an audio generator" : "a video generator"); + : prog_.is_audio_generator() ? "an audio generator" + : prog_.is_video_generator() ? "a video generator" : "a shape generator"); return RAD_E_STATE; } if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID && d->layout != RAD_GEN_LAYOUT_JOINT_STEP) { @@ -1505,13 +1516,14 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { return RAD_E_STATE; } if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || - prog_.generator.layout != 0 || prog_.is_video_generator()) { + prog_.generator.layout != 0 || prog_.is_video_generator() || prog_.is_shape_generator()) { err(RAD_E_STATE, "declare_audio_generator '%s': this program already declared %s; a " - "program generates text, embeds, makes images, audio or video -- one of " - "the five", nm, + "program generates text, embeds, makes images, audio, video or shapes -- " + "one of the six", nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits" : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" - : prog_.generator.layout != 0 ? "an image generator" : "a video generator"); + : prog_.generator.layout != 0 ? "an image generator" + : prog_.is_video_generator() ? "a video generator" : "a shape generator"); return RAD_E_STATE; } if (!d->tmpl && !d->tmpl_plain) { @@ -1682,13 +1694,14 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) { return RAD_E_STATE; } if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || - prog_.generator.layout != 0 || prog_.is_audio_generator()) { + prog_.generator.layout != 0 || prog_.is_audio_generator() || prog_.is_shape_generator()) { err(RAD_E_STATE, "declare_video_generator '%s': this program already declared %s; a " - "program generates text, embeds, makes images, audio or video -- one of " - "the five", nm, + "program generates text, embeds, makes images, audio, video or shapes -- " + "one of the six", nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits" : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" - : prog_.generator.layout != 0 ? "an image generator" : "an audio generator"); + : prog_.generator.layout != 0 ? "an image generator" + : prog_.is_audio_generator() ? "an audio generator" : "a shape generator"); return RAD_E_STATE; } if (!d->tmpl || !std::strstr(d->tmpl, "{prompt}") || d->max_text <= 0) { @@ -1903,6 +1916,108 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) { return RAD_OK; } +/* The shape generator (rad_declare_shape_generator). Checked here rather than at the first request: + * the picture's geometry, the sampler, the grid and the field's buffer, which the core reads back + * after every query pass. */ +int Builder::declare_shape_generator(const RadShapeGenDecl* d) { + if (finished_) { + err(RAD_E_STATE, "declare_shape_generator after declare finished"); + return RAD_E_STATE; + } + if (!d) { err(RAD_E_INVAL, "declare_shape_generator: null declaration"); return RAD_E_INVAL; } + const char* nm = d->name && *d->name ? d->name : "(unnamed)"; + if (prog_.is_shape_generator()) { + err(RAD_E_STATE, "declare_shape_generator: '%s' was already declared; '%s' is a second one", + prog_.sgen_name.c_str(), nm); + return RAD_E_STATE; + } + if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || + prog_.generator.layout != 0 || prog_.is_audio_generator() || prog_.is_video_generator()) { + err(RAD_E_STATE, "declare_shape_generator '%s': this program already declared %s; a " + "program generates text, embeds, makes images, audio, video or shapes -- " + "one of the six", nm, + prog_.logits_buf != RAD_NULL_HANDLE ? "logits" + : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" + : prog_.generator.layout != 0 ? "an image generator" + : prog_.is_audio_generator() ? "an audio generator" : "a video generator"); + return RAD_E_STATE; + } + if (d->canvas < 1 || d->canvas > 4096 || !(d->border_ratio >= 0.0 && d->border_ratio < 1.0) || + d->enc_patch < 1 || d->enc_size < d->enc_patch || d->enc_size > 4096 || + d->enc_size % d->enc_patch != 0) { + err(RAD_E_INVAL, "declare_shape_generator '%s': the picture is out of range (canvas %lld, " + "border %g, encoder %lld in patches of %lld): the canvas 1..4096, the " + "border in [0, 1), the encoder's side 1..4096 and a whole number of " + "patches", nm, (long long)d->canvas, d->border_ratio, + (long long)d->enc_size, (long long)d->enc_patch); + return RAD_E_INVAL; + } + for (int c = 0; c < 3; ++c) + if (!std::isfinite(d->pix_mean[c]) || !(d->pix_std[c] > 0.0) || + !std::isfinite(d->pix_std[c])) { + err(RAD_E_INVAL, "declare_shape_generator '%s': channel %d's mean %g and deviation %g " + "must be finite and the deviation positive", nm, c, d->pix_mean[c], + d->pix_std[c]); + return RAD_E_INVAL; + } + if (d->latent_rows < 1 || d->latent_channels < 1 || d->step_rows < 2 * d->latent_rows) { + err(RAD_E_INVAL, "declare_shape_generator '%s': a latent of %lld rows of %lld channels " + "and a step of %lld rows; a step holds both branches' latents", nm, + (long long)d->latent_rows, (long long)d->latent_channels, (long long)d->step_rows); + return RAD_E_INVAL; + } + if (d->default_steps < 2 || d->max_steps < d->default_steps || d->max_steps > 1000 || + !(d->default_guidance >= 0.0) || !std::isfinite(d->default_guidance)) { + err(RAD_E_INVAL, "declare_shape_generator '%s': the sampler is out of range (%lld steps " + "by default, %lld at most, guidance %g): at least 2 grid points, at most " + "1000, the guidance finite and not negative", nm, + (long long)d->default_steps, (long long)d->max_steps, d->default_guidance); + return RAD_E_INVAL; + } + if (!(d->bounds > 0.0) || !std::isfinite(d->bounds) || !std::isfinite(d->level) || + d->min_resolution < 2 || d->default_resolution < d->min_resolution || + d->max_resolution < d->default_resolution || d->max_resolution > 2048) { + err(RAD_E_INVAL, "declare_shape_generator '%s': the field is out of range (bounds %g, " + "level %g, resolution %lld in %lld..%lld): the bounds positive, the level " + "finite, the resolutions in order from 2 to 2048", nm, d->bounds, + d->level, (long long)d->default_resolution, (long long)d->min_resolution, + (long long)d->max_resolution); + return RAD_E_INVAL; + } + if (d->max_lanes < 1 || d->max_query < 1) { + err(RAD_E_INVAL, "declare_shape_generator '%s': %lld lanes and %lld points a query pass; " + "both at least 1", nm, (long long)d->max_lanes, (long long)d->max_query); + return RAD_E_INVAL; + } + const int64_t n_patch = (d->enc_size / d->enc_patch) * (d->enc_size / d->enc_patch); + const int64_t rows = std::max({ d->step_rows, d->max_query, n_patch, d->latent_rows }); + if (prog_.ctx.max_tok < rows) { + err(RAD_E_INVAL, "declare_shape_generator '%s': a pass carries %lld rows and this one's " + "largest is %lld", nm, (long long)prog_.ctx.max_tok, (long long)rows); + return RAD_E_INVAL; + } + const rad_buf h = d->field_out; + if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_shape_generator '%s': field_out %u is not a declared buffer", nm, + (unsigned)h); + return RAD_E_INVAL; + } + const RadBufDecl& ob = prog_.buffers[h].decl; + if (ob.dtype != RAD_F32 || ob.domain != RAD_DOMAIN_DEVICE || + decl_numel(ob.rank, ob.shape) < d->max_query) { + err(RAD_E_INVAL, "declare_shape_generator '%s': field_out '%s' must be a device f32 " + "buffer of at least %lld elements", nm, prog_.buffers[h].name.c_str(), + (long long)d->max_query); + return RAD_E_INVAL; + } + prog_.sgen_name = nm; + prog_.shape_gen = *d; + /* As for the other generators: the Program is moved after declare; the name lives in + * sgen_name. */ + prog_.shape_gen.name = nullptr; + return RAD_OK; +} + /* Validates the draft head at declare rather than at the first draft pass, where a bad decl would * only show as zero acceptance. `depth` must equal RadBuildCtx::max_spec, which the plugin sized * its buffers with. */ @@ -2745,6 +2860,11 @@ int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d) { return B(b)->declare_video_generator(d); } +int rad_declare_shape_generator(RadBuilder* b, const RadShapeGenDecl* d) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_shape_generator(d); +} + void rad_note(RadBuilder* b, const char* f, ...) { if (!b) return; va_list ap; diff --git a/core/device/aql.cpp b/core/device/aql.cpp index bf291647..782884e8 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -589,7 +589,7 @@ KernelRec* kernel_for(const void* stub, int ord, std::string* why) { struct Stream { uint64_t magic = kStreamMagic; int ord = 0; - uint32_t id = 0; /* index into g_queue_by_id, never reused */ + uint32_t id = 0; /* queue_of's key, never reused (see there) */ hsa_agent_t agent{}; hsa_queue_t* q = nullptr; uint64_t mask = 0; @@ -623,12 +623,27 @@ struct Stream { void unlock() { busy.store(false, std::memory_order_release); } }; -/* Every queue this process has made, by an id that is never reused, so "packet i of queue n" - * stays meaningful after the queue is destroyed. A destroyed queue's entry is null; everything - * it held has been consumed. */ +/* Every live queue, by an id that is never reused, so "packet i of queue n" stays meaningful after + * the queue is destroyed: queue_of answers null for a destroyed queue's id, and everything it held + * has been consumed. At most kMaxQueues are live at once; a destroyed queue's slot is taken again + * under a new generation, id = generation * kMaxQueues + slot, so a stale id never names the + * slot's next queue. */ constexpr uint32_t kMaxQueues = 1024; std::atomic g_queue_by_id[kMaxQueues]; -std::atomic g_next_queue_id{0}; +std::atomic g_queue_id_at[kMaxQueues]; /* the id holding each slot now */ +std::mutex g_queue_slot_mu; +std::vector g_queue_free; /* destroyed queues' slots */ +uint32_t g_queue_next_slot = 0; +uint32_t g_queue_gen[kMaxQueues]; + +/* The queue an id names, or null once it is destroyed. The slot's id is stored before its queue + * (release), so a queue read here that belongs to a later generation is seen with that + * generation's id and refused. */ +inline hsa_queue_t* queue_of(uint32_t id) { + const uint32_t slot = id % kMaxQueues; + hsa_queue_t* q = g_queue_by_id[slot].load(std::memory_order_acquire); + return g_queue_id_at[slot].load(std::memory_order_acquire) == id ? q : nullptr; +} inline Stream* ours(const void* s) { if ((uintptr_t)s < 4096) return nullptr; @@ -1127,6 +1142,9 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t if (!gx || !gy || !gz) return RAD_OK; if (gx > UINT32_MAX || gy > UINT32_MAX || gz > UINT32_MAX) return RAD_E_INVAL; if ((uint64_t)k->group_size + shm > 65536) return RAD_E_INVAL; + /* The packet's fields are 16 bits wide and the card runs at most 1024 work-items a group; + * HIP refuses a larger block, and so does this. */ + if ((uint64_t)b.x * b.y * b.z > 1024) return RAD_E_INVAL; alignas(64) unsigned char ka[kKargMax]; const uint32_t n = (k->kernarg_size + 15u) & ~15u; @@ -1562,6 +1580,7 @@ int a_stream_create(RadStream* out, int high_priority) { if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 2) * kKargSlot, 0, &ka) != HSA_STATUS_SUCCESS || hsa_amd_agents_allow_access(1, &kpeer, nullptr, ka) != HSA_STATUS_SUCCESS) { + if (ka) hsa_amd_memory_pool_free(ka); /* allocated, then refused access */ hsa_queue_destroy(s->q); device_set_error("rad_stream_create: the kernel argument ring could not be placed in %s", d.host_kargs ? "pinned host memory" : "VRAM the host can write"); @@ -1582,17 +1601,28 @@ int a_stream_create(RadStream* out, int high_priority) { s->bounce = static_cast(bb); note_alloc(ka, (int64_t)(s->mask + 2) * kKargSlot, -1); note_alloc(bb, kBounceBytes, -1); - s->id = g_next_queue_id.fetch_add(1, std::memory_order_relaxed); - if (s->id >= kMaxQueues) { + uint32_t slot = kMaxQueues; + { + std::lock_guard lk(g_queue_slot_mu); + if (!g_queue_free.empty()) { + slot = g_queue_free.back(); + g_queue_free.pop_back(); + } else if (g_queue_next_slot < kMaxQueues) { + slot = g_queue_next_slot++; + } + if (slot < kMaxQueues) s->id = g_queue_gen[slot]++ * kMaxQueues + slot; + } + if (slot >= kMaxQueues) { note_free(bb); note_free(ka); hsa_amd_memory_pool_free(bb); hsa_amd_memory_pool_free(ka); hsa_queue_destroy(s->q); - device_set_error("rad_stream_create: more than %u streams in one process", kMaxQueues); + device_set_error("rad_stream_create: more than %u streams live at once", kMaxQueues); return RAD_E_NOMEM; } - g_queue_by_id[s->id].store(s->q, std::memory_order_release); + g_queue_id_at[slot].store(s->id, std::memory_order_release); + g_queue_by_id[slot].store(s->q, std::memory_order_release); { std::lock_guard lk(G().streams_mu); G().streams.push_back(s.get()); @@ -1604,14 +1634,24 @@ int a_stream_create(RadStream* out, int high_priority) { void a_stream_destroy(RadStream rs) { Stream* s = ours(rs); if (!s) return; - (void)stream_drain(s); + /* Undrained (a closed gate, a fault), the queue may still be read by the card, and so may its + * kernel argument ring: both are left allocated rather than freed under it. */ + if (const int rc = stream_drain(s); rc < 0) { + RAD_WARN("device: a stream was destroyed with work it could not drain (%s); its queue and " + "argument ring stay allocated", rad_strerror(rc)); + return; + } { std::lock_guard lk(G().streams_mu); auto& v = G().streams; for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; } } - g_queue_by_id[s->id].store(nullptr, std::memory_order_release); + g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release); hsa_queue_destroy(s->q); + { + std::lock_guard lk(g_queue_slot_mu); + g_queue_free.push_back(s->id % kMaxQueues); + } note_free(s->karg); note_free(s->bounce); hsa_amd_memory_pool_free(s->karg); @@ -1676,7 +1716,7 @@ bool xp_list_finished(int ord, uint32_t k); bool reusable(const Sig* g) { if (g->stamped || hsa_signal_load_relaxed(g->h) != 0) return false; for (const auto& w : g->waiters) { - hsa_queue_t* q = g_queue_by_id[w.first].load(std::memory_order_acquire); + hsa_queue_t* q = queue_of(w.first); if (q && hsa_queue_load_read_index_relaxed(q) <= w.second) return false; } const int32_t xd = g->xp_dev.load(std::memory_order_acquire); @@ -1902,7 +1942,7 @@ std::vector g_tape_retired; * kReserveMargin past it has launched, which proves it as in reserve(). */ bool tape_idle(const Tape* t) { for (const auto& l : t->last) { - hsa_queue_t* q = g_queue_by_id[l.first].load(std::memory_order_acquire); + hsa_queue_t* q = queue_of(l.first); if (q && hsa_queue_load_read_index_scacquire(q) < l.second + kReserveMargin) return false; } return true; diff --git a/core/device/device.h b/core/device/device.h index fc35ec41..76596661 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -406,7 +406,8 @@ int64_t dev_stuck_ms(); constexpr int kTapeOverlapRun = 6; /* ------------------------------------------------------------------ the allocation ledger - * What rad_dev_alloc has handed out since process start, by RAD_MEM_* kind. It does not see a + * By RAD_MEM_* kind: the bytes rad_dev_alloc has handed out and rad_dev_free has not taken back, + * and the number of allocations since process start. It does not see a * kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */ void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count); diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 2a076734..03ee4f2b 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -143,6 +144,26 @@ struct Ledger { std::atomic count{0}; }; Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kind */ +/* Each live allocation's size, so rad_dev_free (which has none) takes it back off the ledger's + * bytes: pinned ranges are freed and taken again during bring-up, and the pin-cap check reads the + * ledger as what the process holds. Allocations are rare, never per step. */ +struct LiveAlloc { int64_t bytes; int kind; }; +std::mutex g_ledger_mu; +std::unordered_map g_ledger_live; + +void ledger_add(void* p, int64_t bytes, int kind) { + g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed); + std::lock_guard lk(g_ledger_mu); + g_ledger_live[p] = LiveAlloc{ bytes, kind }; +} +void ledger_drop(void* p) { + if (!p) return; + std::lock_guard lk(g_ledger_mu); + const auto it = g_ledger_live.find(p); + if (it == g_ledger_live.end()) return; + g_ledger[it->second.kind].bytes.fetch_sub(it->second.bytes, std::memory_order_relaxed); + g_ledger_live.erase(it); +} /* Live event handles, counted here so the number is backend-independent; the only place an * event leaked at teardown shows. */ @@ -421,7 +442,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) { thread_local int64_t t_device_ordinal = 0; void* p = dev()->alloc(bytes, kind); if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) { - rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed); + rad::ledger_add(p, bytes, kind); const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1; const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total; const int64_t floor_ = rad::trace_floor(); @@ -447,8 +468,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) { return p; } void rad_dev_free(void* p, int kind) { - /* The ledger counts allocations, not live bytes: rad_dev_free has no size. The engine frees - * only at teardown, so the two agree while running. */ + rad::ledger_drop(p); dev()->free(p, kind); } void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); } @@ -665,7 +685,7 @@ void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) { } void* p = f(fd, foff, bytes); if (p) { - rad::g_ledger[RAD_MEM_HOST_MAPPED].bytes.fetch_add(bytes, std::memory_order_relaxed); + rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED); rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed); } return p; diff --git a/core/device/host.cpp b/core/device/host.cpp index e739d0ac..60d28d68 100644 --- a/core/device/host.cpp +++ b/core/device/host.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -723,6 +724,21 @@ constexpr int64_t kVmemGranule = RAD_ALIGN_POOL; int64_t h_vmem_granularity(void) { return kVmemGranule; } +/* Each reservation's card, recorded at reserve: the thread that later commits into a pool, or + * releases it at teardown, may have selected another card, and the pages count against the card + * the range was reserved for (as the AQL backend's VRes does). Keyed by base. */ +struct VRange { char* end; int device; }; +std::mutex g_vres_mu; +std::map g_vres; + +int vmem_device_of(const void* addr) { + std::lock_guard lk(g_vres_mu); + auto it = g_vres.upper_bound((const char*)addr); + if (it == g_vres.begin()) return t_device; + --it; + return (const char*)addr < it->second.end ? it->second.device : t_device; +} + void* h_vmem_reserve(int64_t bytes, int64_t align) { if (bytes <= 0) return nullptr; if (align < kVmemGranule) align = kVmemGranule; @@ -740,11 +756,20 @@ void* h_vmem_reserve(int64_t bytes, int64_t align) { if (head) ::munmap(raw, head); const size_t tail = raw_len - head - (size_t)bytes; if (tail) ::munmap(base + bytes, tail); + { + std::lock_guard lk(g_vres_mu); + g_vres[base] = VRange{ base + bytes, t_device }; + } return base; } void h_vmem_release(void* base, int64_t bytes) { - if (base && bytes > 0) ::munmap(base, (size_t)bytes); + if (!base || bytes <= 0) return; + { + std::lock_guard lk(g_vres_mu); + g_vres.erase((const char*)base); + } + ::munmap(base, (size_t)bytes); } int h_vmem_commit(void* addr, int64_t bytes) { @@ -755,7 +780,7 @@ int h_vmem_commit(void* addr, int64_t bytes) { device_set_error("vmem_commit(%p, %lld): mmap failed", addr, (long long)bytes); return RAD_E_NOMEM; } - g_used[t_device].fetch_add(bytes, std::memory_order_relaxed); + g_used[vmem_device_of(addr)].fetch_add(bytes, std::memory_order_relaxed); return RAD_OK; } @@ -769,7 +794,7 @@ int h_vmem_decommit(void* addr, int64_t bytes) { device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes); return RAD_E_INVAL; } - g_used[t_device].fetch_sub(bytes, std::memory_order_relaxed); + g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed); return RAD_OK; } diff --git a/core/engine.cpp b/core/engine.cpp index 83d8d62f..1178c604 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -6,6 +6,7 @@ #include "gen/driver.h" #include "gen/audio_driver.h" #include "gen/video_driver.h" +#include "gen/shape_driver.h" #include "kld.h" #include "mm/processor.h" #include "mm/media.h" @@ -1809,17 +1810,20 @@ int Engine::serve(std::unique_ptr watch) { embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE; const bool audio_gen = ranks_[0]->program.is_audio_generator(); const bool video_gen = ranks_[0]->program.is_video_generator(); + const bool shape_gen = ranks_[0]->program.is_shape_generator(); const bool generator = ranks_[0]->program.is_pass_driven(); if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) { RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output " "(rad_declare_pooled) and no generator (rad_declare_generator, " - "rad_declare_audio_generator, rad_declare_video_generator), so a step produces " + "rad_declare_audio_generator, rad_declare_video_generator, " + "rad_declare_shape_generator), so a step produces " "nothing anyone can read. An encoder-only plugin cannot serve.", plugins_.arch_plugin.c_str()); return RAD_E_UNSUPPORTED; } if (generator) { - const char* const what = audio_gen ? "audio" : video_gen ? "video" : "images"; + const char* const what = audio_gen ? "audio" : video_gen ? "video" + : shape_gen ? "shapes" : "images"; if (cfg_.kld() || cfg_.n_spec > 0) { RAD_ERR("the '%s' plugin makes %s: --kld and speculative decoding have no tokens to " "work on", plugins_.arch_plugin.c_str(), what); @@ -1828,6 +1832,7 @@ int Engine::serve(std::unique_ptr watch) { for (size_t i = 1; i < ranks_.size(); ++i) if (ranks_[i]->program.is_audio_generator() != audio_gen || ranks_[i]->program.is_video_generator() != video_gen || + ranks_[i]->program.is_shape_generator() != shape_gen || !ranks_[i]->program.is_pass_driven()) { RAD_ERR("rank %zu declared a different generator from rank 0's", i); return RAD_E_STATE; @@ -1838,6 +1843,8 @@ int Engine::serve(std::unique_ptr watch) { "after them" : video_gen ? "a video generator: a prompt is read by its own request's steps and keeps no KV" + : shape_gen + ? "a shape generator: a picture is read by its own request's steps and keeps no KV" : "an image generator: a conditioning is read by its own request's images and by " "nothing after them"; decide("--no-prefix-cache", "prefix caching off", prefix_off_why_); @@ -1994,7 +2001,16 @@ int Engine::serve(std::unique_ptr watch) { rio.push_back({ rk->device, rk->ctx.stream(), &rk->program, rk->pools.kv().base(), rank_stream_views_[r].data() }); } - if (video_gen) { + if (shape_gen) { + /* As for the image generator below. */ + std::vector gio; + for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() }); + auto d = std::make_unique(); + RAD_TRY(d->init(ranks_[0]->program, gio)); + shp_gen_ = d.get(); + gen_ = std::move(d); + RAD_TRY(rad_dev_set(ranks_[0]->device)); + } else if (video_gen) { /* As for the image generator below; the plugin lays out each request's rows. */ std::vector gio; for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() }); @@ -2596,6 +2612,7 @@ int Engine::run_server() { o.image_model = img_gen_ != nullptr; o.audio_model = aud_gen_ != nullptr; o.video_model = vid_gen_ != nullptr; + o.shape_model = shp_gen_ != nullptr; o.decision_type = rad_meta_gets(&meta_, "decision.type", ""); /* clef's learned scalars, which the server applies to what the head returns (server/clef.h); * rad-convert writes them beside decision.type. */ @@ -3159,6 +3176,29 @@ int Engine::run_server() { /* A video generator's endpoints: the driver's queue and the declared prompt, sizes and * lengths. */ + struct ShapeBridge final : server::IShapeGen { + gen::ShapeDriver* drv = nullptr; + const gen::ShapeGenInfo& info() const override { return drv->info(); } + int submit(std::unique_ptr r, std::string* why) override { + return drv->submit(std::move(r), why); + } + int64_t queued() const override { return drv->queued(); } + int64_t running() const override { return drv->running(); } + } shape_bridge; + if (shp_gen_) { + shape_bridge.drv = shp_gen_; + d.shapes = &shape_bridge; + const gen::ShapeGenInfo& in = shp_gen_->info(); + if (cfg_.served_model_name.empty() && !in.name.empty()) { + o.model_id = in.name; + decide("--served-model-name", o.model_id, "a shape generator: its own name"); + } + RAD_INFO("shape: '%s', a %lldx%lld picture to a field sampled at %lld cells a side by " + "default (%lld..%lld), %lld steps by default at guidance %g", + in.name.c_str(), (long long)in.canvas, (long long)in.canvas, + (long long)in.default_resolution, (long long)in.min_resolution, + (long long)in.max_resolution, (long long)in.default_steps, in.default_guidance); + } struct VideoBridge final : server::IVideoGen { gen::VideoDriver* drv = nullptr; server::VideoGenInfo inf; @@ -3308,6 +3348,9 @@ int Engine::run_server() { else if (vid_gen_) RAD_INFO("serving on http://%s:%d (/v1/videos; completions and chat are 501%s)", o.host.c_str(), o.port, keyed); + else if (shp_gen_) + RAD_INFO("serving on http://%s:%d (/generate, /send and /status/{uid}; completions and " + "chat are 501%s)", o.host.c_str(), o.port, keyed); else if (gen_) RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are " "501%s)", o.host.c_str(), o.port, diff --git a/core/engine.h b/core/engine.h index 13bd3d43..1fc219ab 100644 --- a/core/engine.h +++ b/core/engine.h @@ -50,7 +50,7 @@ namespace rad { class Kld; class StallWatch; -namespace gen { class Driver; class AudioDriver; class VideoDriver; struct IPassDriver; } +namespace gen { class Driver; class AudioDriver; class VideoDriver; class ShapeDriver; struct IPassDriver; } namespace server { class Sink; } struct TierPump; struct TierJob; @@ -431,14 +431,16 @@ private: int collect_pooled_issue(const RadBatch* b, StepOut& so); int collect_pooled(const RadBatch* b, StepOut& so); /* A generator (rad_declare_generator, rad_declare_audio_generator, - * rad_declare_video_generator): the driver that turns requests into passes and the loop that - * runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every other - * program. `img_gen_`, `aud_gen_` and `vid_gen_` are the same driver by its kind, for the - * endpoints; one of them is set when `gen_` is. */ + * rad_declare_video_generator, rad_declare_shape_generator): the driver that turns requests + * into passes and the loop that runs them, replacing the scheduler and step loop + * (engine_gen.cpp). Null for every other program. `img_gen_`, `aud_gen_`, `vid_gen_` and + * `shp_gen_` are the same driver by its kind, for the endpoints; one of them is set when + * `gen_` is. */ std::unique_ptr gen_; gen::Driver* img_gen_ = nullptr; gen::AudioDriver* aud_gen_ = nullptr; gen::VideoDriver* vid_gen_ = nullptr; + gen::ShapeDriver* shp_gen_ = nullptr; int gen_loop(); /* Zeroes the state slots the KV manager granted since the last step, on every rank's stream, * before the step or pass that first reads them. */ diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index c290455e..1df6f69a 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -11,6 +11,7 @@ #include "gen/driver.h" #include "gen/audio_driver.h" #include "gen/video_driver.h" +#include "gen/shape_driver.h" #include "build/startup.h" #include "build/rad_build.h" @@ -1110,6 +1111,25 @@ int Engine::declare() { if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0; if (cfg_.n_spec < 0) cfg_.n_spec = 0; cfg_.prefix_cache = false; + } else if (pb.gen_rows > 0 && pb.gen_shape) { + if (!cfg_.given.count("--max-num-batched-tokens")) { + cfg_.max_tok = pb.gen_rows; + decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok), + "a shape generator: a denoising step's two branches or a query pass's " + "points, whichever is more"); + } + if (!cfg_.given.count("--max-num-seqs")) { + cfg_.max_seqs = 1; + decide("--max-num-seqs", "1", "a shape generator: a pass is one request's"); + } + if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) { + cfg_.max_ctx = pb.gen_rows; + decide("--max-model-len", std::to_string(cfg_.max_ctx), + "a shape generator: a pass's rows"); + } + if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0; + if (cfg_.n_spec < 0) cfg_.n_spec = 0; + cfg_.prefix_cache = false; } else if (pb.gen_rows > 0 && pb.gen_video) { if (!cfg_.given.count("--max-num-batched-tokens")) { cfg_.max_tok = pb.gen_rows; @@ -1809,6 +1829,7 @@ int Engine::plan() { f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program) : r->program.is_audio_generator() ? gen::AudioDriver::device_bytes(r->program) : r->program.is_video_generator() ? gen::VideoDriver::device_bytes(r->program) + : r->program.is_shape_generator() ? gen::ShapeDriver::device_bytes(r->program) : BatchBuilder::device_bytes(r->program, cfg_, kg); if (f.staging < 0) return RAD_E_INVAL; late_step_bytes_ = std::max(late_step_bytes_, f.staging); @@ -4185,6 +4206,8 @@ int Engine::load_vocab() { return RAD_E_FORMAT; } RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), vs.h, vb)); + } else if (meta_textless(rad_meta_gets(&meta_, "radiance.text", nullptr))) { + vocab_textless(vb); } else if (ckpt_->is_gguf()) { /* GGUF names its pre-tokeniser; the chain is reconstructed from the name or refused (a * container converted with --tokenizer bakes in the declared one). */ diff --git a/core/engine_gen.cpp b/core/engine_gen.cpp index e4e02569..862f95a8 100644 --- a/core/engine_gen.cpp +++ b/core/engine_gen.cpp @@ -1,6 +1,6 @@ /* engine_gen.cpp -- a generator's loop: the driver's passes (core/gen/pass.h; driver.h for - * images, audio_driver.h for audio, video_driver.h for video) run on the ranks like token steps, one at a time, each drained - * before the next. + * images, audio_driver.h for audio, video_driver.h for video, shape_driver.h for shapes) run on the + * ranks like token steps, one at a time, each drained before the next. * * Draining is cheap: a pass is tens to thousands of milliseconds of device work, and the next * pass depends only on the driver's host bookkeeping, so the wait costs the microseconds of @@ -29,6 +29,12 @@ static const char* pass_name(int gen) { case RAD_GEN_PASS_ADECODE: return "adecode"; case RAD_GEN_PASS_VDECODE: return "vdecode"; case RAD_GEN_PASS_VUPSCALE: return "vupscale"; + case RAD_GEN_PASS_VENCODE: return "vencode"; + case RAD_GEN_PASS_AENCODE: return "aencode"; + case RAD_GEN_PASS_SCOND: return "scond"; + case RAD_GEN_PASS_SSTEP: return "sstep"; + case RAD_GEN_PASS_SLATENT: return "slatent"; + case RAD_GEN_PASS_SQUERY: return "squery"; default: return ""; } } diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 66739bfc..982aef00 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace rad { @@ -688,6 +689,124 @@ int Checkpoint::open_diffusers() { return RAD_OK; } +/* config.yaml's maps of scalars as dotted keys, a list's items space-separated, booleans as 1 and + * 0 and a trailing comment dropped: the subset Hunyuan3D-2's configs are written in. Anything else + * (a multi-line value, a list of maps) is refused, not guessed at. */ +static int meta_from_yaml(const std::string& path, MetaOwn* out) { + std::ifstream f(path); + if (!f) { + RAD_ERR("%s: cannot read", path.c_str()); + return RAD_E_IO; + } + std::vector> stack; /* indentation, key */ + std::string line; + int ln = 0; + auto trim = [](std::string s) { + const size_t a = s.find_first_not_of(" \t\r"), b = s.find_last_not_of(" \t\r"); + return a == std::string::npos ? std::string() : s.substr(a, b - a + 1); + }; + while (std::getline(f, line)) { + ++ln; + if (const size_t h = line.find(" #"); h != std::string::npos) line.resize(h); + const std::string body = trim(line); + if (body.empty() || body[0] == '#') continue; + const size_t ind = line.find_first_not_of(' '); + const size_t colon = body.find(':'); + if (colon == std::string::npos || body[0] == '-') { + RAD_ERR("%s:%d: not a `key: value` line of the YAML this importer reads", path.c_str(), ln); + return RAD_E_FORMAT; + } + while (!stack.empty() && stack.back().first >= ind) stack.pop_back(); + const std::string key = trim(body.substr(0, colon)); + std::string val = trim(body.substr(colon + 1)); + std::string full; + for (const auto& s : stack) full += s.second + "."; + full += key; + if (val.empty()) { + stack.emplace_back(ind, key); + continue; + } + if (val.front() == '[') { + if (val.back() != ']') { + RAD_ERR("%s:%d: a list must close on its line", path.c_str(), ln); + return RAD_E_FORMAT; + } + std::string items; + for (char& ch : val) if (ch == '[' || ch == ']' || ch == ',') ch = ' '; + std::istringstream is(val); + for (std::string it; is >> it;) items += (items.empty() ? "" : " ") + it; + val = items; + } else if (val == "True" || val == "true") { + val = "1"; + } else if (val == "False" || val == "false") { + val = "0"; + } else if (val.size() >= 2 && (val.front() == '"' || val.front() == '\'') && + val.back() == val.front()) { + val = val.substr(1, val.size() - 2); + } + out->set(full, val); + } + return RAD_OK; +} + +/* A Hunyuan3D-2 shape model (tencent/Hunyuan3D-2's hunyuan3d-dit-v2-0 and its kin): a folder of + * config.yaml and one safetensors holding three networks under `model.` (the DiT), + * `conditioner.` (DINOv2's image encoder) and `vae.` (the shape VAE), the names kept. config.yaml's + * keys go into the metadata by dotted path (model.params.hidden_size, vae.params.scale_factor, + * conditioner.params.main_image_encoder.kwargs.config.num_hidden_layers, ...). The architecture + * is `hunyuan3d2`, and the model reads no text (`radiance.text` none). */ +int Checkpoint::open_hy3d(const std::string& weights) { + kind_ = SafeT; + RAD_TRY(add_shard(weights)); + RAD_TRY(meta_from_yaml(dir_ + "/config.yaml", &meta_)); + meta_.arch = "hunyuan3d2"; + meta_.set("radiance.text", "none"); + /* The typed dimensions are the denoiser's: its blocks, width and heads, read off its tensors; + * the vocabulary is the one token of a model that reads no text, and the context a step's + * rows (both branches of the 1370 conditioning rows and the latent). */ + { + RadModelMeta& m = meta_.m; + const SrcTensor* lat = find("model.latent_in.weight"); + const SrcTensor* mlp = find("model.double_blocks.0.img_mlp.0.weight"); + const SrcTensor* qn = find("model.double_blocks.0.img_attn.norm.query_norm.scale"); + const SrcTensor* vae = find("vae.post_kl.weight"); + int64_t layers = 0; + while (find("model.double_blocks." + std::to_string(layers) + ".img_mod.lin.weight")) + ++layers; + for (int64_t s = 0; find("model.single_blocks." + std::to_string(s) + ".linear1.weight"); ++s) + ++layers; + if (!lat || lat->shape.size() != 2 || !mlp || mlp->shape.size() != 2 || !qn || + qn->shape.size() != 1 || qn->shape[0] <= 0 || !vae || !layers) { + RAD_ERR("%s: Hunyuan3D-2's DiT or shape VAE is incomplete", weights.c_str()); + return RAD_E_FORMAT; + } + m.n_layers = layers; + m.n_embd = lat->shape[0]; + m.head_dim = qn->shape[0]; + m.n_head = m.n_head_kv = m.n_embd / m.head_dim; + m.n_ff = mlp->shape[0]; + m.n_vocab = 1; + m.n_ctx_train = 2 * (1370 + 3072); + m.rms_eps = 1e-6f; + m.rope_theta = 10000.0f; + m.rope_scale = 1.0f; + } + meta_.finish(); + return RAD_OK; +} + +/* Whether `file` is a Hunyuan3D-2 shape checkpoint: its DiT and image encoder by name. */ +static bool hy3d_weights(const std::string& file) { + SafeTensorsFile probe; + if (probe.open(file) != RAD_OK) return false; + bool dit = false, enc = false; + for (const auto& t : probe.tensors()) { + dit = dit || t.name == "model.latent_in.weight"; + enc = enc || t.name.rfind("conditioner.main_image_encoder.", 0) == 0; + } + return dit && enc; +} + /* A single-file Stable Diffusion XL checkpoint in Stability's (sgm) layout, the form SDXL and its * finetunes (Illustrious, NoobAI, Pony and the rest) are published in: one safetensors holding * @@ -887,6 +1006,16 @@ int Checkpoint::open_safetensors(const std::string& path) { ((path_exists(dir_ + "/model_index.json") && !path_exists(dir_ + "/config.json")) || path_exists(dir_ + "/modular_model_index.json"))) return open_diffusers(); + /* A Hunyuan3D-2 shape model: config.yaml beside its one safetensors (the fp16 one when the + * folder holds both). */ + if (!is_index && path_exists(dir_ + "/config.yaml")) { + std::string w = path; + if (!is_file) + for (const char* f : { "/model.fp16.safetensors", "/model.safetensors" }) + if (path_exists(dir_ + f)) { w = dir_ + f; break; } + if (w != path || is_file) + if (hy3d_weights(w)) return open_hy3d(w); + } if (is_file) { shards.push_back(path); /* A single-file Stable Diffusion XL checkpoint, as Stability and every SDXL finetune diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 27821d4a..5bcdb44f 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -209,6 +209,7 @@ private: int open_safetensors(const std::string& path); int open_diffusers(); int open_sgm(); + int open_hy3d(const std::string& weights); int add_companions(); int add_torch_files(); int open_gguf(const std::string& path); diff --git a/core/format/imatrix.cpp b/core/format/imatrix.cpp index 4b9568a9..9e289d5d 100644 --- a/core/format/imatrix.cpp +++ b/core/format/imatrix.cpp @@ -56,6 +56,9 @@ struct Cursor { case GT_ARR: { uint32_t et = 0; uint64_t n = 0; if (!get(&et) || !get(&n)) return false; + /* An array of arrays is refused, as the GGUF reader refuses it: each level costs a + * file 12 bytes and this walker a stack frame. */ + if (et == GT_ARR) { ok = false; return false; } for (uint64_t i = 0; i < n && ok; ++i) if (!skip_value(et)) return false; return ok; } diff --git a/core/format/radfile.cpp b/core/format/radfile.cpp index c8167e96..9d7946d7 100644 --- a/core/format/radfile.cpp +++ b/core/format/radfile.cpp @@ -48,7 +48,7 @@ void RadFile::close() { int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const { if (fd_ < 0) { RAD_ERR("read_at on a closed container"); return RAD_E_STATE; } - if (off < 0 || bytes < 0 || off + bytes > size_) { + if (off < 0 || bytes < 0 || off > size_ || bytes > size_ - off) { RAD_ERR("read_at [%lld, %lld) is outside the %lld-byte container", (long long)off, (long long)(off + bytes), (long long)size_); return RAD_E_FORMAT; @@ -210,6 +210,21 @@ int RadFile::validate() { return RAD_E_FORMAT; } + /* The tables are read in place through typed pointers, so each must sit on its element's + * alignment (the writer places every one 8-aligned), as the vocab section's arrays must. */ + auto aligned = [&](uint64_t off, uint64_t count, size_t align, const char* what) { + if (count == 0 || off % align == 0) return true; + RAD_ERR("%s: %s starts at %llu, which is not %zu-aligned", path_.c_str(), what, + (unsigned long long)off, align); + return false; + }; + if (!aligned(hdr_->meta_off, hdr_->meta_count, alignof(RadFileKV), "the metadata table") || + !aligned(hdr_->dir_off, hdr_->dir_count, alignof(RadFileEntry), "the weight directory") || + !aligned(hdr_->plane_off, hdr_->plane_count, alignof(RadFilePlane), "the plane table") || + !aligned(hdr_->enc_off, hdr_->enc_count, alignof(RadEncoding), "the encoding table") || + !aligned(hdr_->prof_off, hdr_->prof_count, alignof(RadFileProfile), "the expert profile")) + return RAD_E_FORMAT; + meta_ = (const RadFileKV*)(base_ + hdr_->meta_off); dir_ = (const RadFileEntry*)(base_ + hdr_->dir_off); planes_ = (const RadFilePlane*)(base_ + hdr_->plane_off); @@ -335,18 +350,21 @@ int RadFile::validate() { } const RadVocabHeader* v = (const RadVocabHeader*)(base_ + voff); /* Offset 0 means an optional array is absent (scores are unigram-only; types default to - * normal). Nothing real lives at file offset 0. */ - auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) { - return bytes == 0 || off == 0 || - (off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) && - off % align == 0); + * normal). Nothing real lives at file offset 0. Token texts, merges and steps are not + * optional: the writer places each one its count says exists, and a reader handed a + * count with no array would read the file header in its place. */ + auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align, bool optional) { + if (bytes == 0) return true; + if (off == 0) return optional; + return off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) && + off % align == 0; }; const uint64_t nt = v->n_tokens, nm = v->n_merges, ns = v->n_steps; - if (!arr_ok(v->tok_text_off, nt * sizeof(rad_stroff), alignof(rad_stroff)) || - !arr_ok(v->tok_score_off, nt * sizeof(float), alignof(float)) || - !arr_ok(v->tok_type_off, nt, 1) || - !arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t)) || - !arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep))) { + if (!arr_ok(v->tok_text_off, nt * sizeof(rad_stroff), alignof(rad_stroff), false) || + !arr_ok(v->tok_score_off, nt * sizeof(float), alignof(float), true) || + !arr_ok(v->tok_type_off, nt, 1, true) || + !arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t), false) || + !arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep), false)) { RAD_ERR("%s: the %s section's arrays do not fit inside it, or one is not aligned to its " "element", path_.c_str(), what); @@ -458,7 +476,17 @@ int RadFile::index_experts() { return RAD_E_FORMAT; } const uint64_t ebase = dir_[j].offset; - if (e_id == 1) g.stride = ebase - g.base; + if (e_id == 1) { + /* Expert 1 defines the stride, so the arithmetic test below cannot check it: it + * must step forward by at least one whole unit, or experts overlap (or wrap). */ + if (ebase < g.base || ebase - g.base < g.unit_bytes) { + RAD_ERR("%s: layer %d expert 1 starts at %llu, inside or before expert 0's " + "%llu bytes at %llu", path_.c_str(), layer, (unsigned long long)ebase, + (unsigned long long)g.unit_bytes, (unsigned long long)g.base); + return RAD_E_FORMAT; + } + g.stride = ebase - g.base; + } if (ebase != g.base + (uint64_t)e_id * g.stride) { RAD_ERR("%s: layer %d expert %d starts at %llu, but base + %d*%llu is %llu -- the " "layer has no fixed stride and cannot be addressed by arithmetic", @@ -565,8 +593,16 @@ void RadWriter::abort() { /* The file is the caller's container: restore its header (a no-op unless finish_append() * failed in that write) and truncate the tail. */ if (fd_out_ >= 0) { - (void)!::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0); - (void)!::ftruncate(fd_out_, (off_t)old_size_); + /* A failed restore leaves a file that is neither the old container nor the new one, + * and the caller has only been told that the write failed. */ + const bool hdr_ok = ::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0) == + (ssize_t)sizeof old_hdr_; + const bool cut_ok = ::ftruncate(fd_out_, (off_t)old_size_) == 0; + if (!hdr_ok || !cut_ok) + RAD_ERR("%s: the append was undone only in part (%s) -- the container is damaged; " + "restore it from a copy", path_.c_str(), + !hdr_ok ? "its header could not be rewritten" + : "its tail could not be cut back"); ::close(fd_out_); } if (fd_spill_ >= 0) ::close(fd_spill_); @@ -1009,8 +1045,11 @@ int RadWriter::set_vocab_section(const void* blob, int64_t bytes) { !fits(h->tok_score_off, h->tok_score_off ? (uint64_t)h->n_tokens * sizeof(float) : 0) || !fits(h->tok_type_off, h->tok_type_off ? h->n_tokens : 0) || !fits(h->merge_off, (uint64_t)h->n_merges * 2 * sizeof(uint32_t)) || - !fits(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep))) { - RAD_ERR("the vocab section's arrays do not fit inside its %lld bytes. Its offsets must be " + !fits(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep)) || + (h->n_tokens && !h->tok_text_off) || (h->n_merges && !h->merge_off) || + (h->n_steps && !h->step_off)) { + RAD_ERR("the vocab section's arrays do not fit inside its %lld bytes, or one its count " + "names is absent. Its offsets must be " "SECTION-RELATIVE -- serialise with a section_file_off of 0 and let finish() " "rebase them.", (long long)bytes); return RAD_E_INVAL; diff --git a/core/format/safetensors.cpp b/core/format/safetensors.cpp index e83b8775..e5bcf5df 100644 --- a/core/format/safetensors.cpp +++ b/core/format/safetensors.cpp @@ -295,7 +295,13 @@ int SafeTensorsFile::open(const std::string& path) { return RAD_E_FORMAT; } - index_.emplace(t.name, tensors_.size()); + /* A JSON object's keys are unique; a header naming one tensor twice has two answers to + * find() and is refused rather than resolved to the first. */ + if (!index_.emplace(t.name, tensors_.size()).second) { + RAD_ERR("%s: the header names '%s' twice", path.c_str(), name.c_str()); + close(); + return RAD_E_FORMAT; + } tensors_.push_back(std::move(t)); if (!sc.eat(',')) break; diff --git a/core/format/share.cpp b/core/format/share.cpp index f038ba09..aa75b5ea 100644 --- a/core/format/share.cpp +++ b/core/format/share.cpp @@ -155,6 +155,20 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con } } + /* The view's rectangles come from plugin-stated spans and parts, sum-checked only. A single + * selected plane takes them as its own rectangles below, with no enc_plane_rect to bound + * them, so every one is held to the entry here. */ + for (int g = 0; !whole && g < w.n_part_spans; ++g) + if (w.part_lo[g] < 0 || w.part_lo[g] > w.part_hi[g] || w.part_hi[g] > w.part_total[g]) + return refuse(fmt("part %d's span [%lld, %lld) is outside its %lld", g, + (long long)w.part_lo[g], (long long)w.part_hi[g], + (long long)w.part_total[g])); + for (const VRect& q : view) + if (q.r0 < 0 || q.r0 > q.r1 || q.r1 > VR || q.c0 < 0 || q.c0 > q.c1 || q.c1 > VC) + return refuse(fmt("the slice [%lld, %lld) x [%lld, %lld) is outside the entry's " + "%lld x %lld", (long long)q.r0, (long long)q.r1, (long long)q.c0, + (long long)q.c1, (long long)VR, (long long)VC)); + for (int k = 0; k < w.n_sel; ++k) { const RadEncPlane& p = enc.plane[w.sel[k]]; PlaneShare& s = out[k]; diff --git a/core/format/tunecache.cpp b/core/format/tunecache.cpp index 06069234..8e4ecdd4 100644 --- a/core/format/tunecache.cpp +++ b/core/format/tunecache.cpp @@ -175,10 +175,15 @@ int TuneCache::load(const std::string& home, const std::string& machine) { continue; } if (tok[0] == "machine") { - if (tok.size() >= 2 && std::string(tok[1]) != machine) - RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- the rows may not " - "describe this card", path.c_str(), (int)tok[1].size(), tok[1].data(), - machine.c_str()); + /* A cache from another card is wrong, not just slow (tunecache.h): a file renamed or + * copied to this machine's name is refused, as another format version is. */ + if (tok.size() >= 2 && std::string(tok[1]) != machine) { + RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- ignoring the cache", + path.c_str(), (int)tok[1].size(), tok[1].data(), machine.c_str()); + std::free(line); + ::fclose(f); + return RAD_E_FORMAT; + } continue; } if (tok.size() < 5) { ++bad; continue; } diff --git a/core/gen/shape.cpp b/core/gen/shape.cpp new file mode 100644 index 00000000..726129c9 --- /dev/null +++ b/core/gen/shape.cpp @@ -0,0 +1,771 @@ +/* shape.cpp -- the shape generator's host geometry (shape.h): the picture, the sampler's grid, the + * field's levels, marching cubes and the mesh's files; and the ticket a caller waits on. */ +#include "shape.h" +#include "rad_internal.h" + +#include + +#include +#include +#include +#include +#include + +namespace rad { +namespace gen { + +ShapeGenInfo shape_info(const RadShapeGenDecl& d, const std::string& name) { + ShapeGenInfo g; + g.name = name; + g.canvas = d.canvas; + g.enc_size = d.enc_size; + g.enc_patch = d.enc_patch; + g.border_ratio = d.border_ratio; + for (int c = 0; c < 3; ++c) { g.pix_mean[c] = d.pix_mean[c]; g.pix_std[c] = d.pix_std[c]; } + g.default_steps = d.default_steps; + g.max_steps = d.max_steps; + g.default_guidance = d.default_guidance; + g.bounds = d.bounds; + g.level = d.level; + g.default_resolution = d.default_resolution; + g.min_resolution = d.min_resolution; + g.max_resolution = d.max_resolution; + g.max_lanes = d.max_lanes; + return g; +} + +/* ================================================================== the picture */ +namespace { + +/* An 8-bit image, `ch` channels interleaved. */ +struct Img { + int32_t w = 0, h = 0, ch = 0; + std::vector px; + uint8_t* at(int32_t y, int32_t x) { return px.data() + ((size_t)y * w + x) * ch; } + const uint8_t* at(int32_t y, int32_t x) const { return px.data() + ((size_t)y * w + x) * ch; } +}; + +/* OpenCV's saturate_cast of a float: round half to even, clipped. */ +inline uint8_t sat_u8(float v) { + const float r = std::nearbyint(v); + return (uint8_t)(r < 0.0f ? 0.0f : r > 255.0f ? 255.0f : r); +} + +/* cv::resize's INTER_AREA when it shrinks both sides: computeResizeAreaTab's weights, a row's + * horizontal sums, then the weighted rows, in float. */ +struct AreaTap { int32_t di, si; float alpha; }; +std::vector area_tab(int32_t ssize, int32_t dsize, double scale) { + std::vector tab; + for (int32_t dx = 0; dx < dsize; ++dx) { + const double fsx1 = dx * scale, fsx2 = fsx1 + scale; + const double cell = std::min(scale, ssize - fsx1); + int32_t sx1 = (int32_t)std::ceil(fsx1), sx2 = (int32_t)std::floor(fsx2); + sx2 = std::min(sx2, ssize - 1); + sx1 = std::min(sx1, sx2); + if (sx1 - fsx1 > 1e-3) tab.push_back({ dx, sx1 - 1, (float)((sx1 - fsx1) / cell) }); + for (int32_t sx = sx1; sx < sx2; ++sx) tab.push_back({ dx, sx, (float)(1.0 / cell) }); + if (fsx2 - sx2 > 1e-3) + tab.push_back({ dx, sx2, (float)(std::min(std::min(fsx2 - sx2, 1.0), cell) / cell) }); + } + return tab; +} + +void resize_area_down(const Img& s, int32_t dw, int32_t dh, Img* d) { + const double sx = (double)s.w / dw, sy = (double)s.h / dh; + const std::vector xt = area_tab(s.w, dw, sx), yt = area_tab(s.h, dh, sy); + const int32_t ch = s.ch; + std::vector row((size_t)dw * ch), acc((size_t)dw * ch); + d->w = dw; d->h = dh; d->ch = ch; + d->px.assign((size_t)dw * dh * ch, 0); + size_t k = 0; + for (int32_t dy = 0; dy < dh; ++dy) { + std::fill(acc.begin(), acc.end(), 0.0f); + for (; k < yt.size() && yt[k].di == dy; ++k) { + std::fill(row.begin(), row.end(), 0.0f); + const uint8_t* src = s.at(yt[k].si, 0); + for (const AreaTap& t : xt) + for (int32_t c = 0; c < ch; ++c) + row[(size_t)t.di * ch + c] += src[(size_t)t.si * ch + c] * t.alpha; + for (size_t i = 0; i < acc.size(); ++i) acc[i] += row[i] * yt[k].alpha; + } + uint8_t* dst = d->at(dy, 0); + for (size_t i = 0; i < acc.size(); ++i) dst[i] = sat_u8(acc[i]); + } +} + +/* cv::resize's fixed-point separable filter for 8-bit images: each tap's float coefficient + * rounded to 11 bits, the horizontal sums in int, the vertical sum shifted back by 22 with + * rounding. `taps` coefficients a destination pixel, first at source index ofs[d] (indices + * clamped to the image, OpenCV's BORDER_REPLICATE). */ +struct Taps { + int32_t ksize = 0; + std::vector ofs; + std::vector c; +}; + +Taps taps_linear_area(int32_t ssize, int32_t dsize) { + /* INTER_AREA when it does not shrink both sides: linear taps in OpenCV's area mode. */ + const double scale = (double)ssize / dsize, inv = (double)dsize / ssize; + Taps t; + t.ksize = 2; + for (int32_t dx = 0; dx < dsize; ++dx) { + const int32_t sx = (int32_t)std::floor(dx * scale); + float fx = (float)((dx + 1) - (sx + 1) * inv); + fx = fx <= 0 ? 0.0f : fx - std::floor(fx); + t.ofs.push_back(sx); + t.c.push_back((int16_t)std::nearbyint((1.0f - fx) * 2048.0f)); + t.c.push_back((int16_t)std::nearbyint(fx * 2048.0f)); + } + return t; +} + +Taps taps_cubic(int32_t ssize, int32_t dsize) { + const double scale = (double)ssize / dsize; + const float A = -0.75f; + Taps t; + t.ksize = 4; + for (int32_t dx = 0; dx < dsize; ++dx) { + float fx = (float)((dx + 0.5) * scale - 0.5); + const int32_t sx = (int32_t)std::floor(fx); + fx -= sx; + float w[4]; + w[0] = ((A * (fx + 1) - 5 * A) * (fx + 1) + 8 * A) * (fx + 1) - 4 * A; + w[1] = ((A + 2) * fx - (A + 3)) * fx * fx + 1; + w[2] = ((A + 2) * (1 - fx) - (A + 3)) * (1 - fx) * (1 - fx) + 1; + w[3] = 1.0f - w[0] - w[1] - w[2]; + t.ofs.push_back(sx - 1); + for (float v : w) t.c.push_back((int16_t)std::nearbyint(v * 2048.0f)); + } + return t; +} + +void resize_fixed(const Img& s, const Taps& tx, const Taps& ty, int32_t dw, int32_t dh, Img* d) { + const int32_t ch = s.ch; + /* Every source row through the horizontal taps, then each destination row from its rows. */ + std::vector hrow((size_t)s.h * dw * ch); + for (int32_t y = 0; y < s.h; ++y) + for (int32_t dx = 0; dx < dw; ++dx) + for (int32_t c = 0; c < ch; ++c) { + int32_t sum = 0; + for (int32_t k = 0; k < tx.ksize; ++k) { + const int32_t sx = std::clamp(tx.ofs[(size_t)dx] + k, 0, s.w - 1); + sum += s.at(y, sx)[c] * tx.c[(size_t)dx * tx.ksize + k]; + } + hrow[((size_t)y * dw + dx) * ch + c] = sum; + } + d->w = dw; d->h = dh; d->ch = ch; + d->px.assign((size_t)dw * dh * ch, 0); + for (int32_t dy = 0; dy < dh; ++dy) + for (int32_t i = 0; i < dw * ch; ++i) { + int64_t v = 0; + for (int32_t k = 0; k < ty.ksize; ++k) { + const int32_t sy = std::clamp(ty.ofs[(size_t)dy] + k, 0, s.h - 1); + v += (int64_t)hrow[(size_t)sy * dw * ch + i] * ty.c[(size_t)dy * ty.ksize + k]; + } + const int64_t r = (v + (1 << 21)) >> 22; + d->px[(size_t)dy * dw * ch + i] = (uint8_t)std::clamp(r, 0, 255); + } +} + +/* cv2.resize(src, (dw, dh), INTER_AREA). */ +void resize_area(const Img& s, int32_t dw, int32_t dh, Img* d) { + if (dw == s.w && dh == s.h) { *d = s; return; } + if (s.w >= dw && s.h >= dh) { resize_area_down(s, dw, dh, d); return; } + resize_fixed(s, taps_linear_area(s.w, dw), taps_linear_area(s.h, dh), dw, dh, d); +} + +/* cv2.resize(src, (dw, dh), INTER_CUBIC). */ +void resize_cubic(const Img& s, int32_t dw, int32_t dh, Img* d) { + if (dw == s.w && dh == s.h) { *d = s; return; } + resize_fixed(s, taps_cubic(s.w, dw), taps_cubic(s.h, dh), dw, dh, d); +} + +/* torchvision's antialiased bilinear resize along one axis (align_corners false): the triangle + * filter around each output's centre, widened by the scale when shrinking, normalised over the + * taps inside the image. */ +struct AaTaps { std::vector lo; std::vector> w; }; +AaTaps aa_taps(int32_t in, int32_t out) { + const double scale = (double)in / out; + const double support = scale >= 1.0 ? scale : 1.0; + const double inv = scale >= 1.0 ? 1.0 / scale : 1.0; + AaTaps t; + for (int32_t i = 0; i < out; ++i) { + const double center = scale * (i + 0.5); + const int32_t lo = std::max((int32_t)(center - support + 0.5), 0); + const int32_t hi = std::min((int32_t)(center + support + 0.5), in); + std::vector w; + double total = 0.0; + for (int32_t j = lo; j < hi; ++j) { + const double x = std::fabs((j - center + 0.5) * inv); + const double v = x < 1.0 ? 1.0 - x : 0.0; + w.push_back((float)v); + total += v; + } + if (total > 0.0) for (float& v : w) v = (float)(v / total); + t.lo.push_back(lo); + t.w.push_back(std::move(w)); + } + return t; +} + +} /* namespace */ + +int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector* patches, + std::string* why) { + auto no = [&](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + const int32_t H = rgba.h, W = rgba.w; + if (H < 1 || W < 1 || rgba.rgba.size() != (size_t)H * W * 4) return no("the picture is empty"); + /* ---- ImageProcessorV2.recenter: the alpha's bounding box on a square of the longer side */ + int32_t y0 = H, y1 = -1, x0 = W, x1 = -1; + for (int32_t y = 0; y < H; ++y) + for (int32_t x = 0; x < W; ++x) + if (rgba.rgba[((size_t)y * W + x) * 4 + 3]) { + y0 = std::min(y0, y); y1 = std::max(y1, y); + x0 = std::min(x0, x); x1 = std::max(x1, x); + } + if (y1 < 0) return no("the picture is fully transparent: nothing to make a shape of"); + const int32_t h = y1 - y0, w = x1 - x0; + if (h == 0 || w == 0) + return no("the picture's opaque part is a single row or column: nothing to make a shape " + "of"); + const int32_t size = std::max(H, W); + const int32_t desired = (int32_t)(size * (1.0 - g.border_ratio)); + const double scale = (double)desired / std::max(h, w); + const int32_t h2 = (int32_t)(h * scale), w2 = (int32_t)(w * scale); + if (h2 < 1 || w2 < 1) + return no("the picture's opaque part is too thin to scale onto the canvas"); + Img crop; + crop.w = w; crop.h = h; crop.ch = 4; + crop.px.resize((size_t)w * h * 4); + for (int32_t y = 0; y < h; ++y) + std::memcpy(crop.at(y, 0), rgba.rgba.data() + ((size_t)(y0 + y) * W + x0) * 4, + (size_t)w * 4); + Img fit; + resize_area(crop, w2, h2, &fit); + const int32_t oy = (size - h2) / 2, ox = (size - w2) / 2; + /* Flattened onto white in float, then truncated to 8 bits, as numpy's astype does. */ + Img sq; + sq.w = size; sq.h = size; sq.ch = 3; + sq.px.assign((size_t)size * size * 3, 255); + for (int32_t y = 0; y < h2; ++y) + for (int32_t x = 0; x < w2; ++x) { + const uint8_t* p = fit.at(y, x); + const float a = (float)p[3] / 255.0f; + uint8_t* q = sq.at(oy + y, ox + x); + for (int c = 0; c < 3; ++c) { + const float v = (float)p[c] * a + 255.0f * (1.0f - a); + q[c] = (uint8_t)std::clamp(v, 0.0f, 255.0f); + } + } + /* ---- the canvas, INTER_CUBIC */ + const int32_t C = (int32_t)g.canvas; + Img can; + resize_cubic(sq, C, C, &can); + /* ---- the encoder's transform: 0..1, bilinear (antialiased) to enc_size, normalised */ + const int32_t E = (int32_t)g.enc_size, P = (int32_t)g.enc_patch, G = E / P; + const AaTaps ta = aa_taps(C, E); + std::vector hor((size_t)C * E * 3), img((size_t)E * E * 3); + for (int32_t y = 0; y < C; ++y) + for (int32_t x = 0; x < E; ++x) + for (int c = 0; c < 3; ++c) { + float s = 0.0f; + const std::vector& wt = ta.w[(size_t)x]; + for (size_t k = 0; k < wt.size(); ++k) + s += wt[k] * ((float)can.at(y, ta.lo[(size_t)x] + (int32_t)k)[c] / 255.0f); + hor[((size_t)y * E + x) * 3 + c] = s; + } + for (int32_t y = 0; y < E; ++y) + for (int32_t x = 0; x < E; ++x) + for (int c = 0; c < 3; ++c) { + float s = 0.0f; + const std::vector& wt = ta.w[(size_t)y]; + for (size_t k = 0; k < wt.size(); ++k) + s += wt[k] * hor[(((size_t)ta.lo[(size_t)y] + k) * E + x) * 3 + c]; + img[((size_t)y * E + x) * 3 + c] = + (float)((s - g.pix_mean[c]) / g.pix_std[c]); + } + /* ---- patches, row-major; a patch's values (channel, row, column) */ + const int64_t pd = 3 * (int64_t)P * P; + patches->assign((size_t)G * G * pd, 0.0f); + for (int32_t py = 0; py < G; ++py) + for (int32_t px = 0; px < G; ++px) { + float* o = patches->data() + ((size_t)py * G + px) * pd; + for (int c = 0; c < 3; ++c) + for (int32_t i = 0; i < P; ++i) + for (int32_t j = 0; j < P; ++j) + o[((size_t)c * P + i) * P + j] = + img[(((size_t)py * P + i) * E + px * P + j) * 3 + c]; + } + return RAD_OK; +} + +/* ================================================================== the sampler and the grid */ +std::vector shape_sigmas(int32_t steps) { + std::vector s; + if (steps < 2) return s; + const double step = 1.0 / (steps - 1); + for (int32_t i = 0; i < steps; ++i) s.push_back(i == steps - 1 ? 1.0f : (float)(i * step)); + return s; +} + +std::vector shape_levels(int32_t resolution) { + std::vector r; + if (resolution < 63) r.push_back(resolution); + for (int32_t v = resolution; v >= 63; v /= 2) r.push_back(v); + std::reverse(r.begin(), r.end()); + return r; +} + +std::vector shape_axis(double bounds, int32_t r) { + std::vector a((size_t)r + 1); + const double step = 2.0 * bounds / r; + for (int32_t i = 0; i <= r; ++i) a[(size_t)i] = (float)(i * step + -bounds); + a[(size_t)r] = (float)bounds; + return a; +} + +namespace { + +/* A 3 x 3 x 3 dilation of an n^3 mask (zero outside), as separable maxima along each axis. */ +void dilate(std::vector& m, int64_t n) { + std::vector t(m.size()); + auto pass = [&](const std::vector& src, std::vector& dst, int64_t stride) { + for (int64_t p = 0; p < (int64_t)src.size(); ++p) { + const int64_t c = (p / stride) % n; + uint8_t v = src[(size_t)p]; + if (c > 0) v |= src[(size_t)(p - stride)]; + if (c + 1 < n) v |= src[(size_t)(p + stride)]; + dst[(size_t)p] = v; + } + }; + pass(m, t, 1); + pass(t, m, n); + pass(m, t, n * n); + m.swap(t); +} + +} /* namespace */ + +std::vector shape_refine(const std::vector& prev, int32_t rp, int32_t r, + double level, bool last) { + const int64_t np = (int64_t)rp + 1, n = (int64_t)r + 1; + std::vector near((size_t)(np * np * np), 0); + auto sgn = [](float v) { return (v > 0.0f) - (v < 0.0f); }; + const float lv = (float)level; + for (int64_t i = 0; i < np; ++i) + for (int64_t j = 0; j < np; ++j) + for (int64_t k = 0; k < np; ++k) { + const int64_t p = (i * np + j) * np + k; + const float raw = prev[(size_t)p]; + if (std::isnan(raw)) continue; + const float v = raw - lv; + const int s = sgn(v); + bool cross = std::fabs(v) < 0.95f; + const int64_t nb[6][3] = { { i - 1, j, k }, { i + 1, j, k }, { i, j - 1, k }, + { i, j + 1, k }, { i, j, k - 1 }, { i, j, k + 1 } }; + for (int q = 0; q < 6 && !cross; ++q) { + const int64_t a = nb[q][0], b = nb[q][1], c = nb[q][2]; + /* Outside the grid the reference replicates the border, and a neighbour not + * sampled stands in as the point itself: neither crosses. */ + if (a < 0 || a >= np || b < 0 || b >= np || c < 0 || c >= np) continue; + const float u = prev[(size_t)((a * np + b) * np + c)]; + if (std::isnan(u)) continue; + cross = sgn(u - lv) != s; + } + near[(size_t)p] = cross; + } + if (!last) dilate(near, np); + std::vector mark((size_t)(n * n * n), 0); + auto up = [&](int64_t c) { return (c * r + rp / 2) / rp; }; + for (int64_t i = 0; i < np; ++i) + for (int64_t j = 0; j < np; ++j) + for (int64_t k = 0; k < np; ++k) + if (near[(size_t)((i * np + j) * np + k)]) + mark[(size_t)((up(i) * n + up(j)) * n + up(k))] = 1; + dilate(mark, n); + if (last) dilate(mark, n); + std::vector pts; + for (int64_t p = 0; p < (int64_t)mark.size(); ++p) + if (mark[(size_t)p]) pts.push_back((uint32_t)p); + return pts; +} + +/* ================================================================== marching cubes */ +namespace { + +/* Corner c of a cube is at (c & 1, c >> 1 & 1, c >> 2 & 1) along the grid's (i, j, k). Edge e is + * along axis e / 4 from corner kEdge[e][0] to kEdge[e][1]. */ +struct McTables { + int32_t edge[12][2]; + /* Each case's triangles as edge triples, -1 ended. */ + int8_t tri[256][31]; +}; + +McTables build_tables() { + McTables T{}; + int ne = 0; + for (int a = 0; a < 3; ++a) + for (int c = 0; c < 8; ++c) + if (!(c >> a & 1)) { T.edge[ne][0] = c; T.edge[ne][1] = c | (1 << a); ++ne; } + auto edge_of = [&](int c0, int c1) { + for (int e = 0; e < 12; ++e) + if ((T.edge[e][0] == c0 && T.edge[e][1] == c1) || + (T.edge[e][0] == c1 && T.edge[e][1] == c0)) + return e; + return -1; + }; + auto pos = [](int c, double* p) { p[0] = c & 1; p[1] = c >> 1 & 1; p[2] = c >> 2 & 1; }; + for (int m = 0; m < 256; ++m) { + for (int i = 0; i < 31; ++i) T.tri[m][i] = -1; + if (m == 0 || m == 255) continue; + auto in = [&](int c) { return (m >> c & 1) != 0; }; + /* Each face's segments between its crossing edges. A face with all four edges crossing + * (its inside corners diagonal) separates the inside corners, the rule both cubes that + * share the face apply, so the surface has no cracks. */ + std::vector> seg; + for (int a = 0; a < 3; ++a) + for (int s = 0; s < 2; ++s) { + const int u = (a + 1) % 3, v = (a + 2) % 3; + const int base = s << a; + const int cyc[4] = { base, base | (1 << u), base | (1 << u) | (1 << v), + base | (1 << v) }; + int fe[4]; + bool cr[4]; + int ncr = 0; + for (int q = 0; q < 4; ++q) { + fe[q] = edge_of(cyc[q], cyc[(q + 1) % 4]); + cr[q] = in(cyc[q]) != in(cyc[(q + 1) % 4]); + ncr += cr[q]; + } + if (ncr == 2) { + int a0 = -1, a1 = -1; + for (int q = 0; q < 4; ++q) { + if (!cr[q]) continue; + if (a0 < 0) a0 = fe[q]; else a1 = fe[q]; + } + seg.push_back({ a0, a1 }); + } else if (ncr == 4) { + for (int q = 0; q < 4; ++q) + if (in(cyc[q])) seg.push_back({ fe[(q + 3) % 4], fe[q] }); + } + } + /* The segments close into loops; each crossing edge is in exactly two. */ + std::vector used(seg.size(), false); + int nt = 0; + for (size_t s0 = 0; s0 < seg.size(); ++s0) { + if (used[s0]) continue; + std::vector loop = { seg[s0][0], seg[s0][1] }; + used[s0] = true; + for (bool grew = true; grew;) { + grew = false; + for (size_t q = 0; q < seg.size(); ++q) { + if (used[q]) continue; + const int tail = loop.back(); + int nx = -1; + if (seg[q][0] == tail) nx = seg[q][1]; + else if (seg[q][1] == tail) nx = seg[q][0]; + if (nx < 0) continue; + used[q] = true; + grew = true; + if (nx != loop.front()) loop.push_back(nx); + } + } + /* Orientation: the loop's normal (Newell's, over the edges' midpoints) points from the + * inside corners to the outside ones. */ + double nrm[3] = { 0, 0, 0 }, out[3] = { 0, 0, 0 }; + std::vector> mid; + for (int e : loop) { + double p0[3], p1[3]; + pos(T.edge[e][0], p0); + pos(T.edge[e][1], p1); + mid.push_back({ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2, (p0[2] + p1[2]) / 2 }); + const double sg = in(T.edge[e][0]) ? 1.0 : -1.0; + for (int d = 0; d < 3; ++d) out[d] += sg * (p1[d] - p0[d]); + } + for (size_t q = 0; q < mid.size(); ++q) { + const auto& c = mid[q]; + const auto& d = mid[(q + 1) % mid.size()]; + nrm[0] += (c[1] - d[1]) * (c[2] + d[2]); + nrm[1] += (c[2] - d[2]) * (c[0] + d[0]); + nrm[2] += (c[0] - d[0]) * (c[1] + d[1]); + } + if (nrm[0] * out[0] + nrm[1] * out[1] + nrm[2] * out[2] < 0) + std::reverse(loop.begin(), loop.end()); + for (size_t q = 1; q + 1 < loop.size() && nt < 10; ++q) { + T.tri[m][3 * nt] = (int8_t)loop[0]; + T.tri[m][3 * nt + 1] = (int8_t)loop[q]; + T.tri[m][3 * nt + 2] = (int8_t)loop[q + 1]; + ++nt; + } + } + } + return T; +} + +const McTables& tables() { + static const McTables t = build_tables(); + return t; +} + +} /* namespace */ + +void shape_mesh(const std::vector& field, int32_t r, double bounds, double level, + ShapeMesh* out) { + out->v.clear(); + out->f.clear(); + const McTables& T = tables(); + const int64_t n = (int64_t)r + 1, nn = n * n; + const float lv = (float)level; + const double sc = 2.0 * bounds / (double)n; + /* An edge's vertex by its first grid point: the x edges between planes i and i + 1, and the + * y and z edges of planes i and i + 1. */ + std::vector ex((size_t)nn), ey[2], ez[2]; + for (int p = 0; p < 2; ++p) { ey[p].assign((size_t)nn, -1); ez[p].assign((size_t)nn, -1); } + auto value = [&](int64_t i, int64_t j, int64_t k) { + return field[(size_t)((i * n + j) * n + k)]; + }; + for (int64_t i = 0; i + 1 < n; ++i) { + std::fill(ex.begin(), ex.end(), -1); + if (i > 0) { + std::swap(ey[0], ey[1]); + std::swap(ez[0], ez[1]); + std::fill(ey[1].begin(), ey[1].end(), -1); + std::fill(ez[1].begin(), ez[1].end(), -1); + } + for (int64_t j = 0; j + 1 < n; ++j) + for (int64_t k = 0; k + 1 < n; ++k) { + float v[8]; + bool skip = false; + int m = 0; + for (int c = 0; c < 8 && !skip; ++c) { + v[c] = value(i + (c & 1), j + (c >> 1 & 1), k + (c >> 2 & 1)); + if (std::isnan(v[c])) skip = true; + else if (v[c] > lv) m |= 1 << c; + } + if (skip || m == 0 || m == 255) continue; + for (int t = 0; t < 30 && T.tri[m][t] >= 0; ++t) { + const int e = T.tri[m][t]; + const int c0 = T.edge[e][0], c1 = T.edge[e][1], a = e / 4; + const int64_t bi = c0 & 1, bj = c0 >> 1 & 1, bk = c0 >> 2 & 1; + int32_t* slot = a == 0 ? &ex[(size_t)((j + bj) * n + k + bk)] + : a == 1 ? &ey[bi][(size_t)(j * n + k + bk)] + : &ez[bi][(size_t)((j + bj) * n + k)]; + if (*slot < 0) { + const float t0 = v[c0], t1 = v[c1]; + const float f = t1 != t0 ? (lv - t0) / (t1 - t0) : 0.5f; + float g[3] = { (float)(i + bi), (float)(j + bj), (float)(k + bk) }; + g[a] += f; + *slot = (int32_t)(out->v.size() / 3); + for (int d = 0; d < 3; ++d) out->v.push_back((float)(g[d] * sc - bounds)); + } + out->f.push_back((uint32_t)*slot); + } + } + } +} + +/* ================================================================== files */ +namespace { + +void put(std::string& s, const void* p, size_t n) { s.append((const char*)p, n); } +template void put_v(std::string& s, T v) { put(s, &v, sizeof v); } + +/* Area-weighted vertex normals, unit length (zero for a vertex of only degenerate faces). */ +std::vector vertex_normals(const ShapeMesh& m) { + std::vector nrm(m.v.size(), 0.0f); + for (size_t t = 0; t + 2 < m.f.size(); t += 3) { + const float* a = &m.v[(size_t)m.f[t] * 3]; + const float* b = &m.v[(size_t)m.f[t + 1] * 3]; + const float* c = &m.v[(size_t)m.f[t + 2] * 3]; + const float u[3] = { b[0] - a[0], b[1] - a[1], b[2] - a[2] }; + const float w[3] = { c[0] - a[0], c[1] - a[1], c[2] - a[2] }; + const float x[3] = { u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], + u[0] * w[1] - u[1] * w[0] }; + for (int q = 0; q < 3; ++q) + for (int d = 0; d < 3; ++d) nrm[(size_t)m.f[t + q] * 3 + d] += x[d]; + } + for (size_t i = 0; i + 2 < nrm.size(); i += 3) { + const float l = + std::sqrt(nrm[i] * nrm[i] + nrm[i + 1] * nrm[i + 1] + nrm[i + 2] * nrm[i + 2]); + if (l > 0.0f) for (int d = 0; d < 3; ++d) nrm[i + d] /= l; + } + return nrm; +} + +std::string glb(const ShapeMesh& m) { + const size_t nv = m.v.size() / 3, ni = m.f.size(); + const std::vector nrm = vertex_normals(m); + float lo[3] = { INFINITY, INFINITY, INFINITY }, hi[3] = { -INFINITY, -INFINITY, -INFINITY }; + for (size_t i = 0; i < nv; ++i) + for (int d = 0; d < 3; ++d) { + lo[d] = std::min(lo[d], m.v[i * 3 + d]); + hi[d] = std::max(hi[d], m.v[i * 3 + d]); + } + const size_t vb = nv * 12, ib = ni * 4; + std::string bin; + put(bin, m.v.data(), vb); + put(bin, nrm.data(), vb); + put(bin, m.f.data(), ib); + while (bin.size() % 4) bin.push_back('\0'); + using nlohmann::json; + json j; + j["asset"] = { { "version", "2.0" }, { "generator", "radiance" } }; + j["scene"] = 0; + j["scenes"] = json::array({ { { "nodes", json::array({ 0 }) } } }); + j["nodes"] = json::array({ { { "mesh", 0 } } }); + const json prim = { { "attributes", { { "POSITION", 0 }, { "NORMAL", 1 } } }, + { "indices", 2 }, { "mode", 4 } }; + j["meshes"] = json::array({ { { "primitives", json::array({ prim }) } } }); + j["buffers"] = json::array({ { { "byteLength", bin.size() } } }); + j["bufferViews"] = json::array({ + { { "buffer", 0 }, { "byteOffset", 0 }, { "byteLength", vb }, { "target", 34962 } }, + { { "buffer", 0 }, { "byteOffset", vb }, { "byteLength", vb }, { "target", 34962 } }, + { { "buffer", 0 }, { "byteOffset", 2 * vb }, { "byteLength", ib }, { "target", 34963 } } }); + j["accessors"] = json::array({ + { { "bufferView", 0 }, { "componentType", 5126 }, { "count", nv }, { "type", "VEC3" }, + { "min", { lo[0], lo[1], lo[2] } }, { "max", { hi[0], hi[1], hi[2] } } }, + { { "bufferView", 1 }, { "componentType", 5126 }, { "count", nv }, { "type", "VEC3" } }, + { { "bufferView", 2 }, { "componentType", 5125 }, { "count", ni }, + { "type", "SCALAR" } } }); + std::string js = j.dump(); + while (js.size() % 4) js.push_back(' '); + std::string out; + put_v(out, 0x46546C67u); /* "glTF" */ + put_v(out, 2); + put_v(out, (uint32_t)(12 + 8 + js.size() + 8 + bin.size())); + put_v(out, (uint32_t)js.size()); + put_v(out, 0x4E4F534Au); /* "JSON" */ + out += js; + put_v(out, (uint32_t)bin.size()); + put_v(out, 0x004E4942u); /* "BIN\0" */ + out += bin; + return out; +} + +std::string obj(const ShapeMesh& m) { + std::string s; + char line[128]; + for (size_t i = 0; i + 2 < m.v.size(); i += 3) { + const int n = std::snprintf(line, sizeof line, "v %.9g %.9g %.9g\n", (double)m.v[i], + (double)m.v[i + 1], (double)m.v[i + 2]); + s.append(line, (size_t)n); + } + for (size_t t = 0; t + 2 < m.f.size(); t += 3) { + const int n = std::snprintf(line, sizeof line, "f %u %u %u\n", m.f[t] + 1, m.f[t + 1] + 1, + m.f[t + 2] + 1); + s.append(line, (size_t)n); + } + return s; +} + +std::string ply(const ShapeMesh& m) { + const size_t nv = m.v.size() / 3, nf = m.f.size() / 3; + std::string s = "ply\nformat binary_little_endian 1.0\nelement vertex " + std::to_string(nv) + + "\nproperty float x\nproperty float y\nproperty float z\nelement face " + + std::to_string(nf) + "\nproperty list uchar int vertex_indices\nend_header\n"; + put(s, m.v.data(), m.v.size() * 4); + for (size_t t = 0; t < nf; ++t) { + put_v(s, 3); + for (int q = 0; q < 3; ++q) put_v(s, (int32_t)m.f[t * 3 + q]); + } + return s; +} + +std::string stl(const ShapeMesh& m) { + std::string s(80, '\0'); + std::memcpy(&s[0], "radiance", 8); + const size_t nf = m.f.size() / 3; + put_v(s, (uint32_t)nf); + for (size_t t = 0; t < nf; ++t) { + const float* a = &m.v[(size_t)m.f[t * 3] * 3]; + const float* b = &m.v[(size_t)m.f[t * 3 + 1] * 3]; + const float* c = &m.v[(size_t)m.f[t * 3 + 2] * 3]; + const float u[3] = { b[0] - a[0], b[1] - a[1], b[2] - a[2] }; + const float w[3] = { c[0] - a[0], c[1] - a[1], c[2] - a[2] }; + float x[3] = { u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], + u[0] * w[1] - u[1] * w[0] }; + const float l = std::sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]); + if (l > 0.0f) for (float& q : x) q /= l; + put(s, x, 12); + put(s, a, 12); + put(s, b, 12); + put(s, c, 12); + put_v(s, 0); + } + return s; +} + +} /* namespace */ + +int shape_export(const ShapeMesh& m, const std::string& format, std::string* bytes, + std::string* mime, std::string* why) { + if (format == "glb") { *bytes = glb(m); *mime = "model/gltf-binary"; return RAD_OK; } + if (format == "obj") { *bytes = obj(m); *mime = "model/obj"; return RAD_OK; } + if (format == "ply") { *bytes = ply(m); *mime = "application/x-ply"; return RAD_OK; } + if (format == "stl") { *bytes = stl(m); *mime = "model/stl"; return RAD_OK; } + if (why) *why = "type '" + format + "' is not one this server writes: glb, obj, ply or stl"; + return RAD_E_INVAL; +} + +/* ================================================================== the ticket */ +void ShapeTicket::progress(int32_t steps_done, int32_t points_done) { + std::lock_guard lk(mu_); + steps_done_ = steps_done; + points_done_ = points_done; +} + +void ShapeTicket::set_field(std::vector&& field, int32_t r) { + std::lock_guard lk(mu_); + field_ = std::move(field); + r_ = r; +} + +void ShapeTicket::finish(int status, const std::string& why) { + { + std::lock_guard lk(mu_); + if (done_) return; + done_ = true; + status_ = status; + why_ = why; + } + cv_.notify_all(); +} + +bool ShapeTicket::wait(int ms) { + std::unique_lock lk(mu_); + cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return done_; }); + return done_; +} + +bool ShapeTicket::finished() const { + std::lock_guard lk(mu_); + return done_; +} + +int ShapeTicket::status() const { + std::lock_guard lk(mu_); + return status_; +} + +std::string ShapeTicket::why() const { + std::lock_guard lk(mu_); + return why_; +} + +std::vector ShapeTicket::take_field(int32_t* r) { + std::lock_guard lk(mu_); + if (r) *r = r_; + return std::move(field_); +} + +void ShapeTicket::progress_of(int32_t* steps_done, int32_t* points_done) const { + std::lock_guard lk(mu_); + if (steps_done) *steps_done = steps_done_; + if (points_done) *points_done = points_done_; +} + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/shape.h b/core/gen/shape.h new file mode 100644 index 00000000..9947dc77 --- /dev/null +++ b/core/gen/shape.h @@ -0,0 +1,137 @@ +/* shape.h -- shape generation: the request, the channel its field comes back on, and the host + * geometry around the model's passes. + * + * A shape generator (abi/rad_builder.h, rad_declare_shape_generator) makes a 3-D shape from one + * picture: it denoises a latent, then decodes it into an occupancy field that is sampled on a + * grid. core/gen/shape_driver.h turns a request into those passes; this is what a caller hands it + * (the picture already prepared, shape_picture), what it hands back (progress as the steps and + * the grid's levels run, then the finest grid), and the geometry both sides share: the sampler's + * sigmas, the grid's levels and the points each level queries, and the mesh made of the grid + * (shape_mesh) with its file formats. + */ +#pragma once +#include "rad_core.h" +#include "mm/media.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace gen { + +/* What the driver knows of the declaration, for the server and the geometry below. */ +struct ShapeGenInfo { + std::string name; + int64_t canvas = 0, enc_size = 0, enc_patch = 0; + double border_ratio = 0.0; + double pix_mean[3] = {}, pix_std[3] = {}; + int64_t default_steps = 0, max_steps = 0; + double default_guidance = 0.0; + double bounds = 1.0, level = 0.0; + int64_t default_resolution = 0, min_resolution = 0, max_resolution = 0; + int64_t max_lanes = 1; +}; +ShapeGenInfo shape_info(const RadShapeGenDecl& d, const std::string& name); + +/* The picture as an SCOND pass carries it (RadShapeGenDecl, "The picture"): `rgba` decoded with + * its alpha, out as f32 [(enc_size / enc_patch)^2, 3 enc_patch^2]. Refuses a picture whose alpha + * leaves nothing, or a bounding box of one row or column, as the reference does. */ +int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector* patches, + std::string* why); + +/* The sampler's grid points: numpy's linspace(0, 1, steps) taken to f32. An evaluation at each + * but the last steps to the next. */ +std::vector shape_sigmas(int32_t steps); + +/* The grid's levels, coarsest first: `resolution` halved while it stays at least 63, then + * reversed (one level when it is below 63). */ +std::vector shape_levels(int32_t resolution); + +/* One axis of a level's grid: numpy's linspace(-bounds, bounds, r + 1) in f32. */ +std::vector shape_axis(double bounds, int32_t r); + +/* The grid points of level `r` (index (i, j, k) at (i (r+1) + j) (r+1) + k) to query, given the + * coarser level's field `prev` at resolution `rp` (NaN where it was not sampled): the coarse + * points whose sign against `level` differs from a neighbour's, or whose value is within 0.95 of + * zero, dilated once unless this is the last level, put at their places on this grid and dilated + * twice there (once when the coarse set was). As FlashVDM's hierarchical decoding. */ +std::vector shape_refine(const std::vector& prev, int32_t rp, int32_t r, + double level, bool last); + +/* A triangle mesh: positions xyz, and faces as three vertex indices, counter-clockwise seen from + * outside the shape. */ +struct ShapeMesh { + std::vector v; + std::vector f; +}; + +/* Marching cubes over `field` ((r+1)^3 values, the layout above) at `level`, inside above it. A + * cube with a corner not sampled (NaN) makes nothing. Vertices sit on the grid's edges where the + * linear interpolation of their ends crosses the level, one vertex an edge, and grid index g goes + * to g 2 bounds / (r + 1) - bounds (RadShapeGenDecl, "The field"). */ +void shape_mesh(const std::vector& field, int32_t r, double bounds, double level, + ShapeMesh* out); + +/* The mesh as a file: "glb" (positions, smooth normals and indices), "obj", "ply" (binary) or + * "stl" (binary). The content type goes to `mime`. Refuses another format by name. */ +int shape_export(const ShapeMesh& m, const std::string& format, std::string* bytes, + std::string* mime, std::string* why); + +/* ================================================================== the request */ +class ShapeTicket { +public: + /* driver side */ + void progress(int32_t steps_done, int32_t points_done); + /* The finest grid, at resolution `r`, and the end. */ + void finish(int status, const std::string& why = std::string()); + void set_field(std::vector&& field, int32_t r); + + /* caller side: waits at most `ms` milliseconds for the end; true once it came. */ + bool wait(int ms); + bool finished() const; + int status() const; + std::string why() const; + /* The field, once finished with RAD_OK; moved out. */ + std::vector take_field(int32_t* r); + void progress_of(int32_t* steps_done, int32_t* points_done) const; + + std::atomic cancel{false}; + + /* Written by the driver at submit: the evaluations, the resolution and the guidance. */ + int32_t steps = 0, resolution = 0; + double guidance = 0.0; + /* Usage, written by the driver before finish(): the points the decoder was queried at, and + * per-phase times. */ + int64_t points = 0; + int64_t t_submit_ns = 0, t_cond_ns = 0, t_denoised_ns = 0, t_done_ns = 0; + +private: + mutable std::mutex mu_; + std::condition_variable cv_; + bool done_ = false; + int status_ = RAD_OK; + std::string why_; + int32_t steps_done_ = 0, points_done_ = 0; + std::vector field_; + int32_t r_ = 0; +}; + +struct ShapeRequest { + /* The picture, prepared (shape_picture). */ + std::vector patches; + int32_t steps = 0; /* sigma grid points; 0: the model's default */ + double guidance = NAN; /* NaN: the model's default */ + int32_t resolution = 0; /* the finest grid's cells a side; 0: the model's default */ + bool dense = false; /* sample every point of the finest grid, no coarser levels */ + uint64_t seed = 0; + std::shared_ptr ticket; +}; + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/shape_driver.cpp b/core/gen/shape_driver.cpp new file mode 100644 index 00000000..88d7547d --- /dev/null +++ b/core/gen/shape_driver.cpp @@ -0,0 +1,436 @@ +/* shape_driver.cpp -- the shape generator's pass driver (shape_driver.h). */ +#include "shape_driver.h" +#include "rad_internal.h" + +#include +#include +#include + +namespace rad { +namespace gen { + +namespace { + +constexpr int64_t kAlign = 256; + +/* Region offsets and sizes, in the enum's order (shape_driver.h), and the total; shared by the + * allocation and the VRAM budget. */ +int64_t carve(const RadShapeGenDecl& d, int64_t (*bytes)[2], int n) { + const int64_t side = d.enc_size / d.enc_patch; + const int64_t want[] = { + side * side * 3 * d.enc_patch * d.enc_patch * 4, /* R_PATCH: f32 */ + 2 * 4, /* R_SIGMA */ + 2 * 4, /* R_SNEXT */ + 2 * 4, /* R_CFG */ + 2 * 4, /* R_PAIR */ + 2 * 4, /* R_LANES */ + 2 * 4, /* R_FLAGS */ + 2 * 2 * 4, /* R_SEED */ + 3 * 4, /* R_LATCU */ + d.max_query * 3 * 4, /* R_QUERY: f32 */ + 2 * 4, /* R_QCU */ + }; + int64_t off = 0; + for (int r = 0; r < n; ++r) { + bytes[r][0] = off; + bytes[r][1] = want[r]; + off = align_up(off + want[r], kAlign); + } + return off; +} + +} /* namespace */ + +int64_t ShapeDriver::device_bytes(const Program& prog) { + if (!prog.is_shape_generator()) return 0; + int64_t b[R_N][2]; + return carve(prog.shape_gen, b, R_N); +} + +int ShapeDriver::init(const Program& prog, const std::vector& ranks) { + fini(); + if (!prog.is_shape_generator()) return RAD_E_STATE; + decl_ = prog.shape_gen; + info_ = shape_info(decl_, prog.sgen_name); + ranks_ = ranks; + n_patch_ = (decl_.enc_size / decl_.enc_patch) * (decl_.enc_size / decl_.enc_patch); + patch_dim_ = 3 * decl_.enc_patch * decl_.enc_patch; + int64_t b[R_N][2]; + bytes_ = carve(decl_, b, R_N); + for (int r = 0; r < R_N; ++r) { + reg_[r].off = b[r][0]; + reg_[r].bytes = b[r][1]; + reg_[r].used = 0; + } + host_ = static_cast(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED)); + field_host_ = static_cast(rad_dev_alloc(decl_.max_query * 4, RAD_MEM_HOST_PINNED)); + if (!host_ || !field_host_) { + RAD_ERR("shape generator: no pinned host memory for the pass staging and the field " + "(%lld + %lld bytes)", (long long)bytes_, (long long)(decl_.max_query * 4)); + return RAD_E_NOMEM; + } + std::memset(host_, 0, (size_t)bytes_); + dev_.assign(ranks_.size(), nullptr); + for (size_t r = 0; r < ranks_.size(); ++r) { + RAD_TRY(rad_dev_set(ranks_[r].device)); + dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE); + if (!dev_[r]) { + RAD_ERR("shape generator: rank %zu has no room for the pass staging (%lld bytes)", r, + (long long)bytes_); + return RAD_E_NOMEM; + } + } + if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device)); + out_.assign(ranks_.size(), RadBatch{}); + sout_.assign(ranks_.size(), RadShapeGenBatch{}); + free_lanes_.clear(); + for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i); + return RAD_OK; +} + +void ShapeDriver::fini() { + for (size_t r = 0; r < dev_.size(); ++r) + if (dev_[r]) { + if (r < ranks_.size()) rad_dev_set(ranks_[r].device); + rad_dev_free(dev_[r], RAD_MEM_DEVICE); + } + dev_.clear(); + if (!ranks_.empty()) rad_dev_set(ranks_[0].device); + if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED); + if (field_host_) rad_dev_free(field_host_, RAD_MEM_HOST_PINNED); + host_ = nullptr; + field_host_ = nullptr; +} + +/* ================================================================== requests */ +int ShapeDriver::submit(std::unique_ptr r, std::string* why) { + if (!r || !r->ticket) return RAD_E_INVAL; + const RadShapeGenDecl& d = decl_; + auto no = [&](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + if ((int64_t)r->patches.size() != n_patch_ * patch_dim_) + return no("the picture is not prepared for this model's image encoder"); + const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps; + if (steps < 2 || steps > d.max_steps) + return no("num_inference_steps must be 2.." + std::to_string(d.max_steps) + + " (sigma grid points, the last one the clean shape)"); + const double cfg = std::isnan(r->guidance) ? d.default_guidance : r->guidance; + if (!(cfg >= 0.0) || !std::isfinite(cfg)) + return no("guidance_scale must be finite and not negative"); + const int32_t res = r->resolution > 0 ? r->resolution : (int32_t)d.default_resolution; + if (res < d.min_resolution || res > d.max_resolution) + return no("octree_resolution must be " + std::to_string(d.min_resolution) + ".." + + std::to_string(d.max_resolution)); + + auto j = std::make_unique(); + j->sigmas = shape_sigmas(steps); + j->evals = steps - 1; + j->cfg = (float)cfg; + j->levels = r->dense ? std::vector{ res } : shape_levels(res); + ShapeTicket& t = *r->ticket; + t.steps = j->evals; + t.resolution = res; + t.guidance = cfg; + t.t_submit_ns = (int64_t)rad_mono_ns(); + std::lock_guard lk(mu_); + if (closed_) { + if (why) *why = closed_why_; + return closed_status_; + } + j->id = next_id_++; + j->req = std::move(r); + jobs_.push_back(std::move(j)); + return RAD_OK; +} + +void ShapeDriver::shutdown(const char* why, int status) { + std::lock_guard lk(mu_); + closed_ = true; + closed_why_ = why ? why : "the engine stopped"; + closed_status_ = status; + for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_); +} + +int64_t ShapeDriver::queued() const { + std::lock_guard lk(mu_); + int64_t n = 0; + for (const auto& j : jobs_) if (!j->admitted) ++n; + return n; +} + +int64_t ShapeDriver::running() const { + std::lock_guard lk(mu_); + int64_t n = 0; + for (const auto& j : jobs_) if (j->admitted) ++n; + return n; +} + +ShapeDriver::Job* ShapeDriver::job_locked(uint64_t id) { + for (auto& j : jobs_) if (j->id == id) return j.get(); + return nullptr; +} + +void ShapeDriver::release_locked(Job& j) { + if (j.lane >= 0) { + free_lanes_.push_back(j.lane); + j.lane = -1; + } +} + +void ShapeDriver::fail_locked(Job& j, int status, const std::string& why) { + j.failed = true; + j.req->ticket->finish(status, why); +} + +/* In arrival order: a request needs only a lane. */ +void ShapeDriver::admit_locked() { + for (auto& jp : jobs_) { + Job& j = *jp; + if (j.admitted || j.failed) continue; + if (free_lanes_.empty()) break; + j.lane = free_lanes_.back(); + free_lanes_.pop_back(); + j.admitted = true; + } +} + +/* A level of the grid begins: its field unsampled, its points `pts` (every point when `all`). */ +void ShapeDriver::start_level(Job& j, size_t level, std::vector&& pts, bool all) { + const int32_t r = j.levels[level]; + const int64_t n = (int64_t)r + 1; + j.level = level; + j.field.assign((size_t)(n * n * n), NAN); + j.axis = shape_axis(decl_.bounds, r); + j.all = all; + j.pts = std::move(pts); + j.n_pts = all ? n * n * n : (int64_t)j.pts.size(); + j.next = 0; +} + +/* ================================================================== staging */ +int ShapeDriver::upload() { + for (size_t r = 0; r < ranks_.size(); ++r) + for (int g = 0; g < R_N; ++g) { + if (reg_[g].used <= 0) continue; + RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off, + reg_[g].used, ranks_[r].stream)); + } + return RAD_OK; +} + +void ShapeDriver::stage_common(const Job& j) { + const int32_t lanes[2] = { j.lane, j.lane }; + const int32_t cu[3] = { 0, (int32_t)decl_.latent_rows, (int32_t)(2 * decl_.latent_rows) }; + std::memcpy(hptr(R_LANES), lanes, sizeof lanes); + std::memcpy(hptr(R_LATCU), cu, sizeof cu); + reg_[R_LANES].used = sizeof lanes; + reg_[R_LATCU].used = sizeof cu; +} + +void ShapeDriver::base_batches(const Job& j, int64_t n_tok, int kind, int step) { + for (size_t r = 0; r < ranks_.size(); ++r) { + RadBatch& B = out_[r]; + RadShapeGenBatch& S = sout_[r]; + const int ri = (int)r; + B = RadBatch{}; + B.step = step; + B.phase = RAD_PHASE_PREFILL; + B.n_tok = n_tok; + B.n_seq = 1; + B.max_q_len = (int32_t)n_tok; + B.max_q_len_prefill = (int32_t)n_tok; + B.gen = kind; + S = RadShapeGenBatch{}; + S.lane = j.lane; + S.patches = dptr(ri, R_PATCH); + S.step = j.step; + S.n_steps = j.evals; + S.sigma = dptr(ri, R_SIGMA); + S.sigma_next = dptr(ri, R_SNEXT); + S.cfg = dptr(ri, R_CFG); + S.pair = dptr(ri, R_PAIR); + S.lanes = dptr(ri, R_LANES); + S.flags = dptr(ri, R_FLAGS); + S.seed = dptr(ri, R_SEED); + S.lat_cu = dptr(ri, R_LATCU); + S.query = dptr(ri, R_QUERY); + S.query_cu = dptr(ri, R_QCU); + B.sgen_b = &S; + } + pass_.kind = kind; + pass_.job = j.id; +} + +/* ================================================================== the passes */ +const RadBatch* ShapeDriver::next(int step) { + std::lock_guard lk(mu_); + pass_ = Pass{}; + rb_.clear(); + if (closed_) return nullptr; + /* Retire finished, failed and cancelled jobs, returning their lanes before admitting. Safe + * because next() runs between passes, with nothing in flight. */ + for (auto it = jobs_.begin(); it != jobs_.end();) { + Job& j = **it; + const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire); + if (!(j.failed || cancelled || j.finished)) { ++it; continue; } + if (cancelled && !j.failed && !j.finished) + j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled"); + release_locked(j); + it = jobs_.erase(it); + } + admit_locked(); + + /* 1. The decoding of a denoised lane: its latent, then its grid. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (!j.admitted || j.failed || !j.cond_done || j.step < j.evals) continue; + return j.latent_done ? build_query(j, step) : build_latent(j, step); + } + /* 2. A picture. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step); + } + /* 3. The oldest lane's next step. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (j.admitted && !j.failed && j.cond_done && j.step < j.evals) return build_step(j, step); + } + return nullptr; +} + +const RadBatch* ShapeDriver::batch_for(int rank) const { + if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr; + return &out_[(size_t)rank]; +} + +const RadBatch* ShapeDriver::build_cond(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + std::memcpy(hptr(R_PATCH), j.req->patches.data(), j.req->patches.size() * 4); + reg_[R_PATCH].used = (int64_t)j.req->patches.size() * 4; + stage_common(j); + if (upload() < 0) return nullptr; + base_batches(j, n_patch_, RAD_GEN_PASS_SCOND, step); + return &out_[0]; +} + +/* The two entries of the step: the picture's latent guided against the unconditioned one, which + * reads the same lane and moves nothing. */ +const RadBatch* ShapeDriver::build_step(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const float s = j.sigmas[(size_t)j.step], sn = j.sigmas[(size_t)j.step + 1]; + const float sig[2] = { s, s }, nxt[2] = { sn, sn }, cfg[2] = { j.cfg, 1.0f }; + const int32_t pair[2] = { 1, -2 }; + const int32_t flags[2] = { j.step == 0 ? (int32_t)RAD_GEN_F_FIRST : 0, 0 }; + const uint32_t lo = (uint32_t)j.req->seed, hi = (uint32_t)(j.req->seed >> 32); + const uint32_t seed[4] = { lo, hi, lo, hi }; + auto stage = [&](int r, const void* p, int64_t n) { + std::memcpy(host_ + reg_[r].off, p, (size_t)n); + reg_[r].used = n; + }; + stage(R_SIGMA, sig, sizeof sig); + stage(R_SNEXT, nxt, sizeof nxt); + stage(R_CFG, cfg, sizeof cfg); + stage(R_PAIR, pair, sizeof pair); + stage(R_FLAGS, flags, sizeof flags); + stage(R_SEED, seed, sizeof seed); + stage_common(j); + if (upload() < 0) return nullptr; + base_batches(j, decl_.step_rows, RAD_GEN_PASS_SSTEP, step); + return &out_[0]; +} + +const RadBatch* ShapeDriver::build_latent(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + stage_common(j); + if (upload() < 0) return nullptr; + base_batches(j, decl_.latent_rows, RAD_GEN_PASS_SLATENT, step); + return &out_[0]; +} + +/* The level's next run of points, at most max_query, as x, y, z. */ +const RadBatch* ShapeDriver::build_query(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const int64_t n = std::min(decl_.max_query, j.n_pts - j.next); + const int64_t side = (int64_t)j.levels[j.level] + 1; + float* q = hptr(R_QUERY); + for (int64_t i = 0; i < n; ++i) { + const int64_t p = j.all ? j.next + i : (int64_t)j.pts[(size_t)(j.next + i)]; + q[3 * i] = j.axis[(size_t)(p / (side * side))]; + q[3 * i + 1] = j.axis[(size_t)(p / side % side)]; + q[3 * i + 2] = j.axis[(size_t)(p % side)]; + } + reg_[R_QUERY].used = n * 3 * 4; + const int32_t qcu[2] = { 0, (int32_t)n }; + std::memcpy(hptr(R_QCU), qcu, sizeof qcu); + reg_[R_QCU].used = sizeof qcu; + stage_common(j); + if (upload() < 0) return nullptr; + base_batches(j, n, RAD_GEN_PASS_SQUERY, step); + for (auto& S : sout_) S.n_query = n; + pass_.n_query = n; + rb_.assign(1, Readback{ decl_.field_out, n * 4, field_host_ }); + return &out_[0]; +} + +int ShapeDriver::done() { + std::lock_guard lk(mu_); + const int64_t now = (int64_t)rad_mono_ns(); + Job* j = job_locked(pass_.job); + switch (j ? pass_.kind : 0) { + case RAD_GEN_PASS_SCOND: + j->cond_done = true; + j->req->ticket->t_cond_ns = now; + /* The patches are on the card for good; the request keeps no copy. */ + std::vector().swap(j->req->patches); + break; + case RAD_GEN_PASS_SSTEP: + ++j->step; + j->req->ticket->progress(j->step, 0); + if (j->step >= j->evals) j->req->ticket->t_denoised_ns = now; + break; + case RAD_GEN_PASS_SLATENT: + j->latent_done = true; + start_level(*j, 0, {}, true); + break; + case RAD_GEN_PASS_SQUERY: { + const int64_t n = pass_.n_query; + for (int64_t i = 0; i < n; ++i) { + const int64_t p = j->all ? j->next + i : (int64_t)j->pts[(size_t)(j->next + i)]; + j->field[(size_t)p] = field_host_[i]; + } + j->next += n; + j->points += n; + j->req->ticket->progress(j->step, (int32_t)std::min(j->points, INT32_MAX)); + if (j->next < j->n_pts) break; + /* The level is complete: the next one's points, or the end (also when no point of this + * level is near the surface, which leaves the finer levels nothing to sample). */ + if (j->level + 1 < j->levels.size()) { + const int32_t rp = j->levels[j->level], r = j->levels[j->level + 1]; + const bool last = j->level + 2 == j->levels.size(); + std::vector pts = shape_refine(j->field, rp, r, decl_.level, last); + if (!pts.empty()) { + start_level(*j, j->level + 1, std::move(pts), false); + break; + } + } + ShapeTicket& t = *j->req->ticket; + t.points = j->points; + t.t_done_ns = now; + t.set_field(std::move(j->field), j->levels[j->level]); + j->finished = true; + t.finish(RAD_OK); + break; + } + default: + break; + } + pass_ = Pass{}; + rb_.clear(); + return RAD_OK; +} + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/shape_driver.h b/core/gen/shape_driver.h new file mode 100644 index 00000000..0821e4d4 --- /dev/null +++ b/core/gen/shape_driver.h @@ -0,0 +1,141 @@ +/* shape_driver.h -- the shape generator's pass driver (shape.h; abi/rad_builder.h's + * RadShapeGenDecl describes the passes). + * + * Driven by the engine thread like the other drivers (pass.h): `next()` picks and stages a pass, + * `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads + * through `submit()` and leave through their ShapeTicket. + * + * A request holds a lane from admission to its last query. Its picture is prepared and its + * schedule fixed at submit; between passes the driver only stages, except when a level of the + * grid is complete, when it works out the points of the next (shape_refine). + * + * Pass priority, one pass at a time: + * + * 1. SLATENT, then the SQUERY passes level by level, of a lane whose denoising is done: they + * finish a request and free its lane. + * 2. SCOND of an admitted request, so its steps can follow the current request's without a gap. + * 3. SSTEP of the oldest lane with steps left. Requests are denoised one after another, not in + * turns: a pass is one request's, so taking turns would only delay the first. + */ +#pragma once +#include "shape.h" +#include "pass.h" +#include "device/device.h" + +#include +#include + +namespace rad { +namespace gen { + +class ShapeDriver final : public IPassDriver { +public: + struct RankIO { + int device = 0; + RadStream stream = nullptr; + }; + + int init(const Program& prog, const std::vector& ranks); + void fini(); + ~ShapeDriver() override { fini(); } + + /* The bytes init() allocates on each rank's card, for the VRAM budget. */ + static int64_t device_bytes(const Program& prog); + + /* ---------------------------------------------------------- HTTP threads */ + /* Queue a request, refused at once with `why` when it can never run. */ + int submit(std::unique_ptr r, std::string* why); + const ShapeGenInfo& info() const { return info_; } + void shutdown(const char* why, int status) override; + + /* ---------------------------------------------------------- the engine thread */ + const RadBatch* next(int step) override; + const RadBatch* batch_for(int rank) const override; + const std::vector& readbacks() const override { return rb_; } + int done() override; + + int64_t queued() const override; + int64_t running() const override; + +private: + struct Job { + uint64_t id = 0; + std::unique_ptr req; + std::vector sigmas; /* the request's grid points */ + float cfg = 0.0f; + int32_t evals = 0; /* steps the request takes: grid points less one */ + int32_t lane = -1; + bool admitted = false; + bool cond_done = false; + int32_t step = 0; /* steps done */ + bool latent_done = false; + /* The grid: its levels, the one being sampled, its field (NaN where not sampled) and + * the points it samples, all of them when `all` (the coarsest level, and dense + * sampling); `next` is the first not yet queried. */ + std::vector levels; + size_t level = 0; + std::vector field; + std::vector axis; + std::vector pts; + bool all = false; + int64_t n_pts = 0, next = 0; + int64_t points = 0; /* every level's, for the usage */ + bool failed = false; + bool finished = false; + }; + struct Pass { + int kind = 0; + uint64_t job = 0; + int64_t n_query = 0; + }; + struct Region { int64_t off = 0, bytes = 0, used = 0; }; + enum { R_PATCH, R_SIGMA, R_SNEXT, R_CFG, R_PAIR, R_LANES, R_FLAGS, R_SEED, R_LATCU, R_QUERY, + R_QCU, R_N }; + + template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } + template T* dptr(int rank, int r) const { + return reinterpret_cast((char*)dev_[(size_t)rank] + reg_[r].off); + } + int upload(); + /* What every pass carries: the lane twice (the step's two entries) and the latents' bounds. */ + void stage_common(const Job& j); + void base_batches(const Job& j, int64_t n_tok, int kind, int step); + void start_level(Job& j, size_t level, std::vector&& pts, bool all); + + void admit_locked(); + void release_locked(Job& j); + void fail_locked(Job& j, int status, const std::string& why); + Job* job_locked(uint64_t id); + + const RadBatch* build_cond(Job& j, int step); + const RadBatch* build_step(Job& j, int step); + const RadBatch* build_latent(Job& j, int step); + const RadBatch* build_query(Job& j, int step); + + RadShapeGenDecl decl_{}; + ShapeGenInfo info_; + int64_t n_patch_ = 0, patch_dim_ = 0; + std::vector ranks_; + + char* host_ = nullptr; /* pinned, same layout as each slab */ + int64_t bytes_ = 0; + std::vector dev_; + Region reg_[R_N]; + float* field_host_ = nullptr; + std::vector rb_; + + std::vector out_; /* one per rank */ + std::vector sout_; + Pass pass_; + + mutable std::mutex mu_; + std::deque> jobs_; /* arrival order */ + std::vector free_lanes_; + uint64_t next_id_ = 1; + bool closed_ = false; + std::string closed_why_; + int closed_status_ = RAD_E_STATE; +}; + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index caa318ad..b7f1a5c2 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -198,6 +198,9 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd, int64_t (*bytes)[2], int n) { /* A guided model's VCOND carries the negative prompt after the positive. */ const int64_t prompts = d.guidance ? 2 : 1; + /* A schedule's steps: a request's, at most max_steps, plus the refinement rungs an upscaling + * request appends after them (video_schedule). */ + const int64_t sched_cap = (int64_t)d.max_steps + std::max(d.n_refine_rungs, 0); const int64_t want[] = { prompts * d.max_text * 4, /* R_TOK */ prompts * d.max_text * 4, /* R_POS */ @@ -205,8 +208,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd, 3 * max_tok * 4, /* R_ROPE: a step's positions, or the prompt's M-RoPE */ RAD_VGEOM_N * 4, /* R_GEOM */ 16 * 4, /* R_SCHED */ - d.max_steps * 4, /* R_TV */ - d.max_steps * 4, /* R_TA */ + sched_cap * 4, /* R_TV */ + sched_cap * 4, /* R_TA */ 4 * 4, /* R_SEED */ 4, /* R_LANE */ 4, /* R_FIRST */ @@ -1008,6 +1011,11 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) { px[i] = rad_f32_to_bf16(2.0f * ((float)img[i] / 255.0f) - 1.0f); reg_[R_IMG].used = (int64_t)img.size() * 2; } + if ((int64_t)j.sched.steps * 4 > reg_[R_TV].bytes) { + fail_locked(j, RAD_E_STATE, "the schedule's " + std::to_string(j.sched.steps) + + " steps are more than the timestep regions hold"); + return nullptr; + } float* tv = hptr(R_TV); float* ta = hptr(R_TA); for (int32_t i = 0; i < j.sched.steps; ++i) { @@ -1238,7 +1246,7 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) { } else { const int64_t nf = m.enc_frames, area = (int64_t)eh * ew * 3; stage_frames = ng > 23 ? gd[23] : 0; - if (stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) { + if (nf < 1 || stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) { fail_locked(j, RAD_E_STATE, "'" + m.name + "' does not fit an encode pass"); return nullptr; } diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index 12e4c656..b8a773d3 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -381,12 +381,16 @@ int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) { fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT); if (counted) { const int64_t was = q.window_blocks * q.bytes_per_block; - /* The plan counted this group's snapshot section, so both totals carry `was`. - * Saturating hides an accounting bug; surface it in debug builds. */ - assert(window_ck_bytes_ >= was && checkpoint_bytes_ >= was && - "runtime window: snapshot byte totals below the section being removed"); - window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0; - checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0; + /* The plan counted this group's snapshot section, so both totals carry `was`; less + * is an accounting bug, and the pool would be sized from a wrong total. */ + if (window_ck_bytes_ < was || checkpoint_bytes_ < was) { + RAD_ERR("kv group %d: runtime window: the snapshot byte totals (%lld, %lld) are " + "below the %lld-byte section being removed", (int)g, + (long long)window_ck_bytes_, (long long)checkpoint_bytes_, (long long)was); + return RAD_E_STATE; + } + window_ck_bytes_ -= was; + checkpoint_bytes_ -= was; } } return RAD_OK; diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp index 640157e6..2ebcde11 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -52,9 +52,10 @@ bool target_covers(const std::string& declared, const char* arch) { } /* Two schemas for one op are the same when every positional slot means the same thing: parameter - * keys, types and requiredness (what the selector matches on) and operand count, roles and - * optionality (arguments are positional). Operand names are for diagnostics only (ABI), so "b" - * and "w_gate" in slot 1 agree. */ + * keys, types, requiredness (what the selector matches on) and roles (the core reads the first + * registrant's: a chunk or a capacity named by one plugin applies to every plugin's rows), and + * operand count, roles and optionality (arguments are positional). Operand names are for + * diagnostics only (ABI), so "b" and "w_gate" in slot 1 agree. */ bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff) { if (a.n_params != b.n_params) { *diff = fmt("%d parameters vs %d", a.n_params, b.n_params); @@ -77,6 +78,10 @@ bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff) x.required ? "required" : "optional", y.required ? "required" : "optional"); return false; } + if (x.role != y.role) { + *diff = fmt("parameter '%s' has role %d vs %d", or_empty(x.key), x.role, y.role); + return false; + } } if (a.n_operands != b.n_operands) { *diff = fmt("%d operands vs %d", a.n_operands, b.n_operands); @@ -291,6 +296,27 @@ int Registry::commit_(Staged& s, int order) { unstage_(s); return RAD_E_INVAL; } + /* The counts are the plugin's word; the tables they index are walked at every + * selection and every issue, so a null table or an operand count past what an issue + * can carry (MAX_OPERANDS) is refused here, by name, rather than read there. */ + if (sch->n_params < 0 || (sch->n_params && !sch->params) || sch->n_operands < 0 || + sch->n_operands > MAX_OPERANDS || (sch->n_operands && !sch->operands)) { + err_("kernel plugin '%s': op '%s' declares %d parameters and %d operands, a table " + "missing, or more operands than an issue carries (%d)", p.name.c_str(), + sch->op, sch->n_params, sch->n_operands, MAX_OPERANDS); + unstage_(s); + return RAD_E_INVAL; + } + for (int q = 0; q < sch->n_params; ++q) { + const RadParamSpec& ps = sch->params[q]; + if (!ps.key || !ps.key[0] || ps.role < RAD_PROLE_NONE || + ps.role > RAD_PROLE_CAPACITY) { + err_("kernel plugin '%s': op '%s' parameter %d has no key or an unknown role " + "(%d)", p.name.c_str(), sch->op, q, ps.role); + unstage_(s); + return RAD_E_INVAL; + } + } std::string diff; auto it = schemas_.find(sch->op); if (it != schemas_.end()) { @@ -338,6 +364,23 @@ int Registry::commit_(Staged& s, int order) { unstage_(s); return RAD_E_INVAL; } + /* The selector reads every constraint of every row at every query, and the tuner every + * tunable, so their tables must exist wherever a count says they do. */ + if (k->n_tunables < 0 || (k->n_tunables && !k->tunables) || k->n_constraints < 0 || + (k->n_constraints && !k->constraints)) { + err_("kernel '%s' in plugin '%s' declares %d tunables and %d constraints with a " + "missing table", k->name, p.name.c_str(), k->n_tunables, k->n_constraints); + unstage_(s); + return RAD_E_INVAL; + } + for (int c = 0; c < k->n_constraints; ++c) + if (!k->constraints[c].key || !k->constraints[c].key[0] || + (k->constraints[c].op == RAD_C_IN && !k->constraints[c].sval)) { + err_("kernel '%s' in plugin '%s' declares constraint %d with no key, or an IN " + "with no set", k->name, p.name.c_str(), c); + unstage_(s); + return RAD_E_INVAL; + } /* Every tunable axis must carry a default that is one of its own values. Untuned * shapes (no cache, an unmeasured shape, another card's cache) run the defaults, with * no other fallback (spec §15). Checked at load rather than first use so a bad axis @@ -382,8 +425,15 @@ int Registry::commit_(Staged& s, int order) { if (no_device_code_) why = "no card is visible, so this process runs on the host backend and no GPU code " "object runs here"; - if (n_device > 0 && s.code_to > s.code_from && - (no_device_code_ || rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0)) { + /* The code range decides only the per-card test: on the host backend the rows go even when + * this dlopen registered no fat binary (no HIP in the build, or the library already + * mapped by another registry). */ + const bool no_code_here = + n_device > 0 && + (no_device_code_ || + (s.code_to > s.code_from && + rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0)); + if (no_code_here) { std::vector> keep; for (const auto& r : staged_rows) if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r); diff --git a/core/rad_core.h b/core/rad_core.h index b92a1d5b..ff01dbe3 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -17,6 +17,11 @@ namespace rad { +/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves + * room for an architecture plugin's private ops without a variable-length array on the hot path. + * The plugin loader refuses a schema with more, so no issue carries more. */ +constexpr int MAX_OPERANDS = 32; + namespace mm { struct Item; struct PromptMedia; } class Registry; @@ -451,9 +456,15 @@ public: std::vector decoder_max_area; } vgen_str; bool is_video_generator() const { return video_gen.max_lanes != 0; } + /* The declared shape generator (rad_declare_shape_generator); `max_lanes` 0 when none. Its + * name points at `sgen_name`. */ + RadShapeGenDecl shape_gen{}; + std::string sgen_name; + bool is_shape_generator() const { return shape_gen.max_lanes != 0; } /* Driven by passes, not token steps: any generator. */ bool is_pass_driven() const { - return is_generator() || is_audio_generator() || is_video_generator(); + return is_generator() || is_audio_generator() || is_video_generator() || + is_shape_generator(); } /* Two arenas, because a host-site activation cannot index device memory. The buffer plan diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index 7fce02f1..fa8f9d38 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -942,9 +942,9 @@ int Ctx::lane_join(int from, int to) { /* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A * field added to RadBatch changes its size: decide whether the key must read it, then update the - * size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded - * (below). */ -static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 408, + * size here. `agen_b`, `vgen_b` and `sgen_b` are set only on generator passes, which are never + * recorded (below). */ +static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 416, "RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on"); static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80, "RadKVGroupBatch changed: check that Ctx::pass_key reads every new field"); @@ -957,8 +957,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { * sequence from their counts), and such a step samples a prompt's first token, which is not * the repeating decode pass. */ if (b->n_plugin_words > 0) return 0; - /* A generator pass is shaped by what RadBatch::gen_b, agen_b or vgen_b carries, which no key - * below reads. */ + /* A generator pass is shaped by what RadBatch::gen_b, agen_b, vgen_b or sgen_b carries, which + * no key below reads. */ if (b->gen) return 0; uint64_t h = 0x9e3779b97f4a7c15ull; auto mix = [&](uint64_t v) { diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 1ee74d2b..de3bedfd 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -40,10 +40,6 @@ class Registry; struct XpState; struct XpLayer; -/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves - * room for an architecture plugin's private ops without a variable-length array on the hot path. */ -constexpr int MAX_OPERANDS = 32; - typedef void (*ArchStepFn)(RadCtx*, const RadBatch*); /* "[shape]/[stride]" of a tensor's live dimensions, for diagnostics. */ diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 84a607eb..06d16d02 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -725,7 +725,13 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& first = kv.first_block_pos(e.seq, (int32_t)gi); has_win = kv.runtime_window(e.seq, (int32_t)gi, &win); if (has_win) { - assert(!ring_blocks || ring_blocks == (int32_t)win.ring_blocks); + /* The ring size sets the group header's geometry, so every sequence in the + * group must report the same one. */ + if (ring_blocks && ring_blocks != (int32_t)win.ring_blocks) { + RAD_ERR("kv group %d: sequences report ring sizes of %d and %d blocks", + (int)gi, (int)ring_blocks, (int)win.ring_blocks); + return RAD_E_STATE; + } ring_blocks = (int32_t)win.ring_blocks; } bt_len = (int64_t)bt.size(); diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp index f185cd74..d052ae62 100644 --- a/core/sched/geometry.cpp +++ b/core/sched/geometry.cpp @@ -9,11 +9,13 @@ namespace rad { -/* lcm, with a non-positive side meaning "no constraint yet". */ +/* lcm, with a non-positive side meaning "no constraint yet". The sides are plugin-declared; an lcm + * past int64 saturates, so the quantum check refuses it rather than wrapping to a small one. */ static int64_t lcm64(int64_t a, int64_t b) { if (a <= 0) return b; if (b <= 0) return a; - return std::lcm(a, b); + const int64_t q = a / std::gcd(a, b); + return q > INT64_MAX / b ? INT64_MAX : q * b; } /* The op's sequence-chunk parameter, found by role (RAD_PROLE_SEQ_CHUNK) in its schema. Steps diff --git a/core/server/admin.cpp b/core/server/admin.cpp index 8e6969b9..de2e8134 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -390,7 +390,7 @@ json Server::capabilities() const { caps["reasoning"] = !rerank && deps_.chat && deps_.chat->supports_reasoning(); /* An image model reads pictures only for edits and writes no text a grammar could constrain, * whatever its conditioning network's processor would take. */ - const bool img = opt_.image_model || opt_.video_model; + const bool img = opt_.image_model || opt_.video_model || opt_.shape_model; caps["grammar"] = !img && !rerank && deps_.grammar != nullptr; /* Laya runs on the embedding path, but answers /v1/systemone, not /v1/embeddings. */ caps["embedding"] = deps_.embed != nullptr && !rerank && opt_.decision_type != "laya"; @@ -403,11 +403,13 @@ json Server::capabilities() const { caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0; caps["audio_generation"] = deps_.audio != nullptr; caps["video_generation"] = deps_.videos != nullptr; + caps["shape_generation"] = deps_.shapes != nullptr; /* The decision protocol /v1/systemone serves (ServerOptions::decision_type), so a proxy can * route to a decision model without trying a generation; null when it serves none. */ caps["decision"] = opt_.decision_type.empty() ? json(nullptr) : json(opt_.decision_type); /* What a video request may carry. */ if (deps_.videos) video_caps(caps, deps_.videos); + if (deps_.shapes) shape_caps(caps, deps_.shapes); /* The efforts a chat request may send, probed from the template at startup; null when it * takes any word. "none" and "minimal" are this server's and turn thinking off. */ if (lim_.reasoning_efforts.empty()) { diff --git a/core/server/iface.h b/core/server/iface.h index 12960e28..5adc13da 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -22,7 +22,8 @@ struct RadModelMeta; namespace rad { -namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket; } +namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket; + struct ShapeRequest; struct ShapeGenInfo; } namespace mm { struct Frame; struct Item; } namespace server { @@ -816,5 +817,19 @@ public: virtual int64_t running() const = 0; }; +/* The shape generator (core/gen/shape_driver.h), for a model that makes a 3-D shape from a + * picture: its declared picture, sampler and grid (gen::ShapeGenInfo) and its request queue. The + * server prepares the picture (gen::shape_picture), queues the request, and meshes the field the + * ticket hands back. */ +class IShapeGen { +public: + virtual ~IShapeGen() = default; + virtual const gen::ShapeGenInfo& info() const = 0; + /* Queue a request; refused at once, with `why`, when it can never run. */ + virtual int submit(std::unique_ptr r, std::string* why) = 0; + virtual int64_t queued() const = 0; + virtual int64_t running() const = 0; +}; + } /* namespace server */ } /* namespace rad */ diff --git a/core/server/oai.cpp b/core/server/oai.cpp index bcefbbd3..ff8d64b5 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -3379,11 +3379,16 @@ int anthropic_image(const json& block, const std::string& at, json* out, ApiErro * continuation sends only the tail of the conversation), so a field outside these lists is * refused by name rather than ignored. The refusal says "Extra inputs are not permitted", as * Anthropic's does; Claude Code matches those words to retry without a beta field it can - * drop. */ + * drop. + * + * The last row is not Anthropic's: the chat path's history penalties and min-p, under the chat + * path's names, ranges and meaning, for clients that speak only this format to a model whose + * card asks for them (Qwen's presence_penalty). */ const char* kAnthropicFields[] = { "model", "messages", "system", "max_tokens", "temperature", "top_p", "top_k", "stream", "stop_sequences", "tools", "tool_choice", "thinking", "metadata", "output_config", "output_format", "context_management", "thread", + "min_p", "presence_penalty", "frequency_penalty", "repetition_penalty", "repeat_last_n", }; /* Accepted and not acted on: none of them can change the answer here. Capacity and placement @@ -3917,8 +3922,11 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string if (one) o["parallel_tool_calls"] = false; } - /* `model` included, since the reply names it back as Anthropic's does. */ - for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream" }) + /* `model` included, since the reply names it back as Anthropic's does. The penalties and + * min-p are the chat path's own fields, checked there. */ + for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream", + "min_p", "presence_penalty", "frequency_penalty", "repetition_penalty", + "repeat_last_n" }) if (b.contains(k)) o[k] = b.at(k); if (b.contains("stop_sequences")) o["stop"] = b.at("stop_sequences"); diff --git a/core/server/realtime.cpp b/core/server/realtime.cpp index c9788901..9417c822 100644 --- a/core/server/realtime.cpp +++ b/core/server/realtime.cpp @@ -220,6 +220,12 @@ void Server::handle_realtime(const HttpRequest& req, WsConn& ws) { "this model does not transcribe: its architecture plugin states no " "transcription format (rad_arch_audio_format), or it was started without " "its audio encoder", 1008); + /* An open turn is cut at the encoder's clip length; without one it would grow for as long as + * the client appends audio. */ + if (deps_.mm->audio_max_samples() <= 0) + return refuse("invalid_request_error", "model_not_supported", + "this model's audio encoder states no clip length, which a realtime turn " + "is cut at", 1008); /* A session holds a connection's thread and one of its own for its whole life, and runs one * pass at a time: more sessions than the engine has sequences would only queue. */ const int64_t cap = std::max(1, opt_.max_seqs); diff --git a/core/server/server.cpp b/core/server/server.cpp index 84432396..a8638215 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -134,6 +134,10 @@ void Server::register_routes() { [this](const HttpRequest& q) { return handle_video_delete(q); }); router_.get ("/v1/videos/:id/content", [this](const HttpRequest& q) { return handle_video_content(q); }); + /* Hunyuan3D-2's API server: a shape from a picture. */ + router_.post("/generate", [this](const HttpRequest& q) { return handle_shape_generate(q); }); + router_.post("/send", [this](const HttpRequest& q) { return handle_shape_send(q); }); + router_.get ("/status/:uid", [this](const HttpRequest& q) { return handle_shape_status(q); }); router_.post("/v1/audio/transcriptions", [this](const HttpRequest& q) { return handle_transcription(q); }); /* The same, live over a WebSocket (OpenAI's realtime transcription session). A plain GET @@ -374,6 +378,7 @@ void Server::stop() { stopping_.store(true); transport_.stop(); stop_videos(); + stop_shapes(); drain_graveyard(2000); } @@ -1389,6 +1394,8 @@ std::optional Server::refuse_text(const std::string& peer, ApiShap "generates no text" : opt_.video_model ? "this is a video model: it serves /v1/videos and generates " "no text" + : opt_.shape_model ? "this is a 3-D shape model: it serves /generate and generates " + "no text" : nullptr; if (!why) return std::nullopt; return error_response(err_not_implemented(why), peer, shape); @@ -1675,6 +1682,7 @@ HttpResponse Server::serve_pooled(const HttpRequest& req, bool rerank) { opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images" : opt_.audio_model ? "/v1/embeddings requires an embedding model; this one makes audio" : opt_.video_model ? "/v1/embeddings requires an embedding model; this one makes video" + : opt_.shape_model ? "/v1/embeddings requires an embedding model; this one makes shapes" : "/v1/embeddings requires an embedding model; this one generates " "text"), req.peer); diff --git a/core/server/server.h b/core/server/server.h index 582a763c..b38feaee 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -43,6 +43,7 @@ struct Deps { IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */ IAudioGen* audio = nullptr; /* absent -> /v1/audio/speech is 501 */ IVideoGen* videos = nullptr; /* absent -> /v1/videos is 501 */ + IShapeGen* shapes = nullptr; /* absent -> /generate is 501 */ const SpeechFormat* speech = nullptr; /* absent -> /v1/audio/transcriptions is 501 */ /* Engine-side state the server cannot see (per-card VRAM, the expert plane), as a snapshot @@ -88,6 +89,10 @@ struct ServerOptions { * many finished videos are kept at most (the oldest go first). */ int64_t video_ttl_s = 3600; int64_t max_videos = 32; + /* A shape generator (rad_declare_shape_generator) generates no text either: the text + * endpoints answer 501 naming /generate. A shape made through /send is kept for /status for + * as long as a video, as many at most. */ + bool shape_model = false; /* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone * (systemone.h), "clef" serves it through the head on the card (clef.h), "laya" through the * Laya plugin's option logits (laya.h), "mica" through Mica's label logits (mica.h); empty @@ -264,6 +269,7 @@ private: struct RealtimeSession; /* realtime.cpp */ struct SpeechSession; /* speech_stream.cpp */ struct VideoJob; /* videos.cpp */ + struct ShapeJob; /* shapes.cpp */ struct StreamState; static UsageOut usage_of(const OaiRequest& r, const std::vector& gens); @@ -366,6 +372,17 @@ private: /* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning * efforts), shared by /server_info's `capabilities` and the model entry so they agree. */ json capabilities() const; + /* ------------------------------------------------------------------ shapes.cpp + * Hunyuan3D-2's own API: a shape from a picture, made at once (/generate) or in the + * background (/send) and collected (/status/{uid}). */ + HttpResponse handle_shape_generate(const HttpRequest& req); + HttpResponse handle_shape_send(const HttpRequest& req); + HttpResponse handle_shape_status(const HttpRequest& req); + void shape_work(std::shared_ptr j); + void sweep_shapes_locked(int64_t now); + void stop_shapes(); + static void shape_caps(json& caps, const IShapeGen* gen); + /* A video model's capabilities (videos.cpp). */ static void video_caps(json& caps, const IVideoGen* gen); HttpResponse handle_reset_prefix_cache(const HttpRequest& req); @@ -453,6 +470,9 @@ private: std::mutex videos_m_; std::vector> videos_; std::vector> videos_gone_; + /* The background shapes (/send), oldest first, and their threads (shapes.cpp). */ + std::mutex shapes_m_; + std::vector> shapes_; }; } /* namespace server */ diff --git a/core/server/shapes.cpp b/core/server/shapes.cpp new file mode 100644 index 00000000..f02010b1 --- /dev/null +++ b/core/server/shapes.cpp @@ -0,0 +1,334 @@ +/* shapes.cpp -- Hunyuan3D-2's API over a shape generator (core/gen/shape_driver.h): a 3-D shape + * from one picture. + * + * The routes and fields are the reference's own API server's (hy3dgen's api_server.py), so its + * clients (its Blender add-on, scripts written against it) work unchanged: + * + * POST /generate the shape, made while the request waits, as the file itself; + * POST /send the same in the background, answered at once with {"uid"}; + * GET /status/{uid} {"status": "processing"}, or "completed" with the file as + * `model_base64`, or "error" with its `message`. + * + * The body is JSON: `image`, the picture as base64 (or a data URL), with an alpha channel for a + * cut-out object -- the reference removes the background of an opaque picture with rembg, which + * this server does not, so an opaque picture is taken whole; `seed` (1234 when absent, as the + * reference), `octree_resolution`, `num_inference_steps` and `guidance_scale` (the model's own + * when absent), and `type`, the file: glb (the default), obj, ply or stl. `volume_decoding` + * "dense" samples every point of the grid instead of refining it coarse to fine. Texturing + * (`texture` true) and the reference's text-to-image and re-texturing inputs (`text`, `mesh`) + * are refused. The reference's knobs that change nothing here are taken and ignored: `face_count` + * (texturing's face budget), `num_chunks` (its decoder's batch) and `mc_algo` "mc"; any other + * field is refused by name. A finished background shape is kept for as long as a video, as many + * as videos. + */ +#include "server.h" +#include "oai.h" + +#include "gen/shape.h" +#include "mm/media.h" +#include "rad_internal.h" + +#include + +#include +#include +#include + +namespace rad { +namespace server { + +namespace { + +/* The largest picture decoded, as the image endpoints bound theirs. */ +constexpr int64_t kMaxSourcePixels = (int64_t)1 << 26; + +/* A request as the routes read it, and its file's format. */ +struct ShapeAsk { + std::unique_ptr req; + std::string type = "glb"; +}; + +int read_ask(const HttpRequest& q, const OaiLimits& lim, const gen::ShapeGenInfo& info, + ShapeAsk* out, ApiError* err) { + json b; + if (parse_request_object(q.body, lim, &b, err) < 0) return RAD_E_INVAL; + auto bad = [&](const std::string& p, const std::string& why) { + *err = err_bad(p, why); + return RAD_E_INVAL; + }; + static const char* const kFields[] = { "image", "seed", "octree_resolution", + "num_inference_steps", "guidance_scale", "type", + "volume_decoding", "texture", "text", "mesh", + "face_count", "num_chunks", "mc_algo" }; + for (auto it = b.begin(); it != b.end(); ++it) { + bool known = false; + for (const char* k : kFields) known = known || it.key() == k; + if (!known) + return bad(it.key(), "'" + it.key() + "' is not a field of /generate"); + } + if (b.contains("mc_algo") && !b["mc_algo"].is_null() && + !(b["mc_algo"].is_string() && b["mc_algo"].get() == "mc")) { + *err = err_unsupported("mc_algo", "the surface is marching cubes ('mc'); differentiable " + "marching cubes ('dmc') is not served"); + return RAD_E_INVAL; + } + for (const char* k : { "text", "mesh" }) + if (b.contains(k) && !b[k].is_null()) { + *err = err_unsupported(k, std::string("this server makes a shape from a picture; '") + + k + "' (the reference's text-to-image and re-texturing " + "inputs) is not served"); + return RAD_E_INVAL; + } + if (b.contains("texture") && b["texture"].is_boolean() && b["texture"].get()) { + *err = err_unsupported("texture", "texturing (Hunyuan3D-Paint) is not served: this " + "server makes the untextured shape"); + return RAD_E_INVAL; + } + if (!b.contains("image") || !b["image"].is_string() || b["image"].get().empty()) + return bad("image", "'image' must be the picture as base64"); + std::string img = b["image"].get(); + if (img.rfind("data:", 0) == 0) { + const size_t comma = img.find(','); + if (comma == std::string::npos || img.compare(comma - 7, 7, ";base64") != 0) + return bad("image", "a data URL must be base64 ('data:;base64,...')"); + img = img.substr(comma + 1); + } + std::vector bytes; + if (!base64_decode(img, &bytes) || bytes.empty()) + return bad("image", "'image' is not valid base64"); + mm::FrameRGBA f; + std::string why; + if (mm::decode_image_rgba(bytes.data(), bytes.size(), kMaxSourcePixels, &f, &why) < 0) + return bad("image", "the picture could not be decoded: " + why); + + auto r = std::make_unique(); + if (gen::shape_picture(info, f, &r->patches, &why) < 0) return bad("image", why); + auto int_field = [&](const char* k, int64_t lo, int64_t hi, int32_t* v) { + if (!b.contains(k) || b[k].is_null()) return true; + if (!b[k].is_number_integer() || b[k].get() < lo || b[k].get() > hi) { + bad(k, std::string("'") + k + "' must be an integer " + std::to_string(lo) + ".." + + std::to_string(hi)); + return false; + } + *v = (int32_t)b[k].get(); + return true; + }; + if (!int_field("num_inference_steps", 2, info.max_steps, &r->steps) || + !int_field("octree_resolution", info.min_resolution, info.max_resolution, + &r->resolution)) + return RAD_E_INVAL; + if (b.contains("guidance_scale") && !b["guidance_scale"].is_null()) { + if (!b["guidance_scale"].is_number() || !(b["guidance_scale"].get() >= 0.0) || + !std::isfinite(b["guidance_scale"].get())) + return bad("guidance_scale", "'guidance_scale' must be a finite number, not negative"); + r->guidance = b["guidance_scale"].get(); + } + r->seed = 1234; + if (b.contains("seed") && !b["seed"].is_null()) { + if (!b["seed"].is_number_integer()) + return bad("seed", "'seed' must be an integer"); + r->seed = b["seed"].is_number_unsigned() ? b["seed"].get() + : (uint64_t)b["seed"].get(); + } + if (b.contains("volume_decoding") && !b["volume_decoding"].is_null()) { + const std::string v = b["volume_decoding"].is_string() + ? b["volume_decoding"].get() : ""; + if (v != "hierarchical" && v != "dense") + return bad("volume_decoding", "'volume_decoding' is hierarchical or dense"); + r->dense = v == "dense"; + } + if (b.contains("type") && !b["type"].is_null()) { + if (!b["type"].is_string()) return bad("type", "'type' is glb, obj, ply or stl"); + out->type = b["type"].get(); + if (out->type != "glb" && out->type != "obj" && out->type != "ply" && out->type != "stl") + return bad("type", "type '" + out->type + "' is not one this server writes: glb, obj, " + "ply or stl"); + } + r->ticket = std::make_shared(); + out->req = std::move(r); + return RAD_OK; +} + +/* The ticket's field as a mesh file, once the driver is done with it. */ +int finish_file(gen::ShapeTicket& t, const gen::ShapeGenInfo& info, const std::string& type, + std::string* file, std::string* mime, std::string* why) { + if (t.status() < 0) { + *why = t.why(); + return t.status(); + } + int32_t r = 0; + std::vector field = t.take_field(&r); + gen::ShapeMesh mesh; + gen::shape_mesh(field, r, info.bounds, info.level, &mesh); + std::vector().swap(field); + if (mesh.f.empty()) { + *why = "the model's field crosses the surface level nowhere in the grid: the picture made " + "no shape"; + return RAD_E_INVAL; + } + return gen::shape_export(mesh, type, file, mime, why); +} + +} /* namespace */ + +struct Server::ShapeJob { + std::string uid, type; + int64_t created_at = 0, done_at = 0; + std::shared_ptr ticket; + std::thread worker; + /* Under Server::shapes_m_ from here on. */ + bool finished = false, failed = false; + std::string file, message; +}; + +void Server::shape_caps(json& caps, const IShapeGen* gen) { + const gen::ShapeGenInfo& info = gen->info(); + caps["shape_max_steps"] = info.max_steps; + caps["shape_resolutions"] = { info.min_resolution, info.max_resolution }; + caps["shape_formats"] = json::array({ "glb", "obj", "ply", "stl" }); +} + +HttpResponse Server::handle_shape_generate(const HttpRequest& req) { + if (!deps_.shapes) + return error_response(err_not_implemented( + "/generate requires a 3-D shape model; this one does not make shapes"), req.peer); + const gen::ShapeGenInfo& info = deps_.shapes->info(); + ShapeAsk a; + ApiError err; + if (read_ask(req, lim_, info, &a, &err) < 0) return error_response(err, req.peer); + std::shared_ptr t = a.req->ticket; + std::string why; + if (const int st = deps_.shapes->submit(std::move(a.req), &why); st < 0) + return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_overloaded(why), + req.peer); + while (!t->wait(500)) + if (stopping_.load()) { + t->cancel.store(true); + return error_response(err_overloaded("the server is stopping"), req.peer); + } + std::string file, mime; + if (const int st = finish_file(*t, info, a.type, &file, &mime, &why); st < 0) + return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_internal(why), + req.peer); + HttpResponse res; + res.content_type = mime; + res.body = std::move(file); + return res; +} + +void Server::shape_work(std::shared_ptr j) { + const gen::ShapeGenInfo& info = deps_.shapes->info(); + gen::ShapeTicket& t = *j->ticket; + while (!t.wait(500)) + if (stopping_.load()) { + t.cancel.store(true); + t.wait(60000); + break; + } + std::string file, mime, why; + const int st = t.finished() ? finish_file(t, info, j->type, &file, &mime, &why) + : RAD_E_CANCELLED; + std::lock_guard lk(shapes_m_); + j->finished = true; + j->done_at = unix_now(); + if (st < 0) { + j->failed = true; + j->message = why.empty() ? std::string(rad_strerror(st)) : why; + } else { + j->file = std::move(file); + } +} + +void Server::sweep_shapes_locked(int64_t now) { + for (size_t i = 0; i < shapes_.size();) { + ShapeJob& j = *shapes_[i]; + const bool expired = j.finished && now - j.done_at > opt_.video_ttl_s; + if (!expired) { ++i; continue; } + if (j.worker.joinable()) j.worker.join(); + shapes_.erase(shapes_.begin() + (std::ptrdiff_t)i); + } + /* Past the cap the oldest finished shapes go first. */ + size_t done = 0; + for (const auto& j : shapes_) done += j->finished; + const size_t cap = (size_t)std::max(opt_.max_videos, 1); + for (size_t i = 0; done > cap && i < shapes_.size();) { + if (!shapes_[i]->finished) { ++i; continue; } + if (shapes_[i]->worker.joinable()) shapes_[i]->worker.join(); + shapes_.erase(shapes_.begin() + (std::ptrdiff_t)i); + --done; + } +} + +void Server::stop_shapes() { + std::vector> all; + { + std::lock_guard lk(shapes_m_); + all = shapes_; + } + for (auto& j : all) j->ticket->cancel.store(true); + for (auto& j : all) + if (j->worker.joinable()) j->worker.join(); +} + +HttpResponse Server::handle_shape_send(const HttpRequest& req) { + if (!deps_.shapes) + return error_response(err_not_implemented( + "/send requires a 3-D shape model; this one does not make shapes"), req.peer); + const gen::ShapeGenInfo& info = deps_.shapes->info(); + ShapeAsk a; + ApiError err; + if (read_ask(req, lim_, info, &a, &err) < 0) return error_response(err, req.peer); + auto j = std::make_shared(); + j->uid = random_id("shape_"); + j->type = a.type; + j->created_at = unix_now(); + j->ticket = a.req->ticket; + std::string why; + if (const int st = deps_.shapes->submit(std::move(a.req), &why); st < 0) + return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_overloaded(why), + req.peer); + { + std::lock_guard lk(shapes_m_); + sweep_shapes_locked(unix_now()); + shapes_.push_back(j); + } + j->worker = std::thread([this, j] { shape_work(j); }); + json o; + o["uid"] = j->uid; + return HttpResponse::json_body(200, json_dump(o)); +} + +HttpResponse Server::handle_shape_status(const HttpRequest& req) { + if (!deps_.shapes) + return error_response(err_not_implemented( + "/status requires a 3-D shape model; this one does not make shapes"), req.peer); + const std::string uid = req.param("uid"); + std::lock_guard lk(shapes_m_); + sweep_shapes_locked(unix_now()); + for (const auto& j : shapes_) { + if (j->uid != uid) continue; + json o; + if (!j->finished) { + o["status"] = "processing"; + int32_t steps = 0, points = 0; + j->ticket->progress_of(&steps, &points); + o["steps_done"] = steps; + o["steps"] = j->ticket->steps; + } else if (j->failed) { + o["status"] = "error"; + o["message"] = j->message; + } else { + o["status"] = "completed"; + o["type"] = j->type; + o["model_base64"] = base64_encode(j->file.data(), j->file.size()); + } + return HttpResponse::json_body(200, json_dump(o)); + } + ApiError e = err_bad("uid", "no shape '" + uid + "'; it may have expired"); + e.status = 404; + e.type = "not_found_error"; + return error_response(e, req.peer); +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/videos.cpp b/core/server/videos.cpp index eceee3bd..23ffda22 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -535,7 +535,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { canvas_for(rw, rh, se, info.max_area, info.size_multiple, &W, &H); } if (W % info.size_multiple || H % info.size_multiple || W < info.min_side || - H < info.min_side || W * H > info.max_area || + H < info.min_side || W > info.max_area || H > info.max_area || W * H > info.max_area || std::max(W, H) > info.max_aspect * std::min(W, H)) { int64_t sw = 0, sh = 0; canvas_for((double)W, (double)H, short_def, info.max_area, info.size_multiple, &sw, &sh); diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h index fe0740fc..edf8c55f 100644 --- a/core/text/tokenizer.h +++ b/core/text/tokenizer.h @@ -320,6 +320,12 @@ int parse_tokenizer_json(const char* path, VocabBuild& out); /* Same, from an in-memory buffer, for a tokenizer.json that arrived some other way. */ int parse_tokenizer_json_buf(std::string_view json, const char* origin, VocabBuild& out); +/* The vocabulary of a model that reads no text (container metadata `radiance.text` = none: a + * picture-to-shape generator): one control token, which no request reaches, since such a program + * serves no text endpoint. rad-convert bakes it and the engine builds it for a checkpoint. */ +void vocab_textless(VocabBuild& out); +inline bool meta_textless(const char* v) { return v && std::string_view(v) == "none"; } + /* Read a standalone chat template file into out.chat_template, trailing newlines stripped. * A release that ships no template (DeepSeek's does not) needs one from elsewhere; the caller * passes the file. An unreadable or empty file is an error, never a silent skip. Returns diff --git a/core/text/tokenizer_json.cpp b/core/text/tokenizer_json.cpp index 79e389e4..85ec896b 100644 --- a/core/text/tokenizer_json.cpp +++ b/core/text/tokenizer_json.cpp @@ -892,6 +892,14 @@ const PreEntry k_pre[] = { } /* namespace */ +void vocab_textless(VocabBuild& out) { + out = VocabBuild{}; + out.kind = RAD_TOK_BPE; + out.tokens = { "<|no-text|>" }; + out.types = { RAD_TT_CONTROL }; + out.source = "none: the model reads no text"; +} + int vocab_from_gguf(const GgufFile& g, VocabBuild& out) { out = VocabBuild{}; out.source = g.path(); @@ -1107,7 +1115,8 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab * in, so the caller cannot pass a mismatched one. */ if (file_bytes < sizeof(RadFileHeader)) return RAD_E_FORMAT; const RadFileHeader* fh = reinterpret_cast(base); - if (fh->str_off + fh->str_bytes > file_bytes) return RAD_E_FORMAT; + if (fh->str_off > file_bytes || fh->str_bytes > file_bytes - fh->str_off) + return RAD_E_FORMAT; strs = reinterpret_cast(base + fh->str_off); str_bytes = fh->str_bytes; } @@ -1128,7 +1137,8 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab out.ignore_merges = (h->flags & RAD_VOCAB_IGNORE_MERGES) != 0; out.chat_template = S(h->chat_template); - if (!in_file(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff))) + if ((h->n_tokens && !h->tok_text_off) || + !in_file(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff))) return RAD_E_FORMAT; const rad_stroff* toff = reinterpret_cast(base + h->tok_text_off); out.tokens.resize(h->n_tokens); diff --git a/data/recipes/hunyuan3d-2-bf16.recipe b/data/recipes/hunyuan3d-2-bf16.recipe new file mode 100644 index 00000000..13fc9ec5 --- /dev/null +++ b/data/recipes/hunyuan3d-2-bf16.recipe @@ -0,0 +1,15 @@ +# hunyuan3d-2-bf16.recipe -- Hunyuan3D-2's shape model (hunyuan3d-dit-v2-0) served at bf16. +# +# rad-convert /hunyuan3d-dit-v2-0 \ +# --recipe data/recipes/hunyuan3d-2-bf16.recipe -o hunyuan3d-2-bf16.rad +# +# The folder holds config.yaml and model.fp16.safetensors (the DiT, the DINOv2 image encoder and +# the shape VAE in one file), read as one checkpoint. The release ships fp16; every weight is cast +# to bf16 but the two projections that read f32 inputs (the picture's patches and the query points' +# embedding) and the DiT's q and k norm gains, which are widened to f32 exactly. + +dino.patch.* cast dtype=f32 +geo.query_proj.* cast dtype=f32 +dit.*.q_norm cast dtype=f32 +dit.*.k_norm cast dtype=f32 +* cast dtype=bf16 diff --git a/docker/build.sh b/docker/build.sh index db5c59fd..042618a8 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -9,7 +9,8 @@ # docker/build.sh HEAD, here # docker/build.sh -s HOST HEAD, built on and kept by HOST # docker/build.sh -r COMMIT another commit -# docker/build.sh -t 'gfx1200;gfx1201' other GPU architectures (default gfx1201) +# docker/build.sh -t 'gfx1200;gfx1201' other GPU architectures (default +# 'gfx1201;gfx11-generic;gfx1151') # docker/build.sh -j 8 fewer compile jobs, for a host that is also serving # docker/build.sh -J 4 fewer tests at a time (default: the compile jobs) # docker/build.sh -B 5 multiply every test's CPU budget, for a host slower per @@ -24,7 +25,7 @@ cd "$(dirname "$0")/.." REV=HEAD HOST= -TARGETS=gfx1201 +TARGETS='gfx1201;gfx11-generic;gfx1151' JOBS= TEST_JOBS= BUDGET_SCALE= diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 9a26457c..1edf4136 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -35,6 +35,7 @@ plugin claims. | `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 | | `arch/breeze` | `breeze` | *(empty)* | Breeze-TTS-2, speech from text and a description of the voice: a T5Gemma 2 text encoder, a Qwen3 backbone with a 16-codebook depth decoder and the Qwen3-TTS 12 Hz codec, from the release directory, bf16, one card | | `arch/fishomni` | `fishomni` | `bsgemm-moe` | Fish Audio drama-3, speech from text with speaker tags and inline direction, its voices cloned from reference clips: the Qwen3.5-35B-A3B backbone with its routed experts block fp8 at f32 scales and everything else bf16, a 13-layer codebook tower over the backbone's full-attention cache, and Fish S2's modified DAC, encoder and decoder (`codec.pth`, read as data); from the release directory, two cards | +| `arch/hunyuan3d2` | `hunyuan3d2` | *(empty)* | Hunyuan3D-2's shape model (hunyuan3d-dit-v2-0), an untextured 3-D shape from one picture: DINOv2-giant over the picture, a FLUX-shaped flow-matching DiT (16 double-stream and 32 single-stream blocks of 1024) over a set of 3072 latents, and the shape VAE's geometry decoder, whose occupancy field the core samples on a grid and meshes; from the release folder (config.yaml and one safetensors), its fp16 weights cast to bf16 (`data/recipes/hunyuan3d-2-bf16.recipe`) | | `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text, between keyframes or from reference media: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`), or the DiT's per-token linears int8, served w8a8 (`minimax-h3-w8a8.recipe`); a curve-form checkpoint, whose timestep embeddings ship as a table, by the `minimax-h3-curve-*` recipes | | `arch/ltx2` | `ltx2` | *(empty)* | LTX-2.5 (base and distilled), a video with its stereo soundtrack from text or from text and a first frame: Gemma 4's language model and two text connectors, the duration head, a dual-stream audio-video DiT with four-way guidance, the causal video VAE (tiled past the default canvas) or the diffusion decoder, the audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; bf16 or block fp8, one card | @@ -2337,3 +2338,43 @@ with and without a first frame; diffusers on CUDA and on the CPU differ from eac On an R9700 (libr4d) the same five renders land within 0.15% of diffusers' CUDA rows, every op agreeing with its host reference under the op oracle. Block fp8 moves the random model's rows by 0.2 to 0.4% (the card's fp8a8 GEMMs, the CPU's fp8 codes widened to bf16). + +# `hunyuan3d2`: Hunyuan3D-2, a 3-D shape from a picture + +`arch/hunyuan3d2` declares a shape generator (`rad_declare_shape_generator`), which makes the +program one the engine drives through `core/gen/shape_driver.h`: SCOND runs the image encoder over +the picture and `cond_in` over its rows and over the unconditioned branch's zeros, into the lane; +SSTEP is one denoising step of both branches together; SLATENT runs the shape VAE's latent network +and leaves the geometry decoder's keys and values in the lane; each SQUERY pass is the geometry +decoder at up to 32768 points the core chose. The core samples the grid coarse to fine (FlashVDM's +hierarchical decoding with full attention) and meshes the finest level with marching cubes. A +request is a lane; two hold state at once. It is served on Hunyuan3D-2's own routes, `/generate`, +`/send` and `/status/{uid}` ([GUIDE §5.17](GUIDE.md)), bf16 on one card. The checkpoint is the +release's hunyuan3d-dit-v2-0 folder: config.yaml (its keys under their dotted paths) and one +safetensors holding `model.`, `conditioner.` and `vae.`. + +``` +picture the alpha's box at 85% of the picture's square, centred on white (OpenCV's INTER_AREA), + 512 x 512 (INTER_CUBIC), then 518 x 518 (bilinear) normalised by ImageNet's statistics, + in 37 x 37 patches of 14 x 14, f32 into the patch projection +encoder DINOv2-giant: 40 layers of 1536 (24 heads of 64), LayerNorm eps 1e-6, SwiGLU 4096 with + biases, layer scales on both branches, the class token and a learned position table; + the last hidden state after the final LayerNorm, 1370 rows. The unconditioned branch is + zeros, so its rows after cond_in are cond_in's bias +DiT FLUX's layout without a rotary: 16 double-stream blocks (the conditioning and the latent + each with their own weights, one joint attention) and 32 single-stream blocks + (linear1 = [qkv | mlp], linear2 over [attn | gelu_tanh(mlp)]), width 1024, 16 heads of + 64, q and k RMS-normed per head (eps 1e-6), LayerNorms without affine modulated as + (1 + scale) LN(x) + shift with gates and no tanh. The timestep embedding is the sinusoid + of 1000 sigma at a period of 1000 (the reference passes its time factor where + timestep_embedding takes max_period), then time_in. Rows a step: [cond | latent] for + the picture's branch and [latent | cond] for the unconditioned one, so each branch is + one attention run and the two latents one run for the latent stream's ops +sampler flow matching from sigma 0 (noise) to 1: Euler on numpy's linspace(0, 1, steps), the + last grid point's evaluation (a zero step in the reference) skipped; guidance 5 +VAE latent / scale_factor, post_kl 64 -> 1024, 16 self-attention blocks (q, k, v and the + geometry decoder's k, v are head-interleaved in the checkpoint and gathered per head at + conversion; per-head LayerNorms on q and k, exact GELU MLP 4096) +geometry a point's [x | sin | cos] at 8 octaves (51 values, f32, point_fourier), query_proj, one + cross-attention block over the latent rows (its own MLP), ln_post (eps 1e-5), a logit +``` diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 5861b95f..1ee7fec6 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -7,7 +7,8 @@ Docker, an AMD GPU and an `amdgpu` kernel driver that supports ROCm 10.1. It doe compiler or FFmpeg. The image is published as [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), -with its kernels built for `gfx1201`: `docker pull stilldeadcode/radiance`. Build it yourself for +with its kernels built for RDNA4 (`gfx1201`, libr4d), RDNA3 (`gfx11-generic`, libr3d) and Strix Halo +(`gfx1151`, libhalo): `docker pull stilldeadcode/radiance`. Build it yourself for other cards or another commit. The examples below use `radiance`, the tag a local build gets; with the published image, write `stilldeadcode/radiance` instead. @@ -26,7 +27,7 @@ docker/build.sh -j 8 # cap compile jobs (a device kernel takes docker/build.sh -J 4 # tests at a time (default: the compile jobs) docker/build.sh -B 5 # every test's CPU budget times 5, for a host slower per thread docker/build.sh -E tokenizer_perf_test # leave tests matching a regex out of the test stage -docker/build.sh -t 'gfx1200;gfx1201' # GPU architectures to compile kernels for (default gfx1201) +docker/build.sh -t 'gfx1200;gfx1201' # GPU architectures (default 'gfx1201;gfx11-generic;gfx1151') docker/build.sh -r # any other commit docker/build.sh --target build # stop at a stage, tagged radiance- ``` diff --git a/docs/GUIDE.md b/docs/GUIDE.md index eff75f60..add724eb 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -316,6 +316,7 @@ and runs. | `fishomni` | Fish Audio drama-3, speech from text with speaker tags and inline direction (§5.15) | | `minimaxh3` | MiniMax-H3 and FastH3, video with its stereo soundtrack from text (§5.16) | | `ltx2` | LTX-2.5, video with its stereo soundtrack from text or a first frame (§5.16) | +| `hunyuan3d2` | Hunyuan3D-2's shape model, an untextured 3-D mesh from one picture (§5.17) | **4. Falling back to the reference library is fatal.** If any op resolves to `libref`, the engine refuses to start and names the ops, because serving from it is orders of magnitude slower with nothing @@ -2132,7 +2133,7 @@ by 0.002-0.003 nats. | `--allow-host NAME` | — | a `Host` name the keyless loopback-only routes accept besides the loopback names; repeatable (§6.6) | | `--trusted-proxy CIDR` | — | a network whose sockets may name the client behind them, via `X-Forwarded-For`, for the log; vouching changes attribution, never access; repeatable (§6.6) | | `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the loaded one serves it | -| `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels, 14x14 on GLM-5.3). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card. A pass is not one tower invocation: inside it the tower batches at most 8 tiles per weight read, and the pass size may reduce that (4 tiles at the 64-pixel grid with the default 16384 patches); a picture contributes a separate pass per grid. See the concurrency notes for Unlimited-OCR (§5.17) | +| `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels, 14x14 on GLM-5.3). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card. A pass is not one tower invocation: inside it the tower batches at most 8 tiles per weight read, and the pass size may reduce that (4 tiles at the 64-pixel grid with the default 16384 patches); a picture contributes a separate pass per grid. See the concurrency notes for Unlimited-OCR (§5.18) | | `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the container's. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup | | `--max-queued-requests N` | 8 × `--max-num-seqs` | requests admitted and unfinished at once; past it, 429 | | `--http-threads N` | one per hardware thread, at least 4 | HTTP workers kept while idle | @@ -2229,6 +2230,7 @@ flags are refused on it, and so are the pixel bands. | `POST /v1/audio/speech` | OpenAI's speech API, whole or streamed: speech from a speech model (Breeze-TTS-2, `instructions` describing the voice; drama-3, speakers and direction in the input); songs from a music model (MiniMax-Music3), `input` the lyrics and `instructions` the song; else 501 (§5.15) | | `GET /v1/audio/speech/stream` (WebSocket) | vLLM-Omni's realtime speech session: text streamed in, each sentence's audio streamed out as soon as the sentence is complete; needs an audio generation model (§5.15) | | `POST /v1/videos`, `GET /v1/videos[/:id[/content]]`, `DELETE /v1/videos/:id` | OpenAI's video jobs: a video with its soundtrack from a prompt, made in the background and downloaded as MP4; needs a video model (MiniMax-H3), else 501 (§5.16) | +| `POST /generate`, `POST /send`, `GET /status/:uid` | Hunyuan3D-2's API server's routes: a 3-D mesh (GLB, OBJ, PLY or STL) from a picture, at once or in the background; needs a shape model (Hunyuan3D-2), else 501 (§5.17) | | `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs (§5.9, §5.11) | | `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client (§5.9) | | `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and clients of llama-server's own API (§5.9) | @@ -2638,7 +2640,7 @@ passes but not launches (the UNet runs once per image and branch), so two take t |---|---| | `model` | accepted and not enforced: one server serves one model | | `messages` / `prompt` / `input` | chat / completion / embedding | -| `images_config` | image models only: the processor mode the request wants, by name (`gundam`, `base`) or as an object restating the served sizes; a geometry the model does not serve is refused (Unlimited-OCR, §5.17) | +| `images_config` | image models only: the processor mode the request wants, by name (`gundam`, `base`) or as an object restating the served sizes; a geometry the model does not serve is refused (Unlimited-OCR, §5.18) | | `max_tokens`, `max_completion_tokens`, `n_predict` | default: what the context leaves after the prompt (`--default-max-tokens`); -1 is llama-server's "no limit", the same without the default. Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused (§5.8) | | `temperature` | [0, 2] | | `top_p` | (0, 1] | @@ -2856,6 +2858,7 @@ each field is read, taken without effect, or refused by name. | `role: "system"` in `messages` | after the head of the conversation, its text joins a user message at its position, since templates read a system message only at the head: as a text block ahead of the user message right after it, else after the one right before it, else as a user message of its own, so no two user turns follow each other. `clear_at: "next_user_message"` stops rendering it once a later user message (a `tool_result`-only one included) exists. An effort-only message (no text, `output_config: {"effort": ...}`) sets the effort from the next user message on. Blocks other than text (`tool_addition`, ...) are refused | | `tools`, `tool_choice` | client tools; server tools (`web_search_…`, `code_execution_…`) are refused. `tool_choice` as an object (`auto`, `any`, `tool`, `none`, `disable_parallel_tool_use`) or a string (`"auto"`, `"none"`, `"any"`); `any` is the chat path's `required` (§5.4) | | `max_tokens`, `temperature`, `top_p`, `top_k`, `stop_sequences`, `stream` | as on the chat path; `max_tokens` is optional there too | +| `min_p`, `presence_penalty`, `frequency_penalty`, `repetition_penalty`, `repeat_last_n` | not Anthropic's: the chat path's fields with its ranges and meaning (§5.7), for clients that speak only this format. The penalties count a token's occurrences in the last `repeat_last_n` tokens of prompt and reply (64 by default, `--repeat-last-n`), as llama.cpp does | | `thinking` | `enabled` (its `budget_tokens` is the chat request's `thinking_token_budget`), `adaptive`, `disabled`, `between_tools` (off). `display` and `block_binding` are taken: the reasoning comes back whole, with an empty `signature` | | `output_config` | `effort` (`low`, `medium`, `high`, `xhigh`, `max`) is the chat request's `reasoning_effort`, which the template reads in its own level names: a level it does not take is refused with the ones it does, and `--reasoning-effort-map` renames them (§4.9). `format` (`{"type": "json_schema", "schema": ...}`, or the older top-level `output_format`) is a `response_format` (§5.5). `task_budget` is taken | | `context_management` | validated; the conversation is served as sent, and the answer says so: `"context_management": {"applied_edits": []}`, on `message_delta` in a stream | @@ -3526,7 +3529,53 @@ The MP4's soundtrack is 48 kHz stereo. LTX-2.5 runs on one card; `--tp` above 1 Gemma 4 text encoder (13 GiB in fp8) does not fit a 32 GB card beside the DiT: serve it with `--vision-tower-placement ram`, which keeps it in pinned host memory and reads it once a prompt. -### 5.17 Documents: Unlimited-OCR +### 5.17 3-D shapes: `/generate` + +A shape generation model (Hunyuan3D-2) makes an untextured 3-D mesh from one picture of an object. +It answers Hunyuan3D-2's own API server's routes, so that server's clients (its Blender add-on, +scripts written against it) work unchanged: `POST /generate` makes the shape while the request +waits and answers with the file; `POST /send` makes it in the background and answers at once with +`{"uid": ...}`; `GET /status/{uid}` reports `{"status": "processing"}` (with `steps_done` of +`steps`), then `"completed"` with the file as base64 in `model_base64`, or `"error"` with its +`message`. + +```sh +# The shape model is tencent/Hunyuan3D-2's hunyuan3d-dit-v2-0 folder: config.yaml and +# model.fp16.safetensors. Its weights ship in fp16 and are cast to bf16 at conversion. +rad-convert Hunyuan3D-2/hunyuan3d-dit-v2-0 --recipe data/recipes/hunyuan3d-2-bf16.recipe \ + -o hunyuan3d-2-bf16.rad +radiance --model hunyuan3d-2-bf16.rad + +curl -s http://localhost:8000/generate -H 'Content-Type: application/json' \ + -d "{\"image\": \"$(base64 -w0 penguin.png)\"}" -o penguin.glb +``` + +- **`image`** is the picture as base64 (a data URL is taken too). Give it an alpha channel that cuts + the object out: the reference removes an opaque picture's background with rembg first, which this + server does not, so an opaque picture is taken whole, background and all. The picture is prepared + as the reference prepares it: the alpha's bounding box scaled to 85% of the square that holds the + picture, centred on white, 512 x 512, then the image encoder's 518 x 518. +- **`num_inference_steps`** counts sigma grid points (50, so 49 evaluations, by default; 2 to + 200); **`guidance_scale`** is the classifier-free guidance against the unconditioned branch (5 + by default); **`seed`** makes a shape repeatable (1234 when absent, as the reference). +- **`octree_resolution`** is the grid's cells a side the field is sampled on (256 by default, 16 + to 512). The grid is sampled coarse to fine, as FlashVDM's hierarchical decoding does: the whole + grid at the coarsest level (the resolution halved while it stays at least 63), then only the + points near the surface at each finer level; with `"volume_decoding": "dense"` every point of + the finest grid is sampled instead, as the reference's default decoder does (slower, the same + field). The surface is marching cubes over the finest grid at level 0. +- **`type`** is the file: `glb` (the default; positions, smooth normals and faces), `obj`, `ply` + (binary) or `stl` (binary). The mesh is the raw surface, as the reference's `/generate` returns + it without texturing: no floater removal or face reduction. +- **`texture`** true (Hunyuan3D-Paint) is refused: this server makes the untextured shape. So are + the reference's `text` (its text-to-image front end) and `mesh` (re-texturing) inputs. + +A shape is about 3 TFLOP of conditioning, 18 TFLOP a denoising step (both branches) and 34 MFLOP +a sampled grid point. The model runs on one card (2.2B parameters, 4.4 GiB in bf16); `--tp` above 1 +is refused. The licence (Tencent Hunyuan 3D 2.0 Community License) does not cover the European +Union, the United Kingdom or South Korea. + +### 5.18 Documents: Unlimited-OCR `unlimited-ocr` (baidu/Unlimited-OCR, bf16; the converted container is [Aijuus/unlimited-ocr-bf16](https://huggingface.co/Aijuus/unlimited-ocr-bf16), with its recipe; @@ -3895,7 +3944,7 @@ is the part of a log to paste into an issue. Its sections: warning is also printed as a `W` line of its own. ``` -I STARTUP REPORT -- radiance 1.15.1 +I STARTUP REPORT -- radiance 1.16.0 I CONFIGURATION -- every option, the value in force, and where it came from I --model /models/flashnext.rad [command line] I --tp 2 [command line] diff --git a/docs/OPS.md b/docs/OPS.md index 98b7be5f..5e24b173 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -1908,6 +1908,24 @@ over its encoded rows after the VAE encoder's fold. The weight is a declared con rows at a time, so each item's draws start at `e = 0`. MiniMax-H3: `n` 96, `stream` 2, `aug` 0.999. +## Shape generation + +The op a shape generator (Hunyuan3D-2, `rad_declare_shape_generator`) needs beyond an image +generator's: the embedding of the points its geometry decoder is queried at. Its encoder, denoiser +and decoder are otherwise built of the image and video generators' ops (`rms_mod` `norm` layer, +`gate_add` `act` none, `flow_euler`, `attn_cross`). + +| op | params | operands | +|---|---|---| +| `point_fourier` | `M`(range) `n` `freqs` `pi`/opt `dtype` | `x` → `y` | + +- `point_fourier`: row m of `y` is `[x | sin(x_i f_j) | cos(x_i f_j)]` over `x`'s `n` values, the + sines and then the cosines each `i`-major then `j`, with `f_j = 2^j` for `j < freqs` (times pi + with `pi` 1), so `y` is `[M, n (2 freqs + 1)]`: the shape VAE's FourierEmbedder with its input + included. The products are f32 (exact without pi, a power of two), the sine and cosine f32 and + rounded once to `y`'s dtype. `freqs` is at most 30. libr4d's `point_fourier_f32` serves f32 in + and out with the device's `sinf` and `cosf`. + ## LTX-2 The ops LTX-2's audio-video transformer adds (`libref/ref_ltx.cpp`): its rotary over fractional diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index ae27ab27..50d5777c 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -105,6 +105,10 @@ std::vector build_cases() { HS("dtype", dt) }, EB(27, 648, w, 1)); add("pool_cols", { HI("M", 40), HI("n", 256), HI("k", 8), HS("dtype", dt) }, EB(40, 256, w, 1)); + add("point_fourier", { HI("M", 37), HI("n", 3), HI("freqs", 8), HS("dtype", dt) }, + EB(37, 51, w, 1)); + add("point_fourier", { HI("M", 5), HI("n", 4), HI("freqs", 3), HI("pi", 1), + HS("dtype", dt) }, EB(5, 28, w, 1)); add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); add("scale_rows", { HI("M", 6), HI("n", 645), HS("act", "sigmoid"), HS("dtype", dt) }, EB(6, 645, w, 2)); diff --git a/libavx/avx_elementwise.cpp b/libavx/avx_elementwise.cpp index f6ab2618..c924e6f9 100644 --- a/libavx/avx_elementwise.cpp +++ b/libavx/avx_elementwise.cpp @@ -634,6 +634,40 @@ AVX_KERNEL(pool_cols) { return RAD_OK; } +/* ------------------------------------------------------------------ point_fourier */ +/* As libref: [x | sin(x_i 2^j) | cos(x_i 2^j)] (times pi with `pi` 1), the products, sines and + * cosines f32 and rounded once into y. Parallel over rows. */ +AVX_KERNEL(point_fourier) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0), F = p_int(a, "freqs", 0); + const bool pi = p_int(a, "pi", 0) != 0; + if (n <= 0 || F <= 0 || F > 30) return RAD_E_SHAPE; + const int64_t w = n * (2 * F + 1); + const int64_t M = rows_of(X, n); + if (M <= 0 || numel(Y) < M * w) return RAD_E_SHAPE; + float f[30]; + for (int64_t j = 0; j < F; ++j) + f[j] = pi ? (float)std::ldexp(3.14159265358979323846, (int)j) : std::ldexp(1.0f, (int)j); + + AVX_PARALLEL_FOR_IF(M * w >= AVX_PAR_MIN) + for (int64_t r = 0; r < M; ++r) { + float* acc = scratch_f32((size_t)w); + float* sx = scratch_f32_b((size_t)n); + const float* v = in_row(X, rowoff(X, r, n), n, sx); + for (int64_t i = 0; i < n; ++i) { + acc[i] = v[i]; + for (int64_t j = 0; j < F; ++j) { + const float t = v[i] * f[j]; + acc[n + i * F + j] = std::sin(t); + acc[n + n * F + i * F + j] = std::cos(t); + } + } + out_row(Y, rowoff(Y, r, w), w, acc); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ position_scale */ /* Ministral 3's query multiplier is rounded before multiplication, as in libref. */ AVX_KERNEL(position_scale) { diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 4f596752..a6eb6c6e 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -89,6 +89,7 @@ int avx_par_force(int threads); X(scale_rows) X(scale) X(fill) X(act_mul) \ X(seg_mean_bf16_sum) \ X(seg_mean) X(mul_weight) X(pool_rows) X(pool_cols) \ + X(point_fourier) \ X(seg_softmax_pool) \ X(relu) X(clamp) X(conv2d) X(conv1d_dw) \ X(rel_sinusoid) X(seg_sinusoid) X(conv2d_unfold) \ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 465ef0ae..f9fb37f4 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -166,6 +166,8 @@ static const RadParamSpec pSegPool[] = { P_INT("M"), P_INT("n"), P_STR("dtype") static const RadOperandSpec oSegPool[] = { OPD("score"), OPD("v"), OPD("cu_seqlens"), OUT("y") }; static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), P_STR("dtype") }; +static const RadParamSpec pPointFourier[] = { P_INT("M"), P_INT("n"), P_INT("freqs"), P_INTO("pi"), + P_STR("dtype") }; static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") }; static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") }; /* The audio (USM conformer) tower's operators, as in libref. */ @@ -992,6 +994,10 @@ static const RadOpSchema kSchemas[] = { { "pool_cols", ARR(pPoolRows), ARR(oUnary), "y[m][c] = the mean of x[m]'s columns [c*k, c*k + k), rounded to y's dtype, times mult, rounded " "again." }, +{ "point_fourier", ARR(pPointFourier), ARR(oUnary), + "A point's Fourier features: row m of y is [x | sin(x_i f_j) | cos(x_i f_j)] over x's n values, " + "sines then cosines each i-major then j, f_j = 2^j for j < freqs (times pi with `pi` 1); the " + "products f32, the sine and cosine f32 rounded once to y's dtype. y is [M, n (2 freqs + 1)]." }, { "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn), "Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." }, { "mla_project", ARR(pMlaProject), ARR(oGemm), @@ -1612,6 +1618,8 @@ SIMPLE("avx_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, DT_FLOAT, L(pool_rows)), SIMPLE("avx_pool_cols", "pool_cols", "elem", "mean of every k consecutive columns, then a " "multiplier", DT_FLOAT, L(pool_cols)), +SIMPLE("avx_point_fourier", "point_fourier", "elem", "a point's sines and cosines at octaves", + DT_FLOAT, L(point_fourier)), SIMPLE("avx_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, L(relu)), SIMPLE("avx_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, L(clamp)), SIMPLE("avx_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost", diff --git a/libavx/avx_support.cpp b/libavx/avx_support.cpp index edb57a6b..c0a7873c 100644 --- a/libavx/avx_support.cpp +++ b/libavx/avx_support.cpp @@ -170,14 +170,16 @@ float row_sum(const float* x, int64_t n) { return s; } +/* A NaN element is skipped, as libref's std::max(amax, |x|) skips it: vmaxps returns its second + * operand when either is NaN, so the running maximum goes second. */ float row_amax(const float* x, int64_t n) { vf m0 = vf_zero(), m1 = vf_zero(); int64_t i = 0; for (; i + 2 * VF_N <= n; i += 2 * VF_N) { - m0 = vf_max(m0, vf_abs(vf_loadu(x + i))); - m1 = vf_max(m1, vf_abs(vf_loadu(x + i + VF_N))); + m0 = vf_max(vf_abs(vf_loadu(x + i)), m0); + m1 = vf_max(vf_abs(vf_loadu(x + i + VF_N)), m1); } - for (; i + VF_N <= n; i += VF_N) m0 = vf_max(m0, vf_abs(vf_loadu(x + i))); + for (; i + VF_N <= n; i += VF_N) m0 = vf_max(vf_abs(vf_loadu(x + i)), m0); float m = vf_hmax(vf_max(m0, m1)); for (; i < n; ++i) { float av = x[i] < 0 ? -x[i] : x[i]; if (av > m) m = av; } return m; diff --git a/libhalo/README.md b/libhalo/README.md index 7705de71..ad9c5a52 100644 --- a/libhalo/README.md +++ b/libhalo/README.md @@ -16,7 +16,9 @@ Both are built when `RAD_GPU_TARGETS` names gfx1151, and on a Strix Halo libhalo - `rad_plugin_open` (`halo_rows.cpp`) declines every machine whose KFD topology lists no gfx1151, so on another RDNA3 card libhalo is not loaded at all and declares no schema: libr3d serves it alone. The loader would leave libhalo's device rows out there anyway (its code objects are - gfx1151's); declining also keeps its schemas out. + gfx1151's); declining also keeps its schemas out, and keeps rad-convert, which resolves kernels + without that check, from laying weights out for it. A process without `/dev/kfd` (a container + given no card, a machine with no amdgpu) sees no gfx1151 and declines it too. An explicit `--kernels` list orders the libraries as given; name `libhalo` before `libr3d`. diff --git a/libhalo/halo_attn_args.h b/libhalo/halo_attn_args.h index 9d5ac520..adca65ed 100644 --- a/libhalo/halo_attn_args.h +++ b/libhalo/halo_attn_args.h @@ -103,6 +103,8 @@ static inline int fill_paged_row(const RadArgs* a, HaloArgs* r, int expect_head_ if (kv->stride[3] != 1) return HALO_NO(RAD_E_STRIDE); if (kv->stride[2] != row) return HALO_NO(RAD_E_STRIDE); if (kv->shape[3] != row) return HALO_NO(RAD_E_SHAPE); + /* The kernels divide q_heads by kv_heads for the GQA factor. */ + if (kv->shape[1] <= 0) return HALO_NO(RAD_E_SHAPE); /* 16-byte alignment for 128-bit loads. */ if (!halo_aligned(q->data, 16) || !halo_aligned(o->data, 16) || !halo_aligned(kv->data, 16)) diff --git a/libhalo/halo_encoder_bf16.hip b/libhalo/halo_encoder_bf16.hip index 6cc72978..fd00c8f0 100644 --- a/libhalo/halo_encoder_bf16.hip +++ b/libhalo/halo_encoder_bf16.hip @@ -356,6 +356,31 @@ __global__ __launch_bounds__(kThreads) void pool_cols_kernel( } } +// ---------------------------------------------------------------------------- point_fourier +// ref_point_fourier: row m of y is [x | sin(x_i f_j) | cos(x_i f_j)], f_j = 2^j (times pi), the +// sines then the cosines each i-major then j; f32 in and out. A thread an output column. +__global__ __launch_bounds__(kThreads) void point_fourier_kernel( + const float* __restrict__ x, float* __restrict__ y, uint32_t n, uint32_t F, uint32_t pi, + uint32_t x_ld, uint32_t y_ld, uint32_t M) { + const uint32_t w = n * (2 * F + 1); + const uint32_t c = blockIdx.x * kThreads + threadIdx.x; + if (c >= w) return; + for (uint32_t r = blockIdx.y; r < M; r += gridDim.y) { + float v; + if (c < n) { + v = x[(size_t)r * x_ld + c]; + } else { + const uint32_t k = c - n, half = n * F; + const uint32_t i = (k % half) / F, j = (k % half) % F; + const float f = pi ? (float)ldexp(3.14159265358979323846, (int)j) + : ldexpf(1.0f, (int)j); + const float t = x[(size_t)r * x_ld + i] * f; + v = k < half ? sinf(t) : cosf(t); + } + y[(size_t)r * y_ld + c] = v; + } +} + // ---------------------------------------------------------------------------- cast bf16 -> f32 __global__ __launch_bounds__(kThreads) void widen_kernel( const uint16_t* __restrict__ x, float* __restrict__ y, uint32_t n, uint32_t x_ld, @@ -897,6 +922,19 @@ extern "C" int halo_pool_cols_bf16(long x, long y, int rows, int n, int k, float return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int halo_point_fourier_f32(long x, long y, int rows, int n, int freqs, int pi, + int x_ld, int y_ld, long stream) { + if (!x || !y) return -1; + if (rows <= 0 || n <= 0 || freqs <= 0 || freqs > 30) return -2; + const uint32_t w = (uint32_t)(n * (2 * freqs + 1)); + hipLaunchKernelGGL(point_fourier_kernel, + dim3((w + kThreads - 1) / kThreads, grid_rows(rows)), + dim3(kThreads), 0, (hipStream_t)stream, (const float*)x, (float*)y, + (uint32_t)n, (uint32_t)freqs, (uint32_t)(pi != 0), (uint32_t)x_ld, + (uint32_t)y_ld, (uint32_t)rows); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + extern "C" int halo_widen_bf16_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; @@ -1263,6 +1301,24 @@ extern "C" int halo_rad_pool_cols(const RadArgs* a, RadStream s) { (long)(uintptr_t)s)); } +/* ------------------------------------------------------------------ point_fourier */ +extern "C" int halo_rad_point_fourier(const RadArgs* a, RadStream s) { + const RadTensor* X = halo_opt(a, 0); + const RadTensor* Y = halo_opt(a, 1); + if (!X || !Y) return HALO_NO(RAD_E_INVAL); + if (X->dtype != RAD_F32 || Y->dtype != RAD_F32) return HALO_NO(RAD_E_DTYPE); + const long long n = halo_geti_or(a, "n", 0), F = halo_geti_or(a, "freqs", 0); + if (n <= 0 || F <= 0 || F > 30) return HALO_NO(RAD_E_SHAPE); + long long M = 0, My = 0; + const long long x_ld = halo_rows_pitch(X, n, &M); + const long long y_ld = halo_rows_pitch(Y, n * (2 * F + 1), &My); + if (x_ld < 0 || y_ld < 0) return HALO_NO(RAD_E_STRIDE); + if (M <= 0 || My < M) return HALO_NO(RAD_E_SHAPE); + return enc_status(halo_point_fourier_f32(halo_addr(X), halo_addr(Y), (int)M, (int)n, (int)F, + (int)halo_geti_or(a, "pi", 0), (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); +} + /* ------------------------------------------------------------------ cast bf16 -> f32 */ extern "C" int halo_rad_cast_widen(const RadArgs* a, RadStream s) { const RadTensor* x = halo_opt(a, 0); diff --git a/libhalo/halo_plugin.h b/libhalo/halo_plugin.h index e47feeac..89da9ae2 100644 --- a/libhalo/halo_plugin.h +++ b/libhalo/halo_plugin.h @@ -735,6 +735,7 @@ int halo_rad_cast_f16 (const RadArgs*, RadStream); int halo_rad_cast_bf16 (const RadArgs*, RadStream); int halo_rad_pool_rows (const RadArgs*, RadStream); int halo_rad_pool_cols (const RadArgs*, RadStream); +int halo_rad_point_fourier (const RadArgs*, RadStream); int halo_rad_relu (const RadArgs*, RadStream); int halo_rad_silu (const RadArgs*, RadStream); int halo_rad_gelu (const RadArgs*, RadStream); diff --git a/libhalo/halo_qsa_tail_store_bf16.hip b/libhalo/halo_qsa_tail_store_bf16.hip index f0a35229..bda2b950 100644 --- a/libhalo/halo_qsa_tail_store_bf16.hip +++ b/libhalo/halo_qsa_tail_store_bf16.hip @@ -36,7 +36,7 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx, uint16_t* __restrict__ state, - int T, int n, int ring, int seqs, int k_ld, int s_slot, int s_row, int sidx_ld) { + int T, int n, int ring, int seqs, int slots, int k_ld, int s_slot, int s_row, int sidx_ld) { const int t = (int)blockIdx.x; if (t >= T) return; @@ -50,9 +50,10 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( /* Only the last `ring` tokens of this sequence's chunk -- see the header. */ if (t < cu[s + 1] - ring) return; - /* Column 0 is the committed slot; -1 marks a sequence with no state. */ + /* Column 0 is the committed slot; -1 marks a sequence with no state. A slot past the + * state plane's would write past its allocation. */ const int si = sidx[(size_t)s * sidx_ld]; - if (si < 0) return; + if (si < 0 || si >= slots) return; const int row = pos[t] % ring; const size_t src = (size_t)t * k_ld; @@ -69,17 +70,17 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( // state [slots][ring][n] bf16, this layer's tail cache; written only, untargeted rows // keep their contents static int halo_qsa_tail_store_bf16_emit(long k, long pos, long cu, long sidx, long state, int T, - int n, int ring, int seqs, int k_ld, int s_slot, int s_row, - int sidx_ld, RadStream stream) { + int n, int ring, int seqs, int slots, int k_ld, int s_slot, + int s_row, int sidx_ld, RadStream stream) { if (!k || !pos || !cu || !sidx || !state) return HALO_NO(RAD_E_INVAL); - if (T <= 0 || n <= 0 || ring <= 0 || seqs <= 0) return HALO_NO(RAD_E_SHAPE); + if (T <= 0 || n <= 0 || ring <= 0 || seqs <= 0 || slots <= 0) return HALO_NO(RAD_E_SHAPE); if (!k_ld) k_ld = n; if (!s_row) s_row = n; if (!sidx_ld) sidx_ld = 1; return HALO_EMIT(stream, qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), 0, (const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu, - (const int32_t*)sidx, (uint16_t*)state, T, n, ring, seqs, k_ld, s_slot, s_row, - sidx_ld); + (const int32_t*)sidx, (uint16_t*)state, T, n, ring, seqs, slots, k_ld, s_slot, + s_row, sidx_ld); } // ============================================================== the plugin ABI entry point @@ -116,7 +117,7 @@ extern "C" int halo_rad_qsa_tail_store(const RadArgs* a, RadStream stream) { if (k->dtype != RAD_BF16 || st->dtype != RAD_BF16) return HALO_NO(RAD_E_DTYPE); return halo_qsa_tail_store_bf16_emit(halo_addr(k), halo_addr(po), halo_addr(cu), halo_addr(sx), halo_addr(st), (int)T, (int)n, (int)ring, (int)seqs, - (int)kp, (int)st->stride[0], (int)st->stride[2], - (int)sxp, stream); + (int)st->shape[0], (int)kp, (int)st->stride[0], + (int)st->stride[2], (int)sxp, stream); } diff --git a/libhalo/halo_rows.cpp b/libhalo/halo_rows.cpp index 41b2dfc9..af041c8b 100644 --- a/libhalo/halo_rows.cpp +++ b/libhalo/halo_rows.cpp @@ -823,6 +823,10 @@ static const RadParamSpec pGemmNtQ[] = { /* The width whose K split a row slice of a wider linear takes (docs/OPS.md); only the narrow * fp8a8 / i8a8 rows split K by N, and they read it. */ { "split_n", RAD_P_INT, RAD_OPTIONAL }, + /* The weight rows one scale covers (docs/OPS.md). Accepted and ignored: an int8 weight's + * per-row scale plane holds each block's value in every row, and the trellis forms that need + * the count are IQR dtypes, which no row here serves. */ + { "w_rb", RAD_P_INT, RAD_OPTIONAL }, }; /* docs/OPS.md's `gemm_nt_q` is `a`, `a_scale`, `b`w, `b_scale`w -> `y`. Two of libhalo's six * quantised GEMMs need a seventh operand. RadLayout can declare aux streams beside a weight, but @@ -1212,6 +1216,9 @@ static const RadParamSpec pGramAccum[] = { { "n", RAD_P_INT, RAD_REQUIRED }, { "group", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, + /* 1: only k2 >= k1 need be accumulated (H is symmetric). Accepted and ignored: the whole + * matrix is added, and the entries below the diagonal are then outside the contract. */ + { "upper", RAD_P_INT, RAD_OPTIONAL }, }; static const RadOperandSpec oGramAccum[] = { { "a", RAD_OPD_IN, 0 }, @@ -1904,6 +1911,10 @@ static const RadParamSpec pQkNormRope[] = { static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), P_STR("dtype"), }; +/* `n` is the point's values; y has n (2 freqs + 1) columns. */ +static const RadParamSpec pPointFourier[] = { + P_INT("M"), P_INT("n"), P_INT("freqs"), P_INTO("pi"), P_STR("dtype"), +}; /* `positions` may be absent at `rotary_dim` 0 (the norm alone), and an absent gain is a unit * gain. */ static const RadOperandSpec oQkNormRope[] = { @@ -2929,6 +2940,10 @@ static const RadOpSchema kSchemas[] = { "Column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in f32 and " "rounded, then times `mult` and rounded again. n, the input width, is a multiple of k; " "y has n / k columns."), + SCHEMA("point_fourier", pPointFourier, oUnary, + "A point's Fourier features: row m of y is [x | sin(x_i f_j) | cos(x_i f_j)], f_j = 2^j " + "for j < freqs (times pi with `pi` 1), sines then cosines each i-major then j; y is " + "[M, n (2 freqs + 1)]."), SCHEMA("sigmoid", pMnDtype, oUnary, "y = 1 / (1 + exp(-x))."), SCHEMA("relu", pMnDtype, oUnary, "y = max(x, 0)."), SCHEMA("silu", pMnDtype, oUnary, "y = x * sigmoid(x)."), @@ -5730,6 +5745,15 @@ static const RadKernelInfo kKernels[] = { ROW(cBf16Row), NOTUNE, nullptr, nullptr, halo_rad_pool_cols }, +{ "point_fourier_f32", "point_fourier", "elem", + "a point's Fourier features: x, then its sines and cosines at octaves (a shape decoder's query " + "embedding)", + "any n and freqs up to 30; a thread an output column", + "f32 in and out, the device's sinf and cosf", + RAD_DOMAIN_DEVICE, HALO_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, halo_rad_point_fourier }, + { "rmsnorm_bf16", "rmsnorm", "norm", "root-mean-square norm with a gain, two passes over the row", "any n; the sum of squares accumulates in f32 and only the store narrows", @@ -9738,19 +9762,21 @@ extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } * out entirely, so another RDNA3 card gets libr3d alone. * * The test reads the KFD topology (gfx_target_version 110501 is gfx1151) rather than asking a - * runtime, which open must not initialise. Where the topology cannot be read (no KFD, a sandbox - * without /sys) the library stays: the code-object check is the backstop. */ + * runtime, which open must not initialise. KFD lists only the cards the process may open, so a + * container without /dev/kfd sees the CPU node alone. With no gfx1151 listed, or no topology at + * all, the library declines: rad-convert and the other tools resolve kernels without the + * engine's code-object check, and a library for an absent card would choose the stored form of + * every weight it has a row for. */ extern "C" int rad_plugin_open(void) { const char* root = "/sys/class/kfd/kfd/topology/nodes"; DIR* d = opendir(root); - if (!d) return RAD_OK; - bool readable = false, halo = false; + if (!d) return RAD_E_UNSUPPORTED; + bool halo = false; while (const dirent* e = readdir(d)) { if (e->d_name[0] == '.') continue; const std::string path = std::string(root) + "/" + e->d_name + "/properties"; FILE* f = std::fopen(path.c_str(), "r"); if (!f) continue; - readable = true; char key[64]; unsigned long long v = 0; while (std::fscanf(f, "%63s %llu", key, &v) == 2) @@ -9758,7 +9784,7 @@ extern "C" int rad_plugin_open(void) { std::fclose(f); } closedir(d); - return (!readable || halo) ? RAD_OK : RAD_E_UNSUPPORTED; + return halo ? RAD_OK : RAD_E_UNSUPPORTED; } extern "C" int rad_kernel_schema_count(void) { diff --git a/libhalo/halo_selftest.cpp b/libhalo/halo_selftest.cpp index 0fe49804..a1b4c6a5 100644 --- a/libhalo/halo_selftest.cpp +++ b/libhalo/halo_selftest.cpp @@ -31219,6 +31219,40 @@ static void device_phase(const Plugin& pl) { return v; }; + /* point_fourier: a shape decoder's query points (three values, eight octaves, f32), past + * the 65535 rows one grid row a matrix row would reach, against libm's sinf and cosf. */ + if (sel("point_fourier_f32")) { + if (const RadKernelInfo* r = find(pl, "point_fourier_f32")) { + const int64_t M = 70001, n = 3, F = 8, W = n * (2 * F + 1); + std::vector x = randv((size_t)(M * n), 1.01f); + void* dx = dalloc(x.size() * 4); + void* dy = dalloc((size_t)(M * W) * 4); + if (dx) st_memcpy(dx, x.data(), x.size() * 4, hipMemcpyHostToDevice); + std::vector ts = { T(dx, RAD_F32, { M, n }), T(dy, RAD_F32, { M, W }) }; + std::vector ps = { PI("M", M), PI("n", n), PI("freqs", F), + PS("dtype", "f32") }; + run_case(r, ts, ps); + std::vector got((size_t)(M * W)); + st_memcpy(got.data(), dy, got.size() * 4, hipMemcpyDeviceToHost); + double worst = 0.0; + for (int64_t m = 0; m < M; ++m) + for (int64_t i = 0; i < n; ++i) { + const float v = x[(size_t)(m * n + i)]; + worst = std::max(worst, (double)std::fabs(got[(size_t)(m * W + i)] - v)); + for (int64_t j = 0; j < F; ++j) { + const float t = v * std::ldexp(1.0f, (int)j); + const float* g = &got[(size_t)(m * W)]; + const float es = g[n + i * F + j] - std::sin(t); + const float ec = g[n + n * F + i * F + j] - std::cos(t); + worst = std::max(worst, (double)std::max(std::fabs(es), std::fabs(ec))); + } + } + char d[96]; + std::snprintf(d, sizeof d, "max abs err %.3g", worst); + ok("point_fourier_f32 numerics", worst <= 1e-5, d); + } else ok("point_fourier_f32", false, "row absent"); + } + if (sel("relu_bf16") || sel("silu_bf16") || sel("clamp_bf16")) { const int64_t M = 5, n = 300; std::vector x = randv((size_t)(M * n), 2.0f); diff --git a/libquant/lq_gptq.cpp b/libquant/lq_gptq.cpp index f31ac92d..aed81942 100644 --- a/libquant/lq_gptq.cpp +++ b/libquant/lq_gptq.cpp @@ -483,6 +483,16 @@ int gptq_quantise(const Grid& g, float* w, int32_t* codes, Scales& scales, int64 gptq_tcq_colf(w, scales, N, K); } if (g.tcq_L) { + /* Only the last run can be short, and one shorter than a state's codes cannot hold its + * seam: the decoder refuses it (grid_tcq_decode), so the encoder does too. */ + const int64_t c = (g.tcq_L + g.tcq_k - 1) / g.tcq_k; + if (N > 0 && N - (N - 1) / g.tcq_rows * g.tcq_rows < c) { + if (why) *why = "the last trellis run is " + + std::to_string(N - (N - 1) / g.tcq_rows * g.tcq_rows) + " row(s) of " + + std::to_string(N) + " (tcq_rows " + std::to_string(g.tcq_rows) + + "), shorter than the " + std::to_string(c) + " a seam state needs"; + return RAD_E_SHAPE; + } if (gpu_enabled()) { std::string w1; const int st = gptq_tcq_gpu(g, w, codes, scales, N, K, u, dynamic, &w1); diff --git a/libquant/lq_grid.cpp b/libquant/lq_grid.cpp index 9d14664d..1b79c76f 100644 --- a/libquant/lq_grid.cpp +++ b/libquant/lq_grid.cpp @@ -418,8 +418,11 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) { g->tcq_L = (int)L; g->tcq_k = k; g->tcq_rows = rad_param_geti(o, n_o, "tcq_rows", 256); - if (g->tcq_rows < 1) { - if (why) *why = "tcq_rows= is the rows one trellis runs over, 1 or more"; + /* A run holds its seam state in its rows' codes, so it needs at least a state's worth + * of them; the decoder refuses a shorter run. */ + if (g->tcq_rows < (L + k - 1) / k) { + if (why) *why = "tcq_rows= is the rows one trellis runs over, at least the " + + std::to_string((L + k - 1) / k) + " whose codes hold one state"; return RAD_E_INVAL; } const int64_t S = (int64_t)1 << L; diff --git a/libr3d/CMakeLists.txt b/libr3d/CMakeLists.txt index 39529746..63bf060f 100644 --- a/libr3d/CMakeLists.txt +++ b/libr3d/CMakeLists.txt @@ -115,16 +115,15 @@ set(R3D_UNITS # fragment-order permute is the row's own relayout hook, at load. "r3d_gemm_w4a16_nt_m64|" "r3d_gemm_w5a16_nt_m64|" - # The gated-delta-net chunk preamble: the gram and the blocked inverse of I + the strictly - # lower decayed gram, one 64-chunk a workgroup, the gram per k head. - "r3d_gdn_kkt_solve_c64|" - # The gated-delta-net chunked scan: the chunk's output and its closing state, the recurrent - # state in wave-matrix accumulators across the chunk loop. - "r3d_gdn_chunk_scan_k128_v128_c64|" + # The gated-delta-net chunk preamble, chunked scan and recurrent update: libhalo's kernels + # (r3dh_*, the halo_ -> r3dh_ rename), checked against libref on gfx1151 and compiled here for + # the whole family. The recurrent update serves both state forms (per_candidate and anchor). + "r3dh_gdn_kkt_solve|" + "r3dh_gdn_chunk_scan|" + "r3dh_gdn_recurrent_update|" "r3d_gdn_gated_rmsnorm_h128|" "r3d_gdn_gated_norm_had_quant_i8|" "r3d_gdn_conv_w4_h128|" - "r3d_gdn_recurrent_update_k128_v128|" # Mixture of experts: each routing weight times its expert's own scale, in place. "r3d_expert_scale_bf16|" # The router: softmax over the expert logits, the top_k by value, renormalised if `norm`. diff --git a/libr3d/README.md b/libr3d/README.md index 924788bb..8aa55bac 100644 --- a/libr3d/README.md +++ b/libr3d/README.md @@ -8,7 +8,10 @@ the kernel-plugin rows the engine selects from (`r3d_rows.cpp`); `libr3d/CMakeLi every unit and its flags. It claims `^gfx11` where [`libr4d`](../libr4d/README.md) claims `^gfx12`; a card gets one device -library, chosen by the rows, not the name. The kernels are not ports of libr4d's: gfx11 has no +library, chosen by the rows, not the name. `rad_plugin_open` declines a machine whose KFD +topology lists no gfx11 card (a process without `/dev/kfd` sees none), so in an installation that +also carries libr4d the tools, which resolve kernels without the engine's code-object check, never +lay an RDNA4 container's weights out for libr3d. The kernels are not ports of libr4d's: gfx11 has no bf16 pack and no VOPD, and a different integer instruction set, so every arithmetic path is its own. The matrix work splits by dtype: the bf16/f16 GEMM rows (the m64 band and the prefill-tiled form) and every MoE GEMM row run on the 16x16x16 wave-matrix (WMMA) builtins retiled onto a 16x128 @@ -61,8 +64,8 @@ The table groups the rows by family; `r3d_rows.cpp` and `r3d.h` hold the full se | `vocab` | `logits_gemm_bf16`: the head, read once per token, as bf16 or as E4M3 codes with a bf16 scale per 128x128 block; the `impl` axis picks the decode (the LDS table, the per-byte ALU formula) | | `quant` | `quant_act_fp8_bf16`, `quant_act_i8_bf16`, `quant_act_i8g_bf16`, `had_quant_act_{i8,fp8}_bf16` and `had_quant_act_i8g_bf16` (the same with a block Walsh-Hadamard rotation), `gated_had_quant_{i8,i8g,fp8}_bf16`, `gelu_mul_quant_i8_bf16`, `quant_cols_fp8_bf16`, `rmsnorm_quant_{fp8,i8}_bf16` (norm and quantiser in one pass), `gated_quant_fp8_bf16`, `dequant_fp8`, `dequant_e5m2`, `dequant_i8` | | `sample` | pre-filters `sample_{penalties,dry,ngram_ban,mask,logprobs}_f32`; spine `sample_{argmax,temp,topk,pick,topp,minp,typical,xtc}_f32` — f32 logits in and out, the draw the reference's in its order, the top-R scan single-pass (the plane read once) | -| `moe` | `expert_scale_bf16` (the renormalised top-k weight times the expert's per-expert scale, in place), `moe_router_topk_bf16` (softmax top-k, renormalised if `norm`), `moe_router_topk_scatter` (the top-k and the counting sort as one op), `moe_router_sigmoid_topk` (the GLM-style router: sigmoid scores, selection on scores + bias, the kept weights scaled by `route_scale`), `moe_scatter_small` (the routed slots' stable counting sort; histogram in LDS, T ≤ 1024), `moe_gather` (fold the expert outputs back to the token, with the optional shared arm), `moe_gemm_q_e4m3` (grouped E4M3 GEMM; the `impl` axis: 16x16 table decode, 16x16 ALU decode, 16x128 block with the F32 scales folded), `moe_gemm_bf16` (unquantised experts, wave matrix), `moe_gemm_mxfp4a8` (canonical MXFP4 experts), `row_topk_{bf16,f32}` (the reference files the op under `moe`, so the row does too). `r3d_rad_moe_gemm_w4a8` is an exported WIP launcher (packed int4 weights, the i32 wave matrix) that is not a row: no `r3d_rows.cpp` entry, no selftest, per its kernel header | -| `gdn` | `gdn_kkt_solve_c64` (`A = (I + strict_lower(diag(beta) K K^T e^{g_i-g_j}))^-1` per 64-chunk), `gdn_chunk_scan_k128_v128_c64` (the chunked scan: WY recompute, state recurrence and output in one kernel), `gdn_gated_rmsnorm_h128`, `gdn_gated_norm_had_quant_i8` (the gated norm fused with the rotation and quantiser), `gdn_conv_prep_w4_h128` (causal conv, split, l2norm, gating and the per-chunk gate cumsum in one prefill kernel), `gdn_conv_update_w4_h128` (the same convolution at decode over a rolling conv-state buffer), `gdn_recurrent_update_k128_v128` (the decode-time recurrent state update) | +| `moe` | `expert_scale_bf16` (the renormalised top-k weight times the expert's per-expert scale, in place), `moe_router_topk_bf16` (softmax top-k, renormalised if `norm`), `moe_router_topk_scatter` (the top-k and the counting sort as one op), `moe_router_sigmoid_topk` (the GLM-style router: sigmoid scores, selection on scores + bias, the kept weights scaled by `route_scale`), `moe_scatter_small` (the routed slots' stable counting sort: one workgroup up to 1024 slots, three passes over 256-slot tiles above), `moe_gather` (fold the expert outputs back to the token, with the optional shared arm), `moe_gemm_q_e4m3` (grouped E4M3 GEMM; the `impl` axis: 16x16 table decode, 16x16 ALU decode, 16x128 block with the F32 scales folded), `moe_gemm_bf16` (unquantised experts, wave matrix), `moe_gemm_mxfp4a8` (canonical MXFP4 experts), `row_topk_{bf16,f32}` (the reference files the op under `moe`, so the row does too). `r3d_rad_moe_gemm_w4a8` is an exported WIP launcher (packed int4 weights, the i32 wave matrix) that is not a row: no `r3d_rows.cpp` entry, no selftest, per its kernel header | +| `gdn` | `gdn_kkt_solve_c64` (`A = (I + strict_lower(diag(beta) K K^T e^{g_i-g_j}))^-1` per 64-chunk; libhalo's kernel), `gdn_chunk_scan_k128_v128_c64` (the chunked scan: WY recompute, state recurrence and output in one kernel; libhalo's), `gdn_gated_rmsnorm_h128`, `gdn_gated_norm_had_quant_i8` (the gated norm fused with the rotation and quantiser), `gdn_conv_prep_w4_h128` (causal conv, split, l2norm, gating and the per-chunk gate cumsum in one prefill kernel), `gdn_conv_update_w4_h128` (the same convolution at decode over a rolling conv-state buffer), `gdn_recurrent_update_k128_v128` (the decode-time recurrent state update, per_candidate or anchor; libhalo's) | | `draft` | `dflash_select_bf16`: the drafter's accept step, a walk over the draft block's candidate lattice | The table holds 109 rows over 70 schemas; `r3d_selftest` checks every schema slot for slot against @@ -300,22 +303,29 @@ The grouped GEMM rows share the run-walk / gather structure: the block walks the weights, rows the run does not own are padding and their output is dropped, and a dropped slot (sorted token < 0) writes zero. `y` is in sorted order. +The experts arrive as weight tables (`RAD_OPD_WTAB`, `r3d_moe_tab.h`): a device array of one +pointer per expert, or a stacked plane, read on the device. `a_order` "token" (gate_up) gathers row +`i` from `a[sorted_tok[i] / top_k]`, "sorted" (down) reads `a[i]`. `moe_gemm_q`'s odd class must +match the even one (`N_odd = N`, `K_odd = K`, as on one card); an uneven class is refused by name, +and `parts` is then the identity. `r3d_selftest` checks each row's values against the reference's +arithmetic on routed batches with dropped slots, an N tail block and both orders. + * `moe_gemm_bf16` — unquantised experts: the bf16 operands stage straight into the bf16 wave-matrix - fragments, f32 accumulate over the whole of K, no scales, `y` bf16. The weight is the checkpoint's - own bytes ([n_expert, N, K] row-major, no layout hook). Tunable over `mrows` (the block's row + fragments, f32 accumulate over the whole of K, no scales, `y` bf16. Each expert is the + checkpoint's own [N, K] row-major plane (no layout hook). Tunable over `mrows` (the block's row count), `vgpr` and `acc`; the compiled points are the legal ones (the `moe_bf16_tune_valid` table), the rest refuse. * `moe_gemm_q_e4m3` — canonical E4M3 experts with F32 block scales, on the `moe_gemm_q` - contract: the even experts in `w` / `w_scale`, the odd in `w_odd` / `w_odd_scale`, at index e/2; - the scales fold in f32 per (grid_rows columns, 128 of K); `y` is f32. The `impl` axis: 0 = the + contract (`dtype` fp8a8f32): expert e is entry e/2 of the even (`w` / `w_scale`) or odd + (`w_odd` / `w_odd_scale`) tables; the scales fold in f32 per 128x128 tile; `y` is bf16. The + `impl` axis (the row's tune, dispatched by `r3d_rad_moe_gemm_q`): 0 = the 16x16 tile with the 512-byte LDS decode table, 1 = the same tile with the per-byte ALU formula (no LDS table), 2 = the 16x128 block with the F32 scales folded in f32 (the `vgpr` and `acc` axes are arm 2's). The E4M3 operands widen exactly to f16, the f16 wave matrix (f32 accumulate) - runs the multiply. The `grid_rows` parameter takes 1 (w4a8's per-row) or 128 (fp8a8's - per-128x128). + runs the multiply. * `moe_gemm_mxfp4a8` — canonical MXFP4 experts: the E4M3 activation and the E2M1 weight (decoded exactly to E4M3) upcast to f16, the f16 wave matrix (f32 accumulate), the E8M0 weight scales fold - in f32 per 32 of K; the even/odd split as above, `y` bf16. + in f32 per (row, 32 of K); the even/odd tables as above, `y` bf16. On the prefill geometry (T = N = K = 4096, 8 experts, best / median of nine launches) the `mrows`/`vgpr` points of `moe_gemm_bf16` run 41.67 ms at (16, 512), 26.19 ms at (32, 128) and @@ -364,6 +374,12 @@ arithmetic is the reference's in the reference's order. ## The GDN, QSA, and MoE plumbing rows +The chunk preamble, the chunked scan and the recurrent update are libhalo's kernels (`r3dh_*.hip`, +the `halo_` -> `r3dh_` rename): libr4d's ported to the gfx11 wave matrix, they compile for +`gfx11-generic` unchanged and pass `rad-kbench` against libref on gfx1151 (the kkt solve to +8e-5, the scan to 4e-3, the update to 6e-5, both state forms). They replace the first wave-matrix +ports of the same kernels, which disagreed with libref and whose scan wrote past its output. + `gdn_kkt_solve_c64` runs the gated-delta-net's chunk preamble: the gram `A = (I + strict_lower(diag(beta) K K^T e^{g_i-g_j}))^-1` per 64-chunk, the gram and the blocked triangular inverse in one kernel, the fp32 gram never reaching memory. `gdn_chunk_scan_k128_v128_c64` @@ -374,11 +390,8 @@ touch HBM. `gdn_gated_rmsnorm_h128` is the layer's own output norm, and per-row int8 quantiser. `gdn_conv_prep_w4_h128` is the causal conv width 4 + silu, the q/k/v split, the qk l2norm, the gating and the per-chunk gate cumsum in one prefill kernel, and `gdn_conv_update_w4_h128` / `gdn_recurrent_update_k128_v128` are the same convolution and the -recurrent state update at decode, over a rolling conv-state buffer and a paged fp32 state cache. -The decode half (`gdn_recurrent_update_k128_v128`) and the single-chunk case of the scan are -value-verified against a CPU reference; the scan's multi-chunk state carry carries a small -documented residual on the development card (its kernel header states the band and the suspected -cause), so the gate there is bounded, not exact. +recurrent state update at decode, over a rolling conv-state buffer and a paged f32 or f16 state +cache, per candidate token or as one committed state with a replay scratch slot (`anchor`). The QSA rows are the indexer's tail: `kv_len_trim_i32` trims each sequence's context lengths by `trim` (the slice's own last row), and `qsa_tail_store_bf16` writes the QSA indexer's tail into a @@ -386,8 +399,10 @@ per-layer linear KV state, ring addressed by position. The MoE plumbing rows are the sort: `moe_router_topk_bf16` (softmax top-k, renormalised if `norm`), `moe_router_sigmoid_topk` (the GLM-style router: sigmoid scores, selection on scores + bias, the kept weights scaled by `route_scale`), `moe_router_topk_scatter` (the top-k and the counting sort -as one op), `moe_scatter_small` (the routed slots' stable counting sort; histogram in LDS, -T ≤ 1024) and `moe_gather` (fold the expert outputs back to the token, +as one op), `moe_scatter_small` (the routed slots' stable counting sort: up to 1024 slots one +workgroup, histogram in LDS; above, libhalo's three passes, a histogram per 256-slot tile into +scratch, the per-expert scan across tiles and the placement) and `moe_gather` (fold the expert +outputs back to the token, `y[t,c] = sum_j expert_w[t,j] * y_expert[slot(t,j),c]`, with the optional shared arm; top_k ≤ 64). `expert_scale_bf16` scales the renormalised top-k weights by the expert's per-expert scale in place, and `dflash_select_bf16` is the drafter's accept step, a walk over the draft block's diff --git a/libr3d/r3d_gdn_chunk_scan_k128_v128_c64.hip b/libr3d/r3d_gdn_chunk_scan_k128_v128_c64.hip deleted file mode 100644 index 53d94a01..00000000 --- a/libr3d/r3d_gdn_chunk_scan_k128_v128_c64.hip +++ /dev/null @@ -1,740 +0,0 @@ -/* r3d_gdn_chunk_scan_k128_v128_c64.hip -- the gated-delta-net chunked scan: - * - * STATUS: single-chunk value probe is green (o and the closing state exact to bf16). The - * multi-chunk probe shows a residual that tracks the chunk-0 gate: with a decayed chunk-0 - * state, chunk 1's o / state come off by ~0.2-0.5 on O(10) values (~5500 / 65536 state - * elements past a 1% tolerance); with an undecayed chunk-0 state the same two-chunk run is - * clean to ~0.12. The chunk-1 s.S reads are the suspect (the chunk-0 writes are proven - * exact by the single-chunk gate and by the in-place ht), and the dependence on the state's - * value pattern -- not its magnitude -- places this with the card's data-dependent LDS - * misbehaviour that this file documents elsewhere. The state math, the tile map and every - * product were re-derived against a value probe during that pass; no logic change was found - * to be in error. - * - * The original status: the manual-FMA path is in. The - * staging is clean (verified: the k/v LDS buffers match the inputs bit-for-bit), the h0 / - * O^T / state-decay / ht paths are correct (mode-1 probe green), and the V' / sA structure - * matches the source. The wmma A-operand fragment read of the s.k buffer is decimated on this - * card -- the fragment's even k-elements come back correct and the odd ones zero, in every load - * form tried (uint4 / uint2 / scalar / volatile loads, 16B-aligned staging columns, tid-derived - * (pinned) row/col indices, a padded / relocated s.k, and swapping the operands to P = Q@K^T, - * s.k as the B-operand, which produced NaNs). The raw LDS value s.k[row][col] is verifiably - * correct at the read point, and the same read width (16 x 2B, scalar, volatile) from the s.S - * buffer is exact -- so it is the s.k A-operand path specifically, not the load, the offset, or - * the data. The three products that take s.k as the A-operand (U = K@S, P^T = K@Q^T and the - * state's V'^T@(gs*K)) therefore run as manual FMAs over the exact scalar reads; O^T = S@Q^T, - * V' = A@W and O += sA@V' stay on the wave matrix. - * - * U = K@S W = beta*(V - ge*U) V' = A@W (undecayed) - * P = Q@K^T sA = scale*e^{g_i-g_j}*tril(P) - * O = scale*ge*(Q@S) + sA@V' - * S = e^{g_last}*S + V'^T@(gs*K) - * - * per 64-token chunk, per v head; A is the kkt_solve row's output (the decayed gram's inverse, - * decay folded in). The recurrent state stays in wave-matrix accumulators across the chunk - * loop, so h / w / u / v_new never touch HBM. Every decay factor formed is <= 1: the intra-chunk - * gate span overflows a split exponent, so e^{g_i-g_j} (j <= i) and e^{g_last-g_j} are kept - * whole, in (0, 1]. - * - * ---- the tile map (the port's structural change) ------------------------------------------- - * - * The source row was written for the wave-matrix ISA of the card it was probed on, whose - * 16x16x16 fragment map differs from this card's. This card's map (probed in the bf16 GEMM row, - * r3d_gemm_bf16_nt_m16_wmma.hip): - * - * A fragment: lane L holds row L % 16 of the tile, the 16 k contiguous - * B fragment: lane L holds column L % 16 of the tile, the 16 k contiguous - * C/D: lane L, element e holds D[2e + L / 16][L % 16], eight f32 a lane - * - * so the fragment loads are the GEMM row's 32-byte reads (the source's 16-byte half-K reads, - * doubled), and every accumulator store the source made as one 16-byte vector is here eight - * scalar bf16 stores along the map's stride-2 axis -- the W, sA, V', state and output stores, - * and the h0 / ht state transfers (k = 2e + hi strides two). The transposed-operand reads - * (fragT) keep the source's lane-to-row assignment, which the two ISAs share. - * - * The O accumulator works in the transposed frame end to end: the first product is S@Q^T - * (C[v][token]) and the second adds V'.(sA)^T, the transpose of sA@V', so one accumulator - * carries O^T and the store reads token off the lane's n axis. - */ - -#include - -#include "r3d.h" -#include "r3d_common.h" -#include "r3d_launch.h" -#include "r3d_args.h" -#include "r3d_codecs.h" - -#include -#include -#include - -namespace { - -constexpr int kBT = 64; // chunk -constexpr int kKD = 128; // head_k -constexpr int kVD = 128; // head_v -constexpr int kBV = 64; // v per workgroup; also halves the Q@K^T redundancy -constexpr int kKP = 132; // row pitch of the [.][KD] buffers, in shorts -constexpr int kAP = 68; // row pitch of the [.][BT] buffers, in shorts -constexpr int kNW = 8; // waves; the [4 token][4 v] tile grid is fixed by BT and BV, so - // eight waves carry two tiles each -constexpr int kNTHR = kNW * 32; -constexpr int kNTV = 2; // n tiles per wave in the main / V' / O loops -constexpr int kSKT = 2; // the wave's slice of the 8 k-tile x 4 v-tile state grid is 2 x 2 -constexpr int kSVT = 2; -constexpr int kNST = kSKT * kSVT; - -struct CsSmem { - // k must not sit at a low LDS offset: on this card a 16-element fragment read from the - // first ~16 KB of the block is decimated (odd elements read back zero), while the same - // read from a higher offset is exact. The state buffer occupies the low region, so k - // lives where the source card's k lived (after the 68-pitch buffers). - unsigned short S[kBV][kKP]; // B: state, V-major - unsigned short A[kBT][kAP]; // B-source for sA (written as [i][j]) - unsigned short k[kBT][kKP]; // A: K / B: K^T for P=Q@K^T - unsigned short W[kBV][kAP]; // B: W (transposed) - unsigned short D[kBV][kAP]; // staged V as [token][v]; then V' as [v][token] - float ge[kBT], gv[kBT], gg[kBT], bt[kBT]; -}; - -using v8f = float __attribute__((ext_vector_type(8))); -using v16short = short __attribute__((ext_vector_type(16))); - -/* One 16x16x16 tile, f32 accumulate. */ -__device__ __forceinline__ v8f mmab(const v16short& a, const v16short& b, const v8f& c) -{ - return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); -} - -/* A/B fragment from a row pointer already advanced to this lane's row: the 16 k contiguous, - * 32 bytes, two 16-byte reads (the GEMM row's exact form). */ -__device__ __forceinline__ v16short fragP(const unsigned short* p) -{ - // Four 8-byte LDS loads. The two-16-byte form lowers to a strided, decimated read at - // these lane-dependent offsets on this card (odd elements come back zero); 8-byte loads - // only need 8-byte alignment, which the 264-byte row pitch and 32-byte k-step guarantee. - union { uint2 w[4]; v16short f; } u; - u.w[0] = *(const uint2*)(p + 0); - u.w[1] = *(const uint2*)(p + 4); - u.w[2] = *(const uint2*)(p + 8); - u.w[3] = *(const uint2*)(p + 12); - return u.f; -} - -/* Global fragment off a 32-bit element offset split from a uniform base. */ -__device__ __forceinline__ v16short fragGo(const unsigned short* base, unsigned off) -{ - return fragP(base + off); -} - -/* Scalar A-fragment: sixteen 2-byte LDS loads. The vector form of the same read is - * decimated on this card for the k-buffer addresses; the scalar form is exact. */ -__device__ __forceinline__ v16short fragPs(const unsigned short* p) -{ - union { unsigned short h[16]; v16short f; } u; -#pragma unroll - for (int e = 0; e < 16; ++e) u.h[e] = p[e]; - return u.f; -} - -/* Volatile scalar A-fragment: the non-volatile scalar read of the k-buffer has its odd - * k-elements constant-folded to zero on this card; a volatile pointer stops that. */ -__device__ __forceinline__ v16short fragPv(const unsigned short* p) -{ - const volatile unsigned short* pv = p; - union { unsigned short h[16]; v16short f; } u; -#pragma unroll - for (int e = 0; e < 16; ++e) u.h[e] = pv[e]; - return u.f; -} - -/* K-contiguous fragment: src[idx][k], row pitch `pitch` (in elements). */ -__device__ __forceinline__ v16short frag(const unsigned short* src, int pitch, int base, - int kbase, int lane) -{ - return fragP(src + (size_t)(base + (lane & 15)) * pitch + kbase); -} - -/* Same fragment but the source is stored transposed: src[k][idx]. Sixteen scalar reads. */ -__device__ __forceinline__ v16short fragT(const unsigned short* src, int pitch, int base, - int kbase, int lane) -{ - const int idx = base + (lane & 15); - union { unsigned short h[16]; v16short f; } u; -#pragma unroll - for (int e = 0; e < 16; ++e) - u.h[e] = src[(size_t)(kbase + e) * pitch + idx]; - return u.f; -} - -/* A block barrier the backend cannot move; see the GEMM rows' note. */ -#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) - -/* byte offset of buffer[base + lo] from the base of the shared block (the 16-k fragment starts - * at the row's head on this card; the source's + 4*hi half-K offset does not exist here) */ -#define ROWO(buf, pitch, base) \ - ((unsigned)((const char*)&(buf)[0][0] - (const char*)&s) + \ - (unsigned)(((base) + lo) * (pitch) * 2)) - -/* The state cache's element type (0 = fp32, 1 = fp16); all arithmetic is fp32. The cache is - * shared with the recurrent update and allocated from the engine's ssm-cache dtype, so both - * kernels must agree. */ -template struct cs_state { using T = float; }; -template <> struct cs_state<1> { using T = _Float16; }; - -#define PFW 8 // shorts staged per lane per step -#define PFZERO make_uint4(0u, 0u, 0u, 0u) -#define NKB (kBT * kKD / (kNTHR * PFW)) -#define NVB (kBT * kBV / (kNTHR * PFW)) - -template -__global__ __launch_bounds__(kNTHR) void r3d_gdn_chunk_scan_kernel( - const unsigned short* __restrict__ q, const unsigned short* __restrict__ k, - const unsigned short* __restrict__ v, const unsigned short* __restrict__ Amat, - const float* __restrict__ gcs, const float* __restrict__ beta, - const typename cs_state::T* __restrict__ h0, unsigned short* __restrict__ o, - typename cs_state::T* __restrict__ ht, const int* __restrict__ cu, - const int* __restrict__ sidx, long sidx_stride, long st_slot, long st_head, - int H, int Hg, float scale, unsigned short* __restrict__ dbg) -{ - __shared__ CsSmem s; - const int bv = blockIdx.x, hv = blockIdx.y, nq = blockIdx.z; - int tid = threadIdx.x; - asm volatile("" : "+v"(tid)); // pin the hw thread-id vreg before the allocator can reuse it - const int w = tid >> 5, lane = tid & 31; - const int hq = hv / (H / Hg), v0 = bv * kBV; - const int tb = cu[nq], te = cu[nq + 1]; - // The state slot comes from the cache manager (sidx), not the batch position; without sidx - // the kernel uses state[nq], valid only while slots match batch order. - const long si = sidx ? (long)sidx[(size_t)nq * sidx_stride] : (long)nq; - if (si < 0) return; // a padded row owns no state - const size_t st_base = (size_t)si * st_slot + (size_t)hv * st_head; - const int nchunk = (te - tb + kBT - 1) / kBT; - const int lo = lane & 15, hi = lane >> 4; - - const int mt = w >> 1, ntb = (w & 1) * 2; // [BT][BV]: 2 tiles/wave - // The state accumulator is held transposed, C[m=k-dim][n=v]. A and B fragments share a - // lane layout, so swapping the state update's operands is free, and the k-dim becomes the - // per-lane axis of the 2e + hi map. - const int kt0 = (w >> 1) * 2, vt0 = (w & 1) * 2; // 2 x 2 - - uint4 kb[NKB], vb[NVB]; - // Staging index, derived from the pinned tid at every point of use. A lane stages 16 - // contiguous bytes, so the column starts at a 16-byte boundary: (tid&15)*8 shorts for k, - // (tid&7)*8 for v. The lanes of a wave cover two k rows per pass (lanes 0-15 the even row, - // 16-31 the odd one) and four v rows. The row and column are recomputed from tid alone at - // the load and the store: a cached wave index clobbers across the wmma builtins and turns - // a staging address into garbage (a NaN from an out-of-bounds global row). -#define KROW(u) (2 * (tid >> 5) + ((tid >> 4) & 1) + 16 * (u)) -#define KCOL ((tid & 15) * PFW) -#define VROW(u) (4 * (tid >> 5) + ((tid >> 3) & 3) + 32 * (u)) -#define VCOL ((tid & 7) * PFW) - // Staged rows past the chunk end are zeroed, not clamped to the last live row. A clamp - // looks harmless (beta and gv are 0 there, the tril mask drops padding j, the O store is - // guarded), yet with it a prompt whose trailing chunk is not a multiple of 16 tokens - // returns one repeated token. -#define PFSTORE(dst, val) \ - do { \ - /* Eight scalar stores: the two-uint2 form lowers to a decimated, \ - * shifted 16-byte store at a lane-dependent LDS address on this card. \ - */ \ - unsigned short* dp_ = (dst); \ - dp_[0] = (unsigned short)((val).x & 0xffffu); \ - dp_[1] = (unsigned short)((val).x >> 16); \ - dp_[2] = (unsigned short)((val).y & 0xffffu); \ - dp_[3] = (unsigned short)((val).y >> 16); \ - dp_[4] = (unsigned short)((val).z & 0xffffu); \ - dp_[5] = (unsigned short)((val).z >> 16); \ - dp_[6] = (unsigned short)((val).w & 0xffffu); \ - dp_[7] = (unsigned short)((val).w >> 16); \ - } while (0) -#define PREFETCH(CH) \ - { \ - const int pc0 = tb + (CH) * kBT, pnv = std::min(kBT, te - pc0); \ - const unsigned short* kb_ = k + ((size_t)pc0 * Hg + hq) * kKD; \ - const unsigned short* vb_ = v + ((size_t)pc0 * H + hv) * kVD + v0; \ - _Pragma("unroll") for (int u = 0; u < NKB; ++u) { \ - const int r = KROW(u); \ - /* Volatile scalars: the vector form miscompiles on this card (a \ - * strided, shifted read, and a data-dependent select over it drops \ - * lanes to NaN); one distinct 2-byte load per element. \ - */ \ - if (r < pnv) { \ - const volatile unsigned short* kp = kb_ + (unsigned)(r * (Hg * kKD)) + KCOL; \ - kb[u].x = kp[0] | (kp[1] << 16); \ - kb[u].y = kp[2] | (kp[3] << 16); \ - kb[u].z = kp[4] | (kp[5] << 16); \ - kb[u].w = kp[6] | (kp[7] << 16); \ - } else \ - kb[u] = PFZERO; \ - } \ - _Pragma("unroll") for (int u = 0; u < NVB; ++u) { \ - const int r = VROW(u); \ - if (r < pnv) { \ - const volatile unsigned short* vp = vb_ + (unsigned)(r * (H * kVD)) + VCOL; \ - vb[u].x = vp[0] | (vp[1] << 16); \ - vb[u].y = vp[2] | (vp[3] << 16); \ - vb[u].z = vp[4] | (vp[5] << 16); \ - vb[u].w = vp[6] | (vp[7] << 16); \ - } else \ - vb[u] = PFZERO; \ - } \ - } - - v8f St[kNST]; // state: SKT k-tiles x SVT v-tiles -#define KT(t) (kt0 + (t) / kSVT) -#define VT(t) (vt0 + (t) % kSVT) - // This card's D map puts element e at k = 2e + hi: the h0 / ht rows stride two. - if (H0) { -#pragma unroll - for (int t = 0; t < kNST; ++t) { - const typename cs_state::T* p = h0 + st_base + (size_t)(v0 + VT(t) * 16 + lo) * kKD - + KT(t) * 16; -#pragma unroll - for (int e = 0; e < 8; ++e) { - if (SDT) - St[t][e] = (float)p[2 * e + hi]; - else - St[t][e] = p[2 * e + hi]; - } - } - } else { -#pragma unroll - for (int t = 0; t < kNST; ++t) -#pragma unroll - for (int e = 0; e < 8; ++e) St[t][e] = 0.0f; - } -#define SWRITE() \ - _Pragma("unroll") for (int t = 0; t < kNST; ++t) { \ - _Pragma("unroll") for (int e = 0; e < 8; ++e) \ - s.S[VT(t) * 16 + lo][KT(t) * 16 + 2 * e + hi] = f32_to_bf16(St[t][e]); \ - } - SWRITE(); - R3D_BARRIER(); - PREFETCH(0); - - const char* const sbase = (const char*)&s; - // scale goes inside the score exponent, exp(g_i + log(scale) - g_j), saving eight multiplies - // per tile. - const float lgs = __logf(scale); - for (int ci = 0; ci < nchunk; ++ci) { - const int c0 = tb + ci * kBT, nval = std::min(kBT, te - c0); - const int lim = nval - 1; - const unsigned short* qg = q + ((size_t)c0 * Hg + hq) * kKD; - const unsigned short* ag = Amat + ((size_t)c0 * H + hv) * kBT; - const size_t qrs = (size_t)Hg * kKD, ars = (size_t)H * kBT; - const float gl = gcs[(size_t)(c0 + lim) * H + hv]; - - // Issued before the staging store so the LDS writes cover their latency. Only waves 0-1 - // (tid < BT) run this; the others wait at (1). - float ggr = 0.f, btr = 0.f; - if (tid < kBT) { - const bool ok = tid < nval; - ggr = ok ? gcs[(size_t)(c0 + tid) * H + hv] : 0.f; - btr = ok ? beta[(size_t)(c0 + tid) * H + hv] : 0.f; - } - { // consume the previous iteration's prefetch, issued a whole chunk of compute ago -#pragma unroll - for (int u = 0; u < NKB; ++u) PFSTORE(&s.k[KROW(u)][KCOL], kb[u]); -#pragma unroll - for (int u = 0; u < NVB; ++u) PFSTORE(&s.D[VROW(u)][VCOL], vb[u]); - } - if (tid < kBT) { - const bool ok = tid < nval; - s.bt[tid] = btr; - s.ge[tid] = __expf(ggr); - // g is a within-chunk cumsum of log-sigmoid gates, so it is non-increasing and gl is - // its minimum. A padding row gets gl, not 0: it is scored against live j with very - // negative g_j, and g_i = 0 would give exp(+400) = inf in s.A. With gl the exponent - // stays in (0, scale]. The row is discarded anyway (the O store is guarded). - s.gg[tid] = ok ? ggr : gl; - s.gv[tid] = ok ? __expf(gl - ggr) : 0.f; // gs - } - R3D_BARRIER(); // (1) - PREFETCH(std::min(ci + 1, nchunk - 1)); // issue only; consumed next iteration - if (dbg && ci == 0) { - for (int i = tid; i < kBT * (kKD / 4); i += kNTHR) { - const int r = i / (kKD / 4), c = (i % (kKD / 4)) * 4; - unsigned short* o = dbg + 4 * kBT * kBT + (size_t)r * kBT + c; - const unsigned short* a1 = &s.k[r][c]; - o[0] = a1[0]; o[1] = a1[1]; o[2] = a1[2]; o[3] = a1[3]; - } - } - - // ---- U = K@S, O^T = S@Q^T and P^T = K@Q^T share the q and k fragments. - // Tiles above the diagonal (A is unit lower triangular, sA is masked) are computed - // anyway: skipping them is 2.4% slower on the source card, since some wave still - // carries two tiles, so the barrier arrival does not move, and the guards stop - // fragment loads batching ahead of the WMMAs. - v8f O[kNTV], u[kNTV], p[kNTV]; -#pragma unroll - for (int i = 0; i < kNTV; ++i) { O[i] = (v8f){}; u[i] = (v8f){}; p[i] = (v8f){}; } - { - const char* sb = sbase; - unsigned oSn[kNTV]; -#pragma unroll - for (int i = 0; i < kNTV; ++i) { - oSn[i] = ROWO(s.S, kKP, (ntb + i) * 16); - asm volatile("" : "+v"(oSn[i])); - } -#define pSnf(i, ko) fragP((const unsigned short*)(sb + oSn[i] + (ko) * 2u)) - const unsigned qo = (unsigned)std::min(mt * 16 + (lane & 15), lim) * (unsigned)qrs; -#define pqf(ko) fragGo(qg, qo + (ko)) - // O^T = S@Q^T stays on the wave matrix: its s.S B-operand and the global Q read are - // exact. U = K@S and P^T = K@Q^T run as manual FMAs: the s.k A-operand fragment - // read is decimated on this card (the odd k-elements come back zero, in every load - // form tried), while the scalar read of the same buffer is verifiably exact. -#pragma unroll - for (int sk = 0; sk < kKD / 16; ++sk) { - const int ko = sk * 16; - const v16short aq = pqf(ko); -#pragma unroll - for (int i = 0; i < kNTV; ++i) - O[i] = mmab(pSnf(i, ko), aq, O[i]); // O^T: m = v-tile, n = token-tile - } -#pragma unroll - for (int i = 0; i < kNTV; ++i) { - const unsigned short* srow = &s.S[(ntb + i) * 16 + lo][0]; -#pragma unroll - for (int e = 0; e < 8; ++e) { - const unsigned short* krow = &s.k[mt * 16 + 2 * e + hi][0]; - float acc = 0.f; -#pragma unroll - for (int kk = 0; kk < kKD; ++kk) - acc = fmaf(bf16_to_f32(krow[kk]), bf16_to_f32(srow[kk]), acc); - u[i][e] = acc; - } - } - // P^T: the Q row is clamped to the last live token, as the fragment read was. - { - const unsigned short* qrow = - qg + (unsigned)std::min(mt * 16 + lo, lim) * (unsigned)qrs; -#pragma unroll - for (int i = 0; i < kNTV; ++i) { - if (dbg && ci == 0 && i == 0) - dbg[9 * kBT * kBT + lane] = s.k[(ntb) * 16 + lo][0]; // raw LDS value -#pragma unroll - for (int e = 0; e < 8; ++e) { - const unsigned short* krow = &s.k[(ntb + i) * 16 + 2 * e + hi][0]; - float acc = 0.f; -#pragma unroll - for (int kk = 0; kk < kKD; ++kk) - acc = fmaf(bf16_to_f32(krow[kk]), bf16_to_f32(qrow[kk]), acc); - p[i][e] = acc; - } - } - } - } - { - const float g = scale * s.ge[mt * 16 + lo]; // token index is constant per lane -#pragma unroll - for (int i = 0; i < kNTV; ++i) -#pragma unroll - for (int e = 0; e < 8; ++e) O[i][e] *= g; - } - // W = beta * (V - ge*U) (beta folded here: (A*beta_col)@W == A@(beta_row*W)) - { - float wa[kNTV][8]; -#pragma unroll - for (int e = 0; e < 8; ++e) { // the U token is 2e + hi on this card - const int tok = mt * 16 + 2 * e + hi; - const float f = s.bt[tok], g = s.ge[tok]; -#pragma unroll - for (int i = 0; i < kNTV; ++i) - wa[i][e] = f * (bf16_to_f32(s.D[tok][(ntb + i) * 16 + lo]) - g * u[i][e]); - } -#pragma unroll - for (int i = 0; i < kNTV; ++i) -#pragma unroll - for (int e = 0; e < 8; ++e) - s.W[(ntb + i) * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(wa[i][e]); - } - // sA = scale * e^{g_i-g_j} * tril(P). Row ii is constant per lane and the eight g_j are - // uniform per 16 lanes: eight broadcast LDS reads and a v_exp per tile (log(scale) is - // in the exponent). Where kept, g_i - g_j <= 0, so the exp cannot overflow. - if (dbg && ci == 0) { -#pragma unroll - for (int i = 0; i < kNTV; ++i) -#pragma unroll - for (int e = 0; e < 8; ++e) - dbg[3 * kBT * kBT + (mt * 16 + lo) * kBT + (ntb + i) * 16 + 2 * e + hi] = - f32_to_bf16(p[i][e]); - } - { - const int ii = mt * 16 + lo; - const float gis = s.gg[ii] + lgs; -#pragma unroll - for (int i = 0; i < kNTV; ++i) { - const int j0 = (ntb + i) * 16; - float a[8]; -#pragma unroll - for (int e = 0; e < 8; ++e) { - const int j = j0 + 2 * e + hi; - a[e] = (j <= ii) ? p[i][e] * __expf(gis - s.gg[j]) : 0.f; - } -#pragma unroll - for (int e = 0; e < 8; ++e) - s.A[ii][j0 + 2 * e + hi] = f32_to_bf16(a[e]); - } - } - R3D_BARRIER(); // (2) - - // ---- V' = A @ W -> D (stored [v][token], transposed for the state read) - { - v8f d[kNTV]; -#pragma unroll - for (int i = 0; i < kNTV; ++i) d[i] = (v8f){}; - const unsigned ao = (unsigned)std::min(mt * 16 + (lane & 15), lim) * (unsigned)ars; -#define paf(ko) fragGo(ag, ao + (ko)) - const unsigned short* pwn[kNTV]; -#pragma unroll - for (int i = 0; i < kNTV; ++i) - pwn[i] = &s.W[(ntb + i) * 16 + lo][0]; -#define pwnf(i, ko) fragP(pwn[i] + (ko)) -#pragma unroll - for (int sk = 0; sk < kBT / 16; ++sk) { - const int ko = sk * 16; - const v16short a = paf(ko); -#pragma unroll - for (int i = 0; i < kNTV; ++i) d[i] = mmab(a, pwnf(i, ko), d[i]); - } -#pragma unroll - for (int i = 0; i < kNTV; ++i) -#pragma unroll - for (int e = 0; e < 8; ++e) - s.D[(ntb + i) * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(d[i][e]); - } - // K <- gs * K in place, for the state's V'^T @ K: (diag(gs) V')^T K == V'^T (diag(gs) K), - // and K is otherwise dead. All raw-K reads (U, P) retired before barrier (2); s.k is - // restaged next chunk; barrier (3) publishes the scaled K. -#pragma unroll - for (int u = 0; u < kBT * (kKD / 4) / kNTHR; ++u) { - const int idx = tid + u * kNTHR; - const int t = idx / (kKD / 4), c = (idx % (kKD / 4)) * 4; - const float f = s.gv[t]; - unsigned short* kp = &s.k[t][c]; -#pragma unroll - for (int e = 0; e < 4; ++e) kp[e] = f32_to_bf16(bf16_to_f32(kp[e]) * f); - } - R3D_BARRIER(); // (3) - if (dbg && ci == 0) { - for (int i = tid; i < kBT * (kBT / 4); i += kNTHR) { - const int r = i / (kBT / 4), c = (i % (kBT / 4)) * 4; - unsigned short* o = dbg + (size_t)r * kBT + c; - const unsigned short* a1 = &s.A[r][c]; - const unsigned short* a2 = &s.W[r][c]; - const unsigned short* a3 = &s.D[r][c]; - o[0] = a1[0]; o[1] = a1[1]; o[2] = a1[2]; o[3] = a1[3]; - o[kBT*kBT] = a2[0]; o[kBT*kBT+1] = a2[1]; o[kBT*kBT+2] = a2[2]; o[kBT*kBT+3] = a2[3]; - o[2*kBT*kBT] = a3[0]; o[2*kBT*kBT+1] = a3[1]; o[2*kBT*kBT+2] = a3[2]; o[2*kBT*kBT+3] = a3[3]; - } - } - - // ---- O += sA @ V' ; store. V' also feeds the state update, unchanged. The product - // runs in the transposed frame (V' as A, sA as B), adding (sA@V')^T to O^T. - { - const unsigned short* pA = &s.A[mt * 16 + lo][0]; - const unsigned short* pdn[kNTV]; -#pragma unroll - for (int i = 0; i < kNTV; ++i) - pdn[i] = &s.D[(ntb + i) * 16 + lo][0]; -#define pAf(ko) fragP(pA + (ko)) -#define pdnf(i, ko) fragP(pdn[i] + (ko)) -#pragma unroll - for (int sk = 0; sk < kBT / 16; ++sk) { - const int ko = sk * 16; - const v16short b = pAf(ko); -#pragma unroll - for (int i = 0; i < kNTV; ++i) O[i] = mmab(pdnf(i, ko), b, O[i]); - } - } - { - const int tok = mt * 16 + lo; - // The padding rows carry zero (the zeroed K, beta, gv and Q rows), so the store is - // unguarded and the output is finite at every row the caller can index. - { - unsigned short* op = o + ((size_t)(c0 + tok) * H + hv) * kVD + v0; -#pragma unroll - for (int i = 0; i < kNTV; ++i) -#pragma unroll - for (int e = 0; e < 8; ++e) - op[(ntb + i) * 16 + 2 * e + hi] = f32_to_bf16(O[i][e]); - } - } - - // ---- S = e^{gl} * S + V'^T @ (gs*K) (A needs K as [dim][token] -> strided fragT) - { - const float ec = __expf(gl); // gl <= 0: the decay is already on K -#pragma unroll - for (int t = 0; t < kNST; ++t) -#pragma unroll - for (int e = 0; e < 8; ++e) St[t][e] *= ec; - // The s.k A-operand (the fragT read) is decimated like the U / P reads, so the - // product runs as a manual FMA over the exact scalar reads. -#pragma unroll - for (int t = 0; t < kNST; ++t) { - const int v = VT(t) * 16 + lo; -#pragma unroll - for (int e = 0; e < 8; ++e) { - const int kx = KT(t) * 16 + 2 * e + hi; - float acc = 0.f; -#pragma unroll - for (int tk = 0; tk < kBT; ++tk) - acc = fmaf(bf16_to_f32(s.k[tk][kx]), bf16_to_f32(s.D[v][tk]), acc); - St[t][e] += acc; - } - } - } - // No barrier before the writeback: s.S aliases nothing, and barrier (2) proves every - // wave finished its U/O reads of s.S this chunk. - SWRITE(); - R3D_BARRIER(); // (4) - } - - if (HT) { - typename cs_state::T* p = ht + st_base; -#pragma unroll - for (int t = 0; t < kNST; ++t) { - typename cs_state::T* pw = p + (size_t)(v0 + VT(t) * 16 + lo) * kKD + KT(t) * 16; -#pragma unroll - for (int e = 0; e < 8; ++e) { - if (SDT) - pw[2 * e + hi] = (typename cs_state::T)St[t][e]; - else - pw[2 * e + hi] = St[t][e]; - } - } - } -} - -int r3d_gdn_chunk_scan_launch(const void* q, const void* k, const void* v, const void* A, - const void* g, const void* beta, const void* h0, void* o, - void* ht, const void* cu, const void* sidx, long sidx_stride, - long st_slot, long st_head, int N, int H, int Hg, int K, int V, - int chunk, float scale, int state_fp16, void* dbg, hipStream_t stream) -{ - if (K != kKD || V != kVD || chunk != kBT) return -1; - if (Hg <= 0 || H % Hg) return -2; - dim3 grid(V / kBV, H, N), blk(kNTHR); -#define CS_LAUNCH(SDTC, H0C, HTC) \ - R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_chunk_scan_kernel)), grid, blk, 0, stream, \ - (const unsigned short*)q, (const unsigned short*)k, (const unsigned short*)v, \ - (const unsigned short*)A, (const float*)g, (const float*)beta, \ - (const cs_state::T*)h0, (unsigned short*)o, (cs_state::T*)ht, \ - (const int*)cu, (const int*)sidx, sidx_stride, st_slot, st_head, H, Hg, scale, (unsigned short*)dbg) -#define CS_PICK(SDTC) \ - do { if (h0 && ht) CS_LAUNCH(SDTC, true, true); \ - else if (h0) CS_LAUNCH(SDTC, true, false); \ - else if (ht) CS_LAUNCH(SDTC, false, true); \ - else CS_LAUNCH(SDTC, false, false); } while (0) - if (state_fp16) CS_PICK(1); else CS_PICK(0); -#undef CS_PICK -#undef CS_LAUNCH - return (int)hipGetLastError(); -} - -} // namespace - -/* ------------------------------------------------------------------ the raw entry */ - -extern "C" int r3d_gdn_chunk_scan_k128_v128_c64(long q, long k, long v, long A, long g, long beta, - long h0, long o, long ht, long cu, long sidx, - long sidx_stride, long st_slot, long st_head, - int N, int H, int Hg, int K, int V, int chunk, - double scale, int state_fp16, long dbg, long stream) -{ - if (!q || !k || !v || !A || !g || !beta || !cu || !o) return -1; - if (N < 1 || H < 1 || Hg < 1) return -2; - return r3d_gdn_chunk_scan_launch((const void*)q, (const void*)k, (const void*)v, (const void*)A, - (const void*)g, (const void*)beta, (const void*)h0, - (void*)o, (void*)ht, (const void*)cu, (const void*)sidx, - sidx_stride, st_slot, st_head, N, H, Hg, K, V, chunk, - (float)scale, state_fp16, (void*)dbg, (hipStream_t)stream); -} - -/* ------------------------------------------------------------------ the plugin ABI */ - -enum { CS_Q = 0, CS_K, CS_V, CS_A, CS_G, CS_BETA, CS_H0, CS_CU, CS_O, CS_HT, CS_SIDX }; - -extern "C" int r3d_rad_gdn_chunk_scan(const RadArgs* a, RadStream s) -{ - if (!a) return R3D_NO(RAD_E_INVAL); - const RadTensor* qt = r3d_opt(a, CS_Q); - const RadTensor* kt = r3d_opt(a, CS_K); - const RadTensor* vt = r3d_opt(a, CS_V); - const RadTensor* At = r3d_opt(a, CS_A); - const RadTensor* gt = r3d_opt(a, CS_G); - const RadTensor* btt = r3d_opt(a, CS_BETA); - const RadTensor* h0t = r3d_opt(a, CS_H0); - const RadTensor* cut = r3d_opt(a, CS_CU); - const RadTensor* ot = r3d_opt(a, CS_O); - const RadTensor* htt = r3d_opt(a, CS_HT); - const RadTensor* sit = r3d_opt(a, CS_SIDX); - if (!r3d_p(qt) || !r3d_p(kt) || !r3d_p(vt) || !r3d_p(At) || !r3d_p(gt) || !r3d_p(btt) || - !r3d_p(cut) || !r3d_wp(ot)) - return R3D_NO(RAD_E_INVAL); - // bf16 q/k/v/A/o, f32 gate/beta; the state cache is f32 or f16, taken from the operand's - // dtype (a property of the allocation), so this kernel and the recurrent update, which - // share the cache, agree on it. - if (!r3d_is_bf16(qt) || !r3d_is_bf16(kt) || !r3d_is_bf16(vt) || !r3d_is_bf16(At) || - !r3d_is_f32(gt) || !r3d_is_f32(btt) || !r3d_is_bf16(ot)) - return R3D_NO(RAD_E_DTYPE); - uint32_t st_dt = RAD_F32; - if (r3d_has(h0t)) { if (!r3d_is_f32(h0t) && !r3d_is_f16(h0t)) return R3D_NO(RAD_E_DTYPE); - st_dt = h0t->dtype; } - if (r3d_has(htt)) { - if (htt->dtype != st_dt) return R3D_NO(RAD_E_DTYPE); - st_dt = htt->dtype; - } - if (r3d_has(sit) && !r3d_is_i32(sit)) return R3D_NO(RAD_E_DTYPE); - - if (cut->rank != 1 || cut->shape[0] < 2 || !r3d_contig(cut)) return R3D_NO(RAD_E_SHAPE); - const int N = (int)(cut->shape[0] - 1); - - const long long T = r3d_dim(qt, 0), Hg = r3d_dim(qt, 1), K = r3d_dim(qt, 2); - const long long H = r3d_dim(vt, 1), V = r3d_dim(vt, 2); - const long long chunk = r3d_dim(At, 2); - if (r3d_dim(kt, 0) != T || r3d_dim(kt, 1) != Hg || r3d_dim(kt, 2) != K) return R3D_NO(RAD_E_SHAPE); - if (r3d_dim(vt, 0) != T) return R3D_NO(RAD_E_SHAPE); - if (r3d_dim(ot, 0) != T || r3d_dim(ot, 1) != H || r3d_dim(ot, 2) != V) return R3D_NO(RAD_E_SHAPE); - if (r3d_dim(At, 0) != T || r3d_dim(At, 1) != H) return R3D_NO(RAD_E_SHAPE); - if (r3d_dim(gt, 0) != T || r3d_dim(gt, 1) != H) return R3D_NO(RAD_E_SHAPE); - if (r3d_dim(btt, 0) != T || r3d_dim(btt, 1) != H) return R3D_NO(RAD_E_SHAPE); - if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE); - // The state slot strides come from the tensor, not from H, V and K, so a cache with padded - // slots is served too. h0 and ht must share strides: the kernel uses one base for both. - long long st_slot = 0, st_head = 0; - if (r3d_has(h0t)) { - if (h0t->rank < 2) return R3D_NO(RAD_E_SHAPE); - st_slot = h0t->stride[0]; st_head = h0t->stride[1]; - } - if (r3d_has(htt)) { - if (htt->rank < 2) return R3D_NO(RAD_E_SHAPE); - if (r3d_has(h0t) && (htt->stride[0] != st_slot || htt->stride[1] != st_head)) - return R3D_NO(RAD_E_STRIDE); - st_slot = htt->stride[0]; st_head = htt->stride[1]; - } - if (r3d_has(sit)) { - if (sit->rank < 1 || sit->shape[0] != N) return R3D_NO(RAD_E_SHAPE); - if (sit->stride[sit->rank - 1] != 1) return R3D_NO(RAD_E_STRIDE); - } - if (!r3d_contig(qt) || !r3d_contig(kt) || !r3d_contig(vt) || !r3d_contig(At) || - !r3d_contig(gt) || !r3d_contig(btt) || !r3d_contig(ot)) - return R3D_NO(RAD_E_STRIDE); - - const double scale = r3d_getf(a, "scale", 1.0); - const int state_fp16 = st_dt == RAD_F16; - - const int e = r3d_gdn_chunk_scan_launch(r3d_p(qt), r3d_p(kt), r3d_p(vt), r3d_p(At), r3d_p(gt), - r3d_p(btt), r3d_has(h0t) ? r3d_p(h0t) : nullptr, r3d_wp(ot), - r3d_has(htt) ? r3d_wp(htt) : nullptr, r3d_p(cut), - r3d_has(sit) ? r3d_p(sit) : nullptr, - r3d_has(sit) && sit->rank >= 2 ? sit->stride[0] : 1, - st_slot, st_head, N, (int)H, (int)Hg, (int)K, (int)V, - (int)chunk, (float)scale, state_fp16, nullptr, (hipStream_t)s); - /* The launcher's codes are raw: its own negatives and hipGetLastError's positives. The - * plugin ABI takes RadStatus, so normalise. */ - if (e < 0) return R3D_NO(RAD_E_INVAL); - return e ? R3D_NO(RAD_E_DEVICE) : RAD_OK; -} diff --git a/libr3d/r3d_gdn_kkt_solve_c64.hip b/libr3d/r3d_gdn_kkt_solve_c64.hip deleted file mode 100644 index bbf0388b..00000000 --- a/libr3d/r3d_gdn_kkt_solve_c64.hip +++ /dev/null @@ -1,475 +0,0 @@ -/* r3d_gdn_kkt_solve_c64.hip -- the gated-delta-net chunk preamble in one kernel: - * - * A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1} per chunk of 64 - * - * The FLA chunk_scaled_dot_kkt_fwd + solve_tril pair, fused: the gram stays in LDS and only the - * bf16 inverse is stored. The gram is computed once per k head, not per v head: K K^T does not - * depend on beta or g, so one workgroup owns a (chunk, k head) and applies each v head's scales - * to it. The decay is applied per element as e^{g_i-g_j}, not split about a per-chunk reference: - * each half of e^{g_i-c} * e^{c-g_j} can overflow fp32 on its own, and the exponent is always - * <= 0 here (g decreases along the chunk and only i > j is kept). - * - * The inverse is blocked 16 -> 32 -> 64. The four diagonal blocks use fp32 forward substitution - * (one wave each, one lane per column), cheaper than a WMMA Neumann series at this size and exact - * in fp32, as in FLA. The 32-merges and the 64-merge are wave-matrix, using - * - * [[P, 0], [R, Q]]^-1 = [[P^-1, 0], [-Q^-1 R P^-1, Q^-1]] - * - * mma(X, Y) computes X . Y^T from two k-contiguous operands, so a left operand is row-major and a - * right operand is stored transposed. The intermediates are staged transposed in the 32x32 - * scratch; the final inverse is assembled row-major for the HBM store. - * - * ---- the tile map (the port's one structural change) --------------------------------------- - * - * The source row was written for the wave-matrix ISA of the card it was probed on, whose - * 16x16x16 fragment map differs from this card's. This card's map (probed in the bf16 GEMM row, - * r3d_gemm_bf16_nt_m16_wmma.hip): - * - * A fragment: lane L holds row L % 16 of the tile, the 16 k contiguous - * B fragment: lane L holds column L % 16 of the tile, the 16 k contiguous - * C/D: lane L, element e holds D[2e + L / 16][L % 16], eight f32 a lane - * - * so the fragment loads are the bf16 GEMM row's 32-byte reads, and every accumulator store that - * the source row made as one 16-byte vector is here eight scalar bf16 stores along the map's - * stride-2 axis. The transposed-operand reads (fragT) keep the source's lane-to-row assignment, - * which the two ISAs share. - * - * The blocked inverse reads the blocks it overwrites before writing them, with barriers between - * stages, so one 64x64 buffer plus a 32x32 scratch carries the whole solve: 11 KiB of LDS. - */ - -#include - -#include "r3d.h" -#include "r3d_common.h" -#include "r3d_launch.h" -#include "r3d_args.h" -#include "r3d_codecs.h" - -#include -#include -#include - -namespace { - -constexpr int kBT = 64; // chunk -constexpr int kKD = 128; // head_k -constexpr int kNBK = 4; // 16x16 blocks per chunk edge -constexpr int kAP = 68; // row pitch of the [BT][BT] buffers, in shorts: 8-byte aligned - // for the store, and 16 rows still cover every bank -constexpr int kNW = 4; -constexpr int kNTHR = kNW * 32; -constexpr int kNTILE = 10; // upper-triangular tiles of a 4x4 tiling -constexpr int kMAXT = (kNTILE + kNW - 1) / kNW; - -using v8f = float __attribute__((ext_vector_type(8))); -using v16short = short __attribute__((ext_vector_type(16))); - -/* One 16x16x16 tile, f32 accumulate. */ -__device__ __forceinline__ v8f mmab(const v16short& a, const v16short& b, const v8f& c) -{ - return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); -} - -/* A/B fragment from a row pointer already advanced to this lane's row and half-K: the 16 k - * contiguous, 32 bytes, two 16-byte reads. The row pitches are multiples of 4 shorts and the - * kbase is a multiple of 16, so the 16-byte alignment the reads need holds. */ -__device__ __forceinline__ v16short fragP(const unsigned short* p) -{ - // The GEMM row's exact form: load a uint4, bit-cast it. Loading the ext-vector type - // directly lowers differently on this backend and corrupts the fragment. - union { r3d_u32x4 w[2]; v16short f; } u; - u.w[0] = __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); - u.w[1] = __builtin_bit_cast(r3d_u32x4, *(const uint4*)(p + 8)); - return u.f; -} - -/* Global fragment off a 32-bit element offset split from a uniform base: the immediate-offset - * form the bf16 GEMM row's note describes. The row is clamped at the call site so a partial last - * chunk cannot read past the tensor (those rows are discarded downstream). */ -__device__ __forceinline__ v16short fragGo(const unsigned short* base, unsigned off) -{ - return fragP(base + off); -} - -/* K-contiguous fragment: src[idx][k], row pitch `pitch` (in elements). */ -__device__ __forceinline__ v16short frag(const unsigned short* src, int pitch, int base, - int kbase, int lane) -{ - return fragP(src + (size_t)(base + (lane & 15)) * pitch + kbase); -} - -/* Same fragment but the source is stored transposed: src[k][idx]. Sixteen scalar reads. */ -__device__ __forceinline__ v16short fragT(const unsigned short* src, int pitch, int base, - int kbase, int lane) -{ - const int idx = base + (lane & 15); - union { unsigned short h[16]; v16short f; } u; -#pragma unroll - for (int e = 0; e < 16; ++e) - u.h[e] = src[(size_t)(kbase + e) * pitch + idx]; - return u.f; -} - -/* C[mt*16 .. ][nt*16 .. ] += A[M][K] @ B[N][K]^T over KSTEP 16-wide steps. */ -template -__device__ __forceinline__ v8f gemm16(const unsigned short* A, int Ap, int mt, - const unsigned short* B, int Bp, int nt, - int lane, v8f acc) -{ -#pragma unroll - for (int s = 0; s < KSTEP; ++s) - acc = mmab(frag(A, Ap, mt * 16, s * 16, lane), frag(B, Bp, nt * 16, s * 16, lane), acc); - return acc; -} - -/* A block barrier the backend cannot move; see the GEMM rows' note. */ -#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) - -/* The chunk's buffers. One 64x64 buffer plus a 32x32 scratch. ST is a staging line: every - * scattered store out of a wmma accumulator goes through it first. A scattered store issued - * directly from the accumulator registers is miscompiled on this backend (the wmma result is - * corrupted by the store's address arithmetic); a contiguous lane-major store into LDS, a - * barrier, and the scatter out of LDS is the proven safe form. */ -struct KkSmem { - unsigned short A[kBT][kAP]; // A on the way in, its inverse on the way out - unsigned short TMP[32][36]; // one 32x32 intermediate, transposed - float ST[kNTHR * 8]; // one gram round (128 threads x 8), contiguous per thread - float gb[kBT], bt[kBT]; // the chunk's gate cumsum and beta, per token -}; - -/* (mt, nt) of upper-triangular tile ti, computed with wave-uniform arithmetic instead of a - * table load. */ -__device__ __forceinline__ void kkt_tile(int ti, int* mt, int* nt) -{ - int m = 0, n = ti; - while (n >= kNBK - m) { n -= (kNBK - m); ++m; } - *mt = m; *nt = n + m; -} - -template -__global__ __launch_bounds__(kNTHR) -void r3d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, - const float* __restrict__ beta, - const float* __restrict__ g, - unsigned short* __restrict__ Ao, - const int* __restrict__ cu, - int N, int H, int Hg) -{ - __shared__ KkSmem s; - int tid = threadIdx.x; - asm volatile("" : "+v"(tid)); // pin the hw thread-id vreg before the allocator can reuse it - const int lane = tid & 31, warp = tid >> 5; - const int lo = lane & 15, hi = lane >> 4; - const int hg = blockIdx.y; - - // Resolve the flat chunk id to (sequence, chunk). The grid is an upper bound on the chunk - // count, so surplus workgroups exit here; this saves the host a device-to-host sync to size - // the grid exactly. - int n = -1, t0 = 0, bos = 0, rows = 0; - { - int acc = 0, want = blockIdx.x; - for (int i = 0; i < N; ++i) { - const int b = cu[i], e = cu[i + 1]; - const int nc = (e - b + kBT - 1) / kBT; - if (want < acc + nc) { n = i; bos = b; t0 = (want - acc) * kBT; - rows = std::min(kBT, e - b - t0); break; } - acc += nc; - } - if (n < 0) return; - } - - // ---- zero A once: the parts no store reaches (the upper tiles) are the same for every head. - // 16-byte stores (the buffer is 8704 bytes, 16-byte aligned). - for (int i = tid; i < kBT * kAP / 8; i += kNTHR) ((uint4*)&s.A[0][0])[i] = make_uint4(0, 0, 0, 0); - - // ---- the gram, once for all HG_RATIO v heads of this k head ----------------------------- - const unsigned short* kp = k + ((size_t)(bos + t0) * Hg + hg) * kKD; - const unsigned krow = (unsigned)(Hg * kKD); - // The gram, once for all v heads: tile (mt, nt) of P is staged lane-contiguous into ST and - // then parked in A's upper triangle, where A is zero. An off-diagonal tile goes into the - // (mt, nt) slot; a diagonal tile goes straight into its (nt, mt) target slot, so the - // per-head pass below is an in-place scale for it (no cross-lane read/write on one tile). -#pragma unroll - for (int t = 0; t < kMAXT; ++t) { - const int ti = warp + t * kNW; - v8f P = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; - if (ti < kNTILE) { - int mt, nt; kkt_tile(ti, &mt, &nt); - // One 32-bit offset per operand row, hoisted out of the k loop. - const unsigned om = (unsigned)(std::min(mt * 16 + (lane & 15), rows - 1)) * krow; - const unsigned on = (unsigned)(std::min(nt * 16 + (lane & 15), rows - 1)) * krow; -#pragma unroll - for (int sk = 0; sk < kKD / 16; ++sk) { - const v16short fa = fragGo(kp, om + sk * 16); - const v16short fb = fragGo(kp, on + sk * 16); - - P = mmab(fa, fb, P); - } - } - -#pragma unroll - for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = P[e]; - R3D_BARRIER(); - if (ti < kNTILE) { - int mt, nt; kkt_tile(ti, &mt, &nt); -#pragma unroll - for (int e = 0; e < 8; ++e) { - if (mt == nt) - s.A[nt * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(s.ST[tid * 8 + e]); - else - s.A[mt * 16 + 2 * e + hi][nt * 16 + lo] = f32_to_bf16(s.ST[tid * 8 + e]); - } - } - } - R3D_BARRIER(); - - for (int hh = 0; hh < HG_RATIO; ++hh) { - const int hv = hg * HG_RATIO + hh; - - // ---- per-head gate and beta for this chunk - if (tid < kBT) { - const int t = std::min(tid, rows - 1); - s.gb[tid] = g[(size_t)(bos + t0 + t) * H + hv]; - s.bt[tid] = beta[(size_t)(bos + t0 + t) * H + hv]; - } - R3D_BARRIER(); - - // ---- scale, mask and place the gram as the strictly lower half of A ----------------- - // Element e of tile (mt, nt) lands at A[i = nt*16 + lo][j = mt*16 + 2e + hi], the lower - // triangle when i > j. Off-diagonal tiles were parked transposed at A[j][i], so the - // scale reads that slot; diagonal tiles are scaled in place. -#pragma unroll - for (int t = 0; t < kMAXT; ++t) { - const int ti = warp + t * kNW; - if (ti < kNTILE) { - int mt, nt; kkt_tile(ti, &mt, &nt); - const int i = nt * 16 + lo; // row of A - const bool live = (i < rows); - const float bi = live ? s.bt[i] : 0.0f; - const float gi = live ? s.gb[i] : 0.0f; -#pragma unroll - for (int e = 0; e < 8; ++e) { - const int j = mt * 16 + 2 * e + hi; - const float pv = (mt == nt) ? bf16_to_f32(s.A[i][j]) - : bf16_to_f32(s.A[j][i]); - // For a live row, i > j gives g_i <= g_j, so the exponent is never positive. - // Padding rows and columns must be masked to -inf: with gi = 0 the exponent - // -gb[j] is large and positive, 0 * inf = NaN, and the WMMA merges in the - // blocked inverse would spread it into live rows. - const float d = (live && i > j && j < rows) ? (gi - s.gb[j]) : -INFINITY; - s.A[i][j] = f32_to_bf16(bi * __expf(d) * pv); - } - } - } - - R3D_BARRIER(); - - // ---- 1. the four diagonal blocks, by fp32 forward substitution ---------------------- - // D = (I + N)^-1 solves D = I - N D row by row. Lane l owns column l of D, so the dot - // product over j < i is in 16 registers and N[i][j] is a broadcast LDS read. - for (int p = warp; p < kNBK; p += kNW) { - const int b0 = p * 16; - float d[16]; -#pragma unroll - for (int i = 0; i < 16; ++i) { - float acc = 0.0f; -#pragma unroll - for (int j = 0; j < 16; ++j) - if (j < i) acc += bf16_to_f32(s.A[b0 + i][b0 + j]) * d[j]; - d[i] = ((lo == i) ? 1.0f : 0.0f) - acc; - } - if (lane < 16) { -#pragma unroll - for (int i = 0; i < 16; ++i) s.A[b0 + i][b0 + lo] = f32_to_bf16(d[i]); - } - } - R3D_BARRIER(); - - // ---- 2. the two 32-merges: M10 = -D1 A10 D0 ----------------------------------------- - for (int blk = warp; blk < 2; blk += kNW) { - const int r0 = blk * 32; // 32-block origin - // X = A10 . D0 (left A10 row-major, right D0 transposed) - v8f X = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; - const v16short af = frag(&s.A[0][0], kAP, r0 + 16, r0, lane); - X = mmab(af, fragT(&s.A[0][0], kAP, r0, r0, lane), X); - // Stage X lane-contiguous, then scatter it out of ST (see the KkSmem note). The - // stage is transposed for the next product: TMP[n][m] = X[m][n], and element e is - // X[m = 2e + hi][n = lo]. Each of the two merges owns 16 rows of TMP. -#pragma unroll - for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = X[e]; - R3D_BARRIER(); -#pragma unroll - for (int e = 0; e < 8; ++e) - s.TMP[blk * 16 + lo][2 * e + hi] = f32_to_bf16(s.ST[tid * 8 + e]); - R3D_BARRIER(); - // M10 = -D1 . X (left D1 row-major, in place in A; right X transposed, in TMP) - v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; - Y = mmab(frag(&s.A[0][0], kAP, r0 + 16, r0 + 16, lane), - frag(&s.TMP[0][0], 36, blk * 16, 0, lane), Y); -#pragma unroll - for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = Y[e]; - R3D_BARRIER(); - // Element e is A[r0 + 16 + 2e + hi][r0 + lo]. -#pragma unroll - for (int e = 0; e < 8; ++e) - s.A[r0 + 16 + 2 * e + hi][r0 + lo] = f32_to_bf16(-s.ST[tid * 8 + e]); - } - R3D_BARRIER(); - - - R3D_BARRIER(); - - // Flip the sign of the R block with a binary subtraction. In this kernel context the - // compiler drops unary minus on the 64-merge accumulator store, so the overall minus - // of M[32:,:32] = -Q^-1 (R P^-1) is carried by the negated R: the merge computes - // Q^-1 . (-R) . P^-1 and stores it as-is. (Flipping Q^-1 in place instead breaks its - // final value, because the restoring flip is dropped in the same way.) - for (int idx = tid; idx < 32 * 32; idx += kNTHR) { - const int r = 32 + idx / 32, c = idx % 32; - s.A[r][c] = f32_to_bf16(0.0f - bf16_to_f32(s.A[r][c])); - } - R3D_BARRIER(); - - // ---- 3. the 64-merge: M[32:,:32] = -Q^-1 (R P^-1) ----------------------------------- - // Y = R . P^-1, R = A[32:,:32] row-major, P^-1 read transposed out of A[:32,:32] - for (int t = warp; t < 4; t += kNW) { - const int mt = t >> 1, nt = t & 1; - v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; -#pragma unroll - for (int sk = 0; sk < 2; ++sk) - Y = mmab(frag(&s.A[0][0], kAP, 32 + mt * 16, sk * 16, lane), - fragT(&s.A[0][0], kAP, nt * 16, sk * 16, lane), Y); - // Stage Y lane-contiguous for the transposed scatter below. -#pragma unroll - for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = Y[e]; - } - R3D_BARRIER(); - // TMP[n][m] = Y[m][n]; element e is Y[m = 2e + hi (within the mt tile)][n = lo - // (within the nt tile)]. - for (int t = warp; t < 4; t += kNW) { - const int mt = t >> 1, nt = t & 1; -#pragma unroll - for (int e = 0; e < 8; ++e) - s.TMP[nt * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(s.ST[tid * 8 + e]); - } - R3D_BARRIER(); // every wave has read R into TMP; now it may be overwritten - // Z = -Q^-1 . Y, Q^-1 = A[32:,32:] row-major, Y transposed = TMP - for (int t = warp; t < 4; t += kNW) { - const int mt = t >> 1, nt = t & 1; - v8f Z = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; -#pragma unroll - for (int sk = 0; sk < 2; ++sk) - Z = mmab(frag(&s.A[0][0], kAP, 32 + mt * 16, 32 + sk * 16, lane), - frag(&s.TMP[0][0], 36, nt * 16, sk * 16, lane), Z); -#pragma unroll - for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = Z[e]; - } - R3D_BARRIER(); - for (int t = warp; t < 4; t += kNW) { - const int mt = t >> 1, nt = t & 1; - // Element e is A[32 + mt*16 + 2e + hi][nt*16 + lo]. This wmma instance - // negates its product on this toolchain, so the minus belongs to it: - // store the accumulator as-is. -#pragma unroll - for (int e = 0; e < 8; ++e) - s.A[32 + mt * 16 + 2 * e + hi][nt * 16 + lo] = f32_to_bf16(s.ST[tid * 8 + e]); - } - R3D_BARRIER(); - - // Clear the upper-triangular parking slots (they still hold gram values) so the - // stored matrix is a clean lower-triangular inverse. - for (int idx = tid; idx < 64 * 64; idx += kNTHR) { - const int r = idx / 64, c = idx % 64; - if (c > r) s.A[r][c] = 0; - } - R3D_BARRIER(); - - - // ---- store: one row of the inverse is 64 bf16, contiguous in HBM --------------------- - { - unsigned short* op = Ao + ((size_t)(bos + t0) * H + hv) * kBT; - const size_t orow = (size_t)H * kBT; - for (int r = tid / 8; r < rows; r += kNTHR / 8) { - const int c8 = (tid & 7) * 8; - *(uint4*)(op + (size_t)r * orow + c8) = *(const uint4*)(&s.A[r][c8]); - } - } - if (hh + 1 < HG_RATIO) R3D_BARRIER(); - } -} - -int r3d_gdn_kkt_solve_launch(const void* k, const void* beta, const void* g, void* A, - const void* cu, int N, int T, int H, int Hg, int K, int chunk, - hipStream_t stream) -{ - if (K != kKD || chunk != kBT) return -1; - if (H % Hg) return -2; - const int nchunk_ub = (T + kBT - 1) / kBT + N; // sum of per-sequence chunk counts, bounded - dim3 grid(nchunk_ub, Hg), blk(kNTHR); -#define R3D_KKLAUNCH(R) \ - R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_kkt_solve_kernel)), grid, blk, 0, stream, \ - (const unsigned short*)k, (const float*)beta, (const float*)g, \ - (unsigned short*)A, (const int*)cu, N, H, Hg) - switch (H / Hg) { - case 1: R3D_KKLAUNCH(1); break; - case 2: R3D_KKLAUNCH(2); break; - case 3: R3D_KKLAUNCH(3); break; - case 4: R3D_KKLAUNCH(4); break; - case 6: R3D_KKLAUNCH(6); break; - case 8: R3D_KKLAUNCH(8); break; - default: return -3; - } -#undef R3D_KKLAUNCH - return (int)hipGetLastError(); -} - -} // namespace - -/* ------------------------------------------------------------------ the raw entry */ - -extern "C" int r3d_gdn_kkt_solve_c64(long k, long beta, long g, long A, long cu, - int N, int T, int H, int Hg, int K, int chunk, - long stream) -{ - if (!k || !beta || !g || !A || !cu) return -1; - if (N < 1 || T < 1) return -2; - if (H < 1 || Hg < 1) return -2; - return r3d_gdn_kkt_solve_launch((const void*)k, (const void*)beta, (const void*)g, (void*)A, - (const void*)cu, N, T, H, Hg, K, chunk, (hipStream_t)stream); -} - -/* ------------------------------------------------------------------ the plugin ABI */ - -enum { QK_K = 0, QK_BETA, QK_G, QK_CU, QK_A }; - -extern "C" int r3d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s) -{ - if (!a) return R3D_NO(RAD_E_INVAL); - const RadTensor* kt = r3d_opt(a, QK_K); - const RadTensor* bt = r3d_opt(a, QK_BETA); - const RadTensor* gt = r3d_opt(a, QK_G); - const RadTensor* cu = r3d_opt(a, QK_CU); - const RadTensor* Ao = r3d_opt(a, QK_A); - if (!r3d_p(kt) || !r3d_p(bt) || !r3d_p(gt) || !r3d_p(cu) || !r3d_wp(Ao)) - return R3D_NO(RAD_E_INVAL); - if (!r3d_is_bf16(kt) || !r3d_is_f32(bt) || !r3d_is_f32(gt) || !r3d_is_i32(cu) || - !r3d_is_bf16(Ao)) - return R3D_NO(RAD_E_DTYPE); - - if (cu->rank != 1 || cu->shape[0] < 2 || !r3d_contig(cu)) return R3D_NO(RAD_E_SHAPE); - const int N = (int)(cu->shape[0] - 1); - - const long long T = r3d_dim(kt, 0), Hg = r3d_dim(kt, 1), K = r3d_dim(kt, 2); - const long long H = r3d_dim(bt, 1), chunk = r3d_dim(Ao, 2); - if (r3d_dim(gt, 0) != T || r3d_dim(gt, 1) != H || r3d_dim(bt, 0) != T) - return R3D_NO(RAD_E_SHAPE); - if (r3d_dim(Ao, 0) != T || r3d_dim(Ao, 1) != H) return R3D_NO(RAD_E_SHAPE); - if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE); - if (!r3d_contig(kt) || !r3d_contig(bt) || !r3d_contig(gt) || !r3d_contig(Ao)) - return R3D_NO(RAD_E_STRIDE); - - return r3d_gdn_kkt_solve_launch(r3d_p(kt), r3d_p(bt), r3d_p(gt), r3d_wp(Ao), r3d_p(cu), - N, (int)T, (int)H, (int)Hg, (int)K, (int)chunk, - (hipStream_t)s); -} diff --git a/libr3d/r3d_gdn_recurrent_update_k128_v128.hip b/libr3d/r3d_gdn_recurrent_update_k128_v128.hip deleted file mode 100644 index f1cd2308..00000000 --- a/libr3d/r3d_gdn_recurrent_update_k128_v128.hip +++ /dev/null @@ -1,350 +0,0 @@ -/* r3d_gdn_recurrent_update_k128_v128.hip -- the gated-delta-net recurrent state update, run by - * - * STATUS: the loop-restructure workaround is in; the value probe is the remaining gate. Three - * compiler bugs were found, two worked around outright and the third around by loop shape: - * - * 1. A DPP shuffle (__shfl_xor) inside the token loop miscompiles: 48 of the 256 threads drop - * out and the row's stores never land. Worked around: every cross-lane exchange (the l2 - * norms, the S k / S q closes, the gated-norm wave sum) goes through an __shared__ scratch - * instead of a shuffle. - * - * 2. As a template the kernel's device code is present and the launch - * succeeds, but the kernel never runs (not even a prologue sentinel lands), while a plain - * kernel in the same file runs fine. Worked around: the kernel is plain; norm and ab_bf16 - * are runtime parameters. - * - * 3. With both fixes in, the loop was compiler-sensitive: the fused in-loop pair (the state - * update h[j] += u*kk[j] with the on accumulation) plus the third cross-lane exchange and - * the o write produced a kernel whose token loop did not land its o stores, while - * near-identical variants did. The trigger is a specific interaction of the 64-element - * register state, the LDS exchanges and the o write; it has not been reduced to a minimal - * repro. Worked around: the update and the o dot run as separate loops, and the o store is - * volatile. The value probe is the gate. - * - * decode (prefill runs the chunked scan). One kernel for the whole step: - * - * g = -exp(A_log) . softplus(a + dt_bias) beta = sigmoid(b) q, k l2-normalised - * S *= e^g - * u = beta . (v - S k) S += u k^T o = S q - * - * per token, against a paged state cache: the initial state is read from the slot the step's - * tokens leave, and every token writes its own slot. The state stays in registers: one thread - * owns one v row and half its k range, so - * - * * S k and S q are in-lane dot products closed by a single lane<->lane^1 exchange, not a tree; - * * the outer-product update is 64 independent FMAs with no cross-lane traffic; - * * a thread's 64 state elements are contiguous in k, so the load and every store is eight - * 8-byte accesses over one 256-byte run. - * - * The cross-lane exchanges (the l2 norms, the S k and S q closes, the gated-norm wave sum) go - * through LDS, not a shuffle. A DPP shuffle inside the token loop miscompiles on gfx1102: with - * the lane<->lane^1 __shfl_xor in the loop, 48 of the 256 threads drop out and the row's stores - * never land. Routing the same exchange through a __shared__ scratch (one store, a barrier, one - * read of the neighbour) is correct and costs a barrier per token. - * - * This is the non-speculative core: a step's tokens are the cu window (width 1 for a plain - * decode step), the state cache is fp32, and the gated RMS norm is folded into the epilogue - * (z and norm_w present) or omitted. The speculative anchor, the folded decode convolution and - * the folded out-projection quantiser are not part of this row. - */ - -#include - -#include "r3d.h" -#include "r3d_common.h" -#include "r3d_launch.h" -#include "r3d_args.h" -#include "r3d_codecs.h" - -#include -#include -#include -#include - -namespace { - -constexpr int kK = 128; // head_k -constexpr int kV = 128; // head_v -constexpr int kHK = 64; // k elements per thread (kK / 2) -constexpr int kTHR = kV * 2; // two threads per v row - -typedef float ru_f4 __attribute__((ext_vector_type(4))); - -template -__device__ __forceinline__ void ru_load8(float* d, const float* p) -{ - const ru_f4* q = (const ru_f4*)p; - *(ru_f4*)d = NT ? __builtin_nontemporal_load(q) : *q; - *(ru_f4*)(d + 4) = NT ? __builtin_nontemporal_load(q + 1) : *(q + 1); -} - -template -__device__ __forceinline__ void ru_store8(float* p, const float* d) -{ - ru_f4* q = (ru_f4*)p; - if (NT) { - __builtin_nontemporal_store(*(const ru_f4*)d, q); - __builtin_nontemporal_store(*(const ru_f4*)(d + 4), q + 1); - } else { - *q = *(const ru_f4*)d; - *(q + 1) = *(const ru_f4*)(d + 4); - } -} - -__device__ __forceinline__ float ru_softplus(float x, float thr) -{ - if (x > thr) return x; - return (x > 0.0f) ? (x + __logf(1.0f + __expf(-x))) : __logf(1.0f + __expf(x)); -} - -template -__device__ __forceinline__ float ru_ab(const void* p, size_t i) -{ - return ABF16 ? bf16_to_f32(((const unsigned short*)p)[i]) : ((const float*)p)[i]; -} - -__device__ __forceinline__ float ru_act(float z, int kind) -{ - const float s = 1.0f / (1.0f + __expf(-z)); - return kind ? s : z * s; -} - -#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) - -/* norm: 0 = no epilogue norm, 1 = sigmoid, 2 = silu (the row's `act`). ab_bf16: a/b are bf16. - * A plain kernel, not a template: on gfx1102 the template instantiation miscompiles (the device - * code is present and the launch succeeds, but the kernel never runs -- not even a prologue - * sentinel lands, while a plain kernel in the same file runs fine). */ -__global__ __launch_bounds__(kTHR) -void r3d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, - const unsigned short* __restrict__ k, - const unsigned short* __restrict__ v, - const void* __restrict__ av, const void* __restrict__ bv, - long long ab_stride, - const float* __restrict__ A_log, const float* __restrict__ dt_bias, - float* __restrict__ state, - long long st_slot, long long st_head, - const int* __restrict__ sidx, long long sidx_stride, - const unsigned short* __restrict__ zg, long long zg_pitch, - const float* __restrict__ nw, - unsigned short* __restrict__ o, - const int* __restrict__ cu, int H, int Hg, - float scale, float sp_thr, float neps, - int norm, int ab_bf16) -{ - const int tid = threadIdx.x; - const int row = (tid >> 1), half = tid & 1, k0 = half * kHK; - const int n = blockIdx.x, hv = blockIdx.y; - const int bos = cu[n], T = cu[n + 1] - bos; - if (T <= 0) return; - const int hk = hv / (H / Hg); - - /* Read early so their latency overlaps the state load. */ - const float a_log_h = A_log[hv], dtb = dt_bias[hv]; - const float alog = __expf(a_log_h); - - float h[kHK]; - { - const float* p = state + (size_t)sidx[(size_t)n * sidx_stride] * st_slot - + (size_t)hv * st_head + (size_t)row * kK + k0; -#pragma unroll - for (int j = 0; j < kHK; j += 8) ru_load8<0>(&h[j], p + j); - } - - // LDS scratch for the cross-lane exchanges. ex holds the per-thread value being exchanged - // (lane<->lane^1, or a full wave for the gated norm); wsum holds the eight wave sums. - __shared__ float ex[2 * kTHR]; - __shared__ float wsum[kTHR / 32]; - - for (int t = 0; t < T; ++t) { - const int tok = bos + t; - const unsigned short* qp = q + ((size_t)tok * Hg + hk) * kK + k0; - const unsigned short* kp = k + ((size_t)tok * Hg + hk) * kK + k0; - - float qq[kHK], kk[kHK]; - for (int j = 0; j < kHK; ++j) { qq[j] = bf16_to_f32(qp[j]); kk[j] = bf16_to_f32(kp[j]); } - - // l2 norms: 64 in-lane terms, then one exchange with the lane holding the other half. - // (LDS, not a shuffle -- a DPP in this loop miscompiles on gfx1102.) - float sq = 0.0f, sk = 0.0f; - for (int j = 0; j < kHK; ++j) { sq += qq[j] * qq[j]; sk += kk[j] * kk[j]; } - ex[tid] = sq; ex[tid + kTHR] = sk; - R3D_BARRIER(); - sq += ex[tid ^ 1]; sk += ex[tid ^ 1 + kTHR]; - const float qs = __frsqrt_rn(sq + 1e-6f) * scale, ks = __frsqrt_rn(sk + 1e-6f); - for (int j = 0; j < kHK; ++j) { qq[j] *= qs; kk[j] *= ks; } - - const size_t ab_i = (size_t)tok * ab_stride + hv; - const float ra = ab_bf16 ? bf16_to_f32(((const unsigned short*)av)[ab_i]) : ((const float*)av)[ab_i]; - const float rb = ab_bf16 ? bf16_to_f32(((const unsigned short*)bv)[ab_i]) : ((const float*)bv)[ab_i]; - const float g = -alog * ru_softplus(ra + dtb, sp_thr); - const float bt = 1.0f / (1.0f + __expf(-rb)); - const float eg = __expf(g); - - float dot = 0.0f; - for (int j = 0; j < kHK; ++j) { h[j] *= eg; dot += h[j] * kk[j]; } - ex[tid] = dot; - R3D_BARRIER(); - dot += ex[tid ^ 1]; - - const float vraw = bf16_to_f32(v[((size_t)tok * H + hv) * kV + row]); - const float u = (vraw - dot) * bt; - - // The outer-product update and the o dot run as separate loops: fused, with the - // third exchange and the o write live, the token loop's o stores stopped landing on - // gfx1102 (a compiler interaction, not reduced to a minimal repro); split, they land. - for (int j = 0; j < kHK; ++j) h[j] += u * kk[j]; - float on = 0.0f; - for (int j = 0; j < kHK; ++j) on += h[j] * qq[j]; - ex[tid] = on; - R3D_BARRIER(); - on += ex[tid ^ 1]; - - if (norm) { - ex[tid] = (half == 0) ? on * on : 0.0f; - R3D_BARRIER(); - const int wave = tid >> 5; - float s = 0.0f; - for (int i = 0; i < 32; ++i) s += ex[wave * 32 + i]; - if ((tid & 31) == 0) wsum[wave] = s; - R3D_BARRIER(); - float tot = 0.0f; - for (int i = 0; i < kTHR / 32; ++i) tot += wsum[i]; - const float sc = __frsqrt_rn(tot * (1.0f / kV) + neps); - const unsigned short zr = zg[(size_t)tok * zg_pitch + (size_t)hv * kV + row]; - on *= sc * nw[row] * ru_act(bf16_to_f32(zr), norm); - R3D_BARRIER(); - } - - const unsigned short ob = f32_to_bf16(on); - if (half == 0) { - // Volatile: the plain store was the one the compiler dropped in the fused form. - volatile unsigned short* ov = o; - ov[((size_t)tok * H + hv) * kV + row] = ob; - } - - const int so = sidx[(size_t)n * sidx_stride + t]; - if (so >= 0) { - float* p = state + (size_t)so * st_slot + (size_t)hv * st_head - + (size_t)row * kK + k0; - for (int j = 0; j < kHK; j += 8) ru_store8<0>(p + j, &h[j]); - } - } -} - -int r3d_gdn_recurrent_update_launch(const void* q, const void* k, const void* v, const void* a, - const void* b, long long ab_stride, const void* A_log, - const void* dt_bias, void* state, long long st_slot, - long long st_head, const void* sidx, long long sidx_stride, - const void* zg, long long zg_pitch, const void* nw, - void* o, const void* cu, int N, int H, int Hg, int norm, - int ab_bf16, float scale, float sp_thr, float neps, - hipStream_t stream) -{ - dim3 grid(N, H), blk(kTHR); - // A plain kernel: norm and ab_bf16 are runtime parameters, not template arguments. - R3D_KLAUNCH(r3d_gdn_recurrent_update_kernel, grid, blk, stream, - (const unsigned short*)q, (const unsigned short*)k, (const unsigned short*)v, - a, b, ab_stride, (const float*)A_log, (const float*)dt_bias, (float*)state, - st_slot, st_head, (const int*)sidx, sidx_stride, (const unsigned short*)zg, - zg_pitch, (const float*)nw, (unsigned short*)o, (const int*)cu, H, Hg, - scale, sp_thr, neps, norm, ab_bf16); - return (int)hipGetLastError(); -} - -} // namespace - -/* ------------------------------------------------------------------ the plugin ABI */ - -enum { RU_Q = 0, RU_K, RU_V, RU_A, RU_B, RU_ALOG, RU_DTB, RU_STATE, RU_SIDX, RU_NACC, RU_CU, - RU_Z, RU_NORMW, RU_O, RU_OQ, RU_OSCALE }; - -extern "C" int r3d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) -{ - if (!a) return R3D_NO(RAD_E_INVAL); - const RadTensor* q = r3d_opt(a, RU_Q); - const RadTensor* k = r3d_opt(a, RU_K); - const RadTensor* v = r3d_opt(a, RU_V); - const RadTensor* ta = r3d_opt(a, RU_A); - const RadTensor* tb = r3d_opt(a, RU_B); - const RadTensor* alog = r3d_opt(a, RU_ALOG); - const RadTensor* dtb = r3d_opt(a, RU_DTB); - const RadTensor* st = r3d_opt(a, RU_STATE); - const RadTensor* sidx = r3d_opt(a, RU_SIDX); - const RadTensor* nacc = r3d_opt(a, RU_NACC); - const RadTensor* cu = r3d_opt(a, RU_CU); - const RadTensor* z = r3d_opt(a, RU_Z); - const RadTensor* nw = r3d_opt(a, RU_NORMW); - const RadTensor* o = r3d_opt(a, RU_O); - // o_q and o_scale are the folded quantiser's outputs; this row does not fold it. - if (!r3d_p(q) || !r3d_p(k) || !r3d_p(v) || !r3d_p(ta) || !r3d_p(tb) || !r3d_p(alog) || - !r3d_p(dtb) || !r3d_wp(st) || !r3d_p(sidx) || !r3d_p(cu) || !r3d_wp(o)) - return R3D_NO(RAD_E_INVAL); - - if (q->rank != 3 || k->rank != 3 || v->rank != 3 || st->rank != 4 || o->rank != 3) - return R3D_NO(RAD_E_SHAPE); - if (sidx->rank < 2) return R3D_NO(RAD_E_SHAPE); - - const long long T = q->shape[0]; - const long long Hg = q->shape[1]; - const long long K = q->shape[2]; - const long long H = v->shape[1]; - const long long V = v->shape[2]; - if (k->shape[0] != T || k->shape[1] != Hg || k->shape[2] != K) return R3D_NO(RAD_E_SHAPE); - if (v->shape[0] != T || o->shape[0] != T || o->shape[1] != H || o->shape[2] != V) - return R3D_NO(RAD_E_SHAPE); - if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE); - if (K != kK || V != kV) return R3D_NO(RAD_E_SHAPE); - - if (!r3d_is_bf16(q) || !r3d_is_bf16(k) || !r3d_is_bf16(v) || !r3d_is_bf16(o)) - return R3D_NO(RAD_E_DTYPE); - if (!r3d_is_f32(alog) || !r3d_is_f32(dtb)) return R3D_NO(RAD_E_DTYPE); - if (!r3d_is_f32(st)) return R3D_NO(RAD_E_DTYPE); // fp32 state cache - if (ta->dtype != RAD_BF16 && ta->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); - if (tb->dtype != ta->dtype) return R3D_NO(RAD_E_DTYPE); - - // state cache [slots, H, V, K]: the per-head and per-slot strides. - if (st->shape[1] != H || st->shape[2] != kV || st->shape[3] != kK) return R3D_NO(RAD_E_SHAPE); - const long long st_head = st->stride[1]; - const long long st_slot = st->stride[0]; - if (st_head != (long long)kV * kK) return R3D_NO(RAD_E_STRIDE); - - // a and b: [T, H] (the ba projection's rows), row pitch in elements. - const long long ab_stride = r3d_row_pitch(ta); - if (ab_stride < 0 || r3d_row_pitch(tb) != ab_stride) return R3D_NO(RAD_E_STRIDE); - - const long long sidx_stride = sidx->stride[sidx->rank - 1] == 1 ? sidx->stride[0] : -1; - if (sidx_stride < 0) return R3D_NO(RAD_E_STRIDE); - - int N = 0; - if (cu->rank != 1 || cu->shape[0] < 2 || !r3d_contig(cu)) return R3D_NO(RAD_E_SHAPE); - N = (int)(cu->shape[0] - 1); - - const float scale = (float)r3d_getf(a, "scale", 1.0 / sqrt((double)kK)); - const float sp_thr = (float)r3d_getf(a, "softplus_thr", 20.0); - const float neps = (float)r3d_getf(a, "eps", 1e-6); - - // The gated RMS norm epilogue: present when both z and norm_w are given. - int norm = 0; - long long zg_pitch = 0; - if (r3d_p(z) && r3d_p(nw)) { - if (z->rank != 3 || z->shape[0] != T || z->shape[1] != H || z->shape[2] != kV) - return R3D_NO(RAD_E_SHAPE); - if (!r3d_is_bf16(z) || !r3d_is_f32(nw) || r3d_numel(nw) != kV) return R3D_NO(RAD_E_DTYPE); - const int act = r3d_act_code(a, "act", nullptr, 0); - if (act != 0 && act != 1) return R3D_NO(RAD_E_INVAL); - norm = (act == 0) ? 2 : 1; // r3d_act_code: 0=silu, 1=sigmoid; kernel: 2=silu, 1=sigmoid - zg_pitch = z->stride[0]; - } - - const int e = r3d_gdn_recurrent_update_launch(r3d_p(q), r3d_p(k), r3d_p(v), r3d_p(ta), r3d_p(tb), - ab_stride, r3d_p(alog), r3d_p(dtb), r3d_wp(st), - st_slot, st_head, r3d_p(sidx), sidx_stride, - r3d_p(z), zg_pitch, r3d_p(nw), r3d_wp(o), r3d_p(cu), - N, (int)H, (int)Hg, norm, (ta->dtype == RAD_BF16), - scale, sp_thr, neps, (hipStream_t)s); - /* The launcher's codes are raw: its own negatives and hipGetLastError's positives. The - * plugin ABI takes RadStatus, so normalise. */ - if (e < 0) return R3D_NO(RAD_E_INVAL); - return e ? R3D_NO(RAD_E_DEVICE) : RAD_OK; -} diff --git a/libr3d/r3d_gemm_mxfp4a8.hip b/libr3d/r3d_gemm_mxfp4a8.hip index 759efd7b..e1f1a02c 100644 --- a/libr3d/r3d_gemm_mxfp4a8.hip +++ b/libr3d/r3d_gemm_mxfp4a8.hip @@ -390,10 +390,13 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__ /* ================================================================== the launchers */ -static int mt_for(int M) +/* The tile's rows: the power of two that holds M, widened while its chunk (2048 / mt codes) does + * not divide K. The extra rows are idle. At 16 rows the chunk is 128, which the row's constraints + * (K a multiple of 128) always divide. */ +static int mt_for(int M, int K) { int mt = 1; - while (mt < M && mt < kMTMax) mt *= 2; + while ((mt < M || K % (2048 / mt)) && mt < kMTMax) mt *= 2; return mt; } @@ -407,7 +410,7 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_sc if (group != kGroup) return -2; if (K % kGroup) return -2; /* the activation's scale group */ if (K % kMX) return -2; /* the weight's 32-block */ - const int mt = mt_for(M); + const int mt = mt_for(M, K); const int chunk = 2048 / mt; if (K % chunk) return -2; if (!a_ld) a_ld = K; @@ -433,6 +436,13 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_sc (const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \ y_ld); \ } while (0) + switch (mt) { + case 1: R3D_MXFP4A8_M16(1); break; + case 2: R3D_MXFP4A8_M16(2); break; + case 4: R3D_MXFP4A8_M16(4); break; + case 8: R3D_MXFP4A8_M16(8); break; + default: R3D_MXFP4A8_M16(16); break; + } #undef R3D_MXFP4A8_M16 return hipGetLastError() == hipSuccess ? 0 : -4; } diff --git a/libr3d/r3d_moe_gather.hip b/libr3d/r3d_moe_gather.hip index a67a965c..ee0a269f 100644 --- a/libr3d/r3d_moe_gather.hip +++ b/libr3d/r3d_moe_gather.hip @@ -12,7 +12,7 @@ * - moe_gather_inv: `slot` is the `inverse` table moe_scatter_inv wrote (read straight). * * An optional shared arm adds `shared[t, c] * act(gate[t])` (two narrows, matching the unfused - * scale_rows pair). `act` is "sigmoid" (the only form we take; "none" is refused, absent = the + * scale_rows pair). `act` is "sigmoid" or "none" (the gate as it is; absent = the * identity). * * The wide-prefill form (a wave per token, 8 cols/lane) is not implemented; this is the decode and @@ -120,9 +120,10 @@ int r3d_rad_moe_gather(const RadArgs* a, RadStream s) if (M <= 0 || n <= 0 || top_k <= 0) return R3D_NO(RAD_E_SHAPE); if (top_k > kGatherSlots) return R3D_NO(RAD_E_SHAPE); // the LDS-cached form only - const uint32_t ye_ld = (uint32_t)(ye->rank >= 2 ? ye->shape[1] : ye->stride[0]); - const uint32_t ew_ld = (uint32_t)(ew->rank >= 2 ? ew->shape[1] : ew->stride[0]); - const uint32_t y_ld = (uint32_t)(y->rank >= 2 ? y->shape[1] : y->stride[0]); + // Row pitches are the tensors' own strides: a view's rows can be wider than its shape. + const uint32_t ye_ld = (uint32_t)ye->stride[0]; + const uint32_t ew_ld = (uint32_t)ew->stride[0]; + const uint32_t y_ld = (uint32_t)y->stride[0]; const uint32_t T = (uint32_t)r3d_numel(sorted); if (T < M * top_k) return R3D_NO(RAD_E_SHAPE); @@ -131,12 +132,13 @@ int r3d_rad_moe_gather(const RadArgs* a, RadStream s) const uint16_t* shp = sh ? (const uint16_t*)r3d_p(sh) : nullptr; const uint16_t* sgp = sg ? (const uint16_t*)r3d_p(sg) : nullptr; if (sh && !sg) return R3D_NO(RAD_E_INVAL); - const uint32_t sh_ld = sh ? (uint32_t)(sh->rank >= 2 ? sh->shape[1] : sh->stride[0]) : 0; - const uint32_t sg_ld = sg ? (uint32_t)(sg->rank >= 1 ? sg->shape[0] : sg->stride[0]) : 1; + // The gate is one value a token ([M] or [M, 1]): its pitch is stride[0], not a shape. + const uint32_t sh_ld = sh ? (uint32_t)sh->stride[0] : 0; + const uint32_t sg_ld = sg ? (uint32_t)sg->stride[0] : 1; int sig = 0; if (const char* act = r3d_gets(a, "act")) { if (std::string(act) == "sigmoid") sig = 1; - else if (std::string(act) == "none") return R3D_NO(RAD_E_INVAL); + else if (std::string(act) != "none") return R3D_NO(RAD_E_INVAL); } const bool f32w = (ew->dtype == RAD_F32); @@ -169,9 +171,10 @@ int r3d_rad_moe_gather_inv(const RadArgs* a, RadStream s) if (M <= 0 || n <= 0 || top_k <= 0) return R3D_NO(RAD_E_SHAPE); if (top_k > kGatherSlots) return R3D_NO(RAD_E_SHAPE); // the LDS-cached form only - const uint32_t ye_ld = (uint32_t)(ye->rank >= 2 ? ye->shape[1] : ye->stride[0]); - const uint32_t ew_ld = (uint32_t)(ew->rank >= 2 ? ew->shape[1] : ew->stride[0]); - const uint32_t y_ld = (uint32_t)(y->rank >= 2 ? y->shape[1] : y->stride[0]); + // Row pitches are the tensors' own strides: a view's rows can be wider than its shape. + const uint32_t ye_ld = (uint32_t)ye->stride[0]; + const uint32_t ew_ld = (uint32_t)ew->stride[0]; + const uint32_t y_ld = (uint32_t)y->stride[0]; const uint32_t T = (uint32_t)r3d_numel(inv); if (T < M * top_k) return R3D_NO(RAD_E_SHAPE); @@ -179,12 +182,13 @@ int r3d_rad_moe_gather_inv(const RadArgs* a, RadStream s) const uint16_t* shp = sh ? (const uint16_t*)r3d_p(sh) : nullptr; const uint16_t* sgp = sg ? (const uint16_t*)r3d_p(sg) : nullptr; if (sh && !sg) return R3D_NO(RAD_E_INVAL); - const uint32_t sh_ld = sh ? (uint32_t)(sh->rank >= 2 ? sh->shape[1] : sh->stride[0]) : 0; - const uint32_t sg_ld = sg ? (uint32_t)(sg->rank >= 1 ? sg->shape[0] : sg->stride[0]) : 1; + // The gate is one value a token ([M] or [M, 1]): its pitch is stride[0], not a shape. + const uint32_t sh_ld = sh ? (uint32_t)sh->stride[0] : 0; + const uint32_t sg_ld = sg ? (uint32_t)sg->stride[0] : 1; int sig = 0; if (const char* act = r3d_gets(a, "act")) { if (std::string(act) == "sigmoid") sig = 1; - else if (std::string(act) == "none") return R3D_NO(RAD_E_INVAL); + else if (std::string(act) != "none") return R3D_NO(RAD_E_INVAL); } const bool f32w = (ew->dtype == RAD_F32); diff --git a/libr3d/r3d_moe_gemm_bf16.hip b/libr3d/r3d_moe_gemm_bf16.hip index 8df7fefd..cadbfb9d 100644 --- a/libr3d/r3d_moe_gemm_bf16.hip +++ b/libr3d/r3d_moe_gemm_bf16.hip @@ -3,8 +3,9 @@ * y[i, n] = sum_k a[tok(i), k] * w_e[n, k], e = the expert of sorted row i * * One block per 16 expert-sorted rows, walking the runs (contiguous rows per expert) in its tile. - * bf16 activation, bf16 weight as the checkpoint stores it ([n_expert, N, K] row-major, no layout - * hook, every expert in class 0), f32 accumulate over the whole of K, bf16 out. The 16-row tile is + * bf16 activation, bf16 weight as the checkpoint stores it (each expert an [N, K] row-major entry + * of one weight table, r3d_moe_tab.h; no layout hook, every expert in class 0), f32 accumulate over + * the whole of K, bf16 out. The 16-row tile is * the same run-walk / gather structure as moe_gemm_q, minus the E4M3 decode and the scale fold: * the operands are bf16, so they stage to LDS and load straight into the bf16 wave-matrix * fragments (v_wmma_f32_16x16x16_bf16, f32 accumulate). @@ -18,6 +19,7 @@ #include "r3d_common.h" #include "r3d_codecs.h" #include "r3d_launch.h" +#include "r3d_moe_tab.h" namespace { @@ -87,11 +89,11 @@ __device__ __forceinline__ float r3d_moe_acc_read(const typename R3dMoeAcc: __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) \ __attribute__((amdgpu_num_vgpr(MBE_VGPR))) void MBE_KNAME( \ const uint16_t* __restrict__ a, \ - const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, \ - const uint16_t* __restrict__ w, \ - uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int w_ld, int y_ld, \ - int n_expert, int top_k) \ + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, R3dTab tw, \ + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int y_ld, \ + int n_expert, int top_k, int a_sorted) \ { \ + const int w_ld = tw.ld; /* elements between an expert's rows */ \ constexpr int kMBlock = MBE_MR; /* a block is MBE_MR rows x 128 cols */ \ constexpr int kRB = MBE_MR / 16; /* row-blocks a wave accumulates */ \ constexpr int kStageA = MBE_MR * kDW / kThreads; /* dwords a thread stages of the activation */ \ @@ -114,7 +116,7 @@ __attribute__((amdgpu_num_vgpr(MBE_VGPR))) void MBE_KNAME( if (tid < kMBlock) { \ const uint32_t i = r0 + tid; \ const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; \ - s_tok[tid] = (f < 0) ? -1 : (f / top_k); \ + s_tok[tid] = (f < 0) ? -1 : (a_sorted ? (int32_t)i : f / top_k); \ } \ /* The runs in [r0, r1): each a contiguous set of rows for one expert. The block walks them. */ \ if (tid == 0) { \ @@ -143,7 +145,7 @@ __attribute__((amdgpu_num_vgpr(MBE_VGPR))) void MBE_KNAME( for (int rb = 0; rb < kRB; ++rb) \ acc[rb] = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; \ if (e >= 0) { \ - const uint16_t* wbase = w + (size_t)e * (size_t)N * w_ld; \ + const uint16_t* wbase = (const uint16_t*)r3d_tab_at(tw, e); \ \ const int ntile = (K + kKT - 1) / kKT; \ /* Prologue: stage tile 0 into buffer 0. */ \ @@ -289,21 +291,19 @@ extern "C" { int r3d_rad_moe_gemm_bf16(const RadArgs* a, RadStream s) { - if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL); - const RadTensor* at = r3d_opt(a, 0), *wt = r3d_opt(a, 1), *st = r3d_opt(a, 2), - *ot = r3d_opt(a, 3), *yt = r3d_opt(a, 4); - if (!r3d_p(at) || !r3d_p(wt) || !r3d_p(st) || !r3d_p(ot) || !r3d_wp(yt)) - return R3D_NO(RAD_E_INVAL); - long long M = 0, K = 0; - if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); - const long long T = (st->rank >= 1) ? st->shape[0] : 0; - const long long N = (wt->rank >= 3) ? wt->shape[1] : 0; - if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || (K & 63)) return R3D_NO(RAD_E_SHAPE); // N tail clamps - const int n_expert = (int)r3d_geti_or(a, "n_expert", 1); - const int top_k = (int)r3d_geti_or(a, "top_k", 1); - const int a_ld = (int)at->stride[0]; - const int w_ld = (int)wt->shape[2]; - const int y_ld = (int)yt->stride[0]; + R3dMoeCall mc; + int rc = r3d_moe_call(a, false, &mc); + if (rc != RAD_OK) return rc; + if (mc.a->dtype != RAD_BF16 || mc.y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + const long long T = mc.T, N = mc.N, K = mc.K; + if (K & 63) return R3D_NO(RAD_E_SHAPE); // N tail clamps + R3dTab tw; + rc = r3d_tab_of(mc.w, RAD_BF16, 16, mc.n_expert, N, K, &tw); + if (rc != RAD_OK) return rc; + const int n_expert = (int)mc.n_expert, top_k = (int)mc.top_k, a_sorted = mc.a_sorted; + const int a_ld = (int)mc.a->stride[0]; + const int y_ld = (int)mc.y->stride[0]; + const RadTensor *at = mc.a, *st = mc.sorted, *ot = mc.off, *yt = mc.y; R3dMoeCfg c; r3d_cfg_moe(a, &c); // the tune's row count (16, 32 or 64), 64 untuned #define R3D_LM(MR, KERN) \ @@ -311,9 +311,8 @@ int r3d_rad_moe_gemm_bf16(const RadArgs* a, RadStream s) dim3 grid((unsigned)((N + kNBlock - 1) / kNBlock), (unsigned)((T + MR - 1) / MR)), \ blk(kThreads); \ KERN<<>>( \ - (const uint16_t*)r3d_p(at), (const int32_t*)r3d_p(st), (const int32_t*)r3d_p(ot), \ - (const uint16_t*)r3d_p(wt), (uint16_t*)r3d_wp(yt), (int)T, (int)N, (int)K, a_ld, w_ld, \ - y_ld, n_expert, top_k); \ + (const uint16_t*)r3d_p(at), (const int32_t*)r3d_p(st), (const int32_t*)r3d_p(ot), tw, \ + (uint16_t*)r3d_wp(yt), (int)T, (int)N, (int)K, a_ld, y_ld, n_expert, top_k, a_sorted); \ } while (0) if (c.mrows <= 16) { if (c.acc) R3D_LM(16, moe_bf16_kernel16_a1); diff --git a/libr3d/r3d_moe_gemm_fp8_f32scale.hip b/libr3d/r3d_moe_gemm_fp8_f32scale.hip index 5f197f5a..81e93ebc 100644 --- a/libr3d/r3d_moe_gemm_fp8_f32scale.hip +++ b/libr3d/r3d_moe_gemm_fp8_f32scale.hip @@ -1,13 +1,13 @@ /* r3d_moe_gemm_fp8_f32scale.hip -- moe_gemm_q (the wave-matrix form): the grouped GEMM with E4M3 * experts and exact F32 block scales. * - * y[i, n] = sum_g as[tok(i), g] * wsb[e, n/grid_rows][g] * sum_{k in g} a[tok(i), k] * w_e[n, k] + * y[i, n] = sum_g as[tok(i), g] * ws_e[n/128][g] * sum_{k in g} a[tok(i), k] * w_e[n, k] * - * The moe_gemm_q contract: a and the weight planes are E4M3, one F32 scale per (row, 128 of K) - * for the activation and one per (plane expert, n/grid_rows, 128 of K) for the weight; the even - * experts live in w / w_scale and the odd in w_odd / w_odd_scale, at index e/2; y is f32 in sorted - * order. E4M3 activation and E4M3 weight (the checkpoint stores the plane as [n_expert/2, N, K] - * row-major, one byte a code). f32 accumulate over the whole of K. + * The moe_gemm_q contract at fp8a8f32: a and the weight entries are E4M3, one F32 scale per (row, + * 128 of K) for the activation and one per 128x128 tile for the weight; expert e is entry e/2 of + * class e%2's weight tables (r3d_moe_tab.h: a pointer per expert, or a stacked plane), each entry + * the checkpoint's own [N, K] row-major codes; y is bf16 in sorted order. f32 accumulate over the + * whole of K. * * gfx11 has no native FP8 wave-matrix, so the codes widen to f16 (exact: every E4M3 grid point is * an f16 grid point) and the multiply runs on the 16x16x16 f16 tile. K is walked in 128-deep @@ -23,6 +23,7 @@ #include "r3d_codecs.h" #include "r3d_fp8_dequant.h" #include "r3d_launch.h" +#include "r3d_moe_tab.h" namespace { @@ -86,11 +87,9 @@ __device__ __forceinline__ float r3d_moe_acc_f16_read(const typename R3dMoeAccF1 __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) \ __attribute__((amdgpu_num_vgpr(MFS_VGPR))) void MFS_KNAME( \ const uint8_t* __restrict__ a, const float* __restrict__ as, \ - const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, \ - const uint8_t* __restrict__ w, const float* __restrict__ ws, \ - const uint8_t* __restrict__ w_odd, const float* __restrict__ w_ws, \ - float* __restrict__ y, int T, int N, int K, int a_ld, int w_ld, int y_ld, \ - int n_expert, int top_k, int grid_rows) \ + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, R3dMoeTabs tw, \ + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int as_ld, int y_ld, \ + int n_expert, int top_k, int a_sorted) \ { \ constexpr int kMBlock = 16; \ constexpr int kRB = 1; \ @@ -116,7 +115,7 @@ __attribute__((amdgpu_num_vgpr(MFS_VGPR))) void MFS_KNAME( if (tid < kMBlock) { \ const uint32_t i = r0 + tid; \ const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; \ - s_tok[tid] = (f < 0) ? -1 : (f / top_k); \ + s_tok[tid] = (f < 0) ? -1 : (a_sorted ? (int32_t)i : f / top_k); \ } \ if (tid == 0) { \ int nruns = 0, i = (int)r0; \ @@ -143,12 +142,12 @@ __attribute__((amdgpu_num_vgpr(MFS_VGPR))) void MFS_KNAME( _Pragma("unroll") \ for (int g = 0; g < 8; ++g) acc[rb][g] = 0.f; \ if (e >= 0) { \ - /* Expert e's plane: even e in w / ws, odd e in w_odd / w_ws, at index e/2. */ \ - const int e2 = e >> 1; \ - const uint8_t* wbase = (e & 1) ? w_odd + (size_t)e2 * (size_t)N * w_ld \ - : w + (size_t)e2 * (size_t)N * w_ld; \ - const float* wsb = (e & 1) ? w_ws + (size_t)e2 * (size_t)(N / grid_rows) * ((K + 127) / 128) \ - : ws + (size_t)e2 * (size_t)(N / grid_rows) * ((K + 127) / 128); \ + /* Expert e's entry: e/2 of class e%2's tables. */ \ + const int cls = e & 1, e2 = e >> 1; \ + const uint8_t* wbase = r3d_tab_at(tw.w[cls], e2); \ + const int w_ld = tw.w[cls].ld; \ + const float* wsb = (const float*)r3d_tab_at(tw.s[cls], e2); \ + const int ws_ld = tw.s[cls].ld; \ \ \ const int ntile = (K + kKT - 1) / kKT; \ @@ -169,8 +168,8 @@ __attribute__((amdgpu_num_vgpr(MFS_VGPR))) void MFS_KNAME( s_w[(size_t)col * kP16 + k] = s_tbl[wbase[(size_t)nn * w_ld + kt + k]]; \ } \ group_barrier(); \ - /* The activation scale for this tile (per row) and the weight scale (per grid_rows cols). */ \ - const float wscale = wsb[(size_t)(n_real / grid_rows) * ((K + 127) / 128) + t]; \ + /* The activation scale for this tile (per row) and the weight scale (per 128x128 tile). */ \ + const float wscale = wsb[(size_t)(n_real / 128) * ws_ld + t]; \ /* Eight 16-wide f16 WMMA steps; f16 values read directly from LDS. The fragment */ \ /* elements are f16 BIT PATTERNS, so the LDS halfs must be bit-cast into the */ \ /* _Float16 vector: any assignment from a uint16_t source into a _Float16 (a plain */ \ @@ -204,21 +203,21 @@ __attribute__((amdgpu_num_vgpr(MFS_VGPR))) void MFS_KNAME( const int row = rb * 16 + g * 2 + (int)(lane >> 4); \ const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) \ ? s_tok[row] : s_tok[rs - (int)r0]; \ - const float ascale = (src < 0) ? 0.f : as[(size_t)src * ((K + 127) / 128) + t] * wscale; \ + const float ascale = (src < 0) ? 0.f : as[(size_t)src * as_ld + t] * wscale; \ acc[rb][g] += r3d_moe_acc_f16_read(blk, g) * ascale; \ } \ } \ group_barrier(); \ } \ } \ - /* Store only the run's rows (f32: the moe_gemm_q contract's output). */ \ + /* Store only the run's rows and the real columns, as bf16. */ \ _Pragma("unroll") \ for (int rb = 0; rb < kRB; ++rb) \ _Pragma("unroll") \ for (int g = 0; g < 8; ++g) { \ const int m = (int)r0 + rb * 16 + g * 2 + (int)(lane >> 4); \ - if (m < re && m >= rs) \ - y[(size_t)m * y_ld + nc] = acc[rb][g]; \ + if (m < re && m >= rs && nc < (uint32_t)N) \ + y[(size_t)m * y_ld + nc] = f32_to_bf16(acc[rb][g]); \ } \ } \ } @@ -246,93 +245,42 @@ R3D_MFS_BODY } // namespace -static int r3d_moe_gemm_fp8_f32scale_v(long a, long as, long sorted, long off, long w, long ws, - long w_odd, long w_ws, long y, - int T, int N, int K, int a_ld, int w_ld, int y_ld, - int n_expert, int top_k, int grid_rows, int vgpr, int acc, - long stream) -{ - if (!a || !as || !sorted || !off || !w || !ws || !w_odd || !w_ws || !y) return -1; - if (T < 1 || N < 1 || K < 1 || grid_rows < 1) return -2; - if (!a_ld) a_ld = K; - if (!w_ld) w_ld = K; - if (!y_ld) y_ld = N; - if (K % kKT) return -2; - const int ntiles = (N + kNBlock - 1) / kNBlock; - const int mrowblk = (T + 16 - 1) / 16; - const dim3 grid(ntiles, mrowblk), block(kThreads); - if (vgpr == 128) { - if (acc) - R3D_KLAUNCH(moe_fp8_f32scale_kernel16_c128_a1, grid, block, (hipStream_t)stream, - (const uint8_t*)a, (const float*)as, (const int32_t*)sorted, - (const int32_t*)off, (const uint8_t*)w, (const float*)ws, - (const uint8_t*)w_odd, (const float*)w_ws, (float*)y, - T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows); - else - R3D_KLAUNCH(moe_fp8_f32scale_kernel16_c128, grid, block, (hipStream_t)stream, - (const uint8_t*)a, (const float*)as, (const int32_t*)sorted, - (const int32_t*)off, (const uint8_t*)w, (const float*)ws, - (const uint8_t*)w_odd, (const float*)w_ws, (float*)y, - T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows); - } - else { - if (acc) - R3D_KLAUNCH(moe_fp8_f32scale_kernel16_a1, grid, block, (hipStream_t)stream, - (const uint8_t*)a, (const float*)as, (const int32_t*)sorted, - (const int32_t*)off, (const uint8_t*)w, (const float*)ws, - (const uint8_t*)w_odd, (const float*)w_ws, (float*)y, - T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows); - else - R3D_KLAUNCH(moe_fp8_f32scale_kernel16, grid, block, (hipStream_t)stream, - (const uint8_t*)a, (const float*)as, (const int32_t*)sorted, - (const int32_t*)off, (const uint8_t*)w, (const float*)ws, - (const uint8_t*)w_odd, (const float*)w_ws, (float*)y, - T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows); - } - return hipGetLastError() == hipSuccess ? 0 : -4; -} - -/* The direct launcher: the tune's default budget (128, the 8-wave cap). */ -extern "C" int r3d_moe_gemm_fp8_f32scale(long a, long as, long sorted, long off, long w, long ws, - long w_odd, long w_ws, long y, - int T, int N, int K, int a_ld, int w_ld, int y_ld, - int n_expert, int top_k, int grid_rows, long stream) -{ - return r3d_moe_gemm_fp8_f32scale_v(a, as, sorted, off, w, ws, w_odd, w_ws, y, T, N, K, a_ld, - w_ld, y_ld, n_expert, top_k, grid_rows, 128, 0, stream); -} - -/* The RadArgs dispatch: the row's entry. The tensors are a, a_scale, sorted_tok, expert_offset, - * w, w_scale, w_odd, w_odd_scale, y (the moe_gemm_q contract: even experts in w / w_scale, odd in - * w_odd / w_odd_scale, at index e/2; y is f32). The params are n_expert, top_k, grid_rows. */ +/* The RadArgs dispatch, moe_gemm_q's arm 2 (r3d_moe_gemm_q.hip): the contract's operands + * (r3d_moe_tab.h) at fp8a8f32, the tune's register budget and accumulator. */ extern "C" int r3d_moe_gemm_fp8_f32scale_run(const RadArgs* a, RadStream s, int vgpr, int acc) { - if (!a || a->n_t < 9) return R3D_NO(RAD_E_INVAL); - const RadTensor* at = &a->t[0], *ast = &a->t[1], *st = &a->t[2], *ot = &a->t[3]; - const RadTensor* wt = &a->t[4], *wst = &a->t[5], *wot = &a->t[6], *wost = &a->t[7]; - const RadTensor* yt = &a->t[8]; - if (!r3d_p(at) || !r3d_p(ast) || !r3d_p(st) || !r3d_p(ot) || - !r3d_p(wt) || !r3d_p(wst) || !r3d_p(wot) || !r3d_p(wost) || !r3d_wp(yt)) - return R3D_NO(RAD_E_INVAL); - long long M = 0, K = 0; - if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); - const long long T = (st->rank >= 1) ? st->shape[0] : 0; - const long long N = (wt->rank >= 3) ? wt->shape[1] : 0; // the plane is [n_expert/2, N, K] - const int n_expert = (int)r3d_geti_or(a, "n_expert", 1); - const int top_k = (int)r3d_geti_or(a, "top_k", 1); - const int grid_rows = (int)r3d_geti_or(a, "grid_rows", 1); // 1 (per col) or 128 (per 128) - if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || K % 128 || n_expert <= 0 || top_k <= 0) - return R3D_NO(RAD_E_SHAPE); - const int a_ld = (int)at->stride[0]; - const int w_ld = (int)wt->shape[2]; - const int y_ld = (int)yt->stride[0]; - return r3d_moe_gemm_fp8_f32scale_v((long)(uintptr_t)r3d_p(at), (long)(uintptr_t)r3d_p(ast), - (long)(uintptr_t)r3d_p(st), (long)(uintptr_t)r3d_p(ot), - (long)(uintptr_t)r3d_p(wt), (long)(uintptr_t)r3d_p(wst), - (long)(uintptr_t)r3d_p(wot), (long)(uintptr_t)r3d_p(wost), - (long)(uintptr_t)r3d_wp(yt), (int)T, (int)N, (int)K, a_ld, - w_ld, y_ld, n_expert, top_k, grid_rows, vgpr, acc, - (long)(uintptr_t)s); + R3dMoeCall c; + int rc = r3d_moe_call(a, true, &c); + if (rc != RAD_OK) return rc; + if (!c.a_scale) return R3D_NO(RAD_E_INVAL); + if (c.a->dtype != RAD_F8E4M3 || c.a_scale->dtype != RAD_F32 || c.y->dtype != RAD_BF16) + return R3D_NO(RAD_E_DTYPE); + if (c.K % kKT) return R3D_NO(RAD_E_SHAPE); + R3dMoeTabs tw; + rc = r3d_moe_q_tabs(c, RAD_F8E4M3, 8, RAD_F32, 32, (c.N + 127) / 128, c.K / 128, &tw); + if (rc != RAD_OK) return rc; + const int T = (int)c.T, N = (int)c.N, K = (int)c.K; + const int a_ld = (int)c.a->stride[0], as_ld = (int)c.a_scale->stride[0]; + const int y_ld = (int)c.y->stride[0]; + const uint8_t* pa = (const uint8_t*)r3d_p(c.a); + const float* pas = (const float*)r3d_p(c.a_scale); + const int32_t* ps = (const int32_t*)r3d_p(c.sorted); + const int32_t* po = (const int32_t*)r3d_p(c.off); + uint16_t* py = (uint16_t*)r3d_wp(c.y); + const dim3 grid((N + kNBlock - 1) / kNBlock, (T + 16 - 1) / 16), block(kThreads); +#define R3D_MFS_LAUNCH(KERN) \ + R3D_KLAUNCH(KERN, grid, block, (hipStream_t)s, pa, pas, ps, po, tw, py, T, N, K, a_ld, \ + as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted) + if (vgpr == 128) { + if (acc) R3D_MFS_LAUNCH(moe_fp8_f32scale_kernel16_c128_a1); + else R3D_MFS_LAUNCH(moe_fp8_f32scale_kernel16_c128); + } + else { + if (acc) R3D_MFS_LAUNCH(moe_fp8_f32scale_kernel16_a1); + else R3D_MFS_LAUNCH(moe_fp8_f32scale_kernel16); + } +#undef R3D_MFS_LAUNCH + return (int)hipGetLastError(); } extern "C" int r3d_rad_moe_gemm_fp8_f32scale(const RadArgs* a, RadStream s) diff --git a/libr3d/r3d_moe_gemm_mxfp4a8.hip b/libr3d/r3d_moe_gemm_mxfp4a8.hip index 7ed37c82..3ee7f60c 100644 --- a/libr3d/r3d_moe_gemm_mxfp4a8.hip +++ b/libr3d/r3d_moe_gemm_mxfp4a8.hip @@ -9,8 +9,9 @@ * wave-matrix (f32 accumulate). Each 32-wide E8M0 scale folds into the f32 accumulator per group. * * One block per 16 expert-sorted rows, walking the runs (contiguous rows per expert) in its tile, - * the same run-walk / gather structure as moe_gemm_q. The even experts are `w` / `w_scale`, the - * odd `w_odd` / `w_odd_scale`, at index e/2. K is a multiple of 128; N a multiple of 16. + * the same run-walk / gather structure as moe_gemm_q. Expert e is entry e/2 of the even (`w` / + * `w_scale`) or odd (`w_odd` / `w_odd_scale`) weight tables (r3d_moe_tab.h). K is a multiple of + * 128; the N tail clamps. */ #include @@ -20,6 +21,7 @@ #include "r3d_codecs.h" #include "r3d_launch.h" #include "r3d_fp8_dequant.h" +#include "r3d_moe_tab.h" namespace { @@ -55,11 +57,9 @@ __device__ __forceinline__ _Float16 h16(uint32_t w) { return __builtin_bit_cast( __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_mx_kernel( const uint8_t* __restrict__ a, const float* __restrict__ a_scale, - const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, - const uint8_t* __restrict__ w, const uint8_t* __restrict__ w_scale, - const uint8_t* __restrict__ w_odd, const uint8_t* __restrict__ w_odd_scale, - uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int w_ld_b, int y_ld, - int n_expert, int top_k, int grid_rows) + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, R3dMoeTabs tw, + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int as_ld, int y_ld, + int n_expert, int top_k, int a_sorted) { __shared__ __align__(16) uint32_t s_a[16 * kAPitch]; __shared__ __align__(16) uint32_t s_w[kNBlock * kWPitch]; @@ -79,11 +79,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_mx_kernel( const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock; const uint32_t r1 = (r0 + 16 < (uint32_t)T) ? r0 + 16 : (uint32_t)T; - // The block's rows' source tokens (the gather). -1 marks a dropped slot. + // The block's rows' source rows of `a` (the gather, or the row itself under a_order + // "sorted"). -1 marks a dropped slot. if (tid < 16) { const uint32_t i = r0 + tid; const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; - s_tok[tid] = (f < 0) ? -1 : (f / top_k); + s_tok[tid] = (f < 0) ? -1 : (a_sorted ? (int32_t)i : f / top_k); } // The runs in [r0, r1): each a contiguous set of rows for one expert. The block walks them. if (tid == 0) { @@ -109,11 +110,13 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_mx_kernel( const int rs = s_rs[run], re = s_re[run], e = s_e[run]; v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; if (e >= 0) { - const int e2 = e >> 1; - const uint8_t* wbase = (e & 1) ? w_odd + (size_t)e2 * (size_t)N * w_ld_b - : w + (size_t)e2 * (size_t)N * w_ld_b; - const uint8_t* wsb = (e & 1) ? w_odd_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / 32) - : w_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / 32); + // Expert e is entry e/2 of class e%2's tables: E2M1 codes two a byte, one E8M0 exponent + // per (row, 32 of K). + const int cls = e & 1, e2 = e >> 1; + const uint8_t* wbase = r3d_tab_at(tw.w[cls], e2); + const int w_ld_b = tw.w[cls].ld / 2; + const uint8_t* wsb = r3d_tab_at(tw.s[cls], e2); + const int ws_ld = tw.s[cls].ld; for (int b = 0; b < K / kGroup; ++b) { const int kt = b * kGroup; @@ -138,7 +141,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_mx_kernel( const uint32_t* ap = s_a + (size_t)r * kAPitch; const uint32_t* wp = s_w + (size_t)(wv * 16 + r) * kWPitch; // this wave's 16 cols // The weight scale for this lane's column, per 32-of-K group. - const int wn = (int)(n_real / grid_rows); + const int wn = n_real; #pragma unroll for (int g32 = 0; g32 < 4; ++g32) { v8float blk = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; @@ -163,13 +166,13 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_mx_kernel( } group_barrier(); // Fold the g32-group's scales: the weight E8M0 (per 32) and the activation f32 (per 128). - const float sw = e8m0_to_f32((uint32_t)wsb[(size_t)wn * (K / 32) + b * 4 + g32]); + const float sw = e8m0_to_f32((uint32_t)wsb[(size_t)wn * ws_ld + b * 4 + g32]); #pragma unroll for (int g = 0; g < 8; ++g) { const int row = (int)(g * 2 + (lane >> 4)); const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] : s_tok[rs - (int)r0]; - const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * (K / kGroup) + b]; + const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * as_ld + b]; acc[g] += blk[g] * sa * sw; } } @@ -193,31 +196,25 @@ extern "C" { int r3d_rad_moe_gemm_mxfp4a8(const RadArgs* a, RadStream s) { - if (!a || a->n_t < 9) return R3D_NO(RAD_E_INVAL); - const RadTensor* at = r3d_opt(a, 0), *asc = r3d_opt(a, 1), *st = r3d_opt(a, 2), - *ot = r3d_opt(a, 3), *wt = r3d_opt(a, 4), *wsc = r3d_opt(a, 5), - *wot = r3d_opt(a, 6), *wosc = r3d_opt(a, 7), *yt = r3d_opt(a, 8); - if (!r3d_p(at) || !r3d_p(asc) || !r3d_p(st) || !r3d_p(ot) || !r3d_p(wt) || !r3d_p(wsc) || - !r3d_wp(yt)) - return R3D_NO(RAD_E_INVAL); - long long M = 0, K = 0; - if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); - const long long T = (st->rank >= 1) ? st->shape[0] : 0; - const long long N = (wt->rank >= 3) ? wt->shape[1] : 0; - if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || K % 128) return R3D_NO(RAD_E_SHAPE); // N tail clamps - const int n_expert = (int)r3d_geti_or(a, "n_expert", 1); - const int top_k = (int)r3d_geti_or(a, "top_k", 1); - const int grid_rows = (int)r3d_geti_or(a, "grid_rows", 128); - const int a_ld = (int)at->stride[0]; - const int w_ld_b = (int)wt->shape[2]; // the weight's K in bytes (K/2 for E2M1) - const int y_ld = (int)yt->stride[0]; + R3dMoeCall c; + int rc = r3d_moe_call(a, true, &c); + if (rc != RAD_OK) return rc; + if (!c.a_scale) return R3D_NO(RAD_E_INVAL); + if (c.a->dtype != RAD_F8E4M3 || c.a_scale->dtype != RAD_F32 || c.y->dtype != RAD_BF16) + return R3D_NO(RAD_E_DTYPE); + if (c.K % kGroup) return R3D_NO(RAD_E_SHAPE); // the N tail clamps + R3dMoeTabs tw; + rc = r3d_moe_q_tabs(c, RAD_FP4E2M1, 4, RAD_E8M0, 8, c.N, c.K / 32, &tw); + if (rc != RAD_OK) return rc; + if ((tw.w[0].ld | tw.w[1].ld) & 1) return R3D_NO(RAD_E_STRIDE); // whole bytes a row + const int a_ld = (int)c.a->stride[0], as_ld = (int)c.a_scale->stride[0]; + const int y_ld = (int)c.y->stride[0]; - dim3 grid((unsigned)((N + kNBlock - 1) / kNBlock), (unsigned)((T + 15) / 16)), blk(kThreads); + dim3 grid((unsigned)((c.N + kNBlock - 1) / kNBlock), (unsigned)((c.T + 15) / 16)), blk(kThreads); moe_mx_kernel<<>>( - (const uint8_t*)r3d_p(at), (const float*)r3d_p(asc), (const int32_t*)r3d_p(st), - (const int32_t*)r3d_p(ot), (const uint8_t*)r3d_p(wt), (const uint8_t*)r3d_p(wsc), - (const uint8_t*)r3d_p(wot), (const uint8_t*)r3d_p(wosc), (uint16_t*)r3d_wp(yt), - (int)T, (int)N, (int)K, a_ld, w_ld_b, y_ld, n_expert, top_k, grid_rows); + (const uint8_t*)r3d_p(c.a), (const float*)r3d_p(c.a_scale), (const int32_t*)r3d_p(c.sorted), + (const int32_t*)r3d_p(c.off), tw, (uint16_t*)r3d_wp(c.y), (int)c.T, (int)c.N, (int)c.K, + a_ld, as_ld, y_ld, (int)c.n_expert, (int)c.top_k, c.a_sorted); return (int)hipGetLastError(); } diff --git a/libr3d/r3d_moe_gemm_q.hip b/libr3d/r3d_moe_gemm_q.hip index f34bf1f9..dd923647 100644 --- a/libr3d/r3d_moe_gemm_q.hip +++ b/libr3d/r3d_moe_gemm_q.hip @@ -15,9 +15,9 @@ * run structure (the block walks the runs in its 16 rows, so a block spanning several experts * is correct). * - * * Phase 3: the even/odd expert split (expert e's weight is in `w` for even e, `w_odd` for odd - * e, at index e/2) and the dtype-selected scale grid (`grid_rows` = 1 for w4a8's per-row scale, - * 128 for fp8a8's per-128x128 tile). + * * Phase 3: the even/odd expert split (expert e's weight is entry e/2 of `w` for even e and of + * `w_odd` for odd e, each a weight table: r3d_moe_tab.h) and fp8a8f32's scale grid, one f32 + * per 128x128 tile of the weight. * * Verified against a CPU reference for runs of 1, 2, 4 and 16 rows, the even/odd split, and both * scale grids (maxrel ~1e-4, the f16 rounding floor). A row: `moe_gemm_q_e4m3` in r3d_rows.cpp, a @@ -29,7 +29,9 @@ #include "r3d_args.h" #include "r3d_common.h" #include "r3d_launch.h" +#include "r3d_codecs.h" #include "r3d_fp8_dequant.h" +#include "r3d_moe_tab.h" namespace { @@ -45,11 +47,9 @@ __device__ __forceinline__ _Float16 h16(uint32_t w) { return __builtin_bit_cast( template __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_q_kernel( const uint8_t* __restrict__ a, const float* __restrict__ a_scale, - const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, - const uint8_t* __restrict__ w, const float* __restrict__ w_scale, - const uint8_t* __restrict__ w_odd, const float* __restrict__ w_odd_scale, - float* __restrict__ y, int T, int N, int K, int a_ld, int w_ld_b, int y_ld, - int n_expert, int top_k, int grid_rows) + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, R3dMoeTabs tw, + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int as_ld, int y_ld, + int n_expert, int top_k, int a_sorted) { __shared__ __align__(16) uint32_t s_a[16 * kPitch]; __shared__ __align__(16) uint32_t s_w[kNBlock * kPitch]; @@ -69,11 +69,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_q_kernel( const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock; const uint32_t r1 = (r0 + 16 < (uint32_t)T) ? r0 + 16 : (uint32_t)T; - // The block's rows' source tokens (the gather). -1 marks a dropped slot. + // The block's rows' source rows of `a` (the gather, or the row itself under a_order + // "sorted"). -1 marks a dropped slot. if (tid < 16) { const uint32_t i = r0 + tid; const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; - s_tok[tid] = (f < 0) ? -1 : (f / top_k); + s_tok[tid] = (f < 0) ? -1 : (a_sorted ? (int32_t)i : f / top_k); } // The runs in [r0, r1): each a contiguous set of rows for one expert. The block walks them. if (tid == 0) { @@ -95,16 +96,16 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_q_kernel( // One GEMM per run: the run's rows read the gathered activation and expert e's weight. Rows the // run does not own are padding (reading the run's first row) and their output is dropped. Expert - // e's weight is in `w` (even e) or `w_odd` (odd e) at index e/2. + // e's weight is entry e/2 of class e%2's tables. for (int run = 0; run < nruns; ++run) { const int rs = s_rs[run], re = s_re[run], e = s_e[run]; v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; if (e >= 0) { - const int e2 = e >> 1; - const uint8_t* wbase = (e & 1) ? w_odd + (size_t)e2 * (size_t)N * w_ld_b - : w + (size_t)e2 * (size_t)N * w_ld_b; - const float* wsb = (e & 1) ? w_odd_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / kGroup) - : w_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / kGroup); + const int cls = e & 1, e2 = e >> 1; + const uint8_t* wbase = r3d_tab_at(tw.w[cls], e2); + const int w_ld_b = tw.w[cls].ld; + const float* wsb = (const float*)r3d_tab_at(tw.s[cls], e2); + const int ws_ld = tw.s[cls].ld; for (int b = 0; b < K / kGroup; ++b) { const int kt = b * kGroup; @@ -148,14 +149,14 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_q_kernel( group_barrier(); // Fold the g-block's scales. acc[g] is at row g*2 + lane/16 (varies with g), column r. - // The weight scale is per (grid_rows columns, 128 of K). - const float sw = wsb[(size_t)(n_real / grid_rows) * (K / kGroup) + b]; + // The weight scale is per 128x128 tile. + const float sw = wsb[(size_t)(n_real / kGroup) * ws_ld + b]; #pragma unroll for (int g = 0; g < 8; ++g) { const int row = (int)(g * 2 + (lane >> 4)); const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] : s_tok[rs - (int)r0]; - const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * (K / kGroup) + b]; + const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * as_ld + b]; acc[g] += blk[g] * sa * sw; } } @@ -166,7 +167,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_q_kernel( for (int g = 0; g < 8; ++g) { const int row = (int)(g * 2 + (lane >> 4)); const int m = (int)(r0 + row); - if (rs <= m && m < re && nc < (uint32_t)N) y[(size_t)m * y_ld + nc] = acc[g]; + if (rs <= m && m < re && nc < (uint32_t)N) y[(size_t)m * y_ld + nc] = f32_to_bf16(acc[g]); } } } @@ -177,50 +178,49 @@ extern "C" { static int r3d_moe_gemm_q_dispatch(const RadArgs* a, RadStream s, int alu) { - if (!a || a->n_t < 9) return R3D_NO(RAD_E_INVAL); - const RadTensor* at = r3d_opt(a, 0), *asc = r3d_opt(a, 1), *st = r3d_opt(a, 2), - *ot = r3d_opt(a, 3), *wt = r3d_opt(a, 4), *wsc = r3d_opt(a, 5), - *wot = r3d_opt(a, 6), *wosc = r3d_opt(a, 7), *yt = r3d_opt(a, 8); - if (!r3d_p(at) || !r3d_p(asc) || !r3d_p(st) || !r3d_p(ot) || !r3d_p(wt) || !r3d_p(wsc) || - !r3d_wp(yt)) - return R3D_NO(RAD_E_INVAL); - long long M = 0, K = 0; - if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); - const long long T = (st->rank >= 1) ? st->shape[0] : 0; - const long long N = (wt->rank >= 3) ? wt->shape[1] : 0; - if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || K % 128) return R3D_NO(RAD_E_SHAPE); // N tail clamps - const int n_expert = (int)r3d_geti_or(a, "n_expert", 1); - const int top_k = (int)r3d_geti_or(a, "top_k", 1); - const int grid_rows = (int)r3d_geti_or(a, "grid_rows", 1); // 1 (w4a8) or 128 (fp8a8) - const int a_ld = (int)at->stride[0]; - const int w_ld_b = (int)wt->shape[2]; // the weight's K in bytes - const int y_ld = (int)yt->stride[0]; + R3dMoeCall c; + int rc = r3d_moe_call(a, true, &c); + if (rc != RAD_OK) return rc; + if (!c.a_scale) return R3D_NO(RAD_E_INVAL); + if (c.a->dtype != RAD_F8E4M3 || c.a_scale->dtype != RAD_F32 || c.y->dtype != RAD_BF16) + return R3D_NO(RAD_E_DTYPE); + if (c.K % kGroup) return R3D_NO(RAD_E_SHAPE); // the N tail clamps + R3dMoeTabs tw; + rc = r3d_moe_q_tabs(c, RAD_F8E4M3, 8, RAD_F32, 32, (c.N + kGroup - 1) / kGroup, c.K / kGroup, + &tw); + if (rc != RAD_OK) return rc; + const int a_ld = (int)c.a->stride[0], as_ld = (int)c.a_scale->stride[0]; + const int y_ld = (int)c.y->stride[0]; - dim3 grid((unsigned)((N + kNBlock - 1) / kNBlock), (unsigned)((T + 15) / 16)), blk(kThreads); - const uint8_t* pa = (const uint8_t*)r3d_p(at); - const float* psa = (const float*)r3d_p(asc); - const int32_t* ps = (const int32_t*)r3d_p(st); - const int32_t* po = (const int32_t*)r3d_p(ot); - const uint8_t* pw = (const uint8_t*)r3d_p(wt); - const float* pws = (const float*)r3d_p(wsc); - const uint8_t* pwo = (const uint8_t*)r3d_p(wot); - const float* pwos = (const float*)r3d_p(wosc); - float* py = (float*)r3d_wp(yt); + dim3 grid((unsigned)((c.N + kNBlock - 1) / kNBlock), (unsigned)((c.T + 15) / 16)), blk(kThreads); + const uint8_t* pa = (const uint8_t*)r3d_p(c.a); + const float* psa = (const float*)r3d_p(c.a_scale); + const int32_t* ps = (const int32_t*)r3d_p(c.sorted); + const int32_t* po = (const int32_t*)r3d_p(c.off); + uint16_t* py = (uint16_t*)r3d_wp(c.y); if (alu) - moe_q_kernel<1><<>>(pa, psa, ps, po, pw, pws, pwo, pwos, py, - (int)T, (int)N, (int)K, a_ld, w_ld_b, y_ld, - n_expert, top_k, grid_rows); + moe_q_kernel<1><<>>(pa, psa, ps, po, tw, py, (int)c.T, (int)c.N, + (int)c.K, a_ld, as_ld, y_ld, + (int)c.n_expert, (int)c.top_k, + c.a_sorted); else - moe_q_kernel<0><<>>(pa, psa, ps, po, pw, pws, pwo, pwos, py, - (int)T, (int)N, (int)K, a_ld, w_ld_b, y_ld, - n_expert, top_k, grid_rows); + moe_q_kernel<0><<>>(pa, psa, ps, po, tw, py, (int)c.T, (int)c.N, + (int)c.K, a_ld, as_ld, y_ld, + (int)c.n_expert, (int)c.top_k, + c.a_sorted); return (int)hipGetLastError(); } -/* The two rows share the dispatch: the table decode (ALU=0) and the ALU decode (ALU=1). The tune - * picks the faster per geometry. */ +/* The row's entry: the tune's `impl` arm picks the kernel -- 0 the table decode, 1 the ALU decode, + * 2 the 16x128 block (r3d_moe_gemm_fp8_f32scale.hip) at the tune's register budget and + * accumulator. */ extern "C" int r3d_rad_moe_gemm_q(const RadArgs* a, RadStream s) -{ return r3d_moe_gemm_q_dispatch(a, s, 0); } +{ + R3dMoeQCfg cfg; + r3d_cfg_moe_q(a, &cfg); + if (cfg.impl == 2) return r3d_moe_gemm_fp8_f32scale_run(a, s, cfg.vgpr, cfg.acc); + return r3d_moe_gemm_q_dispatch(a, s, cfg.impl == 1); +} extern "C" int r3d_rad_moe_gemm_q_alu(const RadArgs* a, RadStream s) { return r3d_moe_gemm_q_dispatch(a, s, 1); } diff --git a/libr3d/r3d_moe_scatter.hip b/libr3d/r3d_moe_scatter.hip index 10283b0a..565aaf77 100644 --- a/libr3d/r3d_moe_scatter.hip +++ b/libr3d/r3d_moe_scatter.hip @@ -15,7 +15,11 @@ * butterfly (a DPP exchange inside the scan's tile loop miscompiles here). Each wave writes its * lane's count to LDS, barriers, and takes the serial prefix of its 32 lanes. * - * The general (three-pass) form for T > 1024 is not implemented here; the shim declines it. + * Above 1024 slots the sort is three passes (libhalo's general form): a histogram per 256-slot + * tile into the caller's scratch, a per-expert scan across the tiles, and the placement (an + * expert's offset, plus its count in earlier tiles, plus the slot's rank in its own tile). Stable + * too, so both forms give the same bytes. The scan's cross-expert prefix is a serial LDS loop, not + * a wave scan, for the same gfx1102 reason as above. */ #include @@ -142,29 +146,100 @@ __global__ __launch_bounds__(kScatWaves * kSortWave) void scatter_small_kernel( scatter_small_place(sorted, off, cnt, T, n_expert, sl, inv); } -} // namespace +/* ================================================================== the general form */ -extern "C" { +constexpr uint32_t kScatterTile = 256; -int r3d_rad_moe_scatter(const RadArgs* a, RadStream s) +/* Pass 1: each tile's count of every expert, bcnt[tile][expert]. */ +__global__ __launch_bounds__(kScatterTile) void scatter_hist_kernel( + const int32_t* __restrict__ ids, int32_t* __restrict__ bcnt, uint32_t T, uint32_t n_expert, + int32_t base, Protect prot) { + __shared__ int32_t s_h[kMaxExpert]; + const uint32_t tid = threadIdx.x, b = blockIdx.x; + for (uint32_t e = tid; e < n_expert; e += kScatterTile) s_h[e] = 0; + R3D_BARRIER(); + const uint32_t i = b * kScatterTile + tid; + if (i < T) { + const int32_t e = ids[i] - base; + if (e >= 0 && e < (int32_t)n_expert) atomicAdd(&s_h[sort_place(e, n_expert, prot)], 1); + } + R3D_BARRIER(); + for (uint32_t e = tid; e < n_expert; e += kScatterTile) + bcnt[(size_t)b * n_expert + e] = s_h[e]; +} + +/* Pass 2: per expert, the count in earlier tiles (bcnt rewritten in place to it) and the total; + * then the offsets, an exclusive prefix over the totals. */ +__global__ __launch_bounds__(kMaxExpert) void scatter_scan_kernel( + int32_t* __restrict__ bcnt, int32_t* __restrict__ off, int32_t* __restrict__ cnt, + uint32_t n_tile, uint32_t n_expert) { + __shared__ int32_t s_run[kMaxExpert]; + const uint32_t e = threadIdx.x; + int32_t run = 0; + if (e < n_expert) { + for (uint32_t b = 0; b < n_tile; ++b) { + const int32_t v = bcnt[(size_t)b * n_expert + e]; + bcnt[(size_t)b * n_expert + e] = run; + run += v; + } + cnt[e] = run; + } + s_run[e] = run; + R3D_BARRIER(); + if (e == 0) { + int32_t acc = 0; + for (uint32_t x = 0; x < n_expert; ++x) { off[x] = acc; acc += s_run[x]; } + off[n_expert] = acc; + } +} + +/* Pass 3: each routed slot at its expert's offset plus the expert's count in earlier tiles plus + * its rank in this tile. Sorted rows past the live count are -1; no placement lands there. INV + * also writes each slot's row, -1 when dropped. */ +template +__global__ __launch_bounds__(kScatterTile) void scatter_place_kernel( + const int32_t* __restrict__ ids, const int32_t* __restrict__ bcnt, + const int32_t* __restrict__ off, int32_t* __restrict__ sorted, + uint32_t T, uint32_t n_expert, int32_t base, Protect prot, int32_t* __restrict__ inv) { + __shared__ int32_t s_id[kScatterTile]; + const uint32_t tid = threadIdx.x, b = blockIdx.x; + const uint32_t i = b * kScatterTile + tid; + const int32_t l = (i < T) ? ids[i] - base : -1; + const int32_t e = (l >= 0 && l < (int32_t)n_expert) ? sort_place(l, n_expert, prot) : -1; + s_id[tid] = e; + const uint32_t live = (uint32_t)off[n_expert]; + if (i >= live && i < T) sorted[i] = -1; + R3D_BARRIER(); + if (INV && i < T && e < 0) inv[i] = -1; + if (i >= T || e < 0) return; + int32_t rank = 0; + for (uint32_t j = 0; j < tid; ++j) rank += (s_id[j] == e); + const int32_t at = off[e] + bcnt[(size_t)b * n_expert + e] + rank; + sorted[at] = (int32_t)i; + if (INV) inv[i] = at; +} + +/* Both entry points: the small form up to kScatterSmall slots, the three passes above it. */ +int scatter_body(const RadArgs* a, RadStream s, bool with_inv) { - if (!a || a->n_t < 4) return R3D_NO(RAD_E_INVAL); + if (!a || a->n_t < (with_inv ? 5 : 4)) return R3D_NO(RAD_E_INVAL); const RadTensor* ids = r3d_opt(a, 0), *sorted = r3d_opt(a, 1), *off = r3d_opt(a, 2), - *cnt = r3d_opt(a, 3); - if (!r3d_p(ids) || !r3d_wp(sorted) || !r3d_wp(off) || !r3d_wp(cnt)) + *cnt = r3d_opt(a, 3), *inv = with_inv ? r3d_opt(a, 4) : nullptr; + if (!r3d_p(ids) || !r3d_wp(sorted) || !r3d_wp(off) || !r3d_wp(cnt) || + (with_inv && !r3d_wp(inv))) return R3D_NO(RAD_E_INVAL); if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 || - cnt->dtype != RAD_I32) + cnt->dtype != RAD_I32 || (inv && inv->dtype != RAD_I32)) return R3D_NO(RAD_E_DTYPE); - if (!r3d_contig(ids) || !r3d_contig(sorted) || !r3d_contig(off) || !r3d_contig(cnt)) + if (!r3d_contig(ids) || !r3d_contig(sorted) || !r3d_contig(off) || !r3d_contig(cnt) || + (inv && !r3d_contig(inv))) return R3D_NO(RAD_E_STRIDE); const long long n_expert = r3d_geti_or(a, "n_expert", 0); if (n_expert <= 0 || n_expert > (long long)kMaxExpert) return R3D_NO(RAD_E_SHAPE); const long long T = r3d_numel(ids); if (T <= 0) return R3D_NO(RAD_E_SHAPE); - if (T > (long long)kScatterSmall) return R3D_NO(RAD_E_SHAPE); // the small form only - if (r3d_numel(sorted) < T) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(sorted) < T || (inv && r3d_numel(inv) < T)) return R3D_NO(RAD_E_SHAPE); if (r3d_numel(off) < n_expert + 1 || r3d_numel(cnt) < n_expert) return R3D_NO(RAD_E_SHAPE); const long long base = r3d_geti_or(a, "expert_base", 0); @@ -192,65 +267,66 @@ int r3d_rad_moe_scatter(const RadArgs* a, RadStream s) int32_t* sp = (int32_t*)r3d_wp(sorted); int32_t* op = (int32_t*)r3d_wp(off); int32_t* cp = (int32_t*)r3d_wp(cnt); + int32_t* ip = inv ? (int32_t*)r3d_wp(inv) : nullptr; - R3D_KLAUNCH(scatter_small_kernel, dim3(1), dim3(kScatWaves * kSortWave), (hipStream_t)s, - idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot, - (int32_t*)nullptr); + if (T <= (long long)kScatterSmall) { + if (ip) + R3D_KLAUNCH(scatter_small_kernel, dim3(1), dim3(kScatWaves * kSortWave), + (hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); + else + R3D_KLAUNCH(scatter_small_kernel, dim3(1), dim3(kScatWaves * kSortWave), + (hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); + return (int)hipGetLastError(); + } + + const long long n_tile = (T + kScatterTile - 1) / kScatterTile; + const long long need = n_tile * n_expert * (long long)sizeof(int32_t); + if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH); + int32_t* bcnt = (int32_t*)a->scratch; + R3D_KLAUNCH(scatter_hist_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), (hipStream_t)s, + idp, bcnt, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot); + R3D_KLAUNCH(scatter_scan_kernel, dim3(1), dim3(kMaxExpert), (hipStream_t)s, + bcnt, op, cp, (uint32_t)n_tile, (uint32_t)n_expert); + if (ip) + R3D_KLAUNCH(scatter_place_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), + (hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); + else + R3D_KLAUNCH(scatter_place_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), + (hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); return (int)hipGetLastError(); } +} // namespace + +extern "C" { + +int r3d_rad_moe_scatter(const RadArgs* a, RadStream s) +{ + return scatter_body(a, s, false); +} + /* moe_scatter_inv: the same sort, plus the inverse permutation (each slot's row in sorted_tok). */ int r3d_rad_moe_scatter_inv(const RadArgs* a, RadStream s) { - if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL); - const RadTensor* ids = r3d_opt(a, 0), *sorted = r3d_opt(a, 1), *off = r3d_opt(a, 2), - *cnt = r3d_opt(a, 3), *inv = r3d_opt(a, 4); - if (!r3d_p(ids) || !r3d_wp(sorted) || !r3d_wp(off) || !r3d_wp(cnt) || !r3d_wp(inv)) - return R3D_NO(RAD_E_INVAL); - if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 || - cnt->dtype != RAD_I32 || inv->dtype != RAD_I32) - return R3D_NO(RAD_E_DTYPE); - if (!r3d_contig(ids) || !r3d_contig(sorted) || !r3d_contig(off) || !r3d_contig(cnt) || - !r3d_contig(inv)) - return R3D_NO(RAD_E_STRIDE); + return scatter_body(a, s, true); +} +/* The three-pass form's per-tile counts, [n_tile, n_expert] i32; the small form needs none. */ +int64_t r3d_rad_moe_scatter_scratch(const RadArgs* a) +{ + if (!a) return 0; const long long n_expert = r3d_geti_or(a, "n_expert", 0); - if (n_expert <= 0 || n_expert > (long long)kMaxExpert) return R3D_NO(RAD_E_SHAPE); - const long long T = r3d_numel(ids); - if (T <= 0) return R3D_NO(RAD_E_SHAPE); - if (T > (long long)kScatterSmall) return R3D_NO(RAD_E_SHAPE); // the small form only - if (r3d_numel(sorted) < T || r3d_numel(inv) < T) return R3D_NO(RAD_E_SHAPE); - if (r3d_numel(off) < n_expert + 1 || r3d_numel(cnt) < n_expert) return R3D_NO(RAD_E_SHAPE); - - const long long base = r3d_geti_or(a, "expert_base", 0); - if (base < 0) return R3D_NO(RAD_E_SHAPE); - - Protect prot{}; - if (const char* str = r3d_gets(a, "protect")) { - const char* p = str; - long long prev = -1; - while (*p) { - char* end = nullptr; - const long long v = std::strtoll(p, &end, 10); - if (end == p || v <= prev || v >= n_expert || prot.n >= kMaxProtect) - return R3D_NO(RAD_E_SHAPE); - prot.e[prot.n++] = (uint16_t)v; - prev = v; - p = end; - if (*p == ',') ++p; - else if (*p) return R3D_NO(RAD_E_SHAPE); - } - } - - const int32_t* idp = (const int32_t*)r3d_p(ids); - int32_t* sp = (int32_t*)r3d_wp(sorted); - int32_t* op = (int32_t*)r3d_wp(off); - int32_t* cp = (int32_t*)r3d_wp(cnt); - int32_t* ip = (int32_t*)r3d_wp(inv); - - R3D_KLAUNCH(scatter_small_kernel, dim3(1), dim3(kScatWaves * kSortWave), (hipStream_t)s, - idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot, ip); - return (int)hipGetLastError(); + /* Called at declare with the band's bound, when the ids may carry no data yet: then + * M x top_k. */ + const RadTensor* ids = r3d_opt(a, 0); + const long long T = ids ? r3d_numel(ids) : r3d_geti_or(a, "M", 0) * r3d_geti_or(a, "top_k", 1); + if (n_expert <= 0 || T <= (long long)kScatterSmall) return 0; + const long long n_tile = (T + kScatterTile - 1) / kScatterTile; + return n_tile * n_expert * (long long)sizeof(int32_t); } } // extern "C" diff --git a/libr3d/r3d_moe_tab.h b/libr3d/r3d_moe_tab.h new file mode 100644 index 00000000..950deb7f --- /dev/null +++ b/libr3d/r3d_moe_tab.h @@ -0,0 +1,132 @@ +/* r3d_moe_tab.h -- the grouped GEMMs' contract operands: weight tables, `a_order` and the classes. + * + * `moe_gemm` and `moe_gemm_q` take their experts as weight tables (RAD_OPD_WTAB, docs/OPS.md): + * a `[entries, rows, cols]` tensor whose data is a device array of one pointer per entry when + * stride[0] is 0 (each expert is its own movement unit, so the core hands a pointer each), or the + * base of a stacked plane with entries stride[0] elements apart. Both are read through + * r3d_tab_at, resolved on the device: the table lives in device memory and the mover may rewrite + * it between launches. + * + * `moe_gemm_q` holds the even experts in `w`/`w_scale` and the odd in `w_odd`/`w_odd_scale`, + * expert e at entry e/2 of class e%2. The contract lets the odd class be narrower + * (`N_odd`/`K_odd`, a rank holding an uneven slice of every expert); these kernels serve equal + * classes and refuse the rest by name. With equal classes `parts` maps output column n to weight + * row n, so it needs no handling beyond the divisibility check. + */ +#pragma once + +#include "r3d_args.h" + +#include + +/* One class's table as the kernels read it: the table, the bytes between stacked entries (0 for + * a pointer array) and the elements between rows of one entry. */ +struct R3dTab { + const void* const* tab; + unsigned long long s0; + int ld; +}; + +/* Both classes' codes and scales, passed to a kernel by value. Class 1 repeats class 0 when the + * call has a single expert and so no odd entries. */ +struct R3dMoeTabs { + R3dTab w[2]; + R3dTab s[2]; +}; + +#if defined(__HIPCC__) +__device__ __forceinline__ const uint8_t* r3d_tab_at(const R3dTab& t, int i) { + if (t.s0 == 0) return (const uint8_t*)t.tab[i]; + return (const uint8_t*)t.tab + (size_t)i * t.s0; +} +#endif + +/* A weight-table operand of `entries` entries, each at least `rows` x `cols`, with the dtype the + * row reads; `bits` is the element width, so a 4-bit plane's stacked stride keeps its half-byte. */ +static inline int r3d_tab_of(const RadTensor* t, uint32_t dtype, int bits, long long entries, + long long rows, long long cols, R3dTab* out) { + if (!t || !t->data || t->rank != 3) return R3D_NO(RAD_E_SHAPE); + if (t->dtype != dtype) return R3D_NO(RAD_E_DTYPE); + if (t->shape[0] < entries || t->shape[1] < rows || t->shape[2] < cols) + return R3D_NO(RAD_E_SHAPE); + if (t->stride[2] != 1 || t->stride[1] < cols) return R3D_NO(RAD_E_STRIDE); + out->tab = (const void* const*)t->data; + out->s0 = (unsigned long long)((t->stride[0] * (long long)bits) / 8); + out->ld = (int)t->stride[1]; + return RAD_OK; +} + +/* The operands and parameters both grouped GEMMs share, checked against the contract. */ +struct R3dMoeCall { + const RadTensor *a, *a_scale, *sorted, *off, *y; + const RadTensor *w, *w_scale, *w_odd, *w_odd_scale; /* w_scale and the odd class: _q only */ + long long T, N, K, n_expert, top_k; + int a_sorted; +}; + +/* `quant`: moe_gemm_q's nine operands (a, a_scale?, w, w_scale, sorted_tok, expert_offset, w_odd, + * w_odd_scale -> y), else moe_gemm's five (a, w, sorted_tok, expert_offset -> y). */ +static inline int r3d_moe_call(const RadArgs* a, bool quant, R3dMoeCall* c) { + if (!a || a->n_t < (quant ? 9 : 5)) return R3D_NO(RAD_E_INVAL); + *c = R3dMoeCall{}; + c->a = r3d_opt(a, 0); + c->a_scale = quant ? r3d_opt(a, 1) : nullptr; + c->w = r3d_opt(a, quant ? 2 : 1); + c->w_scale = quant ? r3d_opt(a, 3) : nullptr; + c->sorted = r3d_opt(a, quant ? 4 : 2); + c->off = r3d_opt(a, quant ? 5 : 3); + c->w_odd = quant ? r3d_opt(a, 6) : nullptr; + c->w_odd_scale = quant ? r3d_opt(a, 7) : nullptr; + c->y = r3d_opt(a, quant ? 8 : 4); + if (!c->a || !c->w || !c->sorted || !c->off || !r3d_wp(c->y)) return R3D_NO(RAD_E_INVAL); + if (quant && !c->w_scale) return R3D_NO(RAD_E_INVAL); + + /* "token" (the default, gate_up): sorted row i reads a[sorted_tok[i] / top_k]. "sorted" (the + * down projection): a already has one row per (token, slot) in the scatter's order. */ + const char* ord = r3d_gets(a, "a_order"); + c->a_sorted = ord && std::strcmp(ord, "sorted") == 0; + if (ord && !c->a_sorted && std::strcmp(ord, "token") != 0) return R3D_NO(RAD_E_UNSUPPORTED); + + c->N = r3d_geti_or(a, "N", c->w->rank >= 3 ? c->w->shape[1] : 0); + c->K = r3d_geti_or(a, "K", c->w->rank >= 3 ? c->w->shape[2] : 0); + c->n_expert = r3d_geti_or(a, "n_expert", 0); + c->top_k = r3d_geti_or(a, "top_k", 0); + if (c->N <= 0 || c->K <= 0 || c->n_expert <= 0 || c->top_k <= 0) return R3D_NO(RAD_E_SHAPE); + if (quant) { + if (r3d_geti_or(a, "N_odd", c->N) != c->N || r3d_geti_or(a, "K_odd", c->K) != c->K) + return R3D_NO(RAD_E_UNSUPPORTED); + const long long parts = r3d_geti_or(a, "parts", 1); + if (parts < 1 || c->N % parts) return R3D_NO(RAD_E_SHAPE); + if (c->n_expert >= 2 && (!c->w_odd || !c->w_odd_scale)) return R3D_NO(RAD_E_INVAL); + } + + /* One output row per (token, slot), the rows the sort placed. */ + long long yr = 0, yc = 0; + if (r3d_rows_of(c->y, &yr, &yc) != RAD_OK || yc < c->N) return R3D_NO(RAD_E_SHAPE); + c->T = yr; + if (r3d_numel(c->sorted) < c->T || r3d_numel(c->off) < c->n_expert + 1) + return R3D_NO(RAD_E_SHAPE); + long long ar = 0, ak = 0; + if (r3d_rows_of(c->a, &ar, &ak) != RAD_OK || ak < c->K) return R3D_NO(RAD_E_SHAPE); + if (ar < (c->a_sorted ? c->T : c->T / c->top_k)) return R3D_NO(RAD_E_SHAPE); + return RAD_OK; +} + +/* Both classes' tables of a moe_gemm_q call: codes at `wdt`/`wbits`, scales at `sdt` (or u8 for + * an E8M0 plane typed raw) with `srows` x `scols` an entry. */ +static inline int r3d_moe_q_tabs(const R3dMoeCall& c, uint32_t wdt, int wbits, uint32_t sdt, + int sbits, long long srows, long long scols, R3dMoeTabs* t) { + const long long n_even = (c.n_expert + 1) / 2, n_odd = c.n_expert / 2; + auto sdt_of = [&](const RadTensor* x) { + return (sdt == RAD_E8M0 && x && x->dtype == RAD_U8) ? (uint32_t)RAD_U8 : sdt; + }; + int rc = r3d_tab_of(c.w, wdt, wbits, n_even, c.N, c.K, &t->w[0]); + if (rc == RAD_OK) rc = r3d_tab_of(c.w_scale, sdt_of(c.w_scale), sbits, n_even, srows, scols, + &t->s[0]); + if (rc != RAD_OK) return rc; + if (n_odd == 0) { t->w[1] = t->w[0]; t->s[1] = t->s[0]; return RAD_OK; } + rc = r3d_tab_of(c.w_odd, wdt, wbits, n_odd, c.N, c.K, &t->w[1]); + if (rc == RAD_OK) rc = r3d_tab_of(c.w_odd_scale, sdt_of(c.w_odd_scale), sbits, n_odd, srows, + scols, &t->s[1]); + return rc; +} diff --git a/libr3d/r3d_plugin.h b/libr3d/r3d_plugin.h index 75fcd997..b074fadf 100644 --- a/libr3d/r3d_plugin.h +++ b/libr3d/r3d_plugin.h @@ -163,14 +163,13 @@ int r3d_relayout_gemm_nt_q_w5a16(const RadParam* p, int n_p, int operand, const int64_t dst_bytes); int r3d_rad_gemm_nt_q_fp8 (const RadArgs* a, RadStream s); -/* --- r3d_gdn_kkt_solve_c64.hip: the gated-delta-net chunk preamble, the gram and the blocked - * inverse of I + the strictly lower decayed gram, one 64-chunk a workgroup. --- */ -int r3d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s); +/* --- r3dh_gdn_kkt_solve.hip (libhalo's): the gated-delta-net chunk preamble, the gram and the + * blocked inverse of I + the strictly lower decayed gram, one 64-chunk a workgroup. --- */ +extern "C" int r3dh_rad_gdn_kkt_solve(const RadArgs* a, RadStream s); - -/* --- r3d_gdn_chunk_scan_k128_v128_c64.hip: the gated-delta-net chunked scan, the chunk's - * output and its closing state, the recurrent state in wave-matrix accumulators. --- */ -int r3d_rad_gdn_chunk_scan(const RadArgs* a, RadStream s); +/* --- r3dh_gdn_chunk_scan.hip (libhalo's): the gated-delta-net chunked scan, the chunk's output + * and its closing state, the recurrent state in wave-matrix accumulators. --- */ +extern "C" int r3dh_rad_gdn_chunk_scan(const RadArgs* a, RadStream s); /* --- r3d_gdn_gated_rmsnorm_h128.hip: the gated RMS norm a gated-delta-net layer applies to its * own output, one wave per (token, head) row. */ @@ -185,9 +184,9 @@ int r3d_rad_gdn_gated_norm_hq_i8(const RadArgs* a, RadStream s); int r3d_rad_gdn_conv_prep(const RadArgs* a, RadStream s); int r3d_rad_gdn_conv_update(const RadArgs* a, RadStream s); -/* --- r3d_gdn_recurrent_update_k128_v128.hip: the gated-delta-net recurrent state update at - * decode, the per-token state step against a paged fp32 state cache. */ -int r3d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s); +/* --- r3dh_gdn_recurrent_update.hip (libhalo's): the gated-delta-net recurrent state update at + * decode against the paged state cache, in either state form (per_candidate or anchor). */ +extern "C" int r3dh_rad_gdn_recurrent_update(const RadArgs* a, RadStream s); /* --- r3d_expert_scale_bf16.hip: each routing weight times its expert's own scale, in place. */ int r3d_rad_expert_scale_bf16(const RadArgs* a, RadStream s); @@ -198,6 +197,7 @@ int r3d_rad_moe_router_topk_bf16(const RadArgs* a, RadStream s); /* --- r3d_moe_scatter.hip: the routed slots' stable counting sort (small form). */ int r3d_rad_moe_scatter(const RadArgs* a, RadStream s); int r3d_rad_moe_scatter_inv(const RadArgs* a, RadStream s); +int64_t r3d_rad_moe_scatter_scratch(const RadArgs* a); /* --- r3d_moe_gather.hip: fold the expert outputs back to the token. */ int r3d_rad_moe_gather(const RadArgs* a, RadStream s); diff --git a/libr3d/r3d_rows.cpp b/libr3d/r3d_rows.cpp index 4fa09152..8b197d85 100644 --- a/libr3d/r3d_rows.cpp +++ b/libr3d/r3d_rows.cpp @@ -48,8 +48,13 @@ #define R3D_BUILD_TARGET "gfx1100 gfx1101 gfx1102 gfx1103 gfx1150 gfx1151" #endif +#include + #include +#include #include +#include +#include #define ROW(a) (a), (int)(sizeof(a) / sizeof((a)[0])) #define NELEM(a) ((int)(sizeof(a) / sizeof((a)[0]))) @@ -58,6 +63,9 @@ #define P_INT(k) { (k), RAD_P_INT, RAD_REQUIRED } #define P_INTO(k) { (k), RAD_P_INT, RAD_OPTIONAL } #define P_INTD(k) { (k), RAD_P_INT, RAD_DERIVED } +/* The sequence-chunk parameter: derived, and the one the core reads by meaning (RAD_PROLE_SEQ_CHUNK). + * Roles are part of a schema, so this must match libref's spelling, not only P_INTD's. */ +#define P_CHUNK(k) { (k), RAD_P_INT, RAD_DERIVED, RAD_PROLE_SEQ_CHUNK } #define P_STR(k) { (k), RAD_P_STR, RAD_REQUIRED } #define P_STRO(k) { (k), RAD_P_STR, RAD_OPTIONAL } #define P_F64(k) { (k), RAD_P_F64, RAD_REQUIRED } @@ -164,18 +172,18 @@ static const RadOperandSpec oRouterTopkScatter[] = { { "logits", RAD_OPD_IN, 0 } { "sorted_tok", RAD_OPD_OUT, 0 }, { "expert_offset", RAD_OPD_OUT, 0 }, { "expert_count", RAD_OPD_OUT, 0 } }; -static const RadParamSpec pRouterTopkScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), - P_INT("n_local"), P_INT("norm"), P_STRO("dtype"), - P_INT("expert_base"), P_STRO("protect") }; +static const RadParamSpec pRouterTopkScatter[] = { P_INT("M"), P_INT("n_expert"), P_INTO("n_local"), + P_INT("top_k"), P_INT("norm"), P_STR("dtype"), + P_INTO("expert_base"), P_STRO("protect") }; /* router_sigmoid_topk: the GLM-style router -- logits, the per-expert correction bias, and the * selection (expert_ids, expert_w). */ static const RadOperandSpec oRouterSigmoid[] = { { "logits", RAD_OPD_IN, 0 }, - { "bias", RAD_OPD_IN, 0 }, - { "expert_ids", RAD_OPD_OUT, 0 }, - { "expert_w", RAD_OPD_OUT, 0 } }; + { "bias", RAD_OPD_WEIGHT, 0 }, + { "ids", RAD_OPD_OUT, 0 }, + { "weights", RAD_OPD_OUT, 0 } }; static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), - P_F64("route_scale"), P_INTO("norm"), P_STRO("dtype") }; + P_INT("norm"), P_F64("route_scale"), P_STR("dtype") }; static const RadOperandSpec oGatedQuant[] = { { "gate_up", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, @@ -212,7 +220,7 @@ static const RadOperandSpec oRmsQuantI8[] = { { "x", RAD_OPD_IN, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "out_bf16", RAD_OPD_OUT, 1 }, { "w_post", RAD_OPD_WEIGHT, 1 }, - { "scalar", RAD_OPD_IN, 1 } }; + { "scalar", RAD_OPD_WEIGHT, 1 } }; static const RadOperandSpec oDequant[] = { { "q", RAD_OPD_IN, 0 }, { "scale", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; @@ -222,9 +230,12 @@ static const RadParamSpec pGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_STR( static const RadOperandSpec oGemm[] = { { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 } }; +/* `w_rb` is libr4d's (docs/OPS.md), accepted and ignored: an int8 weight's per-row scale plane + * holds each block's value in every row, and the trellis forms that need it are IQR dtypes, which + * no row here serves. */ static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"), - P_INTO("split_n") }; + P_INTO("split_n"), P_INTO("w_rb") }; static const RadOperandSpec oGemmQ[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RAD_OPD_IN, 1 }, { "b", RAD_OPD_WEIGHT, 0 }, { "b_scale", RAD_OPD_WEIGHT, 0 }, @@ -232,7 +243,7 @@ static const RadOperandSpec oGemmQ[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RA { "b_ref", RAD_OPD_WEIGHT, 1 } }; /* --- gated-delta-net --- */ -static const RadParamSpec pGdnKktSolve[] = { P_INT("M"), P_INT("head_k"), P_INT("chunk") }; +static const RadParamSpec pGdnKktSolve[] = { P_INT("M"), P_INT("head_k"), P_CHUNK("chunk") }; static const RadOperandSpec oGdnKktSolve[] = { { "k", RAD_OPD_IN, 0 }, { "beta", RAD_OPD_IN, 0 }, { "g", RAD_OPD_IN, 0 }, @@ -240,7 +251,7 @@ static const RadOperandSpec oGdnKktSolve[] = { { "k", RAD_OPD_IN, 0 }, { "A", RAD_OPD_OUT, 0 } }; static const RadParamSpec pGdnChunkScan[] = { P_INT("M"), P_INT("head_k"), P_INT("head_v"), - P_INTD("chunk"), P_F64O("scale"), P_INTO("state_fp16") }; + P_CHUNK("chunk"), P_F64O("scale"), P_INTO("state_fp16") }; static const RadOperandSpec oGdnChunkScan[] = { { "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 0 }, @@ -257,7 +268,7 @@ static const RadParamSpec pGdnGatedRmsnorm[] = { P_INT("M"), P_INT("channels"), P_F64("eps"), P_STR("act") }; static const RadOperandSpec oGdnGatedRmsnorm[] = { { "x", RAD_OPD_IN, 0 }, { "z", RAD_OPD_IN, 0 }, - { "w", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, { "o", RAD_OPD_OUT, 0 } }; static const RadParamSpec pGdnGatedNormHq[] = { P_INT("M"), P_INT("n"), P_INT("head_dim"), @@ -265,18 +276,18 @@ static const RadParamSpec pGdnGatedNormHq[] = { P_INT("M"), P_INT("n"), P_INT("h P_INTO("zgrp"), P_INTO("zblk") }; static const RadOperandSpec oGdnGatedNormHq[] = { { "x", RAD_OPD_IN, 0 }, { "z", RAD_OPD_IN, 0 }, - { "w", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 } }; static const RadParamSpec pGdnConvPrep[] = { P_INT("M"), P_INT("head_k"), P_INT("head_v"), - P_INTD("chunk"), P_INT("conv_width"), + P_CHUNK("chunk"), P_INT("conv_width"), P_F64O("l2_eps"), P_F64O("softplus_thr") }; static const RadOperandSpec oGdnConvPrep[] = { { "x", RAD_OPD_IN, 0 }, - { "w", RAD_OPD_IN, 0 }, - { "b", RAD_OPD_IN, 1 }, - { "A_log", RAD_OPD_IN, 0 }, - { "dt_bias", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "b", RAD_OPD_WEIGHT, 1 }, + { "A_log", RAD_OPD_WEIGHT, 0 }, + { "dt_bias", RAD_OPD_WEIGHT, 0 }, { "conv_state", RAD_OPD_INOUT, 0 }, { "cu", RAD_OPD_IN, 0 }, { "a", RAD_OPD_IN, 1 }, @@ -290,13 +301,13 @@ static const RadOperandSpec oGdnConvPrep[] = { { "x", RAD_OPD_IN, 0 }, { "beta", RAD_OPD_OUT, 0 } }; static const RadParamSpec pGdnConvUpdate[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"), - P_INT("conv_width"), P_F64O("max_query_len") }; + P_INT("conv_width"), P_INTO("max_query_len") }; static const RadOperandSpec oGdnConvUpdate[] = { { "x", RAD_OPD_IN, 0 }, - { "w", RAD_OPD_IN, 0 }, - { "b", RAD_OPD_IN, 1 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "b", RAD_OPD_WEIGHT, 1 }, { "conv_state", RAD_OPD_INOUT, 0 }, { "state_idx", RAD_OPD_IN, 0 }, - { "num_accepted", RAD_OPD_IN, 1 }, + { "num_accepted", RAD_OPD_IN, 0 }, { "cu", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, { "k", RAD_OPD_OUT, 0 }, @@ -305,7 +316,7 @@ static const RadOperandSpec oGdnConvUpdate[] = { { "x", RAD_OPD_IN, 0 }, static const RadParamSpec pExpertScale[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), P_STR("dtype") }; static const RadOperandSpec oExpertScale[] = { { "ids", RAD_OPD_IN, 0 }, - { "w_e", RAD_OPD_IN, 0 }, + { "w_e", RAD_OPD_WEIGHT, 0 }, { "ew", RAD_OPD_INOUT, 0 } }; static const RadParamSpec pMoeRouterTopk[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), @@ -325,33 +336,37 @@ static const RadOperandSpec oMoeScatter[] = { { "expert_ids", RAD_OPD_IN, 0 }, static const RadOperandSpec oMoeGather[] = { { "y_expert", RAD_OPD_IN, 0 }, { "expert_w", RAD_OPD_IN, 0 }, { "sorted_tok", RAD_OPD_IN, 0 }, - { "shared", RAD_OPD_IN, 0 }, - { "shared_gate", RAD_OPD_IN, 0 }, + { "shared", RAD_OPD_IN, 1 }, + { "shared_gate", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 } }; -static const RadParamSpec pMoeGather[] = { P_INT("M"), P_INT("n"), P_INT("top_k"), P_STRO("dtype"), +static const RadParamSpec pMoeGather[] = { P_INT("M"), P_INT("n"), P_INT("top_k"), P_STR("dtype"), P_STRO("act") }; -/* moe_gemm_q: the grouped quantised GEMM. a and the weight tables are E4M3 with an f32 scale per - * (row, grid of K); the even experts are `w` / `w_scale`, the odd `w_odd` / `w_odd_scale`. */ +/* moe_gemm_q: the grouped quantised GEMM, libref's schema. The experts are weight tables + * (RAD_OPD_WTAB): the even experts in `w` / `w_scale`, the odd in `w_odd` / `w_odd_scale`, expert e + * at entry e/2 (r3d_moe_tab.h). */ static const RadOperandSpec oMoeGemmQ[] = { { "a", RAD_OPD_IN, 0 }, - { "a_scale", RAD_OPD_IN, 0 }, + { "a_scale", RAD_OPD_IN, 1 }, + { "w", RAD_OPD_WTAB, 0 }, + { "w_scale", RAD_OPD_WTAB, 0 }, { "sorted_tok", RAD_OPD_IN, 0 }, { "expert_offset", RAD_OPD_IN, 0 }, - { "w", RAD_OPD_WEIGHT, 0 }, - { "w_scale", RAD_OPD_WEIGHT, 0 }, - { "w_odd", RAD_OPD_WEIGHT, 0 }, - { "w_odd_scale", RAD_OPD_WEIGHT, 0 }, + { "w_odd", RAD_OPD_WTAB, 0 }, + { "w_odd_scale", RAD_OPD_WTAB, 0 }, { "y", RAD_OPD_OUT, 0 } }; -static const RadParamSpec pMoeGemmQ[] = { P_INT("n_expert"), P_INT("top_k"), P_INTO("grid_rows"), - P_STRO("dtype") }; +static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), + P_INT("top_k"), P_INT("group"), P_STR("a_order"), + P_STR("dtype"), P_INTO("N_odd"), P_INTO("K_odd"), + P_INTO("parts") }; - /* moe_gemm: the grouped GEMM with unquantised bf16 experts. a and w are bf16, no scales. */ + /* moe_gemm: the grouped GEMM with unquantised experts, libref's schema; one weight table. */ static const RadOperandSpec oMoeGemm[] = { { "a", RAD_OPD_IN, 0 }, - { "w", RAD_OPD_WEIGHT, 0 }, + { "w", RAD_OPD_WTAB, 0 }, { "sorted_tok", RAD_OPD_IN, 0 }, { "expert_offset", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; -static const RadParamSpec pMoeGemm[] = { P_INT("n_expert"), P_INT("top_k") }; +static const RadParamSpec pMoeGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), + P_INT("top_k"), P_STR("a_order"), P_STR("dtype") }; static const RadParamSpec pGdnRecurrent[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"), P_INTO("n_head_v"), P_F64O("scale"), P_F64O("eps"), @@ -362,14 +377,14 @@ static const RadOperandSpec oGdnRecurrent[] = { { "q", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 0 }, { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, - { "A_log", RAD_OPD_IN, 0 }, - { "dt_bias", RAD_OPD_IN, 0 }, + { "A_log", RAD_OPD_WEIGHT, 0 }, + { "dt_bias", RAD_OPD_WEIGHT, 0 }, { "state", RAD_OPD_INOUT, 0 }, { "state_idx", RAD_OPD_IN, 0 }, - { "num_accepted", RAD_OPD_IN, 1 }, + { "num_accepted", RAD_OPD_IN, 0 }, { "cu", RAD_OPD_IN, 0 }, { "z", RAD_OPD_IN, 1 }, - { "norm_w", RAD_OPD_IN, 1 }, + { "norm_w", RAD_OPD_WEIGHT, 1 }, { "o", RAD_OPD_OUT, 0 }, { "o_q", RAD_OPD_OUT, 1 }, { "o_scale", RAD_OPD_OUT, 1 } }; @@ -1183,13 +1198,16 @@ static const RadConstraint cMoeGemmMxfp4[] = { C_IN("dtype", "mxfp4a8"), C_GE("n C_GE("top_k", 1) }; static const RadConstraint cMoeGather[] = { C_GE("M", 1), C_GE("n", 1), C_GE("top_k", 1), C_IN("dtype", "bf16") }; +/* No constraint on `n_local`: it is optional, and a band that leaves it out (every expert local) + * would not resolve to a row that constrains it; the kernel reads it absent as `n_expert`. */ static const RadConstraint cRouterTopkScatter[] = { C_GE("M", 1), C_GE("n_expert", 1), - C_GE("top_k", 1), C_GE("n_local", 1), - C_LE("n_expert", 512), C_IN("dtype", "bf16") }; + C_GE("top_k", 1), C_LE("n_expert", 512), + C_IN("dtype", "bf16") }; static const RadConstraint cRouterSigmoid[] = { C_GE("M", 1), C_GE("n_expert", 1), C_GE("top_k", 1), C_LE("n_expert", 512), C_IN("dtype", "bf16") }; -static const RadConstraint cMoeGemmBf16[] = { C_GE("n_expert", 1), C_GE("top_k", 1) }; +static const RadConstraint cMoeGemmBf16[] = { C_IN("dtype", "bf16"), C_GE("n_expert", 1), + C_GE("top_k", 1) }; /* The vocabulary projection has no `dtype` constraint because its band carries no `dtype` key: the * head's dtype is a property of the weight (libref checks it with a `check_dtypes` hook). A * constraint on a key the band lacks does not hold, which would leave only the host kernel and the @@ -1882,14 +1900,12 @@ static const RadKernelInfo kKernels[] = { */ { "gdn_kkt_solve_c64", "gdn_kkt_solve", "gdn", "A = (I + strict_lower(diag(beta) K K^T e^{g_i - g_j}))^-1 per 64-chunk of a gated delta net", - "head_k 128, chunk 64, H a multiple of head groups; the gram is computed once per k head and " - "scaled per v head, the inverse blocked 16 -> 32 -> 64 with the 16-blocks by fp32 forward " - "substitution and the merges by the card's 16x16x16 wave matrix", - "bf16 k and A, f32 beta and g, i32 cu; the padding rows and columns are masked to -inf so a " - "partial last chunk's NaN cannot ride the WMMA merges into live rows", + "head_k 128, chunk 64, varlen; one gram per k head, applied to every v head of the group, the " + "inverse blocked 16 -> 32 -> 64 on the wave matrix (libhalo's kernel, r3dh_gdn_kkt_solve.hip)", + "bf16 k and A, f32 beta, g, gram and inverse, i32 cu", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cGdnKktC64), NOTUNE, - nullptr, nullptr, r3d_rad_gdn_kkt_solve, + nullptr, nullptr, r3dh_rad_gdn_kkt_solve, nullptr, nullptr, nullptr, nullptr, nullptr }, @@ -1906,11 +1922,10 @@ static const RadKernelInfo kKernels[] = { "accumulators across the chunk loop, so only q, k, v, A, g, beta, the state cache and o " "touch HBM; two workgroups per v head each carry 64 of the v dimension", "bf16 q, k, v, A and o, f32 g and beta, f32 or f16 state cache (the operand's dtype), i32 cu " - "and the optional state slot index; a row's slot comes from the cache manager, not the batch " - "position, and a padded row owns no state", + "and the optional state slot index (libhalo's kernel, r3dh_gdn_chunk_scan.hip)", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cGdnChunkScanC64), NOTUNE, - nullptr, nullptr, r3d_rad_gdn_chunk_scan, + nullptr, nullptr, r3dh_rad_gdn_chunk_scan, nullptr, nullptr, nullptr, nullptr, nullptr }, @@ -2029,14 +2044,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr }, { "moe_scatter_small", "moe_scatter", "moe", - "The routed slots' stable counting sort (the small form, one workgroup)", - "histogram in LDS, an exclusive prefix over the expert counts, each slot placed by its rank " - "inside its expert's run; T <= 1024", + "The routed slots' stable counting sort", + "up to 1024 slots one workgroup (histogram in LDS, an exclusive prefix over the expert counts, " + "each slot placed by its rank inside its expert's run); above, three passes over 256-slot tiles " + "(histogram, scan across tiles, placement) with the per-tile counts in scratch", "i32 expert_ids, sorted_tok, expert_offset, expert_count; n_expert <= 512", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cMoeScatter), NOTUNE, nullptr, nullptr, r3d_rad_moe_scatter, - nullptr, nullptr, nullptr, + r3d_rad_moe_scatter_scratch, nullptr, nullptr, nullptr, nullptr }, /* ------------------------------------------------------------------ r3d_moe_gather.hip */ @@ -2069,10 +2085,9 @@ static const RadKernelInfo kKernels[] = { "table); 2 = the 16x128 block, the E4M3 operands widened exactly to f16 and the F32 scales " "folded in f32 per 128 of K. All arms run the f16 wave-matrix (f32 accumulate) and walk the runs " "in the block's 16 rows, so a block spanning several experts (short runs) is correct; the even " - "experts are `w` / `w_scale`, the odd `w_odd` / `w_odd_scale`, at index e/2", - "E4M3 a and the weight tables, f32 a_scale per (row, 128 of K), f32 w_scale per (grid_rows " - "columns, 128 of K); K % 128; grid_rows 1 (w4a8's per-row) or 128 (fp8a8's per-128x128 tile); " - "y f32 in sorted order", + "experts are entry e/2 of `w` / `w_scale`, the odd of `w_odd` / `w_odd_scale`", + "E4M3 a and the weight tables, f32 a_scale per (row, 128 of K), f32 w_scale per 128x128 tile; " + "K % 128; equal classes (N_odd = N, K_odd = K); token or sorted a; y bf16 in sorted order", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cMoeGemmQ), tMoeGemmQ, NELEM(tMoeGemmQ), moe_q_tune_valid, nullptr, nullptr, r3d_rad_moe_gemm_q, @@ -2086,9 +2101,10 @@ static const RadKernelInfo kKernels[] = { "of sorted row i", "16x16 tiles through LDS, the bf16 operands staged and loaded straight into the bf16 wave-matrix " "fragments (f32 accumulate over the whole of K); the block walks the runs in its 16 rows, so a " - "block spanning several experts (short runs) is correct; the weight is the checkpoint's own bytes " - "([n_expert, N, K] row-major, no layout hook)", - "bf16 a and w, bf16 y in sorted order; K a multiple of 64, the N tail clamped", + "block spanning several experts (short runs) is correct; the weight is a table of the " + "checkpoint's own [N, K] row-major planes (no layout hook)", + "bf16 a and w, bf16 y in sorted order; token or sorted a; K a multiple of 64, the N tail " + "clamped", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cMoeGemmBf16), tMoeGemmBf16, NELEM(tMoeGemmBf16), moe_bf16_tune_valid, nullptr, nullptr, r3d_rad_moe_gemm_bf16, @@ -2101,10 +2117,10 @@ static const RadKernelInfo kKernels[] = { "expert of sorted row i", "16x16 tiles through LDS; the E4M3 activation and the E2M1 weight (decoded exactly to E4M3) " "upcast to f16 in registers, the f16 wave-matrix (f32 accumulate); the E8M0 weight scales fold " - "in f32 per 32 of K; the block walks the runs in its 16 rows; the even experts are `w` / " - "`w_scale`, the odd `w_odd` / `w_odd_scale`, at index e/2", + "in f32 per 32 of K; the block walks the runs in its 16 rows; the even experts are entry e/2 " + "of `w` / `w_scale`, the odd of `w_odd` / `w_odd_scale`", "E4M3 a with f32 a_scale per (row, 128 of K); E2M1 (packed, two a byte) weight tables with E8M0 " - "w_scale per (grid_rows columns, 32 of K); K % 128; y bf16 in sorted order", + "w_scale per (row, 32 of K); K % 128; equal classes; token or sorted a; y bf16 in sorted order", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cMoeGemmMxfp4), NOTUNE, nullptr, nullptr, r3d_rad_moe_gemm_mxfp4a8, @@ -2120,13 +2136,14 @@ static const RadKernelInfo kKernels[] = { { "gdn_recurrent_update_k128_v128", "gdn_recurrent_update", "gdn", "The gated-delta-net recurrent state update at decode: S *= e^g, u = beta (v - S k), S += u k^T, " "o = S q per token", - "head_k 128, head_v 128, fp32 state cache; the state stays in registers, one thread per v row " - "and half its k range; the gated RMS norm is folded in when z and norm_w are present", - "bf16 q, k, v, o and a/b (or f32 a/b), f32 A_log, dt_bias and the state cache; `state_idx` the " - "per-token slot, `num_accepted` the window offset", + "head_k 128, head_v 128, paged state in either form: per_candidate (one state per candidate " + "token) or anchor (one committed state and a replay scratch slot a sequence); the gated RMS " + "norm folded in when z and norm_w are present (libhalo's kernel, r3dh_gdn_recurrent_update.hip)", + "bf16 q, k, v and o, f32 a/b, A_log and dt_bias; the state cache is f32 or f16 and the operand " + "says which", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cGdnRecurrent), NOTUNE, - nullptr, nullptr, r3d_rad_gdn_recurrent_update, + nullptr, nullptr, r3dh_rad_gdn_recurrent_update, nullptr, nullptr, nullptr, nullptr, nullptr }, @@ -2752,3 +2769,33 @@ static const RadPluginInfo kInfo = { extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } RAD_PLUGIN_ABI_LAYOUT_EXPORT extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } + +/* libr3d declines a machine with no gfx11 card. The loader would leave its device rows out there + * (no code object fits), but rad-convert and the other tools resolve kernels without that check, + * and libr3d, ahead of libr4d in file-name order, would choose the stored form of every weight it + * has a row for: an RDNA4 container laid out for RDNA3 kernels, or one weight wanted in two forms. + * + * The test reads the KFD topology (gfx_target_version 110000..119999 is the gfx11 family) rather + * than asking a runtime, which open must not initialise. KFD lists only the cards the process may + * open, so a container without /dev/kfd sees the CPU node alone; with no topology at all there is + * no card, and the library declines too. */ +extern "C" int rad_plugin_open(void) { + const char* root = "/sys/class/kfd/kfd/topology/nodes"; + DIR* d = opendir(root); + if (!d) return RAD_E_UNSUPPORTED; + bool gfx11 = false; + while (const dirent* e = readdir(d)) { + if (e->d_name[0] == '.') continue; + const std::string path = std::string(root) + "/" + e->d_name + "/properties"; + FILE* f = std::fopen(path.c_str(), "r"); + if (!f) continue; + char key[64]; + unsigned long long v = 0; + while (std::fscanf(f, "%63s %llu", key, &v) == 2) + if (!std::strcmp(key, "gfx_target_version") && v >= 110000ull && v < 120000ull) + gfx11 = true; + std::fclose(f); + } + closedir(d); + return gfx11 ? RAD_OK : RAD_E_UNSUPPORTED; +} diff --git a/libr3d/r3d_selftest.cpp b/libr3d/r3d_selftest.cpp index bbdb99b2..e363ea7a 100644 --- a/libr3d/r3d_selftest.cpp +++ b/libr3d/r3d_selftest.cpp @@ -1774,16 +1774,23 @@ static int build_moe_scatter(Case& c, const RadOpSchema* s) { return 0; } +/* moe_gemm_q at fp8a8f32 (the e4m3 row's dtype): E4M3 activation and experts, an f32 scale per + * (row, 128 of K) and per 128x128 tile of each expert, the even/odd weight tables stacked, y bf16. */ static int build_moe_gemm_q(Case& c, const RadOpSchema* s) { - const long long M = 8, N = 128, K = 128, NE = 8, TK = 2, GR = 1; // T = 16; N % 128 - const long long T = M * TK, NE0 = (NE + 1) / 2, NE1 = NE / 2; - if (s->n_operands != 9) { fail("moe_gemm_q: the schema has %d operands, not 9", - s->n_operands); return 1; } + constexpr int NOPD = 9; + const long long M = 8, N = 128, K = 128, NE = 8, TK = 2; // T = 16; N % 128 + const long long T = M * TK, NE0 = (NE + 1) / 2, NE1 = NE / 2, NB = (N + 127) / 128; + if (s->n_operands != NOPD) { fail("moe_gemm_q: the schema has %d operands, not 9", + s->n_operands); return 1; } c.n_p = 0; - const RadParam pp[] = { { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + const RadParam pp[] = { { "M", RAD_P_INT, T, 0, nullptr, 0.0 }, + { "N", RAD_P_INT, N, 0, nullptr, 0.0 }, + { "K", RAD_P_INT, K, 0, nullptr, 0.0 }, + { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, - { "grid_rows", RAD_P_INT, GR, 0, nullptr, 0.0 }, - { "dtype", RAD_P_STR, 0, 0, (const char*)"w4a8", 0.0 } }; + { "group", RAD_P_INT, 128, 0, nullptr, 0.0 }, + { "a_order", RAD_P_STR, 0, 0, (const char*)"token", 0.0 }, + { "dtype", RAD_P_STR, 0, 0, (const char*)"fp8a8f32", 0.0 } }; for (const RadParam& q : pp) c.p[c.n_p++] = q; uint32_t st = 0x0E0E5A1Cu; @@ -1795,8 +1802,8 @@ static int build_moe_gemm_q(Case& c, const RadOpSchema* s) { for (auto& x : ha) x = re4(); for (auto& x : hw0) x = re4(); for (auto& x : hw1) x = re4(); - std::vector hA((size_t)M * (K / 128)), hW0((size_t)NE0 * (N / GR) * (K / 128)), - hW1((size_t)NE1 * (N / GR) * (K / 128)); + std::vector hA((size_t)M * (K / 128)), hW0((size_t)NE0 * NB * (K / 128)), + hW1((size_t)NE1 * NB * (K / 128)); for (auto& x : hA) x = rndf(); for (auto& x : hW0) x = rndf(); for (auto& x : hW1) x = rndf(); @@ -1805,21 +1812,22 @@ static int build_moe_gemm_q(Case& c, const RadOpSchema* s) { for (long long e = 0; e < NE; ++e) ho[e] = (int32_t)(e * (T / NE)); ho[NE] = (int32_t)T; - struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[9] = { + // The contract's order: a, a_scale, w, w_scale, sorted_tok, expert_offset, w_odd, w_odd_scale, y. + struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[NOPD] = { { RAD_F8E4M3, 2, { M, K, 1 }, M * K }, { RAD_F32, 2, { M, K / 128, 1 }, M * (K / 128) }, + { RAD_F8E4M3, 3, { NE0, N, K }, NE0 * N * K }, + { RAD_F32, 3, { NE0, NB, K / 128 }, NE0 * NB * (K / 128) }, { RAD_I32, 1, { T, 1, 1 }, T }, { RAD_I32, 1, { NE + 1, 1, 1 }, NE + 1 }, - { RAD_F8E4M3, 3, { NE0, N, K }, NE0 * N * K }, - { RAD_F32, 3, { NE0, N / GR, K / 128 }, NE0 * (N / GR) * (K / 128) }, { RAD_F8E4M3, 3, { NE1, N, K }, NE1 * N * K }, - { RAD_F32, 3, { NE1, N / GR, K / 128 }, NE1 * (N / GR) * (K / 128) }, - { RAD_F32, 2, { T, N, 1 }, T * N } }; - const uint32_t bytes_of[] = { 1, 4, 4, 4, 1, 4, 1, 4, 4 }; - const void* src[] = { ha.data(), hA.data(), hs.data(), ho.data(), hw0.data(), hW0.data(), - hw1.data(), hW1.data(), nullptr }; - for (int o = 0; o < 9; ++o) { - const size_t bytes = (size_t)qd[o].nel * bytes_of[o]; + { RAD_F32, 3, { NE1, NB, K / 128 }, NE1 * NB * (K / 128) }, + { RAD_BF16, 2, { T, N, 1 }, T * N } }; + const uint32_t bits_of[NOPD] = { 8, 32, 8, 32, 32, 32, 8, 32, 16 }; + const void* src[NOPD] = { ha.data(), hA.data(), hw0.data(), hW0.data(), hs.data(), ho.data(), + hw1.data(), hW1.data(), nullptr }; + for (int o = 0; o < NOPD; ++o) { + const size_t bytes = (size_t)((qd[o].nel * bits_of[o] + 7) / 8); void* d = nullptr; if (hipMalloc(&d, bytes) != hipSuccess) { fail("moe_gemm_q: hipMalloc(%zu) failed", bytes); return 1; } @@ -1835,13 +1843,19 @@ static int build_moe_gemm_q(Case& c, const RadOpSchema* s) { } static int build_moe_gemm_bf16(Case& c, const RadOpSchema* s) { + constexpr int NOPD = 5; const long long M = 8, N = 128, K = 64, NE = 8, TK = 2; // T = 16; N % 128, K % 64 const long long T = M * TK; - if (s->n_operands != 5) { fail("moe_gemm_bf16: the schema has %d operands, not 5", - s->n_operands); return 1; } + if (s->n_operands != NOPD) { fail("moe_gemm_bf16: the schema has %d operands, not 5", + s->n_operands); return 1; } c.n_p = 0; - const RadParam pp[] = { { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, - { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 } }; + const RadParam pp[] = { { "M", RAD_P_INT, T, 0, nullptr, 0.0 }, + { "N", RAD_P_INT, N, 0, nullptr, 0.0 }, + { "K", RAD_P_INT, K, 0, nullptr, 0.0 }, + { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, + { "a_order", RAD_P_STR, 0, 0, (const char*)"token", 0.0 }, + { "dtype", RAD_P_STR, 0, 0, (const char*)"bf16", 0.0 } }; for (const RadParam& q : pp) c.p[c.n_p++] = q; uint32_t st = 0x1A2B3C4Du; @@ -1855,16 +1869,17 @@ static int build_moe_gemm_bf16(Case& c, const RadOpSchema* s) { for (long long e = 0; e < NE; ++e) ho[e] = (int32_t)(e * (T / NE)); ho[NE] = (int32_t)T; - struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[5] = { + // The contract's order: a, w (one stacked table), sorted_tok, expert_offset, y. + struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[NOPD] = { { RAD_BF16, 2, { M, K, 1 }, M * K }, { RAD_BF16, 3, { NE, N, K }, NE * N * K }, { RAD_I32, 1, { T, 1, 1 }, T }, { RAD_I32, 1, { NE + 1, 1, 1 }, NE + 1 }, { RAD_BF16, 2, { T, N, 1 }, T * N } }; - const uint32_t bytes_of[] = { 2, 2, 4, 4, 2 }; - const void* src[] = { ha.data(), hw.data(), hs.data(), ho.data(), nullptr }; - for (int o = 0; o < 5; ++o) { - const size_t bytes = (size_t)qd[o].nel * bytes_of[o]; + const uint32_t bits_of[NOPD] = { 16, 16, 32, 32, 16 }; + const void* src[NOPD] = { ha.data(), hw.data(), hs.data(), ho.data(), nullptr }; + for (int o = 0; o < NOPD; ++o) { + const size_t bytes = (size_t)((qd[o].nel * bits_of[o] + 7) / 8); void* d = nullptr; if (hipMalloc(&d, bytes) != hipSuccess) { fail("moe_gemm_bf16: hipMalloc(%zu) failed", bytes); return 1; } @@ -1879,15 +1894,22 @@ static int build_moe_gemm_bf16(Case& c, const RadOpSchema* s) { return 0; } +/* moe_gemm_q at mxfp4a8: E4M3 activation with an f32 scale per (row, 128 of K); E2M1 experts (two + * codes a byte, shaped in codes) with an E8M0 exponent per (row, 32 of K), typed raw u8; y bf16. */ static int build_moe_gemm_mxfp4a8(Case& c, const RadOpSchema* s) { - const long long M = 8, N = 128, K = 128, NE = 8, TK = 2, GR = 1; // T = 16; N % 128 + constexpr int NOPD = 9; + const long long M = 8, N = 128, K = 128, NE = 8, TK = 2; // T = 16; N % 128 const long long T = M * TK, NE0 = (NE + 1) / 2, NE1 = NE / 2; - if (s->n_operands != 9) { fail("moe_gemm_mxfp4a8: the schema has %d operands, not 9", - s->n_operands); return 1; } + if (s->n_operands != NOPD) { fail("moe_gemm_mxfp4a8: the schema has %d operands, not 9", + s->n_operands); return 1; } c.n_p = 0; - const RadParam pp[] = { { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + const RadParam pp[] = { { "M", RAD_P_INT, T, 0, nullptr, 0.0 }, + { "N", RAD_P_INT, N, 0, nullptr, 0.0 }, + { "K", RAD_P_INT, K, 0, nullptr, 0.0 }, + { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, - { "grid_rows", RAD_P_INT, GR, 0, nullptr, 0.0 }, + { "group", RAD_P_INT, 128, 0, nullptr, 0.0 }, + { "a_order", RAD_P_STR, 0, 0, (const char*)"token", 0.0 }, { "dtype", RAD_P_STR, 0, 0, (const char*)"mxfp4a8", 0.0 } }; for (const RadParam& q : pp) c.p[c.n_p++] = q; @@ -1895,15 +1917,14 @@ static int build_moe_gemm_mxfp4a8(Case& c, const RadOpSchema* s) { auto rnd = [&]() { st = st * 1664525u + 1013904223u; return (st >> 8) & 0xffu; }; auto rndf = [&]() { st = st * 1664525u + 1013904223u; return 0.5f + ((st >> 8) & 0xff) / 255.0f; }; auto re4 = [&]() { return (uint8_t)(((rnd() & 0x7) | 1) << 3 | (rnd() & 0x7) | ((rnd() & 1) << 7)); }; - auto re2 = [&]() { return (uint8_t)(rnd() & 0xF); }; // E2M1 code (4 bits) + auto re2x2 = [&]() { return (uint8_t)(rnd() & 0xFF); }; // two E2M1 codes auto re8 = [&]() { return (uint8_t)(120 + (rnd() & 14)); }; // E8M0 near 1.0 (exp 120..133) std::vector ha((size_t)M * K), hw0((size_t)NE0 * N * (K / 2)), hw1((size_t)NE1 * N * (K / 2)); for (auto& x : ha) x = re4(); - for (auto& x : hw0) x = re2(); - for (auto& x : hw1) x = re2(); + for (auto& x : hw0) x = re2x2(); + for (auto& x : hw1) x = re2x2(); std::vector hA((size_t)M * (K / 128)); - std::vector hW0((size_t)NE0 * (N / GR) * (K / 32)), - hW1((size_t)NE1 * (N / GR) * (K / 32)); + std::vector hW0((size_t)NE0 * N * (K / 32)), hW1((size_t)NE1 * N * (K / 32)); for (auto& x : hA) x = rndf(); for (auto& x : hW0) x = re8(); for (auto& x : hW1) x = re8(); @@ -1912,21 +1933,22 @@ static int build_moe_gemm_mxfp4a8(Case& c, const RadOpSchema* s) { for (long long e = 0; e < NE; ++e) ho[e] = (int32_t)(e * (T / NE)); ho[NE] = (int32_t)T; - struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[9] = { + // The contract's order: a, a_scale, w, w_scale, sorted_tok, expert_offset, w_odd, w_odd_scale, y. + struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[NOPD] = { { RAD_F8E4M3, 2, { M, K, 1 }, M * K }, { RAD_F32, 2, { M, K / 128, 1 }, M * (K / 128) }, + { RAD_FP4E2M1, 3, { NE0, N, K }, NE0 * N * K }, + { RAD_U8, 3, { NE0, N, K / 32 }, NE0 * N * (K / 32) }, { RAD_I32, 1, { T, 1, 1 }, T }, { RAD_I32, 1, { NE + 1, 1, 1 }, NE + 1 }, - { RAD_FP4E2M1, 3, { NE0, N, K / 2 }, NE0 * N * (K / 2) }, - { RAD_U8, 3, { NE0, N / GR, K / 32 }, NE0 * (N / GR) * (K / 32) }, - { RAD_FP4E2M1, 3, { NE1, N, K / 2 }, NE1 * N * (K / 2) }, - { RAD_U8, 3, { NE1, N / GR, K / 32 }, NE1 * (N / GR) * (K / 32) }, + { RAD_FP4E2M1, 3, { NE1, N, K }, NE1 * N * K }, + { RAD_U8, 3, { NE1, N, K / 32 }, NE1 * N * (K / 32) }, { RAD_BF16, 2, { T, N, 1 }, T * N } }; - const uint32_t bytes_of[] = { 1, 4, 4, 4, 1, 1, 1, 1, 2 }; - const void* src[] = { ha.data(), hA.data(), hs.data(), ho.data(), hw0.data(), hW0.data(), - hw1.data(), hW1.data(), nullptr }; - for (int o = 0; o < 9; ++o) { - const size_t bytes = (size_t)qd[o].nel * bytes_of[o]; + const uint32_t bits_of[NOPD] = { 8, 32, 4, 8, 32, 32, 4, 8, 16 }; + const void* src[NOPD] = { ha.data(), hA.data(), hw0.data(), hW0.data(), hs.data(), ho.data(), + hw1.data(), hW1.data(), nullptr }; + for (int o = 0; o < NOPD; ++o) { + const size_t bytes = (size_t)((qd[o].nel * bits_of[o] + 7) / 8); void* d = nullptr; if (hipMalloc(&d, bytes) != hipSuccess) { fail("moe_gemm_mxfp4a8: hipMalloc(%zu) failed", bytes); return 1; } @@ -1995,6 +2017,7 @@ static int build_moe_router_sigmoid(Case& c, const RadOpSchema* s) { const RadParam pp[] = { { "M", RAD_P_INT, M, 0, nullptr, 0.0 }, { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, + { "norm", RAD_P_INT, 1, 0, nullptr, 0.0 }, { "route_scale", RAD_P_F64, 0, 0, nullptr, 1.0 }, { "dtype", RAD_P_STR, 0, 0, (const char*)"bf16", 0.0 } }; for (const RadParam& q : pp) c.p[c.n_p++] = q; @@ -2090,7 +2113,8 @@ static int build_gdn_recurrent(Case& c, const RadOpSchema* s) { c.n_p = 0; const RadParam pp[] = { { "q_len", RAD_P_INT, T, 0, nullptr, 0.0 }, { "head_k", RAD_P_INT, K, 0, nullptr, 0.0 }, - { "head_v", RAD_P_INT, V, 0, nullptr, 0.0 } }; + { "head_v", RAD_P_INT, V, 0, nullptr, 0.0 }, + { "eps", RAD_P_F64, 0, 0, nullptr, 1e-6 } }; for (const RadParam& q : pp) c.p[c.n_p++] = q; uint32_t st = 0x4A7B2C9Du; @@ -2111,7 +2135,9 @@ static int build_gdn_recurrent(Case& c, const RadOpSchema* s) { for (auto& x : hnw) x = (rndf() - 0.5f) * 2.0f; std::vector ho(T*H*V, 0x7fc0u); const int sidxv[T] = { 0, 0, 1, 1 }; - const int nav[1] = { 0 }; + /* num_accepted counts from 1 (docs/OPS.md): the window's history is read at column + * num_accepted - 1, so 1 is the handover out of a prefill. */ + const int nav[1] = { 1 }; const int cuv[2] = { 0, (int)T }; struct { uint32_t dt; long long nel; } qd[16] = { @@ -2478,6 +2504,278 @@ launched: } /* ================================================================== main */ +/* ================================================================== the grouped GEMMs, by value + * + * The row cases above check that each MoE GEMM runs and writes finite planes; this checks what it + * writes. A routed batch (random ids, some outside the local slice and so dropped, stably sorted + * by expert as moe_scatter sorts them) runs through moe_gemm at bf16 and moe_gemm_q at fp8a8f32 + * (every impl arm) and mxfp4a8, in both a_orders, with the experts as the engine hands them: a + * device table of one pointer per expert (stride[0] 0), even and odd experts in separate classes. + * N is not a multiple of the 128-column block, so the tail block is checked too. The reference is + * libref's arithmetic on the host (the products exact, the sums in double); a dropped row must be + * zero. Agreement is the relative L2 error over y, as rad-kbench measures it. + */ +#ifdef RAD_HAVE_HIP +namespace moenum { + +struct Dev { + std::vector p; + ~Dev() { for (void* x : p) hipFree(x); } + void* put(const void* h, size_t n) { + void* d = nullptr; + if (hipMalloc(&d, n ? n : 4) != hipSuccess) return nullptr; + p.push_back(d); + if (h && n) hipMemcpy(d, h, n, hipMemcpyHostToDevice); + else hipMemset(d, 0, n ? n : 4); + return d; + } +}; + +RadTensor dense(void* d, uint32_t dt, long long r, long long c) { + RadTensor t{}; + t.data = d; t.dtype = dt; t.rank = 2; + t.shape[0] = r; t.shape[1] = c; t.stride[0] = c; t.stride[1] = 1; + return t; +} +RadTensor vec(void* d, uint32_t dt, long long n) { + RadTensor t{}; + t.data = d; t.dtype = dt; t.rank = 1; t.shape[0] = n; t.stride[0] = 1; + return t; +} +/* A weight table of `n` entries, each [rows, cols] (cols in elements): the device array of + * pointers the core builds for a run of separately placed experts. */ +RadTensor table(Dev& dv, const std::vector>& ent, uint32_t dt, long long rows, + long long cols) { + std::vector ptr; + for (const auto& e : ent) ptr.push_back(dv.put(e.data(), e.size())); + if (ptr.empty()) ptr.push_back(dv.put(nullptr, 64)); + RadTensor t{}; + t.data = dv.put(ptr.data(), ptr.size() * sizeof(void*)); + t.dtype = dt; t.rank = 3; + t.shape[0] = (long long)ent.size(); t.shape[1] = rows; t.shape[2] = cols; + t.stride[0] = 0; t.stride[1] = cols; t.stride[2] = 1; + return t; +} + +struct Route { + std::vector sorted, off; + long long T = 0; +}; +/* Each token picks top_k distinct experts out of ne + 1, the last meaning "not on this rank": + * those slots are dropped, sorted to the tail as -1. */ +Route route(long long M, long long top_k, long long ne, uint32_t& st) { + auto rnd = [&]() { st = st * 1664525u + 1013904223u; return st >> 8; }; + Route r; + r.T = M * top_k; + std::vector ids(r.T); + for (long long t = 0; t < M; ++t) + for (long long j = 0; j < top_k; ++j) { + int32_t e; + bool dup; + do { + e = (int32_t)(rnd() % (uint32_t)(ne + 1)); + dup = false; + for (long long q = 0; q < j; ++q) dup |= ids[t * top_k + q] == e; + } while (dup); + ids[t * top_k + j] = e; + } + r.off.assign(ne + 1, 0); + for (int32_t e = 0; e < ne; ++e) { + r.off[e] = (int32_t)r.sorted.size(); + for (long long i = 0; i < r.T; ++i) if (ids[i] == e) r.sorted.push_back((int32_t)i); + } + r.off[ne] = (int32_t)r.sorted.size(); + while ((long long)r.sorted.size() < r.T) r.sorted.push_back(-1); + return r; +} + +int expert_of(const Route& r, long long i, long long ne) { + for (long long e = 0; e < ne; ++e) if (r.off[e] <= i && i < r.off[e + 1]) return (int)e; + return -1; +} + +void compare(const char* what, const std::vector& ref, const std::vector& y, + double tol) { + double num = 0, den = 0, worst_zero = 0; + for (size_t i = 0; i < ref.size(); ++i) { + const double v = bf16_to_f32(y[i]); + num += (v - ref[i]) * (v - ref[i]); + den += ref[i] * ref[i]; + if (ref[i] == 0.0) worst_zero = std::max(worst_zero, std::fabs(v)); + } + const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num); + if (rel <= tol && worst_zero == 0.0) ok("%s: rel_l2 %.2e", what, rel); + else fail("%s: rel_l2 %.2e (tolerance %.0e), a dropped row's largest |y| %.3g", what, rel, tol, + worst_zero); +} + +RadParam pi(const char* k, long long v) { return RadParam{ k, RAD_P_INT, v, 0, nullptr, 0.0 }; } +RadParam ps(const char* k, const char* v) { return RadParam{ k, RAD_P_STR, 0, 0, v, 0.0 }; } + +typedef int (*Launch)(const RadArgs*, RadStream); + +} // namespace moenum +#endif + +static void check_moe_numerics() { + std::printf("== the grouped GEMMs, by value\n"); +#ifndef RAD_HAVE_HIP + skip("built without HIP: the grouped GEMMs are not run"); +#else + using namespace moenum; + auto bf16_launch = (Launch)dlsym(g_h, "r3d_rad_moe_gemm_bf16"); + auto q_launch = (Launch)dlsym(g_h, "r3d_rad_moe_gemm_q"); + auto mx_launch = (Launch)dlsym(g_h, "r3d_rad_moe_gemm_mxfp4a8"); + if (!bf16_launch || !q_launch || !mx_launch) { + fail("a grouped GEMM entry point is missing"); + return; + } + + const long long M = 12, TK = 2, NE = 6, N = 192; + for (int sorted_a = 0; sorted_a < 2; ++sorted_a) { + const char* order = sorted_a ? "sorted" : "token"; + uint32_t st = 0x5EED0000u + (uint32_t)sorted_a; + const Route r = route(M, TK, NE, st); + const long long T = r.T, AR = sorted_a ? T : M; + auto rndf = [&]() { + st = st * 1664525u + 1013904223u; + return ((st >> 8) & 0xffffu) / 65536.0f - 0.5f; + }; + auto rnd8 = [&]() { st = st * 1664525u + 1013904223u; return (uint8_t)(st >> 16); }; + /* An E4M3 code in the normal range (exponent 1..14), either sign. */ + auto e4 = [&]() { + return (uint8_t)(((rnd8() & 0x7) | 1) << 3 | (rnd8() & 0x7) | ((rnd8() & 1) << 7)); + }; + auto tok_of = [&](long long i) { return sorted_a ? i : r.sorted[i] / TK; }; + + /* ---- moe_gemm, bf16 experts in one class. */ + { + const long long K = 128; + Dev dv; + std::vector ha(AR * K); + for (auto& x : ha) x = f32_to_bf16(rndf()); + std::vector> we(NE, std::vector(N * K * 2)); + for (auto& e : we) for (long long q = 0; q < N * K; ++q) { + const uint16_t b = f32_to_bf16(rndf()); + std::memcpy(&e[q * 2], &b, 2); + } + RadTensor t[5] = { dense(dv.put(ha.data(), ha.size() * 2), RAD_BF16, AR, K), + table(dv, we, RAD_BF16, N, K), + vec(dv.put(r.sorted.data(), T * 4), RAD_I32, T), + vec(dv.put(r.off.data(), (NE + 1) * 4), RAD_I32, NE + 1), + dense(dv.put(nullptr, T * N * 2), RAD_BF16, T, N) }; + const RadParam p[] = { pi("M", T), pi("N", N), pi("K", K), pi("n_expert", NE), + pi("top_k", TK), ps("a_order", order), ps("dtype", "bf16") }; + RadArgs a{ t, 5, p, (int)(sizeof(p) / sizeof(p[0])), nullptr, 0, nullptr, 0, 1 }; + const int rc = bf16_launch(&a, nullptr); + std::vector y(T * N); + hipDeviceSynchronize(); + hipMemcpy(y.data(), t[4].data, y.size() * 2, hipMemcpyDeviceToHost); + std::vector ref(T * N, 0.0); + for (long long i = 0; i < T; ++i) { + const int e = expert_of(r, i, NE); + if (e < 0) continue; + for (long long n = 0; n < N; ++n) { + double acc = 0; + for (long long k = 0; k < K; ++k) { + uint16_t w; std::memcpy(&w, &we[e][(n * K + k) * 2], 2); + acc += (double)bf16_to_f32(ha[tok_of(i) * K + k]) * bf16_to_f32(w); + } + ref[i * N + n] = acc; + } + } + std::string what = std::string("moe_gemm bf16, a_order ") + order; + if (rc != 0) fail("%s: the launch returned %d", what.c_str(), rc); + else compare(what.c_str(), ref, y, 1e-2); + } + + /* ---- moe_gemm_q at fp8a8f32 (every impl arm) and mxfp4a8: the even and odd classes. */ + for (int mx = 0; mx < 2; ++mx) { + const long long K = 256, NB = (N + 127) / 128; + Dev dv; + std::vector ha(AR * K); + std::vector has(AR * (K / 128)); + for (auto& x : ha) x = e4(); + for (auto& x : has) x = 0.25f + std::fabs(rndf()); + /* Expert e's codes and scales, and their values for the reference. */ + const long long wbytes = mx ? N * K / 2 : N * K; + const long long scols = mx ? K / 32 : K / 128, srows = mx ? N : NB; + std::vector> wc(NE, std::vector(wbytes)), + ws(NE, std::vector(srows * scols * (mx ? 1 : 4))); + for (long long e = 0; e < NE; ++e) { + for (auto& x : wc[e]) x = mx ? rnd8() : e4(); + for (long long q = 0; q < srows * scols; ++q) { + if (mx) { + ws[e][q] = (uint8_t)(120 + (rnd8() & 15)); + } else { + const float f = 0.25f + std::fabs(rndf()); + std::memcpy(&ws[e][q * 4], &f, 4); + } + } + } + auto wval = [&](int e, long long n, long long k) -> double { + if (!mx) { + float sc; std::memcpy(&sc, &ws[e][((n / 128) * scols + k / 128) * 4], 4); + return (double)e4m3_to_f32(wc[e][n * K + k]) * sc; + } + static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f }; + const uint8_t b = wc[e][(n * K + k) / 2]; + const uint8_t nib = (k & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf); + const double v = (nib & 8) ? -kMag[nib & 7] : kMag[nib & 7]; + return v * std::ldexp(1.0, (int)ws[e][n * scols + k / 32] - 127); + }; + std::vector ref(T * N, 0.0); + for (long long i = 0; i < T; ++i) { + const int e = expert_of(r, i, NE); + if (e < 0) continue; + const long long tk = tok_of(i); + for (long long n = 0; n < N; ++n) { + double acc = 0; + for (long long k = 0; k < K; ++k) + acc += (double)e4m3_to_f32(ha[tk * K + k]) * has[tk * (K / 128) + k / 128] * + wval(e, n, k); + ref[i * N + n] = acc; + } + } + std::vector> wc0, wc1, ws0, ws1; + for (long long e = 0; e < NE; ++e) { + (e % 2 ? wc1 : wc0).push_back(wc[e]); + (e % 2 ? ws1 : ws0).push_back(ws[e]); + } + const uint32_t wdt = mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3; + const uint32_t sdt = mx ? (uint32_t)RAD_U8 : (uint32_t)RAD_F32; + RadTensor t[9] = { dense(dv.put(ha.data(), ha.size()), RAD_F8E4M3, AR, K), + dense(dv.put(has.data(), has.size() * 4), RAD_F32, AR, K / 128), + table(dv, wc0, wdt, N, K), table(dv, ws0, sdt, srows, scols), + vec(dv.put(r.sorted.data(), T * 4), RAD_I32, T), + vec(dv.put(r.off.data(), (NE + 1) * 4), RAD_I32, NE + 1), + table(dv, wc1, wdt, N, K), table(dv, ws1, sdt, srows, scols), + dense(dv.put(nullptr, T * N * 2), RAD_BF16, T, N) }; + for (int impl = 0; impl < (mx ? 1 : 3); ++impl) { + /* Stale bytes, which a dropped row must not keep. */ + hipMemset(t[8].data, 0xff, T * N * 2); + const RadParam p[] = { pi("M", T), pi("N", N), pi("K", K), pi("n_expert", NE), + pi("top_k", TK), pi("group", 128), ps("a_order", order), + ps("dtype", mx ? "mxfp4a8" : "fp8a8f32"), pi("impl", impl), + pi("vgpr", 128), pi("acc", 0) }; + RadArgs a{ t, 9, p, (int)(sizeof(p) / sizeof(p[0])), nullptr, 0, nullptr, 0, 1 }; + const int rc = (mx ? mx_launch : q_launch)(&a, nullptr); + std::vector y(T * N); + hipDeviceSynchronize(); + hipMemcpy(y.data(), t[8].data, y.size() * 2, hipMemcpyDeviceToHost); + char what[96]; + std::snprintf(what, sizeof what, "moe_gemm_q %s%s, a_order %s", + mx ? "mxfp4a8" : "fp8a8f32", + mx ? "" : (impl == 0 ? " impl 0" : impl == 1 ? " impl 1" : " impl 2"), + order); + if (rc != 0) fail("%s: the launch returned %d", what, rc); + else compare(what, ref, y, 1e-2); + } + } + } +#endif +} + int main(int argc, char** argv) { /* Unbuffered stdout, so when a row dies the last line printed is the last thing that worked, * even when output goes to a file or pipe. */ @@ -2513,6 +2811,7 @@ int main(int argc, char** argv) { check_reference_schemas(); check_band_reach(); check_shapes(); + check_moe_numerics(); const int n = rows(); int passed = 0, failed = 0; diff --git a/libr3d/r3dh.h b/libr3d/r3dh.h new file mode 100644 index 00000000..fea10dc3 --- /dev/null +++ b/libr3d/r3dh.h @@ -0,0 +1,59 @@ +/* r3dh.h -- the entry points of the gated-delta-net kernels ported from libhalo (libhalo/halo.h's + * gated-delta-net section, the halo_ -> r3dh_ rename): the chunk preamble, the chunked scan and the + * recurrent update. libhalo's kernels are libr4d's ported to the gfx11 wave matrix and checked + * against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged, so libr3d + * carries them for the whole family. Plain C ABI on raw device pointers and a stream; an entry + * point returns a negative code for a geometry it was not compiled for. */ +#pragma once +#include + +extern "C" { + +// ---- gated delta net ----------------------------------------------------------------------- +// One chunked scan over N variable-length sequences: the WY recompute, the recurrent state scan +// and the output in one kernel (FLA's recompute_w_u_fwd + chunk_gated_delta_rule_fwd_h + +// chunk_fwd_o). Layouts, all contiguous and bf16 unless stated: +// q,k [T, Hg, K] v,o [T, H, V] A [T, H, bt] g,beta [T, H] fp32 +// h0,ht [N, H, V, K] fp32 cu [N+1] int32 +// K, V and bt must be the compile-time 128/128/64 in the name; a mismatch returns -1. Prefill and +// chunked prefill run this; decode runs the recurrent update. +int r3dh_gdn_chunk_scan_k128_v128_c64_bf16( + const void* q, const void* k, const void* v, const void* A, + const void* g, const void* beta, const void* h0, void* o, void* ht, + const void* cu, int N, int H, int Hg, int K, int V, int bt, + float scale, int state_fp16, void* stream); +// The same scan against a slot-indexed state cache: `ssm_state_indices` [N] names each batch +// row's slot, and the two strides are the cache's, in elements. The call above is this one with a +// null index and packed [N, H, V, K] strides, which is correct only while slot == batch row. +int r3dh_gdn_chunk_scan_k128_v128_c64_bf16_sidx( + const void* q, const void* k, const void* v, const void* A, + const void* g, const void* beta, const void* h0, void* o, void* ht, + const void* cu, const void* ssm_state_indices, long indices_stride, + long state_slot_stride, long state_head_stride, + int N, int H, int Hg, int K, int V, int bt, + float scale, int state_fp16, void* stream); +void r3dh_gdn_dims(int* head_k, int* head_v, int* chunk); + +// The chunk preamble: A = (I + strict_lower(diag(beta) K K^T e^{g_i-g_j}))^-1 per chunk, i.e. +// FLA's chunk_scaled_dot_kkt_fwd then solve_tril, with the fp32 gram kept out of HBM. +// k [T,Hg,K] bf16; beta, g [T,H] fp32 (g already summed along the chunk); A [T,H,64] bf16 out; +// cu [N+1] int32. Returns -1 for a geometry it was not compiled for. +int r3dh_gdn_kkt_solve_k128_c64_bf16(const void* k, const void* beta, const void* g, void* A, + const void* cu, int N, int T, int H, int Hg, int K, int bt, + void* stream); + +// The recurrent delta-rule update decode runs: gating, the qk l2 norm, the state update and the +// output, against the paged state cache. The state is fp32 (per the model config) and one is +// written per candidate token, which dominates the cost. Replaces +// fused_sigmoid_gating_delta_rule_update. +int r3dh_gdn_recurrent_update_k128_v128_bf16_fp32state( + const void* q, const void* k, const void* v, const void* a, const void* b, + long ab_stride, int ab_is_bf16, const void* A_log, const void* dt_bias, void* state, + long state_slot_stride, long state_head_stride, void* o, void* oq, void* os, + long oq_pitch, long os_ld, const void* cu, + const void* ssm_state_indices, long indices_stride, const void* num_accepted, + const void* z_gate, long z_pitch, const void* norm_weight, float norm_eps, int norm_act, + int N, int H, int Hg, int K, int V, float scale, float softplus_thr, int state_fp16, + void* stream); + +} // extern "C" diff --git a/libr3d/r3dh_args.h b/libr3d/r3dh_args.h new file mode 100644 index 00000000..11a539be --- /dev/null +++ b/libr3d/r3dh_args.h @@ -0,0 +1,382 @@ +/* Ported from libhalo/halo_args.h, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_args.h by the libhalo rename transform (2026-10-26); + * see libhalo/README.md. Op schemas, row names and stored weight layouts are + * shared with libr4d by design. Everything else in this file is libhalo's own + * and diverges as it is measured on gfx1151. */ +/* r3dh_args.h -- how a libhalo entry point reads its arguments. + * + * There is no adapter layer. An entry point takes `(const RadArgs*, RadStream)` and returns a + * status, the same RadLaunchFn contract every other plugin implements; an out-of-tree author can + * write the same kernel without an adapter they could not reach. + * + * This header holds the shared helpers: reading a parameter, finding an operand, testing + * contiguity. Most are one line over rad_abi.h. + * + * Nothing here includes halo.h or HIP: host translation units (the row table, the layouts, the + * shape hooks) include it too, so those tables compile and can be checked without ROCm. + */ +#ifndef R3DH_ARGS_H +#define R3DH_ARGS_H + +#include "rad_abi.h" +#include "rad_plugin.h" + +#include +#include +#include +#include + +/* ================================================================== parameter access + * + * Forwards to rad_abi.h's static inline helpers, the ones a third-party plugin gets, keeping + * libhalo's spelling at its call sites. */ +static inline int r3dh_geti(const RadArgs* a, const char* k, long long* out) { + return rad_args_geti(a, k, out); +} + +static inline long long r3dh_geti_or(const RadArgs* a, const char* k, long long dflt) { + return rad_args_geti_or(a, k, dflt); +} + +static inline const char* r3dh_gets(const RadArgs* a, const char* k) { + return rad_args_gets(a, k); +} + +/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so `dval` arrives + * and the step path runs no strtod. Deliberately laxer than rad_args_getf_or: string and integer + * spellings are still read, because a tool or selftest may call a launch directly with no declare + * to enforce the type. */ +static inline double r3dh_getf(const RadArgs* a, const char* k, double dflt) { + if (!a || !k) return dflt; + for (int i = 0; i < a->n_p; ++i) { + if (!a->p[i].key || std::strcmp(a->p[i].key, k) != 0) continue; + if (a->p[i].kind == RAD_P_F64) return a->p[i].dval; + if (a->p[i].kind == RAD_P_INT) return (double)a->p[i].ival; + if (a->p[i].kind == RAD_P_STR && a->p[i].sval && a->p[i].sval[0]) { + char* end = nullptr; + const double v = std::strtod(a->p[i].sval, &end); + return (end && end != a->p[i].sval) ? v : dflt; + } + return dflt; + } + return dflt; +} + +/* An enumerated parameter: `act` is "silu" or "sigmoid", not 0 or 1, so a --debug-graph dump says + * what runs; the mapping to libhalo's integer lives in the shim. Returns -1 for an unknown name, + * which every caller turns into RAD_E_INVAL. `alt` is libhalo's own integer spelling of the same + * key (`mode` on gated_had_quant_i8), consulted only when the name is absent. */ +static inline int r3dh_act_code(const RadArgs* a, const char* key, const char* alt, int dflt) { + if (const char* s = r3dh_gets(a, key)) { + if (!std::strcmp(s, "silu") || !std::strcmp(s, "swish")) return 0; + if (!std::strcmp(s, "sigmoid")) return 1; + return -1; + } + long long v = 0; + if (alt && r3dh_geti(a, alt, &v)) return (v == 0 || v == 1) ? (int)v : -1; + return dflt; +} + +/* Same, off a bare RadParam list (init() and the layout hooks); forwards to rad_plugin.h's + * rad_param_*. */ +static inline long long r3dh_pgeti_or(const RadParam* p, int n_p, const char* k, long long dflt) { + return rad_param_geti(p, n_p, k, dflt); +} + +static inline const char* r3dh_pgets(const RadParam* p, int n_p, const char* k) { + return rad_param_gets(p, n_p, k, nullptr); +} + +/* ================================================================== operand access + * + * An absent optional operand is a null RadTensor.data (rad_abi.h). r3dh_opt() returns null both + * past the end and for a present-but-null operand, so an optional test is one pointer test. For a + * required operand the caller turns null into RAD_E_INVAL: it is a bug in the issue, not a shape + * the kernel declines. + */ +static inline const RadTensor* r3dh_opt(const RadArgs* a, int i) { return rad_arg_in(a, i); } + +static inline const void* r3dh_p(const RadTensor* t) { return t ? t->data : nullptr; } + +/* The same for an operand a kernel writes, so an output cast reads as one rather than as a + * pointer laundered through `long`. */ +static inline void* r3dh_wp(const RadTensor* t) { return t ? t->data : nullptr; } +static inline long r3dh_addr(const RadTensor* t) { return t ? (long)(uintptr_t)t->data : 0L; } + +static inline long long r3dh_dim(const RadTensor* t, int i) { + if (!t || i < 0 || (uint32_t)i >= t->rank) return 0; + return t->shape[i]; +} + +static inline long long r3dh_stride(const RadTensor* t, int i) { + if (!t || i < 0 || (uint32_t)i >= t->rank) return 0; + return t->stride[i]; +} + +static inline long long r3dh_numel(const RadTensor* t) { return rad_tensor_numel(t); } + +/* [rows..., K] flattened to (M, K). Every per-row kernel in libhalo owns whole rows (one + * workgroup per row), so the leading axes are only a row count. The GEMM makes the same fold + * explicitly (see gemm_ops). */ + +static inline int r3dh_rows_of(const RadTensor* t, long long* M, long long* K) { + if (!t || t->rank < 1) return RAD_E_SHAPE; + *K = t->shape[t->rank - 1]; + *M = 1; + for (uint32_t i = 0; i + 1 < t->rank; ++i) *M *= t->shape[i]; + return (*M >= 1 && *K >= 1) ? RAD_OK : RAD_E_SHAPE; +} + +/* Dense row-major over the whole tensor. libhalo's entry points take at most one pitch, so + * everything else must be tight, and the shim checks it. This is the "necessary condition only" + * boundary of spec §2.1: the constraint table settles geometry, contiguity is a property of the + * call. */ +static inline int r3dh_contig(const RadTensor* t) { return rad_tensor_is_contiguous(t); } + +/* Contiguous in every axis but the leading one, whose stride is the row pitch libhalo takes as an + * explicit argument (`xpitch`, `a_stride`, `xrow`, ...). Returns the pitch in elements, or -1. */ +static inline long long r3dh_row_pitch(const RadTensor* t) { + if (!t || t->rank == 0) return -1; + if (t->rank == 1) return 1; + long long acc = 1; + for (int i = (int)t->rank - 1; i >= 1; --i) { + if (t->shape[i] != 1 && t->stride[i] != acc) return -1; + acc *= t->shape[i]; + } + return t->stride[0]; +} + +/* [rows..., n] read as (rows, n): the leading axes are a row count and only the last is + * structural. Returns the pitch in elements, or -1. + * + * A column slice must refuse. k out of a fused [tok, 2*kv_dim] projection, read as + * [tok*n_head_kv, head_dim] for a per-head norm, has rows `n` apart within a token and a buffer + * row apart between tokens; no single pitch describes that, and the leading stride would make the + * consumer read most heads from garbage. So the trailing axes must cover the whole row. */ +static inline long long r3dh_rows_pitch(const RadTensor* t, long long n, long long* rows) { + if (!t || t->rank < 1 || n <= 0) return -1; + const long long nel = rad_tensor_numel(t); + if (nel % n) return -1; + *rows = nel / n; + if (t->rank == 1) return n; + if (t->shape[t->rank - 1] == n) { + if (t->stride[t->rank - 1] != 1) return -1; + return t->rank >= 2 ? t->stride[t->rank - 2] : n; + } + if (rad_tensor_is_contiguous(t)) return n; + long long trail = 1; + for (int i = 1; i < (int)t->rank; ++i) trail *= t->shape[i]; + return trail == n ? r3dh_row_pitch(t) : -1; +} + +/* An attention operand, [tokens, heads * head_dim] over its trailing axes: the token count, head + * count and row pitch in elements. False when the trailing axes are not whole heads or no single + * pitch describes the rows. */ +static inline bool r3dh_head_rows(const RadTensor* t, long long head_dim, long long* n_tok, + long long* n_head, long long* ld) { + long long width = 1; + for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i]; + if (t->rank < 2 || width % head_dim) return false; + *n_head = width / head_dim; + *ld = r3dh_rows_pitch(t, width, n_tok); + return *ld >= 0; +} + +/* 16-byte alignment, needed by every kernel that pushes over P2P or issues a global_load_b128. + * The kernels do not check it, so the shim does. */ +static inline int r3dh_aligned(const void* p, unsigned bytes) { + return p ? (((uintptr_t)p & (uintptr_t)(bytes - 1)) == 0) : 1; +} + +/* ================================================================== which check refused + * + * A shim refuses in many places with the same few codes, so the engine's report names the kernel + * and geometry but not the failing condition. R3DH_NO() wraps a refusal and prints its own line + * when RAD_HALO_TRACE is set; otherwise it is the bare return plus one cached-flag load on a path + * that is failing anyway. */ +static inline int r3dh_trace_on(void) { + static int on = -1; + if (on < 0) { const char* e = std::getenv("RAD_HALO_TRACE"); on = (e && *e && *e != '0'); } + return on; +} +static inline int r3dh_refused(int code, const char* file, int line) { + if (r3dh_trace_on()) std::fprintf(stderr, "[r4d] %s:%d refused -> %d\n", file, line, code); + return code; +} +#define R3DH_NO(code) r3dh_refused((code), __FILE__, __LINE__) + +/* ================================================================== dtype helpers */ +/* Widest world any libhalo all-reduce serves, fixed by the 8-rank entry points' argument lists + * (seven explicit peers). */ +enum { R3DH_MAX_RANKS = 8, R3DH_MAX_PEERS = 7 }; + +/* libhalo's all-reduce dtype code: 0 bf16, 1 fp16, 2 fp32. Returns -1 for anything else. */ +static inline int r3dh_ar_dtype_code(const char* s) { + if (!s) return -1; + if (!std::strcmp(s, "bf16")) return 0; + if (!std::strcmp(s, "fp16") || !std::strcmp(s, "f16")) return 1; + if (!std::strcmp(s, "fp32") || !std::strcmp(s, "f32")) return 2; + return -1; +} + +static inline int r3dh_ar_esize(int code) { return code == 2 ? 4 : 2; } + + +/* ================================================================== weight layout constants + * + * libhalo's compile-time constants, restated because r3dh_layout.cpp is host code built without + * ROCm and cannot include halo.h, and because the .rad container records them in the layout tag. + * r3dh_gemm_args.h static_asserts the group constants against libhalo's macros. + */ +enum { + R3DH_W4_GROUP = 128, /* K per (scale, zero) dword; libhalo R3DH_GEMM_W4_GROUP */ + R3DH_W4_KPB = 64, /* K per packed block: 4 k steps, 16 bytes per lane */ + R3DH_W8_GROUP = 128, /* libhalo R3DH_GEMM_W8_GROUP and R3DH_GEMM_W8A8_GROUP */ + R3DH_W8_KPB = 32, /* K per packed block: 2 k steps, 16 bytes per lane */ + R3DH_W2_GROUP = 128, /* libhalo R3DH_GEMM_W2A8_GROUP */ + R3DH_MXFP4_GROUP = 32, /* K per E8M0 exponent, fixed by the OCP MX format */ + /* The block-scaled fp8 family's block, on both axes. Not a quantiser choice: it is the + * checkpoint's `quantization_config.weight_block_size`, and the bytes on disk follow it. It + * cannot be static_asserted against `r3dh_gemm_fp8a8_block()` (a function, not a macro), so + * r3dh_gemm_fp8a8.hip checks it at launch. */ + R3DH_FP8_BLOCK = 128, + R3DH_WAVE = 32, + R3DH_NTILE = 16 /* output rows per WMMA n-tile */ +}; + +/* Plugin-private dtypes. The core never interprets these: rad_types.h reserves everything at or + * above RAD_DT_PLUGIN_BASE for this, and the layout hook sizes them. */ +enum { + R3DH_DT_W4_FRAG = RAD_DT_PLUGIN_BASE + 0, /* 4-bit codes in WMMA fragment order */ + R3DH_DT_W4_SZ = RAD_DT_PLUGIN_BASE + 1, /* (f16 scale, f16 -(1024+zero)) dwords */ + R3DH_DT_W8_FRAG = RAD_DT_PLUGIN_BASE + 2, /* 8-bit codes in the same fragment order */ + R3DH_DT_W8_S = RAD_DT_PLUGIN_BASE + 3, /* f16-only scale plane (w8a8) */ + R3DH_DT_W2_FRAG = RAD_DT_PLUGIN_BASE + 4, + R3DH_DT_MXFP4_FRAG = RAD_DT_PLUGIN_BASE + 5, + R3DH_DT_E8M0 = RAD_DT_PLUGIN_BASE + 6, /* [K/32][N] shared exponents, and Wref[N] */ + /* The grouped MoE GEMM's 4-bit expert weight: row-major packed nibbles, each a code into a + * sixteen-entry table, expanded to E4M3 on the way into LDS. Not R3DH_DT_W4_FRAG, which is a + * WMMA fragment permutation for a kernel loading its weight from global; this one stages + * through LDS because its rows are gathered. See r3dh_layout.cpp. */ + R3DH_DT_MOEW4 = RAD_DT_PLUGIN_BASE + 7, + /* The same GEMM's 5-bit expert weight: per row, R3DH_DT_MOEW4's nibble plane of the codes' low + * four bits (the magnitude), then the sign bits, one dword per 32 elements in the order the + * kernel merges them (r3dh_layout.cpp, moew5_row). A row is 5K/8 bytes. */ + R3DH_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8 +}; + +/* The grouped MoE GEMM's code tables, as the four dwords w4_e4m3's byte permutes read + * (r3dh_moe.hip): entries 0..3, 4..7, 8..11 and 12..15, one E4M3 byte an entry, lowest entry in the + * low byte. `w4a8` and `w4a8h` decode a two's complement nibble, -8..7. `w4nla8h` decodes + * libquant's `table=w4nl` (magnitudes ascending, then their negatives); kW4nlTable is that table + * as a container stores it, which the layout hook compares with the container's table plane + * before serving it. */ +static constexpr uint32_t kW4IntPerm[4] = { 0x44403800u, 0x4E4C4A48u, 0xCACCCED0u, 0xB8C0C4C8u }; +static constexpr uint32_t kW4nlPerm[4] = { 0x504B4539u, 0x5B595653u, 0xD0CBC5B9u, 0xDBD9D6D3u }; +static constexpr float kW4nlTable[16] = { 1.125f, 3.25f, 5.5f, 8.0f, 11.0f, 14.0f, 18.0f, 22.0f, + -1.125f, -3.25f, -5.5f, -8.0f, -11.0f, -14.0f, -18.0f, + -22.0f }; + +/* `w5nl64a8h` decodes libquant's `table=w5nl`: thirty-two levels, sixteen magnitudes ascending + * then their negatives, so a code's high bit is its sign and its low four bits index the + * magnitudes. The kernel expands the magnitude from kW5nlMagPerm (their E4M3 bytes in w4_e4m3's + * dword order) and sets the sign bit from the sign plane. Every level is exact in E4M3. */ +static constexpr uint32_t kW5nlMagPerm[4] = { 0x4B484235u, 0x5453514Fu, 0x5A595856u, 0x5F5D5C5Bu }; +static constexpr float kW5nlTable[32] = { + 0.8125f, 2.5f, 4.0f, 5.5f, 7.5f, 9.0f, 11.0f, 12.0f, + 14.0f, 16.0f, 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 30.0f, + -0.8125f, -2.5f, -4.0f, -5.5f, -7.5f, -9.0f, -11.0f, -12.0f, + -14.0f, -16.0f, -18.0f, -20.0f, -22.0f, -24.0f, -26.0f, -30.0f }; + +/* The fixed second-level scale of `w4nl64a8h`, `w4nl32a8h` and `w5nl64a8h`: it multiplies a + * weight's per-(row, 64 or 32 of K) E4M3 scale. A container states it (libquant's scale2_value=), + * and the layout hook compares it with this before serving. Fixed rather than per row because the + * experts' scales (with the rotation's 1/128 folded in) lie between 2^-15 and 2^-10.6 on + * Qwen3.8-Flash-Next at group 64 (slightly lower at 32, half a binade lower for w5nl). Under + * 2^-13 each is a normal E4M3 value, and E4M3 has three mantissa bits in every binade. */ +static constexpr float kW4G64Scale = 0x1p-13f; + + +/* ================================================================== skinny-GEMM variants + * + * libhalo's five skinny-GEMM knobs, exposed as RadVariant.config so `rad-tune` can walk them and + * `--debug-graph` can name the pick (spec §15). The best setting depends on (N, K) and the M band. + * + * sk == 0 means "choose the largest legal split count at issue". Split-K requires + * K % (SK * group) == 0, so no fixed default is legal at every shape, and an illegal default would + * make an untuned install fail rather than run slowly (spec §15). The sentinel is resolved in one + * place, r3dh_gemm_args.h:pick_sk. + */ +struct HaloGemmCfg { int wv, sk, mb, npw, nt; }; + +/* The tiled and prefill GEMMs take one opaque variant index into libhalo's own switch of compiled + * tile arms; the row's tunable lists the arms a tuner may pick (r3dh_rows.cpp, kTileArms). */ +struct HaloTileCfg { int variant; int bm; int bn; }; + +/* The MXFP4 tiled GEMM's column width in 32-column units per wave: TN=2 gives a 256 x 64 block, + * TN=4 a 256 x 128 one. The crossover depends on M (see r3dh_gemm_mxfp4a8_tiled.hip), so 0, the + * default, decides at issue; a fixed value is for a tuner. */ +struct HaloMxTileCfg { int tn; }; + +/* The MXFP4 decode GEMM's split-K width, K slab and weight-load hint. 0 on each is the rule in + * r3dh_gemm_mxfp4a8_decode.hip (it needs M and the shape, which exist only at issue); `nt` 1 streams + * the weight past L2/MALL, 2 loads it plainly. */ +struct HaloMxDecCfg { int ks; int bk; int nt; }; + +/* Split-KV segment count for the paged decode kernels. 0 is libhalo's split law (table in + * r3dh_attn_paged_h256_gqa6.hip), which needs num_seqs and max_ctx from the issue, so it stays the + * default; fixed counts are for a tuner. RadScratchFn gets the same variant index, so the arena + * is sized for what this picks. */ +struct HaloSplitCfg { int splits; }; + +/* The all-reduce launch geometry, passed to libhalo as nblocks/nthreads/drain/acq (and `pub` at + * width). Defaults: nthreads=1024, drain=3 (s_wait_storecnt, which fine-grained uncached scratch + * requires), acq=0, pub=1, and nblocks scaled by message size and clamped; nblocks == 0 selects + * that rule. */ +struct HaloArCfg { int nblocks; int nthreads; int drain; int acq; int pub; }; + +/* rowtopk: RC is how many candidates a chunk keeps (>= R), NCH the requested chunk width (libhalo + * rounds it up to a multiple of eight columns, so the scratch hook asks r3dh_rowtopk_bf16_chunks() + * for the real one), PT1 the stage-1 thread count. */ +struct HaloTopkCfg { int rc; int nch; int pt1; }; + +/* The block-scaled fp8 matvec's rows a wave. Blocking trades waves for memory-level parallelism, + * so the best value depends on whether the kernel waits on loads or the ALU. The default rule is + * fitted to the current inner loop: any change to it (scale load width, activation dtype) + * requires re-fitting. 0 selects that rule; other values pin it for rad-tune. */ +struct HaloMvCfg { int rb; }; + + + +extern "C" { +/* -- the tuned configuration (r3dh_rows.cpp) -- + * + * The core picked a point in the space the row declared and appended it to RadArgs::p. These read + * it back, falling to the axis's default (defined once, in the RadTunable table) when a caller + * supplied none, so a checker with no tuned key runs what an untuned install runs. They cannot + * fail: the loader refuses a plugin whose default is not one of the axis's values. */ +void r3dh_cfg_gemm (const RadArgs*, struct HaloGemmCfg*); +void r3dh_cfg_tiled (const RadArgs*, struct HaloTileCfg*); +void r3dh_cfg_prefill(const RadArgs*, struct HaloTileCfg*); +void r3dh_cfg_mxfp4_tiled(const RadArgs*, struct HaloMxTileCfg*); +void r3dh_cfg_mxfp4_decode(const RadArgs*, struct HaloMxDecCfg*); +void r3dh_cfg_split (const RadArgs*, struct HaloSplitCfg*); +void r3dh_cfg_ar (const RadArgs*, struct HaloArCfg*); +/* Whether the four-rank fused junction takes its tail form from 5 rows (the row's `tail` axis). */ +int r3dh_cfg_ar_tail(const RadArgs*); +/* The four-rank exact one-shot's size, in elements, from which it takes the exact two-shot instead + * (0: never); the all-reduce rows' `ts_min` axis. */ +long r3dh_cfg_ar_ts_min(const RadArgs*); +/* The prefetch's workgroup count (the row's `nb` axis). */ +int r3dh_cfg_prefetch_nb(const RadArgs*); +void r3dh_cfg_topk (const RadArgs*, struct HaloTopkCfg*); +void r3dh_cfg_mv (const RadArgs*, struct HaloMvCfg*); +/* rmsnorm_quant_i8's decode form: 1 the row's operands in registers before the reductions, 0 the + * pass-per-read kernel; the row's `reg` axis. */ +int r3dh_cfg_rmsq8_reg(const RadArgs*); + +} /* extern "C" */ + +#endif /* R3DH_ARGS_H */ diff --git a/libr3d/r3dh_common.h b/libr3d/r3dh_common.h new file mode 100644 index 00000000..f9315f1f --- /dev/null +++ b/libr3d/r3dh_common.h @@ -0,0 +1,328 @@ +/* Ported from libhalo/halo_common.h, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_common.h by the libhalo rename transform (2026-10-26); + * see libhalo/README.md. Op schemas, row names and stored weight layouts are + * shared with libr4d by design. Everything else in this file is libhalo's own + * and diverges as it is measured on gfx1151. */ +// Shared device-side machinery for Halo. The layout algebra here was verified on hardware with +// targeted probes; do not "fix" it from a vendor doc. +#pragma once +#include +#include + +// The W4A8 scale group lives here, not in either GEMM, because both read the same packed weight and +// a disagreement would be silently wrong, not a link error. r3dh_gemm_args.h restates it and checks +// it against the layout constant. +#define R3DH_GEMM_W4A8_GROUP 128 // K per scale + +// ---- ragged query batches ---------------------------------------------------------------------- +// A paged-attention batch may have a different query length per sequence (HaloArgs::cu_q in halo.h). +// These are the two lookups every kernel indexing the dense q or out block needs, plus the inverse +// for the split-KV combine, which walks output rows rather than sequences. With cu_q null they +// compile to one multiply and no load; the branch is wave-uniform (cu_q is a kernel argument). +__device__ __forceinline__ int r3dh_q_off(const int* cu_q, int seq, int q_len) { + return cu_q ? cu_q[seq] : seq * q_len; +} +__device__ __forceinline__ int r3dh_q_len(const int* cu_q, int seq, int q_len) { + return cu_q ? (cu_q[seq + 1] - cu_q[seq]) : q_len; +} +// num_seqs is at most a few tens, so the search is a few scalar loads, once per block. +__device__ __forceinline__ int r3dh_q_seq(const int* cu_q, int num_seqs, int q_len, int tok) { + if (!cu_q) return tok / q_len; + int lo = 0, hi = num_seqs; // invariant: cu_q[lo] <= tok < cu_q[hi] + while (hi - lo > 1) { + const int mid = (lo + hi) >> 1; + if (cu_q[mid] <= tok) lo = mid; else hi = mid; + } + return lo; +} + +// ---- the occupancy a kernel is built for --------------------------------------------------------- +// R3DH_WAVES(n) fixes the waves per SIMD the compiler schedules a kernel for. Otherwise the +// scheduler picks that target itself and the choice moves between compiler releases (LLVM 24 +// serialises a GEMM's loads to win one more wave, paying a load round trip per WMMA). A kernel +// whose speed rests on a register budget states it here. `n` may depend on template arguments. +#define R3DH_WAVES(n) __attribute__((amdgpu_waves_per_eu((n), (n)))) + +typedef short v8s __attribute__((ext_vector_type(8))); +typedef float v8f __attribute__((ext_vector_type(8))); +typedef float v2f __attribute__((ext_vector_type(2))); // what cvt_pk_f32_fp8 actually returns + +/* A 16-byte staging register as a native vector. HIP's uint4 is a class template wrapping a + * union, and an array of them carried across a K loop (the next tile's chunks) is kept in scratch + * by LLVM 22 and 24, adding a scratch store and load per chunk; an ext_vector_type array is + * promoted to registers. Loaded and stored whole only. r3dh_dflash_conv_body.h declares the same + * type for a source also compiled without this header. */ +typedef unsigned int r3dh_u32x4 __attribute__((ext_vector_type(4))); + +// exp2 with the hardware transcendental. + +__device__ __forceinline__ float ex2(float x) { +#if __has_builtin(__builtin_amdgcn_exp2f) + return __builtin_amdgcn_exp2f(x); +#else + return exp2f(x); +#endif +} + +// f32 -> bf16, round-to-nearest-even, in software: gfx1201 has no v_cvt_pk_bf16_f32. +__device__ __forceinline__ uint16_t f32_to_bf16(float f) { + uint32_t u = __builtin_bit_cast(uint32_t, f); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +// And back: a shift, since every bf16 is exactly a float. +__device__ __forceinline__ float bf16_to_f32(uint16_t h) { + return __builtin_bit_cast(float, (uint32_t)h << 16); +} + +// ---- 16-bit values held in whole registers ------------------------------------------------------- +// LLVM 24 gives gfx12 real 16-bit registers: a 16-bit value lives in one half of a VGPR. Packing +// two bf16 then costs a shift and a half move per pair instead of one v_perm_b32, widening costs a +// half move and a shift, and a 16-bit load into a half (global_load_d16_b16) depends on the +// register's earlier contents, so the waitcnt pass waits for them. The helpers below keep bf16 data +// in whole 32-bit registers from load to store, which compiles the same under LLVM 22 and 24 and +// gives the same bits as the 16-bit forms. + +// f32 -> bf16 rounded to nearest even, as the high half of a word whose low half is not zero +// (f32_to_bf16 before its final shift). A NaN can round to infinity, as there. +__device__ __forceinline__ uint32_t bf16_hi_rne(float f) { + const uint32_t u = __float_as_uint(f); + return u + 0x7fffu + ((u >> 16) & 1u); +} +// Rounds as (__hip_bfloat16)f does (LLVM's expansion): a NaN stays NaN, quieted; everything else +// rounds to nearest even. Both results are formed before the select so it compiles to one +// v_cndmask; `nan ? u | 0x400000 : u + ...` makes each element an exec-masked branch. +__device__ __forceinline__ uint32_t bf16_hi_rne_nan(float f) { + const uint32_t u = __float_as_uint(f); + const uint32_t r = u + 0x7fffu + ((u >> 16) & 1u), q = u | 0x400000u; + return f != f ? q : r; +} +// Two such words as one bf16 pair, `lo`'s high half in the low half: one byte permute. +__device__ __forceinline__ uint32_t bf16_pack_hi(uint32_t lo, uint32_t hi) { + return __builtin_amdgcn_perm(hi, lo, 0x07060302u); +} +// Two floats as a bf16 pair (`lo` in the low half), rounded as f32_to_bf16 rounds. +__device__ __forceinline__ uint32_t bf16x2_rne(float lo, float hi) { + return bf16_pack_hi(bf16_hi_rne(lo), bf16_hi_rne(hi)); +} +// Two floats as a bf16 pair, rounded as (__hip_bfloat16) rounds. +__device__ __forceinline__ uint32_t bf16x2_rne_nan(float lo, float hi) { + return bf16_pack_hi(bf16_hi_rne_nan(lo), bf16_hi_rne_nan(hi)); +} +// A bf16 pair word's two values as floats: a shift and a mask, no conversion. +__device__ __forceinline__ float bf16w_lo(uint32_t w) { return __uint_as_float(w << 16); } +__device__ __forceinline__ float bf16w_hi(uint32_t w) { return __uint_as_float(w & 0xffff0000u); } + +// One 16-bit element of global memory, zero-extended into a whole register (global_load_u16). +// Loaded as uint16_t it would go into a register half (global_load_d16_b16 or d16_hi_b16) and wait +// for the other half; through a generic pointer it would also be a flat load. The pointer must +// address global memory. +typedef __attribute__((address_space(1))) const uint16_t* r3dh_gu16; +__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r3dh_gu16)p; } + +// `lane ^ N` without the LDS pipe. `__shfl_xor` lowers to `ds_bpermute_b32` plus `s_wait_dscnt`, +// an LDS round trip that dominates a dependency chain (e.g. a dot product closed in a token loop). +// gfx10+ DPP16 has ROW_XMASK (0x160 | N), so for N < 16 the partner read is a modifier on the +// consuming VALU op (`v_add_f32_dpp ... row_xmask:2`). N = 16 crosses the two 16-lane rows of a +// wave32 and uses v_permlanex16, still one VALU op. Same lane mapping and value as the shuffle, +// provided all lanes are active, which every caller's whole-wave butterfly guarantees. +template +__device__ __forceinline__ uint32_t r3dh_xor_lane_u32(uint32_t v) { + static_assert(N >= 1 && N <= 16 && (N & (N - 1)) == 0, "a lane xor within the wave"); + if constexpr (N < 16) + return (uint32_t)__builtin_amdgcn_update_dpp(0, (int)v, 0x160 | N, 0xf, 0xf, true); + else + return (uint32_t)__builtin_amdgcn_permlanex16((int)v, (int)v, 0x76543210u, 0xFEDCBA98u, + false, false); +} + +template +__device__ __forceinline__ float r3dh_xor_lane(float v) { + return __uint_as_float(r3dh_xor_lane_u32(__float_as_uint(v))); +} + +// A 64-bit value's partner: the halves exchanged separately, as a 64-bit `__shfl_xor` does. +template +__device__ __forceinline__ unsigned long long r3dh_xor_lane_u64(unsigned long long v) { + const uint32_t lo = r3dh_xor_lane_u32((uint32_t)v); + const uint32_t hi = r3dh_xor_lane_u32((uint32_t)(v >> 32)); + return ((unsigned long long)hi << 32) | lo; +} + +// Exchange between lane L and lane L^16 (the two halves a wave32 WMMA fragment splits a row +// across). v_permlanex16_b32 swaps only with identity selectors (each 4-bit field names the source +// lane in the other half; sel0 covers lanes 0-7, sel1 lanes 8-15); zero selectors would silently +// broadcast lane 0. +__device__ __forceinline__ float swap16(float x) { return r3dh_xor_lane<16>(x); } + +// A wave32 sum on DPP instead of the LDS crossbar. `__shfl_xor` is a `ds_bpermute_b32` on gfx1201 +// at any offset, queued behind other LDS traffic; where little arithmetic separates reductions, a +// five-stage shuffle butterfly dominates the run. Offsets 8..1 use row_xmask (dpp_ctrl 0x160 | N) +// as a modifier on the add; 16 uses v_permlanex16_b32 (see swap16). +// +// The lanes exchanged and the order of the adds match the shuffle loop, so this is bit-identical +// and a kernel can move onto it without its output changing. Row and bank masks are all-ones since +// every lane participates; `bound_ctrl` is moot because every lane has a partner. +template +__device__ __forceinline__ float r3dh_dpp_xor_add(float v) { + return v + __builtin_bit_cast(float, + __builtin_amdgcn_update_dpp(0, __builtin_bit_cast(int, v), CTRL, 0xF, 0xF, true)); +} + +__device__ __forceinline__ float r3dh_wave_sum(float v) { + v += swap16(v); /* xor 16 -- crosses the two rows of sixteen */ + v = r3dh_dpp_xor_add<0x168>(v); /* xor 8 -- row_xmask from here down */ + v = r3dh_dpp_xor_add<0x164>(v); /* xor 4 */ + v = r3dh_dpp_xor_add<0x162>(v); /* xor 2 */ + v = r3dh_dpp_xor_add<0x161>(v); /* xor 1 */ + return v; +} + +// The same butterfly over a group of W lanes (W a power of two up to the wave): the exchanges of +// `for (o = W / 2; o; o >>= 1) v = op(v, __shfl_xor(v, o))`, in its order, so bit-identical to +// that loop. +template +__device__ __forceinline__ float r3dh_xor_sum(float v) { + static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave"); + if constexpr (W >= 32) v += r3dh_xor_lane<16>(v); + if constexpr (W >= 16) v += r3dh_xor_lane<8>(v); + if constexpr (W >= 8) v += r3dh_xor_lane<4>(v); + if constexpr (W >= 4) v += r3dh_xor_lane<2>(v); + if constexpr (W >= 2) v += r3dh_xor_lane<1>(v); + return v; +} + +template +__device__ __forceinline__ float r3dh_xor_max(float v) { + static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave"); + if constexpr (W >= 32) v = fmaxf(v, r3dh_xor_lane<16>(v)); + if constexpr (W >= 16) v = fmaxf(v, r3dh_xor_lane<8>(v)); + if constexpr (W >= 8) v = fmaxf(v, r3dh_xor_lane<4>(v)); + if constexpr (W >= 4) v = fmaxf(v, r3dh_xor_lane<2>(v)); + if constexpr (W >= 2) v = fmaxf(v, r3dh_xor_lane<1>(v)); + return v; +} + +__device__ __forceinline__ float r3dh_wave_max(float v) { return r3dh_xor_max<32>(v); } + +/* A wave's inclusive prefix and suffix sums in registers: row_shr (or row_shl) 1, 2, 4 and 8 + * within each row of sixteen, then the other row's total from one readlane. Lane L ends with the + * sum over lanes 0..L (prefix) or L..31 (suffix). Replaces LDS step-doubling scans (two barriers a + * round); integer sums, so combine order does not matter. Every lane must be active. */ +__device__ __forceinline__ uint32_t r3dh_wave_prefix_u32(uint32_t x, int lane) { + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x111, 0xF, 0xF, true); /* row_shr:1 */ + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x112, 0xF, 0xF, true); /* row_shr:2 */ + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x114, 0xF, 0xF, true); /* row_shr:4 */ + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x118, 0xF, 0xF, true); /* row_shr:8 */ + const uint32_t lo = (uint32_t)__builtin_amdgcn_readlane((int)x, 15); + return lane >= 16 ? x + lo : x; +} + +__device__ __forceinline__ uint32_t r3dh_wave_suffix_u32(uint32_t x, int lane) { + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x101, 0xF, 0xF, true); /* row_shl:1 */ + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x102, 0xF, 0xF, true); /* row_shl:2 */ + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x104, 0xF, 0xF, true); /* row_shl:4 */ + x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x108, 0xF, 0xF, true); /* row_shl:8 */ + const uint32_t hi = (uint32_t)__builtin_amdgcn_readlane((int)x, 16); + return lane < 16 ? x + hi : x; +} + +// 8x8 transpose of 16-bit elements across each group of 8 lanes. Lane j receives element j from +// each of the 8 lanes in its group; the 8 addresses may be arbitrarily strided. +// +// gfx1151 has no global_load_tr_b128, so this loads each lane's 16 B and transposes in registers: +// lane (base+i)'s output element j is lane (base+j)'s loaded element i, eight shuffles of the one +// dword that holds it. Same result, more instructions; a caller on a hot path should say so in +// its header so the transpose can be folded into its addressing instead. +__device__ __forceinline__ v8s load_tr_b128(const void* p) { + const uint4 v = *(const uint4*)p; + const uint32_t w[4] = { v.x, v.y, v.z, v.w }; + const int lane = (int)(threadIdx.x & 31u); + const int base = lane & ~7, i = lane & 7; + uint32_t o[4] = { 0, 0, 0, 0 }; + // A shuffle returns the value the SOURCE lane passed, so a lane cannot ask for "my element i" + // in one shuffle: at lane base+j the argument `w[i >> 1]` is evaluated with THAT lane's i (j), + // not this one's. Fetch all four of the source lane's dwords and select this lane's element + // afterwards -- that is the transpose, and it is 32 shuffles rather than 8. +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint32_t d0 = (uint32_t)__shfl((int)w[0], base + j, 32); + const uint32_t d1 = (uint32_t)__shfl((int)w[1], base + j, 32); + const uint32_t d2 = (uint32_t)__shfl((int)w[2], base + j, 32); + const uint32_t d3 = (uint32_t)__shfl((int)w[3], base + j, 32); + const int d = i >> 1; + const uint32_t wd = d == 0 ? d0 : d == 1 ? d1 : d == 2 ? d2 : d3; + const uint32_t e = (i & 1) ? (wd >> 16) : (wd & 0xffffu); + o[j >> 1] |= e << (16 * (j & 1)); + } + v8s r; + __builtin_memcpy(&r, o, sizeof(o)); + return r; +} + +// Gather the low (sel=0) or high (sel=1) byte of each of four 16-bit lanes of {w0,w1} into one +// dword. Written so the compiler can contract each to a single v_perm_b32. +__device__ __forceinline__ uint32_t byte_gather(uint32_t w0, uint32_t w1, int sel) { + uint32_t s = (uint32_t)sel * 8u; + return ((w0 >> s) & 0xffu) + | (((w0 >> (16 + s)) & 0xffu) << 8) + | (((w1 >> s) & 0xffu) << 16) + | (((w1 >> (16 + s)) & 0xffu) << 24); +} + +__device__ __forceinline__ void sched_barrier() { __builtin_amdgcn_sched_barrier(0); } + +// __syncthreads() is a workgroup-scope acquire-release fence over all address spaces, so on gfx12 +// it emits `global_inv scope:SCOPE_SE` on both sides, discarding the L0/L1 lines the next tile's +// KV loads would hit. These barriers only order LDS traffic, so the fence is scoped to the local +// address space and the invalidate disappears. +__device__ __forceinline__ void lds_barrier() { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); + __builtin_amdgcn_s_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); +} + +// Two-dword form of swap16. +__device__ __forceinline__ uint2 swap16_u2p(uint2 v) { + return make_uint2(__builtin_bit_cast(uint32_t, swap16(__builtin_bit_cast(float, v.x))), + __builtin_bit_cast(uint32_t, swap16(__builtin_bit_cast(float, v.y)))); +} + +// --------------------------------------------------------------------------------------------- +// Workgroup width for the activation-path kernels +// +// had_quant_act_i8, rmsnorm_had_quant_i8, gated_had_quant_i8 and gdn_gated_norm_had_quant_i8 launch +// one workgroup per row, so at decode batch sizes the grid is a few tens of workgroups on a 64-CU +// part and they are latency bound. Widening the workgroup is the only knob that adds parallelism, +// and it is the large win at small M. +// +// It reverses once the grid alone fills the machine. At 1024 threads there is a residency cliff +// just past M=32 where the wider workgroup stops fitting and the cost roughly doubles, so 1024 is +// used only with clearance below it. +// +// Where 512 stops paying depends on K, because the K floats of LDS a row needs cap how many +// workgroups a CU holds. At K=8704 only one fits at either width, so wider wins out to large M; at +// K=3072 five fit, the grid fills the part, and past M~72 the narrow width is even. The thresholds +// below are those crossovers. +__host__ __device__ __forceinline__ int r3dh_act_threads(int M, int K) { + if (M <= 32) return 1024; + const int lim = K >= 8192 ? (1 << 24) : (K >= 4096 ? 120 : 72); + return M <= lim ? 512 : 256; +} + +// libr4d's r4d_cliff_rows pads a grid past the R9700's full-card cliff (a launch in the last 32 +// wavefronts below a multiple of its 2048 wave slots runs ~5x slower). gfx1151 has no such cliff: +// measured 2026-10-26 with a fixed 200-iteration kernel at 256-thread workgroups, per-launch time +// rises smoothly through both candidate multiples (253..258 blocks: 10.18 -> 10.46 us, against the +// R9700's 27.6 vs 5.2), with only the ordinary second-round step at 161 blocks -- 160 blocks x 8 +// waves = 1280 = 40 CUs x 2 SIMDs x 16 wave slots exactly. So the row count to launch is the row +// count asked for, and this stays a function because every launch site already calls it: if a +// future part or driver grows a cliff, the pad goes back here and nowhere else. +__host__ __device__ __forceinline__ uint32_t r3dh_cliff_rows(uint32_t rows, uint32_t per_row, + uint32_t waves) { + (void)per_row; + (void)waves; + return rows; +} diff --git a/libr3d/r3dh_fp8_frag.h b/libr3d/r3dh_fp8_frag.h new file mode 100644 index 00000000..8a7a0ebc --- /dev/null +++ b/libr3d/r3dh_fp8_frag.h @@ -0,0 +1,44 @@ +/* Ported from libhalo/halo_fp8_frag.h, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_fp8_frag.h by the libhalo rename transform (2026-10-26); + * see libhalo/README.md. Op schemas, row names and stored weight layouts are + * shared with libr4d by design. Everything else in this file is libhalo's own + * and diverges as it is measured on gfx1151. */ +// r3dh_fp8_frag.h -- where a byte of a block-scaled FP8 weight lives in WMMA fragment order. Pure +// C++ (no HIP, no halo.h) so the host layout hook and the device kernels share one definition. +// +// Why permute: the fp8a8 GEMMs read operands through r3dh_fp8::frag(), which wants lane `l` to hold +// row `l & 15` of a 16-row tile at k `(l >> 4) * 8`, eight bytes. From a row-major weight those +// sixteen rows are `K` bytes apart, so a wave's load is sixteen transactions; the kernels stage +// through LDS to transpose, at the cost of a barrier, 36 KiB per block and a second pass over the +// weight. In fragment order the bytes are already in lane order. +// +// Why 64 k and not 16: a single fragment (16 rows x 16 k = 256 bytes) gives a wave one 256-byte +// cacheline per request, which loses even to LDS staging. Four fragments give each lane 32 +// contiguous bytes and the wave a 1 KiB request, which beats both at every N and K in the family. +// +// The unit is a (16 row, 64 k) tile of 1024 bytes, laid out as 32 lanes x 32 bytes. Lane `l`'s +// 32 bytes are its four fragments back to back: bytes `8t` are fragment `t`, covering +// k `t*16 + (l>>4)*8` of row `l & 15`. +// +// K must be a multiple of 64 and N of 16; the 128 scale block already guarantees both. +#pragma once +#include + +namespace r3dh_fp8 { + +enum { kFragRows = 16, kFragK = 16, kSuperK = 64, kTileBytes = 1024, kLaneBytes = 32 }; + +// Bytes one [N][K] weight occupies in fragment order: exactly N*K, since this is a permutation. +inline int64_t frag_bytes(int64_t N, int64_t K) { return N * K; } + +// The source (row, k) of a given (tile, lane, fragment, byte). The single definition of the +// permutation: the host transform walks it forwards, the device kernels index it backwards. +inline void frag_src(int64_t rt, int64_t ks, int64_t lane, int64_t t, int64_t j, + int64_t* row, int64_t* k) { + *row = rt * (int64_t)kFragRows + (lane & 15); + *k = ks * (int64_t)kSuperK + t * (int64_t)kFragK + (lane >> 4) * 8 + j; +} + +} // namespace r3dh_fp8 diff --git a/libr3d/r3dh_fp8_wmma.h b/libr3d/r3dh_fp8_wmma.h new file mode 100644 index 00000000..06f57501 --- /dev/null +++ b/libr3d/r3dh_fp8_wmma.h @@ -0,0 +1,123 @@ +/* Ported from libhalo/halo_fp8_wmma.h, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_fp8_wmma.h by the libhalo rename transform (2026-10-26); + * see libhalo/README.md. Op schemas, row names and stored weight layouts are + * shared with libr4d by design. Everything else in this file is libhalo's own + * and diverges as it is measured on gfx1151. */ +// Shared device code for the block-scaled FP8 family: the E4M3 decoders and the bf16 block-scale +// load. libr4d's version of this header also carries the gfx12 fp8 WMMA fragment map and its LDS +// staging; gfx1151 has no fp8 matrix instruction, so halo's fp8 GEMMs dequantise to bf16 in +// registers and run on r3dh_wmma.h's bf16 WMMA instead. That machinery lands with the fp8 GEMM +// units, in r3dh_wmma.h's terms; nothing here pretends otherwise. +#pragma once +#include "r3dh_common.h" +#include "r3dh_fp8_frag.h" + +#include +#include + +namespace r3dh_fp8 { + +/* The fp8 matrix machinery (libr4d's mma/mma8, fragment map and staging) is not + * carried over: it names gfx12 instructions and a fragment layout this part does + * not have. The fp8 GEMM units bring their own, built on r3dh_wmma.h. */ + +// ---- E4M3 -> f32 ------------------------------------------------------------------------------- +// +// One instruction on gfx1201 (v_cvt_f32_fp8); the software fallback is ~11 VALU ops. They agree on +// all bytes except 0x7F and 0xFF, E4M3-fn's NaN encodings: hardware returns NaN, the fallback +// +-480. Both quantisers clamp to +-448 = 0x7E, so real data never holds them. +// +// No subnormal-free fast path: a checkpoint weight may hold subnormals, which such a path would +// decode as 2^-7 * 1.MMM instead of MMM * 2^-9. +__device__ __forceinline__ float e4m3(uint32_t b) { +#if __has_builtin(__builtin_amdgcn_cvt_f32_fp8) + return __builtin_amdgcn_cvt_f32_fp8(b, 0); +#else + const uint32_t sign = (b & 0x80u) << 24; + const uint32_t ex = (b >> 3) & 0x0Fu; + const uint32_t mn = b & 0x07u; + const float nrm = __uint_as_float(((ex + 120u) << 23) | (mn << 20)); + const float sub = (float)mn * (1.0f / 512.0f); + return __uint_as_float(__float_as_uint(ex ? nrm : sub) | sign); +#endif +} + +// Two E4M3 bytes of a packed dword to two f32 in one instruction (v_cvt_pk_f32_fp8). `HI` selects +// bytes 2,3 over 0,1 and is a template parameter because the builtin's word select is a constant. +// Returns r3dh_common.h's `v2f`, the builtin's own return type. +template +__device__ __forceinline__ v2f e4m3_pk(uint32_t q) { +#if __has_builtin(__builtin_amdgcn_cvt_pk_f32_fp8) + return __builtin_amdgcn_cvt_pk_f32_fp8(q, HI); +#else + constexpr uint32_t s = HI ? 16u : 0u; + v2f r; + r.x = e4m3((q >> s) & 0xFFu); + r.y = e4m3((q >> (s + 8u)) & 0xFFu); + return r; +#endif +} + +// ---- f32 -> E4M3 ------------------------------------------------------------------------------- +// +// gfx1151 has no v_cvt_pkfp8_f32 (fp8-conversion-insts), so the encode is software. It is a +// transcription of abi/rad_plugin.h's rad_f32_to_fp8e4m3 -- round-to-nearest-even in both the +// normal and subnormal branches, saturating at 448, NaN to 0x7f -- because that function is the +// reference every fp8 store is checked against; a faster form must first be shown to agree with +// it on every input class (the host probe in the unit's bring-up compared 2^31 values). +__device__ __forceinline__ uint32_t f32_to_e4m3(float f) { + const uint32_t u = __builtin_bit_cast(uint32_t, f); + const uint32_t s = (u >> 24) & 0x80u; + const uint32_t a = u & 0x7fffffffu; + if (a > 0x7f800000u) return s | 0x7fu; /* nan */ + if (a >= 0x43e00000u) return s | 0x7eu; /* >= 448: clamp to the largest */ + const int e = (int)(a >> 23) - 127; + uint32_t m = a & 0x7fffffu; + if (e < -10) return s; + if (e < -6) { /* subnormal fp8 */ + const int sh = -6 - e + 20; + m |= 0x800000u; + const uint32_t lo = m & ((1u << sh) - 1u); + uint32_t q = m >> sh; + const uint32_t half = 1u << (sh - 1); + if (lo > half || (lo == half && (q & 1u))) ++q; + return s | q; + } + uint32_t q = m >> 20; + const uint32_t lo = m & 0xfffffu; + if (lo > 0x80000u || (lo == 0x80000u && (q & 1u))) ++q; + int ee = e + 7; + if (q == 0x8u) { q = 0; ++ee; } + if (ee > 15 || (ee == 15 && q >= 7u)) return s | 0x7eu; + return s | ((uint32_t)ee << 3) | q; +} + +/* __builtin_amdgcn_cvt_pk_fp8_f32's shape (two encodes into one half of `old`), so a call site + * moves onto it by name alone. Callers still clamp to +-448 first, as they did for the hardware + * instruction, whose out-of-range result is NaN rather than saturation; with the clamp the bytes + * are the same ones. */ +__device__ __forceinline__ int cvt_pk_fp8_f32(float lo_f, float hi_f, int old, bool word_sel) { + const uint32_t pair = f32_to_e4m3(lo_f) | (f32_to_e4m3(hi_f) << 8); + const uint32_t o = (uint32_t)old; + return (int)(word_sel ? (o & 0x0000ffffu) | (pair << 16) : (o & 0xffff0000u) | pair); +} + +// ---- block scale -------------------------------------------------------------------------------- +// +// The checkpoint's BF16 `weight_scale_inv` (one per 128x128 tile, row-major) is read natively: +// decode is one shift and one bitcast. Converting to UE8M0 would round every tile's gain to a +// power of two and force requantising the E4M3 bytes, for no saving (the scale plane is 21.8 KiB +// against an 89 MiB weight at gate_proj's shape). Unlike UE8M0, bf16 needs no zero test: +// `0u << 16` is +0.0f. +__device__ __forceinline__ float bscale(uint16_t s) { + return __uint_as_float((uint32_t)s << 16); +} +/* The same scale zero-extended in a full register (see u16_load_w in r3dh_moe.hip). The upper + * sixteen bits must be zero. */ +__device__ __forceinline__ float bscale(uint32_t s) { + return __uint_as_float(s << 16); +} + +} // namespace r3dh_fp8 diff --git a/libr3d/r3dh_gdn_args.h b/libr3d/r3dh_gdn_args.h new file mode 100644 index 00000000..2d544348 --- /dev/null +++ b/libr3d/r3dh_gdn_args.h @@ -0,0 +1,67 @@ +/* Ported from libhalo/halo_gdn_args.h, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_gdn_args.h by the libhalo rename transform (2026-10-26); + * see libhalo/README.md. Op schemas, row names and stored weight layouts are + * shared with libr4d by design. Everything else in this file is libhalo's own + * and diverges as it is measured on gfx1151. */ +/* r3dh_gdn_args.h -- argument helpers shared by the gated-delta-net kernels (and the DFlash ops): + * dtype checks, num_seqs from cu_seqlens, the compiled-geometry check and a row-pitch reader. + */ +#ifndef R3DH_GDN_ARGS_H +#define R3DH_GDN_ARGS_H + +#include "r3dh.h" +#include "r3dh_args.h" + + +/* Every `const void*` libhalo takes has one element type, cast inside the kernel (e.g. + * r3dh_gdn_conv_prep_w4_h128_bf16 reads `wgt` as bf16 and `A_log` as f32); the signature does not + * say so. A plugin declaring `ssm_conv1d.weight` or the `gdn_kkt` buffer as f32 would be read as + * bf16 on the device, while libref (which honours each operand's dtype) stays correct, so the bug + * would show only on the device path. The shim therefore checks dtypes by name (spec §2.1). */ +static inline int r3dh_dt(const RadTensor* t, uint32_t want) { + if (!t) return RAD_OK; /* an absent optional operand has no dtype */ + return t->dtype == want ? RAD_OK : RAD_E_DTYPE; +} +#define R3DH_DT(t, want) \ + do { const int _d = r3dh_dt((t), (want)); if (_d != RAD_OK) return R3DH_NO(_d); } while (0) + +/* A raw halo.h entry point's result as a RAD status. Those return 0, a negative code for a + * geometry they were not compiled for, or the positive hipError_t of a failed launch. */ +static inline int r3dh_raw_status(int rc, const char* file, int line) { + if (rc == 0) return RAD_OK; + return r3dh_refused(rc < 0 ? RAD_E_SHAPE : RAD_E_DEVICE, file, line); +} +#define R3DH_RAW(rc) r3dh_raw_status((rc), __FILE__, __LINE__) + +/* num_seqs from the [N+1] cu_seqlens tensor, the only operand that carries N. Requiring rank 1 + * keeps an off-by-one N from reaching kernels that index cu[N] unconditionally. */ +static inline int seqs_of(const RadTensor* cu, int* out) { + if (!cu || cu->rank != 1 || cu->shape[0] < 2) return R3DH_NO(RAD_E_SHAPE); + if (!r3dh_contig(cu)) return R3DH_NO(RAD_E_STRIDE); + *out = (int)(cu->shape[0] - 1); + return RAD_OK; +} + +/* libhalo's compiled-in geometry, so a rebuild at a different head size cannot silently change what + * the rows mean. */ +static inline int gdn_dims_ok(void) { + int hk = 0, hv = 0, ch = 0; + r3dh_gdn_dims(&hk, &hv, &ch); + return (hk == 128 && hv == 128 && ch == 64) ? RAD_OK : RAD_E_SHAPE; +} + + +/* Elements between consecutive `width`-wide rows: the second-to-last stride of a [.., heads, width] + * tensor, or `width` for a dense flattened [tokens, heads*width] one. Negative otherwise. */ +static inline long long gn_row_pitch(const RadTensor* t, long long width) { + if (!t || t->rank < 1) return -1; + if (t->shape[t->rank - 1] == width) { + if (t->stride[t->rank - 1] != 1) return -1; + return t->rank >= 2 ? t->stride[t->rank - 2] : width; + } + return r3dh_contig(t) ? width : -1; +} + +#endif /* R3DH_GDN_ARGS_H */ diff --git a/libr3d/r3dh_gdn_chunk_scan.hip b/libr3d/r3dh_gdn_chunk_scan.hip new file mode 100644 index 00000000..f4b0b118 --- /dev/null +++ b/libr3d/r3dh_gdn_chunk_scan.hip @@ -0,0 +1,724 @@ +/* Ported from libhalo/halo_gdn_chunk_scan.hip, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_gdn_chunk_scan_k128_v128_c64_bf16.hip by the libhalo rename transform (2026-10-26), + * then ported to gfx1151; see libhalo/README.md. */ +// r3dh_gdn: the gated-delta-net chunked scan, gfx1201 WMMA. Entry point +// r3dh_gdn_chunk_scan_k128_v128_c64_bf16 -- head_k 128, head_v 128, chunk 64, bf16 in. +// Used by prefill and chunked prefill; decode uses the recurrent update kernel. Replaces FLA's +// recompute_w_u_fwd + chunk_gated_delta_rule_fwd_h + chunk_fwd_o: the recurrent state stays in +// WMMA accumulators across the chunk loop, so h / w / u / v_new never touch HBM. +// +// Invariant: every decay factor formed is <= 1. The intra-chunk gate span reaches 558 nats on +// real Qwen3.8 prefill activations, so splitting the exponent about a per-chunk reference c +// (e^{g_i-c} * e^{c-g_j}) overflows fp32 on one side and underflows on the other for any c. +// e^{g_i-g_j} (j <= i) and e^{g_last-g_j} stay in (0, 1]. +// +// ge[j]=e^{g_j} gg[j]=g_j gs[j]=e^{g_last-g_j} +// U = K@S W = beta*(V - ge*U) V' = A@W (undecayed) +// P = Q@K^T sA = scale*e^{g_i-g_j}*tril(P) +// O = scale*ge*(Q@S) + sA@V' +// S = e^{g_last}*S + V'^T@(gs*K) +// A is FLA's solve_tril output (decay folded in), so no decay enters W or V'. The (i,j) weight +// is applied per element in the score step (eight __expf per tile), and the state's +// e^{g_last-g_j} is applied to K, which is otherwise dead by then. V' stays undecayed because its +// consumers need different references (e^{g_i-g_j} for the output, e^{g_last-g_j} for the state), +// and serving both from one scaling would need the unsafe split. +#include +#include "r3dh.h" +#include "r3dh_common.h" +#include "r3dh_gdn_args.h" +#include "r3dh_gdn_wmma.h" +// Barriers are lds_barrier(): __syncthreads() fences all address spaces, so the barrier after the +// global O store would wait on s_wait_storecnt_dscnt 0x0. +// +// ---- gfx1151 port notes --------------------------------------------------------------------- +// r3dh_gdn_wmma.h carries the fragment layer, so the *gathers* port by themselves: rowP/rowG lose +// libr4d's `4*(lane>>4)` k term and fragP reads the lane's whole 16-wide k run. What does NOT port +// is every accumulator write-out: on gfx11 element e is D[2e + (lane>>4)][lane & 15], not +// D[8*(lane>>4) + e][lane & 15], so +// +// * a transposed stage (s.S, s.A's score tile, s.W, s.D's V') keeps libr4d's destination and +// takes its eight values from accPackX(), after scaling them per element -- the two halves of +// the wave own different rows, so nothing can be scaled after the exchange; +// * O needs nothing: its hardware row is the v dim, so accPackX()'s eight consecutive rows are +// eight consecutive v of one token -- the contiguous HBM direction -- and both O loops, the +// per-lane scale and the store stay exactly as libr4d wrote them. +// The per-lane state (St[]) is the one place the wider fragment scatters: a lane's eight k values +// are two apart, so h0/ht go through an f32 LDS tile (see SF) rather than straight to HBM. + +// libr4d's rounding helpers (r4d_gdn_wmma.h) -- f2bf / f2bf2 / bf2f -- are r3dh_gdn_wmma.h's +// (included above): f2bf is round-half-AWAY, one add, so the bf16 stages keep libr4d's bits. +// gfx1151 has no v_cvt_pk_bf16_f32 either. + +// One accumulator stage: the eight elements accPackX() assembles, as two 8-byte stores (every +// buffer here is only 8-byte aligned, so a 16-byte store would be misaligned on odd rows). +// accPackX() packs with halo::pk_bf16's round-to-nearest-even, as accPack() does, where libr4d's +// f2bf4 rounds half away; the two differ only on an exact bf16 tie. It is accPack()'s values +// without its ds_bpermute exchange and per-pack branches (see r3dh_gdn_wmma.h). Both operand +// shapes are offered so a call site reads the same whether it holds a v8f or a float[8]. +__device__ __forceinline__ uint4 accPk(v8f v, int lane) { + union { v8f f; float s[8]; } u; + u.f = v; + return accPackX(u.s, lane); +} +__device__ __forceinline__ void accSt(unsigned short* dst, v8f v, int lane) { + const uint4 w = accPk(v, lane); + *(uint2*)dst = make_uint2(w.x, w.y); + *(uint2*)(dst + 4) = make_uint2(w.z, w.w); +} +__device__ __forceinline__ void accSt(unsigned short* dst, const float v[8], int lane) { + const uint4 w = accPackX(v, lane); + *(uint2*)dst = make_uint2(w.x, w.y); + *(uint2*)(dst + 4) = make_uint2(w.z, w.w); +} + +#define BT 64 +#define KD 128 +#define VD 128 +#define BV 64 // V per workgroup; also halves the Q@K^T redundancy +// Row pitches are multiples of 8 shorts (16 B) because r3dh_gdn_wmma.h's fragP reads a lane's whole +// 16-wide k run as two 16-byte LDS loads. They used KP = 132 / AP = 68 on gfx12, where a fragment is +// two 8-byte reads 16 bytes apart and 8-byte alignment suffices; on gfx1151 a buffer whose pitch is +// 136 B or 264 B puts every odd row 8 bytes off a 16-byte boundary, and a misaligned ds_load_b128 +// returns garbage -- silently, and only for some register allocations (measured: infs in a +// trailing partial chunk with the gfx12 pitches, none with these). +#define KP 136 // row pitch of the [.][KD] buffers, in shorts (272 B) +#define AP 72 // row pitch of the [.][BT] buffers, in shorts (144 B) +#define WP AP +// Waves per workgroup. The [4 token][4 v] tile grid is fixed by BT and BV, so 8 waves carry two +// tiles each. +#define NW 8 +#define NTHR (NW * 32) +#define NTV 2 // n tiles per wave in the main / V' / O loops +// A wave's slice of the 8 k-tile x 4 v-tile state grid is 2 x 2. +#define SKT 2 +#define SVT 2 +#define NST (SKT * SVT) // state tiles per wave + +// gfx1151 register plan. libr4d's plan (state, k/v prefetch, six main-loop accumulators) fits +// gfx12's 4-VGPR fragment; ported as is, with gfx11's 8-VGPR fragment, every instantiation sat at +// 256 VGPRs with 357-379 spilled (1.3 KB of scratch a lane: loop-invariant LDS addresses -- fragT's +// sixteen per-row addresses for the transposed K above all -- hoisted out of the chunk loop and +// reloaded inside it), and ~100 us a chunk. Measured on gfx1151 (kbench, M=512, the two fixture +// head counts: 820 / 493 us before, 155 / 118 after), what replaced it: +// * the state update reads gs*K from a transposed copy, s.KT, written by the pass that used to +// scale K in place, so every fragment in the kernel is a fragP. s.KT shares storage with the +// bf16 state s.S, whose last reader (the main loop) retires at barrier (2); the state is +// restaged at the top of the next chunk, after barrier (4) has retired the s.KT reads, so the +// alias costs no barrier. +// * every per-lane LDS address is one base plus immediates (a wave-uniform term goes in the +// base, never in a per-element index), so nothing is left for LICM to hoist. +// * no divergent branch on the chunk path: the accumulator write-outs use accPackX() (accPack() +// lowers to ds_bpermute + an LDS wait + a branch per pack), the score mask is a select after +// the exp, and the prefetch's zero fill is a select at consumption (-12% together). +// * the triangular work stops at the diagonal (P^T tiles, V' and O += sA@V' k steps): 544 +// WMMAs a chunk instead of 640, and the kernel is WMMA-throughput bound now (dropping P^T +// entirely saved its full share). +// * the first q fragments and the V' A fragments are issued ahead of the barrier that precedes +// their loop, so the first WMMAs do not wait out an HBM round trip (-13% / -4%). +// * h0 / ht pass through LDS (see SF): with element-wise HBM access the state traffic was ~45% +// of a one-chunk call. +// The result is 239-248 VGPRs, no spills, with ROCm 7.2.3 and 7.2.4. The margin is not wide: the +// main loop with its P^T count fixed (one all-tiles body instead of the three below) spills ~150. +// 16 waves of one tile each (<= 192 VGPRs, so two workgroups per WGP still fit) is ~12% slower. +struct Smem { + unsigned short k[BT][KP]; // A: K / B: K^T for P=Q@K^T + unsigned short A[BT][AP]; // B-source for sA (written as [i][j]) + union { + unsigned short S[BV][KP]; // B: state, V-major (matches FLA's [V,K] layout); main loop only + unsigned short KT[KD][AP]; // A: gs*K, transposed ([k][token]); state update only + }; + unsigned short W[BV][WP]; // B: W (transposed) + unsigned short D[BV][AP]; // staged V as [token][v]; then V' as [v][token]. + // V dies in the W update; V' is written after barrier (2). + float ge[BT], gv[BT], gg[BT], bt[BT]; // gv = gs, gg = raw g +}; + +// Choices measured against their alternatives on gfx1201, kept so they are not undone: +// - LDS rows in the main loop are opaque 32-bit byte offsets (fragO), global q / A fragments a +// 32-bit offset off a uniform base (fragGo). +// - k and v are staged eight shorts per lane (global_load_b128), issued as a block before the +// main loop: interleaving them into it is ~5% slower. +// - Every bf16 pack rounds (f2bf2 / accPackX). Truncating W, sA and V' is ~2% faster but +// roughly triples the fp64-oracle error, since they feed the recurrence. +// And on gfx1151: prefetching the gates (g, beta, g_last) with k / v, and sched_barrier fences +// in the main loop, measured neutral; more q fragments ahead of barrier (1) than QP spill. +// Byte offset, from the base of the shared block, of the fragment row this lane reads out of +// buf[base + (lane&15)][...]. r3dh_gdn_wmma.h's rowO is libr4d's ROWO without the `4*hi` k term: +// on gfx1151 the half-wave no longer selects which quarter of the k run a lane holds. +#define ROWO(buf, pitch, base) \ + rowO((unsigned)((const char*)&(buf)[0][0] - (const char*)&s), (pitch), (base), lane) + +// SDT is the state cache's element type (0 = fp32, 1 = fp16) and nothing else; all arithmetic is +// fp32. The cache is shared with the recurrent update (whose time is the state traffic, so it +// favours fp16) and allocated from vLLM's --mamba-ssm-cache-dtype, so both kernels must agree. +template struct cs_state { using T = float; }; +template <> struct cs_state<1> { using T = _Float16; }; + +// H0 / HT: whether the optional initial and final state operands are present (template parameters, +// so the common both-present form has no runtime test). As in libref, no initial state starts from +// zero and no final state stores nothing. +template +__global__ __launch_bounds__(NTHR) void r3dh_gdn_chunk_scan_kernel( + const unsigned short* __restrict__ q, const unsigned short* __restrict__ k, + const unsigned short* __restrict__ v, const unsigned short* __restrict__ Amat, + const float* __restrict__ gcs, const float* __restrict__ beta, + const typename cs_state::T* __restrict__ h0, unsigned short* __restrict__ o, + typename cs_state::T* __restrict__ ht, const int* __restrict__ cu, + const int* __restrict__ sidx, long sidx_stride, long st_slot, long st_head, + int H, int Hg, float scale) +{ + __shared__ Smem s; + const int bv = blockIdx.x, hv = blockIdx.y, nq = blockIdx.z; + const int tid = threadIdx.x, w = tid >> 5, lane = tid & 31; + const int hq = hv / (H / Hg), v0 = bv * BV; + const int tb = cu[nq], te = cu[nq + 1]; + // The state slot comes from the cache manager (sidx), not the batch position; without sidx the + // kernel uses state[nq], valid only while slots match batch order. A row may name several slots + // (speculative decode adds scratch slots); column 0 is the state and the only one used here. + const long si = sidx ? (long)sidx[(size_t)nq * sidx_stride] : (long)nq; + if (si < 0) return; // a padded row owns no state + const size_t st_base = (size_t)si * st_slot + (size_t)hv * st_head; + const int nchunk = (te - tb + BT - 1) / BT; + const int lo = lane & 15, hi = lane >> 4; + + // [BT][BV]: 2 tiles/wave. The token tile mt sets the wave's share of the triangular work (P^T, + // V', O += sA@V' all stop at the diagonal), so waves w and w+4 -- likely one SIMD -- pair + // mt with 3 - mt, and the n-tile pair is chosen to even out the P^T tiles (3, 2, 3, 2). + const int mt = (w >> 1) ^ (w >> 2), ntb = ((w ^ (w >> 2)) & 1) * 2; + // The state accumulator is held transposed, C[m=k-dim][n=v]. A and B fragments share a lane + // layout, so swapping the state update's operands is free, and k-dim becomes the per-lane + // contiguous axis: the per-chunk writeback to s.S is four 8-short stores instead of 32 scalar. + const int kt0 = (w >> 1) * 2, vt0 = (w & 1) * 2; // 2 x 2 + +#define PFW 8 // shorts staged per lane per step +#define NKB (BT * KD / (NTHR * PFW)) +#define NVB (BT * BV / (NTHR * PFW)) + uint4 kb[NKB], vb[NVB]; + // Staging index, split into a wave-uniform row and a loop-invariant lane column. As + // `i = tid*4 + u*NTHR*4; r = i>>7` the row looks divergent to LLVM and each load costs ~13 + // instructions of 64-bit address math; readfirstlane makes the row provably uniform (SALU). + // Identities (exact, since u*NTHR*8 is a multiple of both 128 and 64): + // k: r = 2*(tid>>5) + kh + KRU*u c = (tid*8) & 127 kh = (tid>>4) & 1 + // v: r = 4*(tid>>5) + vh + VRU*u c = (tid*8) & 63 vh = (tid>>3) & 3 + const int wu = __builtin_amdgcn_readfirstlane(tid >> 5); + const int kc = (tid * PFW) & (KD - 1), vc = (tid * PFW) & (BV - 1); + const int kr0 = 2 * wu + ((tid >> 4) & 1), vr0 = 4 * wu + ((tid >> 3) & 3); +#define KRU (2 * NW) +#define VRU (4 * NW) + // Do not change: staged rows past the chunk end are zeroed, not clamped to the last live row + // (~4% faster). A clamp looks harmless (beta and gv are 0 there, the tril mask drops padding j, + // the O store is guarded), yet with it any prompt whose trailing chunk is not a multiple of 16 + // tokens returns one repeated token. Zeroing k alone fixes it, so the leak is through some + // consumer of s.k whose path is not yet understood. + // The load itself is clamped (pnv >= 1 wherever this runs) and the zero selected when the + // staging store consumes it (PFSEL, against that chunk's nval): straight-line code, and a select + // at issue would make the prefetch wait for its own loads. +#define PFSTORE(dst, val) \ + do { \ + unsigned short* dp_ = (dst); \ + *(uint2*)dp_ = make_uint2((val).x, (val).y); \ + *(uint2*)(dp_ + 4) = make_uint2((val).z, (val).w); \ + } while (0) +#define PFSEL(r, val) \ + make_uint4((r) < nval ? (val).x : 0u, (r) < nval ? (val).y : 0u, \ + (r) < nval ? (val).z : 0u, (r) < nval ? (val).w : 0u) +#define PREFETCH(CH) \ + { \ + const int pc0 = tb + (CH) * BT, pnv = min(BT, te - pc0); \ + const unsigned short* kb_ = k + ((size_t)pc0 * Hg + hq) * KD; \ + const unsigned short* vb_ = v + ((size_t)pc0 * H + hv) * VD + v0; \ + _Pragma("unroll") for (int u = 0; u < NKB; ++u) { \ + const int r = kr0 + KRU * u, rc = min(r, pnv - 1); \ + kb[u] = *(const uint4*)(kb_ + (unsigned)(rc * (Hg * KD)) + kc); \ + } \ + _Pragma("unroll") for (int u = 0; u < NVB; ++u) { \ + const int r = vr0 + VRU * u, rc = min(r, pnv - 1); \ + vb[u] = *(const uint4*)(vb_ + (unsigned)(rc * (H * VD)) + vc); \ + } \ + } + + v8f St[NST]; // state: SKT k-tiles x SVT v-tiles +#define KT(t) (kt0 + (t) / SVT) +#define VT(t) (vt0 + (t) % SVT) +// State element e is v = VT*16 + lo, k = KT*16 + 2e + hi on gfx1151 (NOT 8*hi + e): a lane's eight +// values are two apart in the [v][k] state. Read straight from HBM that is 32 scalar loads a lane, +// each wave load touching sixteen rows for 8 bytes apiece; at one or two chunks the state traffic +// is half the kernel. So h0 and ht pass through LDS (free before the chunk loop and after barrier +// (4)) as an f32 [v][k] tile: coalesced 16-byte global accesses on one side, the accumulator +// layout on the other (pitch FP: lanes lo / hi land on banks 4*lo + hi, no conflict). +#define FP (KD + 4) + static_assert(sizeof(Smem) >= sizeof(float) * BV * FP, "the f32 state tile overlays Smem"); + float (*const F)[FP] = reinterpret_cast(&s); +#define SF(t, e) F[VT(t) * 16 + lo][KT(t) * 16 + 2 * (e) + hi] + if constexpr (!H0) { +#pragma unroll + for (int t = 0; t < NST; ++t) +#pragma unroll + for (int e = 0; e < 8; ++e) St[t][e] = 0.0f; + } else { + const typename cs_state::T* p = h0 + st_base + (size_t)v0 * KD; + if constexpr (SDT == 0) { // a row is 32 float4: wave wu takes rows wu + NW*u + float4 r[BV / NW]; +#pragma unroll + for (int u = 0; u < BV / NW; ++u) r[u] = *(const float4*)(p + (wu + NW * u) * KD + lane * 4); +#pragma unroll + for (int u = 0; u < BV / NW; ++u) *(float4*)&F[wu + NW * u][lane * 4] = r[u]; + } else { // a row is 16 x 8 halves: rows tid/16 + (NTHR/16)*u + const int r0 = tid >> 4, c = (tid & 15) * 8; + uint4 r[BV * 16 / NTHR]; +#pragma unroll + for (int u = 0; u < BV * 16 / NTHR; ++u) + r[u] = *(const uint4*)(p + (r0 + (NTHR / 16) * u) * KD + c); +#pragma unroll + for (int u = 0; u < BV * 16 / NTHR; ++u) { + union { uint4 w; _Float16 h[8]; } x; + x.w = r[u]; + float* d = &F[r0 + (NTHR / 16) * u][c]; + *(float4*)d = make_float4(x.h[0], x.h[1], x.h[2], x.h[3]); + *(float4*)(d + 4) = make_float4(x.h[4], x.h[5], x.h[6], x.h[7]); + } + } + lds_barrier(); +#pragma unroll + for (int t = 0; t < NST; ++t) +#pragma unroll + for (int e = 0; e < 8; ++e) St[t][e] = SF(t, e); + lds_barrier(); // the chunk loop's staging overwrites the tile + } + if (nchunk > 0) PREFETCH(0); + + const char* const sbase = (const char*)&s; + // scale goes inside the score exponent, exp(g_i + log(scale) - g_j), saving eight multiplies + // per tile. + const float lgs = __logf(scale); + for (int ci = 0; ci < nchunk; ++ci) { + const int c0 = tb + ci * BT, nval = min(BT, te - c0); + const int lim = nval - 1; + const unsigned short* qg = q + ((size_t)c0 * Hg + hq) * KD; + const unsigned short* ag = Amat + ((size_t)c0 * H + hv) * BT; + const size_t qrs = (size_t)Hg * KD, ars = (size_t)H * BT; + const float gl = gcs[(size_t)(c0 + lim) * H + hv]; + + // Issued before the staging stores so the LDS writes cover their latency. Only waves 0-1 + // (tid < BT) run this; the others wait at (1). + float ggr = 0.f, btr = 0.f; + if (tid < BT) { + bool ok = tid < nval; + ggr = ok ? gcs[(size_t)(c0 + tid) * H + hv] : 0.f; + btr = ok ? beta[(size_t)(c0 + tid) * H + hv] : 0.f; + } + // The main loop's first QP q fragments, issued ahead of the staging and barrier (1) so the + // first WMMAs do not wait out a full HBM round trip. +#define QP 4 + const unsigned qo = rowGo((unsigned)qrs, mt * 16, lim, lane); + v16bf aq0[QP]; +#pragma unroll + for (int sk = 0; sk < QP; ++sk) aq0[sk] = fragGo(qg, qo + sk * 16); + // The bf16 state for this chunk's U and O. s.S aliases s.KT, whose last reads (the previous + // chunk's state update) retired at barrier (4). +#pragma unroll + for (int t = 0; t < NST; ++t) + accSt(&s.S[VT(t) * 16 + lo][KT(t) * 16 + 8 * hi], St[t], lane); + { // consume the previous iteration's prefetch, issued a whole chunk of compute ago +#pragma unroll + for (int u = 0; u < NKB; ++u) PFSTORE(&s.k[kr0 + KRU * u][kc], PFSEL(kr0 + KRU * u, kb[u])); +#pragma unroll + for (int u = 0; u < NVB; ++u) PFSTORE(&s.D[vr0 + VRU * u][vc], PFSEL(vr0 + VRU * u, vb[u])); + } + if (tid < BT) { + bool ok = tid < nval; + s.bt[tid] = btr; + s.ge[tid] = __expf(ggr); + // g is a within-chunk cumsum of log-sigmoid gates, so it is non-increasing and gl is its + // minimum: gl - ggr <= 0, and gs underflowing to 0 is correct. + // A padding row gets gl, not 0: it is scored against live j with very negative g_j, and + // g_i = 0 would give exp(+400) = inf in s.A. With gl (the chunk minimum) the exponent + // stays in (0, scale]. The row is discarded anyway (O store is guarded). + s.gg[tid] = ok ? ggr : gl; + s.gv[tid] = ok ? __expf(gl - ggr) : 0.f; // gs + } + lds_barrier(); // (1) + if (ci + 1 < nchunk) PREFETCH(ci + 1); // issue only; consumed next iteration + + // ---- U = K@S, O^T = S@Q^T and P^T = K@Q^T share the q and k fragments. + // P^T tiles above the diagonal are skipped (sA masks them). On gfx12 that was 2.4% slower -- + // some wave still carries two tiles, so the barrier arrival does not move -- but here the + // kernel is throughput bound with two workgroups per WGP, so the WMMAs saved are time saved. + v8f O[NTV], u[NTV], p[NTV]; +#pragma unroll + for (int i = 0; i < NTV; ++i) { O[i] = (v8f){}; u[i] = (v8f){}; p[i] = (v8f){}; } + { + const char* sb = sbase; + // The two n tiles are 16 rows apart, so one base per buffer serves both (an immediate). + unsigned okm = ROWO(s.k, KP, mt * 16), oSn = ROWO(s.S, KP, ntb * 16), + okn = ROWO(s.k, KP, ntb * 16); + LDSOPAQUE(okm); LDSOPAQUE(oSn); LDSOPAQUE(okn); +#define pSnf(i, ko) fragO(sb, oSn + ((i) * 16 * KP + (ko)) * 2u) +#define pkmf(ko) fragO(sb, okm + (ko) * 2u) +#define pknf(i, ko) fragO(sb, okn + ((i) * 16 * KP + (ko)) * 2u) +#define pqf(ko) ((ko) / 16 < QP ? aq0[min((ko) / 16, QP - 1)] : fragGo(qg, qo + (ko))) + // P^T tile ntb+i is wholly above the diagonal (masked in sA) when ntb + i > mt: only the + // first np tiles are computed. np is wave-uniform, so each count gets its own loop. + auto mainloop = [&](auto npc) { + constexpr int NP = decltype(npc)::value; +#pragma unroll + for (int sk = 0; sk < KD / 16; ++sk) { + const int ko = sk * 16; + v16bf ak = pkmf(ko), aq = pqf(ko); +#pragma unroll + for (int i = 0; i < NTV; ++i) { + v16bf b = pSnf(i, ko); + u[i] = mma(ak, b, u[i]); // U: m = token, n = v-tile + O[i] = mma(b, aq, O[i]); // O^T: m = v-tile, n = token-tile + if (i < NP) p[i] = mma(pknf(i, ko), aq, p[i]); // P^T: m = j + } + } + }; + const int np = __builtin_amdgcn_readfirstlane(min(max(mt - ntb + 1, 0), NTV)); + if (np == NTV) mainloop(std::integral_constant{}); + else if (np) mainloop(std::integral_constant{}); + else mainloop(std::integral_constant{}); + } + { + // O's hardware row is the v dim and its column the token, which is the one place gfx1151 and + // gfx12 agree: accPackX()'s eight consecutive rows are eight consecutive v of one token, so + // this is libr4d's scale and store unchanged (a lane's token is mt*16 + lo). + float g = scale * s.ge[mt * 16 + lo]; // token index is constant per lane +#pragma unroll + for (int i = 0; i < NTV; ++i) +#pragma unroll + for (int e = 0; e < 8; ++e) O[i][e] *= g; + } + // The V' loop's A fragments come from HBM/L2: issued here, their latency is covered by the + // W / sA epilogue and barrier (2) instead of stalling the first V' WMMA. + v16bf af[BT / 16]; + { + const unsigned ao = rowGo((unsigned)ars, mt * 16, lim, lane); +#pragma unroll + for (int sk = 0; sk < BT / 16; ++sk) af[sk] = fragGo(ag, ao + sk * 16); + } + // W = beta * (V - ge*U) (beta folded here: (A*beta_col)@W == A@(beta_row*W)) + { + // Element e is token mt*16 + 2e + hi: one row pointer per lane, e and i are immediates. + const unsigned short* dv = &s.D[mt * 16 + hi][ntb * 16 + lo]; + const float* bp = &s.bt[mt * 16 + hi]; + const float* gp = &s.ge[mt * 16 + hi]; + float wa[NTV][8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { // beta / ge read once for both tiles + const float f = bp[2 * e], g = gp[2 * e]; +#pragma unroll + for (int i = 0; i < NTV; ++i) + wa[i][e] = f * (bf2f(dv[2 * e * AP + i * 16]) - g * u[i][e]); + } +#pragma unroll + for (int i = 0; i < NTV; ++i) + accSt(&s.W[(ntb + i) * 16 + lo][mt * 16 + 8 * hi], wa[i], lane); + } + // sA = scale * e^{g_i-g_j} * tril(P). Row ii is constant per lane and the eight g_j are + // uniform per 16 lanes: eight broadcast LDS reads, v_sub and v_exp per tile (log(scale) is + // in the exponent). Where kept, g_i - g_j <= 0, so the exp cannot overflow. + // gfx1151: element e is the key (ntb+i)*16 + 2e + hi, so j and its mask are per element; the + // 16 consecutive keys of the row are reassembled by accPackX(). + { + const int ii = mt * 16 + lo; + const float gis = s.gg[ii] + lgs; + const float* gj = &s.gg[ntb * 16 + hi]; +#pragma unroll + for (int i = 0; i < NTV; ++i) { + // The exp is taken for every element and the mask applied as a select after it: written + // as one conditional expression it lowers to a divergent branch around each LDS read + // and exp. Above the diagonal the exponent may overflow; the select discards it. + float a[8], x[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { + x[e] = p[i][e] * __expf(gis - gj[i * 16 + 2 * e]); + asm volatile("" : "+v"(x[e])); // keeps MachineSink from re-forming the branch + } +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int j = (ntb + i) * 16 + 2 * e + hi; + a[e] = (j <= ii) ? x[e] : 0.f; + } + accSt(&s.A[ii][(ntb + i) * 16 + 8 * hi], a, lane); + } + } + lds_barrier(); // (2) + + // ---- V' = gv * (A @ W) -> D (transposed store is one contiguous pair of dwords) + { + v8f d[NTV]; +#pragma unroll + for (int i = 0; i < NTV; ++i) d[i] = (v8f){}; + const unsigned short* pwn = rowP(&s.W[0][0], WP, ntb * 16, lane); +#define pwnf(i, ko) fragP(pwn + (i) * 16 * WP + (ko)) +#pragma unroll + for (int sk = 0; sk < BT / 16; ++sk) { + if (sk <= mt) { // A is lower triangular: A[mt][sk > mt] = 0 + const int ko = sk * 16; +#pragma unroll + for (int i = 0; i < NTV; ++i) d[i] = mma(af[sk], pwnf(i, ko), d[i]); + } + } +#pragma unroll + for (int i = 0; i < NTV; ++i) + accSt(&s.D[(ntb + i) * 16 + lo][mt * 16 + 8 * hi], d[i], lane); + } + // KT = (gs * K)^T, for the state's V'^T @ K: (diag(gs) V')^T K == V'^T (diag(gs) K). All raw-K + // reads (U, P) and s.S reads retired before barrier (2); barrier (3) publishes KT. A lane + // takes a token pair and eight k: two 16-byte row reads, eight dword stores of a [k] row + // (32 lanes, 32 consecutive dwords: no bank conflict). Same rounding as the old in-place + // scale: one f2bf of bf16(k) * gs per element. + { + const int t0 = 2 * lane; + const float f0 = s.gv[t0], f1 = s.gv[t0 + 1]; +#pragma unroll + for (int it = 0; it < KD / (8 * NW); ++it) { + const int c = (it * NW + wu) * 8; + const uint4 a = *(const uint4*)&s.k[t0][c], b = *(const uint4*)&s.k[t0 + 1][c]; + const unsigned av[4] = { a.x, a.y, a.z, a.w }, bw[4] = { b.x, b.y, b.z, b.w }; + unsigned* kt = (unsigned*)&s.KT[c][t0]; +#pragma unroll + for (int h = 0; h < 4; ++h) { + const float a0 = __builtin_bit_cast(float, av[h] << 16); + const float a1 = __builtin_bit_cast(float, av[h] & 0xffff0000u); + const float b0 = __builtin_bit_cast(float, bw[h] << 16); + const float b1 = __builtin_bit_cast(float, bw[h] & 0xffff0000u); + kt[(2 * h) * (AP / 2)] = f2bf2(a0 * f0, b0 * f1); + kt[(2 * h + 1) * (AP / 2)] = f2bf2(a1 * f0, b1 * f1); + } + } + } + lds_barrier(); // (3) + + // ---- O += sA @ V' ; store. V' also feeds the state update, unchanged. + { + const unsigned short* pA = rowP(&s.A[0][0], AP, mt * 16, lane); + const unsigned short* pdn = rowP(&s.D[0][0], AP, ntb * 16, lane); +#define pAf(ko) fragP(pA + (ko)) +#define pdnf(i, ko) fragP(pdn + (i) * 16 * AP + (ko)) +#pragma unroll + for (int sk = 0; sk < BT / 16; ++sk) { + if (sk <= mt) { // sA is masked to j <= i + const int ko = sk * 16; + v16bf b = pAf(ko); +#pragma unroll + for (int i = 0; i < NTV; ++i) O[i] = mma(pdnf(i, ko), b, O[i]); + } + } + } + { + // The half-wave exchange accPackX() does is a wave-wide lane operation (v_permlanex16), so it is + // taken for the whole wave and only the stores are guarded. A trailing partial chunk leaves + // lanes without a token, and a lane op under a divergent exec mask reads an inactive partner: + // measured as infinities in exactly those lanes' rows (see the pitch note above). + const int tok = mt * 16 + lo; + uint4 w[NTV]; +#pragma unroll + for (int i = 0; i < NTV; ++i) w[i] = accPk(O[i], lane); + if (tok < nval) { + // O's eight packed values are eight consecutive v of row tok (see the scale above). + unsigned short* op = o + ((size_t)(c0 + tok) * H + hv) * VD + v0; +#pragma unroll + for (int i = 0; i < NTV; ++i) + *(uint4*)(op + (ntb + i) * 16 + 8 * hi) = w[i]; + } + } + + // ---- S = e^{gl} * S + V'^T @ (gs*K) (A = KT rows, B = V' rows: both k-contiguous) + { + const float ec = __expf(gl); // gl <= 0: no lam, the decay is already on K +#pragma unroll + for (int t = 0; t < NST; ++t) +#pragma unroll + for (int e = 0; e < 8; ++e) St[t][e] *= ec; + const unsigned short* pvn = rowP(&s.D[0][0], AP, vt0 * 16, lane); + const unsigned short* pkt = rowP(&s.KT[0][0], AP, kt0 * 16, lane); +#pragma unroll + for (int sk = 0; sk < BT / 16; ++sk) { + v16bf bv[SVT]; +#pragma unroll + for (int j = 0; j < SVT; ++j) bv[j] = fragP(pvn + j * 16 * AP + sk * 16); +#pragma unroll + for (int ki = 0; ki < SKT; ++ki) { + v16bf ak = fragP(pkt + ki * 16 * AP + sk * 16); // K^T: m = k-dim +#pragma unroll + for (int j = 0; j < SVT; ++j) + St[ki * SVT + j] = mma(ak, bv[j], St[ki * SVT + j]); + } + } + } + lds_barrier(); // (4) + } + + if constexpr (!HT) return; + // Barrier (4) (or, with no chunk, the h0 load's last barrier) has retired every LDS read. +#pragma unroll + for (int t = 0; t < NST; ++t) +#pragma unroll + for (int e = 0; e < 8; ++e) SF(t, e) = St[t][e]; + lds_barrier(); + typename cs_state::T* p = ht + st_base + (size_t)v0 * KD; + if constexpr (SDT == 0) { +#pragma unroll + for (int u = 0; u < BV / NW; ++u) + *(float4*)(p + (wu + NW * u) * KD + lane * 4) = *(const float4*)&F[wu + NW * u][lane * 4]; + } else { + const int r0 = tid >> 4, c = (tid & 15) * 8; +#pragma unroll + for (int u = 0; u < BV * 16 / NTHR; ++u) { + const float* d = &F[r0 + (NTHR / 16) * u][c]; + const float4 a = *(const float4*)d, b = *(const float4*)(d + 4); + union { uint4 w; _Float16 h[8]; } x; + x.h[0] = (_Float16)a.x; x.h[1] = (_Float16)a.y; x.h[2] = (_Float16)a.z; x.h[3] = (_Float16)a.w; + x.h[4] = (_Float16)b.x; x.h[5] = (_Float16)b.y; x.h[6] = (_Float16)b.z; x.h[7] = (_Float16)b.w; + *(uint4*)(p + (r0 + (NTHR / 16) * u) * KD + c) = x.w; + } + } +} + +// Slot-indexed form (the one radiance calls). `sidx` names each batch row's state slot; without +// it the cache is indexed by row. `st_slot` and `st_head` are the cache strides in elements, which +// may exceed H*V*K when a caller pads its slots (vLLM pads to the attention page size). Pass +// sidx = null and strides 0 for the packed [N, H, V, K] layout. +extern "C" int r3dh_gdn_chunk_scan_k128_v128_c64_bf16_sidx( + const void* q, const void* k, const void* v, const void* A, const void* g, + const void* beta, const void* h0, void* o, void* ht, const void* cu, + const void* ssm_state_indices, long indices_stride, long state_slot_stride, + long state_head_stride, + int N, int H, int Hg, int K, int V, int bt, float scale, int state_fp16, void* stream) +{ + if (K != KD || V != VD || bt != BT) return -1; + // hq = hv / (H / Hg) truncates: H not a multiple of Hg would silently map v heads to the wrong + // k heads. Refused with -2, as in the kkt_solve and recurrent_update siblings. + if (Hg <= 0 || H % Hg) return -2; + const long st_head = state_head_stride > 0 ? state_head_stride : (long)VD * KD; + const long st_slot = state_slot_stride > 0 ? state_slot_stride : (long)H * VD * KD; + dim3 grid(V / BV, H, N), blk(NTHR); +#define CS_LAUNCH(SDTC, H0C, HTC) \ + hipLaunchKernelGGL((r3dh_gdn_chunk_scan_kernel), grid, blk, 0, \ + (hipStream_t)stream, \ + (const unsigned short*)q, (const unsigned short*)k, (const unsigned short*)v, \ + (const unsigned short*)A, (const float*)g, (const float*)beta, \ + (const cs_state::T*)h0, (unsigned short*)o, (cs_state::T*)ht, \ + (const int*)cu, (const int*)ssm_state_indices, (indices_stride > 0 ? indices_stride : 1), \ + st_slot, st_head, H, Hg, scale) +#define CS_PICK(SDTC) \ + do { if (h0 && ht) CS_LAUNCH(SDTC, true, true); \ + else if (h0) CS_LAUNCH(SDTC, true, false); \ + else if (ht) CS_LAUNCH(SDTC, false, true); \ + else CS_LAUNCH(SDTC, false, false); } while (0) + if (state_fp16) CS_PICK(1); else CS_PICK(0); +#undef CS_PICK +#undef CS_LAUNCH + return (int)hipGetLastError(); +} + +// Packed-layout entry point for the out-of-tree vLLM caller: one state per batch row, +// [N, H, V, K]. +extern "C" int r3dh_gdn_chunk_scan_k128_v128_c64_bf16( + const void* q, const void* k, const void* v, const void* A, const void* g, + const void* beta, const void* h0, void* o, void* ht, const void* cu, + int N, int H, int Hg, int K, int V, int bt, float scale, int state_fp16, void* stream) +{ + return r3dh_gdn_chunk_scan_k128_v128_c64_bf16_sidx(q, k, v, A, g, beta, h0, o, ht, cu, + nullptr, 0, 0, 0, N, H, Hg, K, V, bt, scale, + state_fp16, stream); +} + +// The compiled geometry, so callers can check a model's GDN shape against it. +extern "C" void r3dh_gdn_dims(int* head_k, int* head_v, int* chunk) { + if (head_k) *head_k = KD; + if (head_v) *head_v = VD; + if (chunk) *chunk = BT; +} + +// ============================================================== the plugin ABI entry points +// Shared operand helpers: r3dh_gdn_args.h. +/* ------------------------------------------------------------------ chunk scan */ + +enum { CS_Q = 0, CS_K, CS_V, CS_A, CS_G, CS_BETA, CS_H0, CS_CU, CS_O, CS_HT, CS_SIDX }; + +extern "C" int r3dh_rad_gdn_chunk_scan(const RadArgs* a, RadStream s) { + if (gdn_dims_ok() != RAD_OK) return R3DH_NO(RAD_E_SHAPE); + const RadTensor* q = r3dh_opt(a, CS_Q); + const RadTensor* k = r3dh_opt(a, CS_K); + const RadTensor* v = r3dh_opt(a, CS_V); + const RadTensor* A = r3dh_opt(a, CS_A); + const RadTensor* g = r3dh_opt(a, CS_G); + const RadTensor* bt = r3dh_opt(a, CS_BETA); + const RadTensor* h0 = r3dh_opt(a, CS_H0); + const RadTensor* cu = r3dh_opt(a, CS_CU); + const RadTensor* o = r3dh_opt(a, CS_O); + const RadTensor* ht = r3dh_opt(a, CS_HT); + const RadTensor* sidx = r3dh_opt(a, CS_SIDX); + if (!q || !k || !v || !A || !g || !bt || !cu || !o) return R3DH_NO(RAD_E_INVAL); + if (q->rank != 3 || k->rank != 3 || v->rank != 3 || o->rank != 3) return R3DH_NO(RAD_E_SHAPE); + if (A->rank != 3 || g->rank != 2 || bt->rank != 2) return R3DH_NO(RAD_E_SHAPE); + + int N = 0; + int rc = seqs_of(cu, &N); + if (rc != RAD_OK) return rc; + + /* The entry point takes no pitches: everything must be dense. */ + if (!r3dh_contig(q) || !r3dh_contig(k) || !r3dh_contig(v) || !r3dh_contig(A) || + !r3dh_contig(g) || !r3dh_contig(bt) || !r3dh_contig(o)) return R3DH_NO(RAD_E_STRIDE); + + /* bf16 q/k/v/A/out, fp32 gate/beta. */ + R3DH_DT(q, RAD_BF16); R3DH_DT(k, RAD_BF16); R3DH_DT(v, RAD_BF16); R3DH_DT(A, RAD_BF16); + R3DH_DT(o, RAD_BF16); R3DH_DT(g, RAD_F32); R3DH_DT(bt, RAD_F32); + /* The state cache is f32 or f16, taken from the operand's dtype (a property of the + * allocation), so this kernel and the recurrent update, which share the cache, agree on it. */ + const uint32_t st_dt = h0 ? h0->dtype : (ht ? ht->dtype : (uint32_t)RAD_F32); + if (st_dt != RAD_F32 && st_dt != RAD_F16) return R3DH_NO(RAD_E_DTYPE); + if (h0) R3DH_DT(h0, st_dt); + if (ht) R3DH_DT(ht, st_dt); + /* Slot strides come from the tensor, not from H, V and K, so a cache with padded slots is + * served too; the engine's own state cache is dense ([n_states, H, V, K] per layer). h0 and + * ht must share strides, since the kernel uses one base offset for both. */ + long long st_slot = 0, st_head = 0; + if (h0) { + if (h0->rank < 2) return R3DH_NO(RAD_E_SHAPE); + st_slot = h0->stride[0]; + st_head = h0->stride[1]; + } + if (ht) { + if (ht->rank < 2) return R3DH_NO(RAD_E_SHAPE); + if (h0 && (ht->stride[0] != st_slot || ht->stride[1] != st_head)) + return R3DH_NO(RAD_E_STRIDE); + st_slot = ht->stride[0]; + st_head = ht->stride[1]; + } + if (sidx) { + R3DH_DT(sidx, RAD_I32); + if (sidx->rank < 1 || sidx->shape[0] != N) return R3DH_NO(RAD_E_SHAPE); + if (sidx->stride[sidx->rank - 1] != 1) return R3DH_NO(RAD_E_STRIDE); + } + + const long long T = q->shape[0]; + const long long Hg = q->shape[1]; + const long long K = q->shape[2]; + const long long H = v->shape[1]; + const long long V = v->shape[2]; + const long long bt_chunk = A->shape[2]; + if (k->shape[0] != T || k->shape[1] != Hg || k->shape[2] != K) return R3DH_NO(RAD_E_SHAPE); + if (v->shape[0] != T || o->shape[0] != T || o->shape[1] != H || o->shape[2] != V) + return R3DH_NO(RAD_E_SHAPE); + if (A->shape[0] != T || A->shape[1] != H) return R3DH_NO(RAD_E_SHAPE); + if (g->shape[0] != T || g->shape[1] != H) return R3DH_NO(RAD_E_SHAPE); + if (bt->shape[0] != T || bt->shape[1] != H) return R3DH_NO(RAD_E_SHAPE); + if (H == 0 || Hg == 0 || H % Hg) return R3DH_NO(RAD_E_SHAPE); + + const float scale = (float)r3dh_getf(a, "scale", 1.0); + const int state_fp16 = st_dt == RAD_F16; + + return R3DH_RAW(r3dh_gdn_chunk_scan_k128_v128_c64_bf16_sidx( + q->data, k->data, v->data, A->data, g->data, bt->data, + h0 ? h0->data : nullptr, o->data, ht ? ht->data : nullptr, cu->data, + sidx ? sidx->data : nullptr, sidx && sidx->rank >= 2 ? (long)sidx->stride[0] : 1, + (long)st_slot, (long)st_head, + N, (int)H, (int)Hg, (int)K, (int)V, (int)bt_chunk, scale, state_fp16, s)); +} + diff --git a/libr3d/r3dh_gdn_conv_tap.h b/libr3d/r3dh_gdn_conv_tap.h new file mode 100644 index 00000000..80c261b3 --- /dev/null +++ b/libr3d/r3dh_gdn_conv_tap.h @@ -0,0 +1,23 @@ +/* Ported from libhalo/halo_gdn_conv_tap.h, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_gdn_conv_tap.h by the libhalo rename transform (2026-10-26); + * see libhalo/README.md. Op schemas, row names and stored weight layouts are + * shared with libr4d by design. Everything else in this file is libhalo's own + * and diverges as it is measured on gfx1151. */ +// r3dh_gdn_conv_tap.h -- the arithmetic of one gated-delta-net convolution output, shared by the +// standalone conv kernels (r3dh_gdn_conv_w4_h128_bf16.hip) and the recurrent update that folds the +// decode convolution into its prologue (r3dh_gdn_recurrent_update_k128_v128_bf16_fp32state.hip). +// A single definition keeps the fold byte-identical to the standalone path: the reciprocal form +// below changes the last bit of some bf16 outputs. +#pragma once + +#define R3DH_GDN_CONV_W 4 // conv width; the state holds R3DH_GDN_CONV_W - 1 taps of history + +// The result is rounded to bf16 immediately, so an IEEE-exact divide buys nothing: v_rcp_f32 is +// 1 ULP (~1e-7 relative) against bf16's 2^-8 quantum. The exact form is ~10 dependent instructions +// (v_div_scale, v_rcp, Newton, v_div_fmas, v_div_fixup); this is two. The conv update runs four +// waves on five workgroups, so its time is its instruction count. +__device__ __forceinline__ float cp_silu(float z) { + return z * __builtin_amdgcn_rcpf(1.0f + __expf(-z)); +} diff --git a/libr3d/r3dh_gdn_kkt_solve.hip b/libr3d/r3dh_gdn_kkt_solve.hip new file mode 100644 index 00000000..798c143c --- /dev/null +++ b/libr3d/r3dh_gdn_kkt_solve.hip @@ -0,0 +1,366 @@ +/* Ported from libhalo/halo_gdn_kkt_solve.hip, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_gdn_kkt_solve_k128_c64_bf16.hip by the libhalo rename transform (2026-10-26), + * then ported to gfx1151; see libhalo/README.md. */ +// r3dh_gdn_kkt_solve_k128_c64_bf16.hip -- the gated-delta-net chunk preamble in one kernel: +// +// A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1} per chunk of 64 +// +// Replaces FLA's chunk_scaled_dot_kkt_fwd + solve_tril, whose 64x64 fp32 intermediate per +// (chunk, head) round-trips through HBM. Here the gram stays in LDS and only the bf16 inverse is +// stored. Also: +// +// * The gram is computed once per k head, not per v head: K K^T does not depend on beta or g, +// so one workgroup owns a (chunk, k head) and applies each v head's scales to it. +// * The gram is computed as its upper-triangle tiles. K K^T is symmetric, and read transposed +// into A's strictly lower half each accumulator holds eight consecutive columns of one row: +// one 16-byte LDS store instead of eight 2-byte ones. +// +// The decay is applied per element as e^{g_i-g_j}, not split about a per-chunk reference c: each +// half of e^{g_i-c} * e^{c-g_j} can overflow fp32 on its own. Here the exponent is always <= 0 +// (g decreases along the chunk and only i > j is kept), and the eight exps per tile are cheap in +// a memory-bound kernel. +// +// The inverse is blocked 16 -> 32 -> 64. The four diagonal blocks use fp32 forward substitution +// (one wave each, one lane per column), cheaper than a WMMA Neumann series at this size and exact +// in fp32, as in FLA. The 32-merges and the 64-merge are WMMA, using +// +// [[P, 0], [R, Q]]^-1 = [[P^-1, 0], [-Q^-1 R P^-1, Q^-1]] +// +// mma(X, Y) computes X . Y^T from two k-contiguous operands, so a left operand is row-major and a +// right operand is stored transposed. An accumulator writes its transpose contiguously, so the +// intermediates are staged transposed; the final inverse is assembled row-major for the HBM store. +// +// ---- gfx1151 port notes (everything below the gram loop is unchanged in arithmetic) ----------- +// A gfx11 accumulator element e is D[2e + (lane>>4)][lane & 15], not gfx12's D[8*(lane>>4) + e] +// [lane & 15], so NO write-out here can keep libr4d's store arithmetic (r3dh_gdn_wmma.h). Two +// cases, and the kernel is split between them by where the value has to land: +// +// * a TRANSPOSED stage (TMP, and the gram's slice of A) -- eight consecutive rows of one column. +// accPack() reassembles exactly that from the half-pair, so the store is libr4d's (dst[lo] +// [8*hi]) with the eight values coming from accPack instead of f2bf4. The per-element scale +// and mask must be applied BEFORE the exchange: the two halves scale different rows. +// * a ROW-MAJOR stage into A (the two merge results), eight consecutive columns of one row. +// accPack() of the gfx11 accumulator gives rows, so the merge is taken with its two operands +// swapped -- mma is X.Y^T, so swapping them transposes the result and accPack then hands out +// C[lo][8*hi + 0..7]. Same two fragments, read on the other side. +#include +#include "r3dh.h" +#include "r3dh_common.h" // lds_barrier +#include "r3dh_gdn_args.h" +#include "r3dh_gdn_wmma.h" + +// libr4d's rounding helpers (r4d_gdn_wmma.h) -- f2bf / bf2f -- are r3dh_gdn_wmma.h's (included +// above): f2bf is round-half-AWAY, one add, which is what makes this kernel bit-comparable with the +// libr4d path. gfx1151 has no v_cvt_pk_bf16_f32 either. + +// One accumulator stage: the eight elements accPack() assembles, as two 8-byte stores. The buffers +// here are only 8-byte aligned (AP = 68 shorts), so a 16-byte store would be misaligned on odd rows. +// accPack() packs with halo::pk_bf16, i.e. round-to-nearest-even, where libr4d's f2bf4 rounds half +// away; the two differ only on an exact bf16 tie, and these are inverse intermediates. Both operand +// shapes are offered so a call site reads the same whether it holds a v8f or a float[8]. +__device__ __forceinline__ void accSt(unsigned short* dst, v8f v, int lane) { + union { v8f f; float s[8]; } u; + u.f = v; + const uint4 w = accPack(u.s, lane); + *(uint2*)dst = make_uint2(w.x, w.y); + *(uint2*)(dst + 4) = make_uint2(w.z, w.w); +} +__device__ __forceinline__ void accSt(unsigned short* dst, const float v[8], int lane) { + const uint4 w = accPack(v, lane); + *(uint2*)dst = make_uint2(w.x, w.y); + *(uint2*)(dst + 4) = make_uint2(w.z, w.w); +} + +#define BT 64 // chunk +#define KD 128 // head_k +#define NBK 4 // 16x16 blocks per chunk edge +// Row pitches are multiples of 8 shorts (16 B): r3dh_gdn_wmma.h's fragP reads a lane's whole 16-wide +// k run as two 16-byte LDS loads, so a buffer whose pitch is 136 B or 264 B (libr4d's AP = 68 / TMP +// = 36) puts every odd row 8 bytes off a 16-byte boundary, and a misaligned ds_load_b128 returns +// garbage. See r3dh_gdn_chunk_scan.hip's note: measured there as infs in a partial chunk. +#define AP 72 // row pitch of the [BT][BT] buffers, in shorts (144 B), 16-byte + // aligned for the paired stores; 16 rows still cover every bank +#define TMPP 40 // row pitch of the 32x32 transposed scratch, in shorts (80 B) +#define NW 4 +#define NTHR (NW * 32) +#define NTILE 10 // upper-triangular tiles of a 4x4 tiling +#define MAXT ((NTILE + NW - 1) / NW) + +// LDS limits occupancy, and this kernel is memory-bound, so buffers are minimised. No transposed +// inverse is kept (fragT rebuilds the three right operands that need it). The inverse is formed +// in place in A, since each stage reads the block it overwrites before writing it, with barriers +// between stages: +// diagonal p reads A[p][p], writes it after the substitution has finished reading +// 32-merge reads A10 and the two diagonal inverses, writes A10 +// 64-merge reads R = A[32:,:32] into TMP everywhere, barrier, then writes it +// One 64x64 buffer plus a 32x32 scratch: 11 KB instead of 31 KB. +struct KkSmem { + unsigned short A[BT][AP]; // A on the way in, its inverse on the way out + unsigned short TMP[32][TMPP]; // one 32x32 intermediate, transposed + float gb[BT], bt[BT]; // the chunk's gate cumsum and beta, per token +}; + +// (mt, nt) of upper-triangular tile ti, computed with wave-uniform arithmetic instead of a +// __constant__ table load. +__device__ __forceinline__ void kkt_tile(int ti, int* mt, int* nt) { + int m = 0, n = ti; + while (n >= NBK - m) { n -= (NBK - m); ++m; } + *mt = m; *nt = n + m; +} + +// No occupancy hint: at HG_RATIO=3 the kernel uses 190 VGPRs (8 waves per SIMD; LDS would allow +// 10), and forcing 10 waves spills 148 bytes per lane and is ~57% slower. +template +__global__ +__launch_bounds__(NTHR) +void r3dh_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, + const float* __restrict__ beta, + const float* __restrict__ g, + unsigned short* __restrict__ Ao, + const int* __restrict__ cu, + int N, int H, int Hg) +{ + __shared__ KkSmem s; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int lo = lane & 15, hi = lane >> 4; + const int hg = blockIdx.y; + + // Resolve the flat chunk id to (sequence, chunk). The grid is an upper bound on the chunk + // count, so surplus workgroups exit here; this saves the host a device-to-host sync to size + // the grid exactly. + int n = -1, t0 = 0, bos = 0, rows = 0; + { + int acc = 0, want = blockIdx.x; + for (int i = 0; i < N; ++i) { + const int b = cu[i], e = cu[i + 1]; + const int nc = (e - b + BT - 1) / BT; + if (want < acc + nc) { n = i; bos = b; t0 = (want - acc) * BT; + rows = min(BT, e - b - t0); break; } + acc += nc; + } + if (n < 0) return; + } + + // ---- zero A once: the parts no store reaches (the upper tiles) are the same for every head. + // 16-byte stores (the buffer is 8704 bytes, 16-byte aligned). + for (int i = tid; i < BT * AP / 8; i += NTHR) ((uint4*)&s.A[0][0])[i] = make_uint4(0, 0, 0, 0); + + // ---- the gram, once for all HG_RATIO v heads of this k head ----------------------------- + const unsigned short* kp = k + ((size_t)(bos + t0) * Hg + hg) * KD; + const unsigned krow = (unsigned)(Hg * KD); + v8f P[MAXT]; +#pragma unroll + for (int t = 0; t < MAXT; ++t) P[t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; +#pragma unroll + for (int t = 0; t < MAXT; ++t) { + const int ti = warp + t * NW; + if (ti < NTILE) { + int mt, nt; kkt_tile(ti, &mt, &nt); + // One 32-bit offset per operand row, hoisted out of the k loop (see rowGo/fragGo). + const unsigned om = rowGo(krow, mt * 16, rows - 1, lane); + const unsigned on = rowGo(krow, nt * 16, rows - 1, lane); +#pragma unroll + for (int sk = 0; sk < KD / 16; ++sk) + P[t] = mma(fragGo(kp, om + sk * 16), fragGo(kp, on + sk * 16), P[t]); + } + } + + for (int hh = 0; hh < HG_RATIO; ++hh) { + const int hv = hg * HG_RATIO + hh; + + // ---- per-head gate and beta for this chunk + if (tid < BT) { + const int t = min(tid, rows - 1); + s.gb[tid] = g[(size_t)(bos + t0 + t) * H + hv]; + s.bt[tid] = beta[(size_t)(bos + t0 + t) * H + hv]; + } + lds_barrier(); + + // ---- scale, mask and place the gram as the strictly lower half of A --------------------- + // Tile (mt, nt) holds P[m][n]; the element written is A[n][m], in the lower triangle when + // n > m. n is fixed per lane and m runs over the eight accumulator elements: one row of A, + // one 8-short store. + // + // gfx1151: element e is m = mt*16 + 2e + hi, not mt*16 + 8hi + e, so the eight columns this + // lane owns are two-apart and interleaved with its half-partner's. Each element is scaled by + // its OWN exponent first, and accPack() then reassembles the 16 consecutive columns of row i + // out of the half-pair: this lane keeps columns mt*16 + 8*hi .. +7, as on gfx12. +#pragma unroll + for (int t = 0; t < MAXT; ++t) { + const int ti = warp + t * NW; + if (ti < NTILE) { + int mt, nt; kkt_tile(ti, &mt, &nt); + const int i = nt * 16 + lo; // row of A + const int j0 = mt * 16 + 8 * hi; // first column of A, after the exchange + const bool live = (i < rows); + const float bi = live ? s.bt[i] : 0.0f; + const float gi = live ? s.gb[i] : 0.0f; + float vv[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int j = mt * 16 + 2 * e + hi; + // For a live row, i > j gives g_i <= g_j, so the exponent is never positive. Padding + // rows and columns must be masked to -inf: with gi = 0 the exponent -gb[j] is large and + // positive, 0 * inf = NaN, and the WMMA merges in the blocked inverse would spread it + // into live rows. + const float d = (live && i > j && j < rows) ? (gi - s.gb[j]) : -INFINITY; + vv[e] = bi * __expf(d) * P[t][e]; + } + accSt(&s.A[i][j0], vv, lane); + } + } + lds_barrier(); + + // ---- 1. the four diagonal blocks, by fp32 forward substitution -------------------------- + // D = (I + N)^-1 solves D = I - N D row by row. Lane l owns column l of D, so the dot product + // over j < i is in 16 registers and N[i][j] is a broadcast LDS read. + for (int p = warp; p < NBK; p += NW) { + const int b0 = p * 16; + float d[16]; +#pragma unroll + for (int i = 0; i < 16; ++i) { + float acc = 0.0f; +#pragma unroll + for (int j = 0; j < 16; ++j) + if (j < i) acc += bf2f(s.A[b0 + i][b0 + j]) * d[j]; + d[i] = ((lo == i) ? 1.0f : 0.0f) - acc; + } + if (lane < 16) { +#pragma unroll + for (int i = 0; i < 16; ++i) s.A[b0 + i][b0 + lo] = f2bf(d[i]); + } + } + lds_barrier(); + + // ---- 2. the two 32-merges: M10 = -D1 A10 D0 -------------------------------------------- + for (int blk = warp; blk < 2; blk += NW) { + const int r0 = blk * 32; // 32-block origin + // X = A10 . D0 (left A10 row-major, right D0 transposed = MT) + v8f X = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + X = mma(frag(&s.A[0][0], AP, r0 + 16, r0, lane), + fragT(&s.A[0][0], AP, r0, r0, lane), X); + // Stage X transposed for the next product; each of the two merges owns 16 rows of TMP. + accSt(&s.TMP[blk * 16 + lo][8 * hi], X, lane); + // Same wave writes and reads TMP here, and LDS accesses from one wave complete in order. + __builtin_amdgcn_wave_barrier(); + // M10 = -D1 . X (left D1 row-major, in place in A; right X transposed, in TMP) + // Operands swapped on gfx1151: this accumulates Y^T, so accPack() below hands out eight + // consecutive rows of Y -- which is a row-major store into A. TMP already holds X^T (what + // libr4d stages), which is this product's LEFT operand here, and D1 the right one. + v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + Y = mma(frag(&s.TMP[0][0], TMPP, blk * 16, 0, lane), + frag(&s.A[0][0], AP, r0 + 16, r0 + 16, lane), Y); + float yv[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) yv[e] = -Y[e]; + accSt(&s.A[r0 + 16 + lo][r0 + 8 * hi], yv, lane); // rows of M10, 8 columns each + } + lds_barrier(); + + // ---- 3. the 64-merge: M[32:,:32] = -Q^-1 (R P^-1) -------------------------------------- + // Y = R . P^-1, R = A[32:,:32] row-major, P^-1 read transposed out of A[:32,:32] by fragT + for (int t = warp; t < 4; t += NW) { + const int mt = t >> 1, nt = t & 1; + v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; +#pragma unroll + for (int sk = 0; sk < 2; ++sk) + Y = mma(frag(&s.A[0][0], AP, 32 + mt * 16, sk * 16, lane), + fragT(&s.A[0][0], AP, nt * 16, sk * 16, lane), Y); + accSt(&s.TMP[nt * 16 + lo][mt * 16 + 8 * hi], Y, lane); + } + lds_barrier(); // every wave has read R into TMP; now it may be overwritten + // Z = -Q^-1 . Y, Q^-1 = A[32:,32:] row-major, Y transposed = TMP + // Swapped, as M10 above: this accumulates Z^T so accPack() gives a row-major store. Y^T sits + // in TMP ([col][row]) and is the left operand here; Q^-1's rows are the right one. + for (int t = warp; t < 4; t += NW) { + const int mt = t >> 1, nt = t & 1; + v8f Z = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; +#pragma unroll + for (int sk = 0; sk < 2; ++sk) + Z = mma(frag(&s.TMP[0][0], TMPP, nt * 16, sk * 16, lane), + frag(&s.A[0][0], AP, 32 + mt * 16, 32 + sk * 16, lane), Z); + float zv[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) zv[e] = -Z[e]; + accSt(&s.A[32 + mt * 16 + lo][nt * 16 + 8 * hi], zv, lane); + } + lds_barrier(); + + // ---- store: one row of the inverse is 64 bf16, contiguous in HBM ----------------------- + { + unsigned short* op = Ao + ((size_t)(bos + t0) * H + hv) * BT; + const size_t orow = (size_t)H * BT; + for (int r = tid / 8; r < rows; r += NTHR / 8) { + const int c8 = (tid & 7) * 8; + *(uint4*)(op + (size_t)r * orow + c8) = *(const uint4*)(&s.A[r][c8]); + } + } + if (hh + 1 < HG_RATIO) lds_barrier(); + } +} + +extern "C" int r3dh_gdn_kkt_solve_k128_c64_bf16(const void* k, const void* beta, const void* g, + void* A, const void* cu, int N, int T, int H, + int Hg, int K, int bt, void* stream) +{ + if (K != KD || bt != BT) return -1; + if (H % Hg) return -2; + const int nchunk_ub = (T + BT - 1) / BT + N; // sum of per-sequence chunk counts, bounded + dim3 grid(nchunk_ub, Hg), blk(NTHR); +#define KK_LAUNCH(R) \ + hipLaunchKernelGGL((r3dh_gdn_kkt_solve_kernel), grid, blk, 0, (hipStream_t)stream, \ + (const unsigned short*)k, (const float*)beta, (const float*)g, \ + (unsigned short*)A, (const int*)cu, N, H, Hg) + switch (H / Hg) { + case 1: KK_LAUNCH(1); break; + case 2: KK_LAUNCH(2); break; + case 3: KK_LAUNCH(3); break; + case 4: KK_LAUNCH(4); break; + case 6: KK_LAUNCH(6); break; + case 8: KK_LAUNCH(8); break; + default: return -3; + } +#undef KK_LAUNCH + return (int)hipGetLastError(); +} + +// ============================================================== the plugin ABI entry points +// Shared operand helpers: r3dh_gdn_args.h. +/* ------------------------------------------------------------------ kkt solve */ + +enum { KS_K = 0, KS_BETA, KS_G, KS_CU, KS_A }; + +extern "C" int r3dh_rad_gdn_kkt_solve(const RadArgs* a, RadStream s) { + if (gdn_dims_ok() != RAD_OK) return R3DH_NO(RAD_E_SHAPE); + const RadTensor* k = r3dh_opt(a, KS_K); + const RadTensor* bt = r3dh_opt(a, KS_BETA); + const RadTensor* g = r3dh_opt(a, KS_G); + const RadTensor* cu = r3dh_opt(a, KS_CU); + const RadTensor* A = r3dh_opt(a, KS_A); + if (!k || !bt || !g || !cu || !A) return R3DH_NO(RAD_E_INVAL); + if (k->rank != 3 || bt->rank != 2 || g->rank != 2 || A->rank != 3) return R3DH_NO(RAD_E_SHAPE); + if (!r3dh_contig(k) || !r3dh_contig(bt) || !r3dh_contig(g) || !r3dh_contig(A)) + return R3DH_NO(RAD_E_STRIDE); + /* bf16 k and A (the output, written as bf16); fp32 beta and gate. */ + R3DH_DT(k, RAD_BF16); R3DH_DT(A, RAD_BF16); R3DH_DT(bt, RAD_F32); R3DH_DT(g, RAD_F32); + + int N = 0; + int rc = seqs_of(cu, &N); + if (rc != RAD_OK) return rc; + + const long long T = k->shape[0]; + const long long Hg = k->shape[1]; + const long long K = k->shape[2]; + const long long H = bt->shape[1]; + const long long chunk = A->shape[2]; + if (g->shape[0] != T || g->shape[1] != H || bt->shape[0] != T) return R3DH_NO(RAD_E_SHAPE); + if (A->shape[0] != T || A->shape[1] != H) return R3DH_NO(RAD_E_SHAPE); + if (H == 0 || Hg == 0 || H % Hg) return R3DH_NO(RAD_E_SHAPE); + + return R3DH_RAW(r3dh_gdn_kkt_solve_k128_c64_bf16(k->data, bt->data, g->data, A->data, + cu->data, N, (int)T, (int)H, (int)Hg, (int)K, + (int)chunk, s)); +} + diff --git a/libr3d/r3dh_gdn_recurrent_update.hip b/libr3d/r3dh_gdn_recurrent_update.hip new file mode 100644 index 00000000..7fd07aff --- /dev/null +++ b/libr3d/r3dh_gdn_recurrent_update.hip @@ -0,0 +1,1229 @@ +/* Ported from libhalo/halo_gdn_recurrent_update_k128_v128_bf16_fp32state.hip, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip by the libhalo rename transform (2026-10-26), + * then ported to gfx1151; see libhalo/README.md. */ +// r3dh_gdn_recurrent_update_k128_v128_bf16_fp32state.hip -- the gated-delta-net recurrent state +// update, run by decode (prefill runs the chunked scan). One kernel for the whole step: +// +// g = -exp(A_log) . softplus(a + dt_bias) beta = sigmoid(b) q, k l2-normalised +// S *= e^g +// u = beta . (v - S k) S += u k^T o = S q +// +// per token, against a paged state cache: the initial state is read from the slot the last +// accepted token wrote, and every candidate token writes its own slot, since which survives +// verification is unknown until after this layer. Replaces FLA's +// fused_sigmoid_gating_delta_rule_update; the non-speculative case is width 1. +// +// State traffic is the whole cost: one fp32 [V,K] state is 64 KB, written per candidate token per +// head (113 MB per layer per rank at width 9, at the memory bandwidth limit). So the design keeps +// the state in registers: one thread owns one v row and half its k range, so +// +// * S k and S q are in-lane dot products closed by a single lane<->lane^1 exchange, not a +// tree reduction; +// * the outer-product update is 64 independent FMAs with no cross-lane traffic at all; +// * a thread's 64 state elements are contiguous in k, so the load and every store is four +// 16-byte accesses over one 256-byte run. +// +// The state cache is fp32 by default (the model's HF config sets mamba_ssm_dtype=float32, which +// vLLM honours); the conv state is bf16. An fp16 state cache is also supported (SDT). +// +// Slot and head strides are arguments, not H*V*K: vLLM's hybrid cache pads a mamba page to the +// attention page size (e.g. 421888 elements per slot vs 393216 from the shape), so a shape-derived +// stride would read every slot but the first at the wrong offset there. +#include +#include "r3dh.h" +#include "r3dh_gdn_args.h" +#include "r3dh_common.h" // bf16_to_f32 / f32_to_bf16, r3dh_xor_lane +#include "r3dh_gdn_conv_tap.h" +#include "r3dh_q8.h" // the 8-bit codes the folded quantiser writes: E4M3 or int8 +#include +#include +#include +#include +#include + +#define RU_K 128 // head_k +#define RU_V 128 // head_v +#define RU_HK 64 // k elements per thread (RU_K / 2) +#define RU_THR (RU_V * 2) // two threads per v row + +// The state written per step (~12 MB a layer, ~660 MB a step) is read again only once, a step +// later, and cannot stay in the 64 MB last-level cache; its write-back slows the next GEMM (a +// (5120, 3072) GEMM goes from 14.9 us to 20.4 us behind a 12 MB write flood, 18.4 us when the +// flood is non-temporal). A non-temporal hint on the state load and store changes no result, and +// whether it pays depends on the flood size, so it is chosen per launch (RU_NT_MB below). +typedef float ru_f4 __attribute__((ext_vector_type(4))); +typedef _Float16 ru_h8 __attribute__((ext_vector_type(8))); + +// SDT is the state cache's element type (0 = fp32, 1 = fp16); all arithmetic is fp32. At eight +// sequences x eight candidates a call is ~68 us, of which ~45 us is 24 MB of state traffic at 88% +// of achievable bandwidth; halving the state width saves about a third. +// +// Cost model (eight sequences, 16k context, anchor state): ~3.2 us per token walked plus ~57 us +// fixed per layer. State traffic largely overlaps the token loop (fp16 state saves only about a +// fifth of what its byte count predicts), and the loop is on the critical path. +// +// Shipped instantiation: 207 VGPRs, 7 waves/SIMD, no spill, 384 B LDS (the gfx1201 numbers; the +// gfx1151 port keeps the same geometry -- the kernel is scalar per thread and carries no WMMA +// fragment, so no lane mapping changes across the two parts). At seven waves the serial +// `dot +=` and `on +=` chains are hidden; splitting them would only change the summation order. +// +// fp16 rather than bf16: state elements are O(0.1) (sums of beta (v - Sk) k^T with l2-normalised +// k), so range is no issue and fp16's mantissa gives ~5e-4 relative round-trip error. vLLM's +// --mamba-ssm-cache-dtype already accepts float16. +template struct ru_state { using T = float; }; +template <> struct ru_state<1> { using T = _Float16; }; + +// Eight elements per call: two 16-byte accesses in fp32, one in fp16. +template +__device__ __forceinline__ void ru_load8(float* d, const typename ru_state::T* p) { + if constexpr (SDT) { + const ru_h8 t = NT ? __builtin_nontemporal_load((const ru_h8*)p) : *(const ru_h8*)p; +#pragma unroll + for (int e = 0; e < 8; ++e) d[e] = (float)t[e]; + } else { + const ru_f4* q = (const ru_f4*)p; + *(ru_f4*)d = NT ? __builtin_nontemporal_load(q) : *q; + *(ru_f4*)(d + 4) = NT ? __builtin_nontemporal_load(q + 1) : *(q + 1); + } +} + +template +__device__ __forceinline__ void ru_store8(typename ru_state::T* p, const float* d) { + if constexpr (SDT) { + ru_h8 t; +#pragma unroll + for (int e = 0; e < 8; ++e) t[e] = (_Float16)d[e]; + if (NT) __builtin_nontemporal_store(t, (ru_h8*)p); + else *(ru_h8*)p = t; + } else { + ru_f4* q = (ru_f4*)p; + if (NT) { + __builtin_nontemporal_store(*(const ru_f4*)d, q); + __builtin_nontemporal_store(*(const ru_f4*)(d + 4), q + 1); + } else { + *q = *(const ru_f4*)d; + *(q + 1) = *(const ru_f4*)(d + 4); + } + } +} +// VS: workgroups sharing a head's 128 v rows. At one sequence the (sequences, heads) grid is 24 +// workgroups on 64 CUs, and the working set fits the last-level cache. v rows are independent +// (dot products contract over k; the update is per (v, k)); only the fused RMS norm spans the +// row, so VS > 1 is compiled without it. +#define WGTARGET 64 // workgroups the v-row split aims for + +// A group's (decay, beta) as the two adjacent factor values the layout names. +// +// gfx1151: with an fp16 state cache these are two 16-bit stores at consecutive addresses, and +// LLVM's store merging fuses them into one dword built by `v_lshl_or_b32` on a 16-bit +// sub-register, which gfx11's encoding does not accept -- the whole unit then fails to compile +// ("Operand has incorrect register class"). Converting the pair as a vector packs it in one +// `v_cvt_pk_f16_f32`, the same round-to-nearest-even as the two stores, and the layout is +// unchanged: libr4d and libref read this block. +template +__device__ __forceinline__ void ru_store_gb(typename ru_state::T* p, float g, float bt) { + if constexpr (SDT) { + typedef float v2fx __attribute__((ext_vector_type(2))); + typedef _Float16 v2hx __attribute__((ext_vector_type(2))); + union { v2hx h; uint32_t u; } q; + q.h = __builtin_convertvector(v2fx{ g, bt }, v2hx); + *(uint32_t*)p = q.u; + } else { + ((float*)p)[0] = g; + ((float*)p)[1] = bt; + } +} + +__device__ __forceinline__ float ru_softplus(float x, float thr) { + if (x > thr) return x; + return (x > 0.0f) ? (x + __logf(1.0f + __expf(-x))) : __logf(1.0f + __expf(x)); +} + +// a and b are a chunk() of the ba projection (see r3dh_gdn_conv_w4_h128_bf16.hip). +template +__device__ __forceinline__ float ru_ab(const void* p, size_t i) { + return ABF16 ? bf16_to_f32(((const unsigned short*)p)[i]) : ((const float*)p)[i]; +} + +// The layer's gated RMS norm, folded into the epilogue: with NORM a workgroup owns one (sequence, +// head) and so the whole 128-channel output row, and the norm is one workgroup reduction per +// token. Prefill owns half a row and uses r3dh_gdn_gated_rmsnorm_h128_bf16 instead. +__device__ __forceinline__ float ru_act(float z, int kind) { + const float s = 1.0f / (1.0f + __expf(-z)); + return kind ? s : z * s; +} + +// One token's replay factors (anchor state), inside the head's block of a factor slot: +// +// [0 .. 4*K) normalised k, FOUR copies -- one per fixed 32-row group +// [4*K .. 4*K+V) the v row, one float per v row +// [4*K+V .. +8) decay and beta, one pair per row group +// +// Four k copies avoid a cross-workgroup barrier: a head's v rows may be split over up to four +// workgroups, and fixed 32-row groups make every byte belong to exactly one workgroup at any split. +// Read-before-write within a workgroup is ordered by a barrier. +#define RU_FSTR (4 * RU_K + RU_V + 8) + +// RU_TMAX bounds the candidate block STG can stage (LDS for four partials and two scales per +// token). The launcher checks the caller's width against it. +#define RU_TMAX 16 + +// RU_ANC_DUP=0 drops the two neighbouring-page copies of the replay factors (and, without the +// marker, of the anchor). Incorrect without RU_ANC_MARK (a moved page index reads an unwritten +// slot). With the marker it writes the factor block once; `-DRU_ANC_MARK=1 -DRU_ANC_DUP=0` is the +// leanest build, since the factor block (RU_TMAX * RU_FSTR) outweighs the state (RU_V * RU_K). +#ifndef RU_ANC_DUP +#define RU_ANC_DUP 1 +#endif + +// Shift marker: instead of writing the anchor three times (one per possible page shift), each of +// the three factor-block copies records the column it was written to. The reader finds `m` at its +// fixed factor column, so the page index moved by `m - 1`, and reads the anchor at the matching +// column; the anchor is written once (6.3 MB a layer instead of 18.9 at eight sequences, roughly a +// fifth of the layer's time). +// +// The marker lies past all factor data (RU_TMAX tokens of RU_FSTR) within one head's slice, so no +// workgroup reads a marker another is writing. Stored values are 1, 2, 3 (one-based; see the read), +// exact in fp16 and fp32. +// +// Invariant: the anchor is written at column 2 and read at 3 - m, never column 0. vLLM's +// precopy_mamba_align_fused_kernel copies state[bt[src_col + num_accepted - 1]] into this window's +// column 0 before the forward on a page crossing, so a read of column 0 (anchor at 1, read at +// 2 - m, shift +1) would see migrated data and degenerate intermittently. +#ifndef RU_ANC_MARK +#define RU_ANC_MARK 1 +#endif +#define RU_MARK_OFF (RU_TMAX * RU_FSTR) + +// RU_ANC_FRD=1 (diagnostic): use the displaced factor read (column 5 - m) while still writing all +// three factor copies, isolating the marker's read-column logic from the write side. +#ifndef RU_ANC_FRD +#define RU_ANC_FRD 0 +#endif + +// Decode convolution folded in (CV). This kernel is gdn_conv_update's only decode reader, so the +// fold saves a launch and a dependent-dispatch gap. Each workgroup computes the convolution its +// token loop reads (its key head's 128 q and 128 k channels and its value head's 128 v channels) +// from the projection rows into LDS; q, k and v never reach memory. The arithmetic is +// gdn_conv_update's (same taps, order, cp_silu and bf16 rounding), so results are byte-identical. +// +// The conv state is rewritten in place, and a key head's channels are read by all H / Hg value-head +// workgroups of its group, so none may rewrite them until all have read the history. Each +// workgroup arrives on a counter after reading; the last arriver rewrites the key head's q and k +// channels and resets the counter (no waiting). A value head's v channels have one reader and are +// rewritten by it. Two launches sharing a counter block must not overlap; blocks are keyed on +// (stream, output), as split_ctr in r3dh_gemm_fp8a8.hip. +struct RuConv { + const unsigned short* x; long xpitch; // the projection's [q | k | v] columns, row pitch + const unsigned short* w; // [conv_dim, R3DH_GDN_CONV_W] + const unsigned short* b; // [conv_dim] or null + unsigned short* cs; // the conv state cache + long cs_seq, cs_dim, cs_tok; + const int* cidx; long ci_stride; // conv state slot per sequence; negative is padding + unsigned int* ctr; // one arrival counter per (sequence, key head) +}; +// Max tokens per sequence for the folded convolution (preloaded into registers, static indices). +#define RU_CVT 8 + +// A channel's conv state rewritten as gdn_conv_update does: shifted by one, the old history's +// tail then this step's tokens. The launcher requires the window split to be R3DH_GDN_CONV_W - 2, +// so these are the same stores. +__device__ __forceinline__ void ru_conv_rewrite(unsigned short* sp, const unsigned short* hist, + const unsigned short* xs, int T, long cs_tok) { + constexpr int NH = R3DH_GDN_CONV_W - 2; +#pragma unroll + for (int i = 0; i < NH; ++i) sp[(size_t)i * cs_tok] = hist[i + 1]; +#pragma unroll + for (int t = 0; t < RU_CVT; ++t) + if (t < T) sp[(size_t)(t + NH) * cs_tok] = xs[t]; +} + +// A workgroup barrier that completes this wave's loads and LDS operations but leaves its global +// stores in flight. __syncthreads' release fence also waits for every store (gfx11 counts stores +// apart, in vscnt), and behind the anchor publish that is the whole 64 KB state write: at one +// sequence the store drain then ran before the token loop instead of under it. From the publish +// on, the workgroup reads no global memory it writes; its barriers order LDS, and the +// read-before-write of the factor block (and of the conv history, before the arrival) needs only +// the reads complete, which vmcnt(0) gives. +__device__ __forceinline__ void ru_sync() { + asm volatile("s_waitcnt vmcnt(0) lgkmcnt(0)\n\ts_barrier" ::: "memory"); +} + +template +__global__ __launch_bounds__(RU_V / VS * 2) +void r3dh_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, + const unsigned short* __restrict__ k, + const unsigned short* __restrict__ v, + const void* __restrict__ av, + const void* __restrict__ bv, long ab_stride, + const float* __restrict__ A_log, + const float* __restrict__ dt_bias, + typename ru_state::T* __restrict__ state, + long st_slot, long st_head, + unsigned short* __restrict__ o, + unsigned char* __restrict__ oq, + float* __restrict__ os, long oq_pitch, + long os_ld, + const int* __restrict__ cu, + const int* __restrict__ sidx, long sidx_stride, + const int* __restrict__ naccept, + const unsigned short* __restrict__ zg, + long zg_pitch, + const float* __restrict__ nw, float neps, int nact, + int H, int Hg, float scale, float sp_thr, + const RuConv cv) +{ + using ST = typename ru_state::T; + constexpr int NR = RU_V / VS; // v rows this workgroup owns + constexpr int THR = NR * 2; + static_assert(!(NORM && VS > 1), "the fused row norm needs the whole 128-wide row"); + __shared__ float wsum[THR / 32]; + __shared__ float spart[STG ? RU_TMAX * 4 : 1]; // per (token, half): sum q^2, sum k^2 + __shared__ float sscl [STG ? RU_TMAX * 2 : 1]; // per token: the two closed scales + const int n = blockIdx.x, hv = blockIdx.y; + const int bos = cu[n], T = cu[n + 1] - bos; + // With ANC, T == 0 is valid: it folds the previous step's accepted prefix into the anchor before + // something else reads the state cache. Without ANC there is nothing to do. + const bool empty = (T <= 0); + if (empty && !ANC) return; + + const int tid = threadIdx.x; + const int row = (tid >> 1) + (VS > 1 ? blockIdx.z * NR : 0), half = tid & 1, k0 = half * RU_HK; + const int hk = hv / (H / Hg); + /* Read early so their latency overlaps the prologue's loads. */ + const float a_log_h = A_log[hv], dtb = dt_bias[hv]; + + // ---- CV: issue the convolution's inputs first so they are in flight during the anchor replay. + // Thread tid owns one q|k channel of the key head (q below RU_K, k above) and, below RU_V, one v + // channel of the value head. + static_assert(!CV || (NORM && VS == 1 && STG == 0), "the folded convolution is the decode shape"); + static_assert(RU_K == RU_V, "one LDS row pitch serves the q, k and v taps"); + constexpr int CW = R3DH_GDN_CONV_W, CS = R3DH_GDN_CONV_W - 1; + __shared__ unsigned short cvq[CV ? RU_CVT * RU_K : 1], cvk[CV ? RU_CVT * RU_K : 1]; + __shared__ unsigned short cvv[CV ? RU_CVT * RU_V : 1]; + __shared__ int cvlast; + /* The key head's history for the final rewrite (two newest history entries and this step's + * inputs, one channel per thread), parked in LDS: in registers across the token loop they spill. */ + __shared__ unsigned short cvh[CV ? (CS - 1 + RU_CVT) * THR : 1]; + /* The token loop's per-token global reads (a, b and the output gate row) are also staged: at + * decode there is too little occupancy to hide a global load per token. They are issued here, + * parked in LDS at the convolution's barrier and read from there: `ca_b` is one token's a + * (tid < T) or b (T <= tid < 2T), `czg` this thread's strided share of the gate rows. */ + constexpr int ZPT = (RU_CVT * RU_V + THR - 1) / THR; // gate values a thread stages + __shared__ float sab[CV ? 2 * RU_CVT : 1]; + __shared__ unsigned short szg[CV ? RU_CVT * RU_V : 1]; + float ca_b = 0.0f; + unsigned short czg[ZPT]; + const int G = H / Hg; // workgroups that read one key head + float cwa[CW], cwb[CW], cba = 0.0f, cbb = 0.0f; + unsigned short cha[CS], chb[CS], cxa[RU_CVT], cxb[RU_CVT]; + unsigned short* spa = nullptr; + unsigned short* spb = nullptr; + unsigned int arrived = 0; + if constexpr (CV) { + if (!empty) { + const int cslot = cv.cidx[(size_t)n * cv.ci_stride]; + // A negative slot is padding: every workgroup of the sequence leaves here, so none arrives + // on the counter. + if (cslot < 0) return; + const int off = naccept ? naccept[n] - 1 : 0; + const int ca = tid < RU_K ? hk * RU_K + tid : (Hg + hk) * RU_K + (tid - RU_K); + const int cb = (2 * Hg + hv) * RU_V + tid; + const unsigned short* xr = cv.x + (size_t)bos * cv.xpitch; +#pragma unroll + for (int t = 0; t < RU_CVT; ++t) + if (t < T) cxa[t] = xr[(size_t)t * cv.xpitch + ca]; + { + const ushort4 w4 = *(const ushort4*)(cv.w + (size_t)ca * CW); + cwa[0] = bf16_to_f32(w4.x); cwa[1] = bf16_to_f32(w4.y); cwa[2] = bf16_to_f32(w4.z); cwa[3] = bf16_to_f32(w4.w); + if (cv.b) cba = bf16_to_f32(cv.b[ca]); + } + spa = cv.cs + (size_t)cslot * cv.cs_seq + (size_t)ca * cv.cs_dim; +#pragma unroll + for (int i = 0; i < CS; ++i) cha[i] = spa[(size_t)(off + i) * cv.cs_tok]; + if (tid < RU_V) { +#pragma unroll + for (int t = 0; t < RU_CVT; ++t) + if (t < T) cxb[t] = xr[(size_t)t * cv.xpitch + cb]; + const ushort4 w4 = *(const ushort4*)(cv.w + (size_t)cb * CW); + cwb[0] = bf16_to_f32(w4.x); cwb[1] = bf16_to_f32(w4.y); cwb[2] = bf16_to_f32(w4.z); cwb[3] = bf16_to_f32(w4.w); + if (cv.b) cbb = bf16_to_f32(cv.b[cb]); + spb = cv.cs + (size_t)cslot * cv.cs_seq + (size_t)cb * cv.cs_dim; +#pragma unroll + for (int i = 0; i < CS; ++i) chb[i] = spb[(size_t)(off + i) * cv.cs_tok]; + } + if (tid < 2 * T) + ca_b = tid < T ? ru_ab(av, (size_t)(bos + tid) * ab_stride + hv) + : ru_ab(bv, (size_t)(bos + tid - T) * ab_stride + hv); +#pragma unroll + for (int i = 0; i < ZPT; ++i) { + const int zi = tid + i * THR; + if (zi < T * RU_V) + czg[i] = zg[(size_t)(bos + zi / RU_V) * zg_pitch + (size_t)hv * RU_V + (zi % RU_V)]; + } + } + } + + // Without ANC the initial state is the one the last accepted token wrote; with ANC there is one + // state per sequence and the accepted prefix is replayed onto it below. + const int nacc = naccept ? naccept[n] : 1; + // Paged anchor. vLLM addresses mamba state by page, re-derived each step as + // (seq_lens - 1) / block_size, so the column holding a sequence's state can move. seq_lens + // includes this step's query (the draft depth, which varies), so + // start' - start = ((ctx + acc + q') - 1)/bs - ((ctx + q) - 1)/bs + // is +1 when the committed context crosses a page, usually 0, and -1 when a step drafts fewer + // tokens than the previous one. + // + // With the shift in {-1, 0, +1}, a fixed read column works only if all three pages it can land + // on were written. So the anchor is written to columns 0, 1, 2 and read from column 1, and the + // replay factors are written to columns 3, 4, 5 and read from column 4: + // shift -1 -> next column 1 is this column 0 (and next column 4 is this column 3) + // shift 0 -> next column 1 is this column 1 (and next column 4 is this column 4) + // shift +1 -> next column 1 is this column 2 (and next column 4 is this column 5) + // The six columns are distinct writable slots: vLLM's per-candidate path writes to the same + // indices, and indices_stride is num_spec + 1 = 8 whatever the draft depth. + // + // vLLM also migrates state itself: precopy_mamba_align_fused_kernel copies + // state[bt[src_col + num_accepted - 1]] into state[bt[dst_col]] on a page crossing, assuming the + // per-candidate layout. The anchor and factor read columns resolve to pages it never writes. + // Any change to these columns must be re-derived against that kernel too. + // + // Nothing else may write this cache: advancing one copy alone leaves the others stale. Every step + // shape, including non-speculative decode (`kind == "decode1"` in radiance_gdn.py), goes through + // the fused path, and any other step first folds the accepted prefix into a single state. + const int sa0 = ANC ? sidx[(size_t)n * sidx_stride + 0] : 0; // anchor, page before + const int sa1 = ANC ? sidx[(size_t)n * sidx_stride + 1] : 0; // anchor, written here + const int sa2 = ANC ? sidx[(size_t)n * sidx_stride + 2] : 0; // anchor, page after + const int sf0 = ANC ? sidx[(size_t)n * sidx_stride + 3] : 0; // factors, marker 0 + const int sf = ANC ? sidx[(size_t)n * sidx_stride + 4] : 0; // factors, marker 1, read here + const int sf2 = ANC ? sidx[(size_t)n * sidx_stride + 5] : 0; // factors, marker 2 + // A negative slot is padding; 0 is a real slot (as for the per-candidate read below). + if (ANC && (sa0 < 0 || sa1 < 0 || sa2 < 0 || sf0 < 0 || sf < 0 || sf2 < 0)) return; + ST* const fb = ANC ? (state + (size_t)sf * st_slot + (size_t)hv * st_head) : nullptr; + ST* const fb0 = ANC ? (state + (size_t)sf0 * st_slot + (size_t)hv * st_head) : nullptr; + ST* const fb2 = ANC ? (state + (size_t)sf2 * st_slot + (size_t)hv * st_head) : nullptr; + // Anchor column: without markers, column 1 (all three copies written); with them, 3 - m, never 0 + // (column 0 is the migration's target, derived from the committed context; see RU_ANC_MARK). + // A caller whose state does not page (this engine's linear pool: one slot per sequence for its + // life) names the same slot in every column; then duplicates are skipped, saving two thirds of + // the factor traffic. + const bool dup_a = ANC && RU_ANC_DUP && (sa0 != sa2 || sa1 != sa2); + const bool dup_f = ANC && RU_ANC_DUP && (sf0 != sf || sf2 != sf); + int acol = RU_ANC_MARK ? 2 : 1; + int mrk = 1; + if (ANC && RU_ANC_MARK) { + // The marker is one-based so a zeroed (freshly allocated) factor block reads as absent and + // falls back to the default anchor column. Zero-based, it would steer the first read after a + // prefill to column 3, a factor column of zeros, discarding the prefill's state. + const int m = (int)((float)fb[RU_MARK_OFF] + 0.5f) - 1; + mrk = (m >= 0 && m <= 2) ? m : 1; + acol = 3 - mrk; + } + // With RU_ANC_DUP=0 (or RU_ANC_FRD) the factors are read at 5 - m (3, 4 or 5) and written only + // at column 4. The marker itself stays at fixed column 4 and is stamped into all three copies. + const ST* const fr = (ANC && RU_ANC_MARK && (RU_ANC_FRD || !RU_ANC_DUP)) + ? (const ST*)(state + (size_t)(mrk == 0 ? sf2 : (mrk == 1 ? sf : sf0)) * st_slot + + (size_t)hv * st_head) + : (const ST*)fb; + const int si = sidx[(size_t)n * sidx_stride + (ANC ? acol : (nacc - 1))]; + // A negative slot is padding; 0 is a real slot. + if (si < 0) return; + /* Fixed 32-row group (see RU_FSTR), uniform per wave for any VS (a wave is 16 consecutive rows + * from a multiple of 16). readfirstlane makes the factor addresses scalar instead of 64-bit + * VGPR offsets live across the token loop. */ + const int grp = __builtin_amdgcn_readfirstlane(row >> 5); + + float h[RU_HK]; + { + const ST* p = state + (size_t)si * st_slot + (size_t)hv * st_head + + (size_t)row * RU_K + k0; +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) ru_load8(&h[j], p + j); + } + + if (ANC) { + for (int t = 0; t < nacc; ++t) { + const ST* f = fr + (size_t)t * RU_FSTR; + float kk[RU_HK]; +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) ru_load8<0, SDT>(&kk[j], f + grp * RU_K + k0 + j); + const float vv = (float)f[4 * RU_K + row]; + const float eg = __expf((float)f[4 * RU_K + RU_V + 2 * grp]); + const float bt = (float)f[4 * RU_K + RU_V + 2 * grp + 1]; + float dot = 0.0f; +#pragma unroll + for (int j = 0; j < RU_HK; ++j) { h[j] *= eg; dot += h[j] * kk[j]; } + dot += r3dh_xor_lane<1>(dot); // DPP, no LDS round trip + const float u = (vv - dot) * bt; +#pragma unroll + for (int j = 0; j < RU_HK; ++j) h[j] += u * kk[j]; + } + // Publish the advanced anchor, then barrier: every replay read above must complete before the + // token loop overwrites the factor block with this step's factors. + const size_t rowoff = (size_t)hv * st_head + (size_t)row * RU_K + k0; + ST* p = state + (size_t)(RU_ANC_MARK ? sa2 : sa1) * st_slot + rowoff; + ST* p0 = state + (size_t)sa0 * st_slot + rowoff; + ST* p2 = state + (size_t)sa2 * st_slot + rowoff; +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) ru_store8(p + j, &h[j]); + if (dup_a && !RU_ANC_MARK) { +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) ru_store8(p0 + j, &h[j]); +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) ru_store8(p2 + j, &h[j]); + } + ru_sync(); + // Stamp after the barrier: every thread read fb's marker at the top, and stamping earlier + // could steer a late wave to a different column from the rest of the workgroup. + if (RU_ANC_MARK && tid == 0) { // the three copies say where they are + fb0[RU_MARK_OFF] = (ST)1.0f; + fb[RU_MARK_OFF] = (ST)2.0f; + fb2[RU_MARK_OFF] = (ST)3.0f; + } + } + if (empty) return; + + if constexpr (CV) { + // gdn_conv_update's token body, one channel per thread, into LDS instead of q, k and v. + auto conv = [&](const float* wt, float bs, const unsigned short* hist, + const unsigned short* xs, unsigned short* dst) { + float win[CW]; +#pragma unroll + for (int i = 0; i < CS; ++i) win[i] = bf16_to_f32(hist[i]); +#pragma unroll + for (int t = 0; t < RU_CVT; ++t) { + if (t < T) { + win[CW - 1] = bf16_to_f32(xs[t]); + float acc = bs; +#pragma unroll + for (int i = 0; i < CW; ++i) acc += wt[i] * win[i]; + dst[t * RU_K] = f32_to_bf16(cp_silu(acc)); +#pragma unroll + for (int i = 0; i < CW - 1; ++i) win[i] = win[i + 1]; + } + } + }; + conv(cwa, cba, cha, cxa, (tid < RU_K ? cvq : cvk) + (tid & (RU_K - 1))); +#pragma unroll + for (int i = 1; i < CS; ++i) cvh[(i - 1) * THR + tid] = cha[i]; +#pragma unroll + for (int t = 0; t < RU_CVT; ++t) + if (t < T) cvh[(CS - 1 + t) * THR + tid] = cxa[t]; + if (tid < RU_V) { + conv(cwb, cbb, chb, cxb, cvv + tid); + ru_conv_rewrite(spb, chb, cxb, T, cv.cs_tok); + } + if (tid < 2 * T) sab[tid] = ca_b; +#pragma unroll + for (int i = 0; i < ZPT; ++i) { + const int zi = tid + i * THR; + if (zi < T * RU_V) szg[zi] = czg[i]; + } + // All history is consumed (taps are in LDS), so after the barrier this workgroup no longer + // reads the key head's conv state and may arrive on the counter. + ru_sync(); + if (G > 1 && tid == 0) + arrived = __hip_atomic_fetch_add(cv.ctr + (size_t)n * Hg + hk, 1u, __ATOMIC_RELAXED, + __HIP_MEMORY_SCOPE_AGENT); + } + + // CV: every token's q and k l2 norms before the token loop, which then carries only the state's + // two dependent chains. A lane per (token, q|k, half) sums its 64 squares as the loop's lanes do, + // and the two halves close in the loop's exchange order (own half plus the other: commutative, + // so the same sum), so the scales are the same bits. + __shared__ float cvss[CV ? RU_CVT * 4 : 1]; // per (token, q|k, half): the half's sum of squares + __shared__ float cvsc[CV ? RU_CVT * 2 : 1]; // per token: q's scale, k's scale + if constexpr (CV) { + if (tid < 4 * T) { + const int ut = tid >> 2, wk = (tid >> 1) & 1, uh = tid & 1; + const unsigned short* src = (wk ? cvk : cvq) + ut * RU_K + uh * RU_HK; + float ss = 0.0f; +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) { + const uint4 w = *(const uint4*)(src + j); + const unsigned short* e8 = (const unsigned short*)&w; +#pragma unroll + for (int e = 0; e < 8; ++e) { const float f = bf16_to_f32(e8[e]); ss += f * f; } + } + cvss[tid] = ss; + } + ru_sync(); + if (tid < 2 * T) { + const int ut = tid >> 1, wk = tid & 1; + const float ssum = cvss[ut * 4 + wk * 2] + cvss[ut * 4 + wk * 2 + 1]; + cvsc[tid] = wk ? __frsqrt_rn(ssum + 1e-6f) : __frsqrt_rn(ssum + 1e-6f) * scale; + } + ru_sync(); + } + + const float alog = __expf(a_log_h); + + if (STG) { + // One lane per (token, half) computes the same sums each v row computes on the STG=0 path. + if (tid < 2 * T) { + const int ut = tid >> 1, uk0 = (tid & 1) * RU_HK; + const unsigned short* qp = q + ((size_t)(bos + ut) * Hg + hk) * RU_K + uk0; + const unsigned short* kp = k + ((size_t)(bos + ut) * Hg + hk) * RU_K + uk0; + float ssq = 0.0f, ssk = 0.0f; +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) { + const uint4 wq = *(const uint4*)(qp + j), wk = *(const uint4*)(kp + j); + const unsigned short* aq = (const unsigned short*)&wq; + const unsigned short* ak = (const unsigned short*)&wk; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const float fq = bf16_to_f32(aq[e]), fk = bf16_to_f32(ak[e]); + ssq += fq * fq; ssk += fk * fk; + } + } + spart[tid * 2] = ssq; + spart[tid * 2 + 1] = ssk; + } + __syncthreads(); + if (tid < T) { + // Same order as the STG=0 exchange: own half plus the other half. + const float ssq = spart[tid * 4] + spart[tid * 4 + 2]; + const float ssk = spart[tid * 4 + 1] + spart[tid * 4 + 3]; + sscl[tid * 2] = __frsqrt_rn(ssq + 1e-6f) * scale; + sscl[tid * 2 + 1] = __frsqrt_rn(ssk + 1e-6f); + } + __syncthreads(); + } + + for (int t = 0; t < T; ++t) { + const int tok = bos + t; + const unsigned short* qp = CV ? cvq + t * RU_K + k0 : q + ((size_t)tok * Hg + hk) * RU_K + k0; + const unsigned short* kp = CV ? cvk + t * RU_K + k0 : k + ((size_t)tok * Hg + hk) * RU_K + k0; + + // k first, q only once k is consumed: holding both with the state row (three 64-float arrays) + // spilled on gfx1151 (256 VGPRs). Each value meets the same operations in the same order. + float kk[RU_HK]; +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) { + const uint4 wk = *(const uint4*)(kp + j); + const unsigned short* sk = (const unsigned short*)&wk; +#pragma unroll + for (int e = 0; e < 8; ++e) kk[j + e] = bf16_to_f32(sk[e]); + } + + // l2 norm: 64 in-lane terms, then one exchange with the lane holding the other half + float ks; + if (STG) { + ks = sscl[t * 2 + 1]; + } else if (CV) { + ks = cvsc[t * 2 + 1]; + } else { + float sk = 0.0f; +#pragma unroll + for (int j = 0; j < RU_HK; ++j) sk += kk[j] * kk[j]; + sk += r3dh_xor_lane<1>(sk); + ks = __frsqrt_rn(sk + 1e-6f); + } +#pragma unroll + for (int j = 0; j < RU_HK; ++j) kk[j] *= ks; + + const float ra = CV ? sab[t] : ru_ab(av, (size_t)tok * ab_stride + hv); + const float rb = CV ? sab[T + t] : ru_ab(bv, (size_t)tok * ab_stride + hv); + const float g = -alog * ru_softplus(ra + dtb, sp_thr); + const float bt = 1.0f / (1.0f + __expf(-rb)); + const float eg = __expf(g); + + float dot = 0.0f; +#pragma unroll + for (int j = 0; j < RU_HK; ++j) { h[j] *= eg; dot += h[j] * kk[j]; } + dot += r3dh_xor_lane<1>(dot); + + const float vraw = bf16_to_f32(CV ? cvv[t * RU_V + row] : v[((size_t)tok * H + hv) * RU_V + row]); + const float u = (vraw - dot) * bt; + + if (ANC) { + // This step's factors for the next step's replay: one thread pair per row group writes the + // group's k copy and decay/beta; every row writes its own v. + ST* f = fb + (size_t)t * RU_FSTR; + ST* f0 = fb0 + (size_t)t * RU_FSTR; + ST* f2 = fb2 + (size_t)t * RU_FSTR; + if ((row & 31) == 0) { +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) { + float kn[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) kn[e] = kk[j + e]; + ru_store8<0, SDT>(f + grp * RU_K + k0 + j, kn); + if (dup_f) { + ru_store8<0, SDT>(f0 + grp * RU_K + k0 + j, kn); + ru_store8<0, SDT>(f2 + grp * RU_K + k0 + j, kn); + } + } + if (half == 0) { + ru_store_gb(f + 4 * RU_K + RU_V + 2 * grp, g, bt); + if (dup_f) { + ru_store_gb(f0 + 4 * RU_K + RU_V + 2 * grp, g, bt); + ru_store_gb(f2 + 4 * RU_K + RU_V + 2 * grp, g, bt); + } + } + } + if (half == 0) { + f[4 * RU_K + row] = (ST)vraw; + if (dup_f) { f0[4 * RU_K + row] = (ST)vraw; f2[4 * RU_K + row] = (ST)vraw; } + } + } + +#pragma unroll + for (int j = 0; j < RU_HK; ++j) h[j] += u * kk[j]; + + float qq[RU_HK]; +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) { + const uint4 wq = *(const uint4*)(qp + j); + const unsigned short* sq = (const unsigned short*)&wq; +#pragma unroll + for (int e = 0; e < 8; ++e) qq[j + e] = bf16_to_f32(sq[e]); + } + float qs; + if (STG) { + qs = sscl[t * 2]; + } else if (CV) { + qs = cvsc[t * 2]; + } else { + float sq = 0.0f; +#pragma unroll + for (int j = 0; j < RU_HK; ++j) sq += qq[j] * qq[j]; + sq += r3dh_xor_lane<1>(sq); + qs = __frsqrt_rn(sq + 1e-6f) * scale; + } + float on = 0.0f; +#pragma unroll + for (int j = 0; j < RU_HK; ++j) { qq[j] *= qs; on += h[j] * qq[j]; } + on += r3dh_xor_lane<1>(on); + + if (NORM) { + // sum of squares over the row: one channel per thread pair, 16 per wave + float sq = (half == 0) ? on * on : 0.0f; + // compile-time masks: 16 uses v_permlanex16, the rest DPP row_xmask + sq += r3dh_xor_lane<16>(sq); sq += r3dh_xor_lane<8>(sq); sq += r3dh_xor_lane<4>(sq); + sq += r3dh_xor_lane<2>(sq); sq += r3dh_xor_lane<1>(sq); + if ((threadIdx.x & 31) == 0) wsum[threadIdx.x >> 5] = sq; + ru_sync(); + float tot = 0.0f; +#pragma unroll + for (int i = 0; i < THR / 32; ++i) tot += wsum[i]; + const float sc = __frsqrt_rn(tot * (1.0f / RU_V) + neps); + const unsigned short zr = CV ? szg[t * RU_V + row] + : zg[(size_t)tok * zg_pitch + (size_t)hv * RU_V + row]; + on *= sc * nw[row] * ru_act(bf16_to_f32(zr), nact); + ru_sync(); // wsum is reused by the next token + } + + const unsigned short ob = f32_to_bf16(on); + if (half == 0) o[((size_t)tok * H + hv) * RU_V + row] = ob; + + // The out projection's quantiser, folded in (saves 48 launches per decode step, each with less + // work than its launch gap). The quant group (128) is the row and NORM gives one workgroup per + // (token, head), so the amax is a workgroup reduction and the scale index is (tok, hv). + // Bit-identical to the standalone quantiser: it quantises the stored bf16 `ob`, not the f32 + // `on`, with r3dh_fused_quant_fp8.hip's quant_group arithmetic (including the clamp that keeps + // the group maximum from becoming NaN). NORM == 2 writes int8 codes instead (quant_act_i8g: + // scale amax / 127, round to nearest-even). + if (NORM && oq) { + const float ov = bf16_to_f32(ob); + float mv = (half == 0) ? fabsf(ov) : 0.0f; + mv = fmaxf(mv, r3dh_xor_lane<16>(mv)); mv = fmaxf(mv, r3dh_xor_lane<8>(mv)); + mv = fmaxf(mv, r3dh_xor_lane<4>(mv)); mv = fmaxf(mv, r3dh_xor_lane<2>(mv)); + mv = fmaxf(mv, r3dh_xor_lane<1>(mv)); + if ((threadIdx.x & 31) == 0) wsum[threadIdx.x >> 5] = mv; + ru_sync(); + float amax = 0.0f; +#pragma unroll + for (int i = 0; i < THR / 32; ++i) amax = fmaxf(amax, wsum[i]); + const float qs = amax > 0.0f ? amax * (1.0f / q8_top()) : 1.0f; + if (tid == 0) os[(size_t)tok * os_ld + hv] = qs; + if (half == 0) { + unsigned char code; + if constexpr (NORM == 2) { + code = (unsigned char)(int)rintf(fminf(fmaxf(ov * (1.0f / qs), -127.0f), 127.0f)); + } else { + const float cv = fminf(fmaxf(ov * (1.0f / qs), -448.0f), 448.0f); + code = (unsigned char)r3dh_fp8::f32_to_e4m3(cv); /* cvt_pk_fp8_f32's low byte */ + } + oq[(size_t)tok * oq_pitch + (size_t)hv * RU_V + row] = code; + } + ru_sync(); // wsum is reused by the next token + } + + if (!ANC) { + const int so = sidx[(size_t)n * sidx_stride + t]; + // `>= 0`, not `> 0`: a negative slot is padding and 0 is a real slot (a single-sequence + // decode's only slot), as for the read above. + if (so >= 0) { + ST* p = state + (size_t)so * st_slot + (size_t)hv * st_head + + (size_t)row * RU_K + k0; +#pragma unroll + for (int j = 0; j < RU_HK; j += 8) ru_store8(p + j, &h[j]); + } + } + } + + if constexpr (CV) { + // The last arriving reader rewrites the key head's q and k channels. The count was taken + // before the token loop, hiding its latency. + if (G > 1) { + if (tid == 0) { + cvlast = arrived == (unsigned)(G - 1); + if (cvlast) + __hip_atomic_store(cv.ctr + (size_t)n * Hg + hk, 0u, __ATOMIC_RELAXED, + __HIP_MEMORY_SCOPE_AGENT); + } + ru_sync(); + if (!cvlast) return; + } + unsigned short rh[CS], rx[RU_CVT]; + rh[0] = 0; /* never read: the oldest entry is shifted out */ +#pragma unroll + for (int i = 1; i < CS; ++i) rh[i] = cvh[(i - 1) * THR + tid]; +#pragma unroll + for (int t = 0; t < RU_CVT; ++t) + rx[t] = t < T ? cvh[(CS - 1 + t) * THR + tid] : (unsigned short)0; + ru_conv_rewrite(spa, rh, rx, T, cv.cs_tok); + } +} + +// Non-temporal hint on the state load and store (TH_LOAD_NT / TH_STORE_NT): no result changes; +// chosen per launch because its cost and saving land in different kernels. In isolation it makes +// this kernel 43.8% slower (DRAM-write bound), but no state survives the 64 MB last-level cache +// within a step, so the hint only decides who pays for the write-back, and it saves the following +// GEMMs more (about -140 us on the tiled GEMM vs +25 us here under anchor state). +// +// Anchor state: one state per sequence with the accepted prefix replayed onto it. The caller's +// prefill path must zero state slot sidx[n][1] for every sequence it writes. Off (per_candidate), +// every candidate writes its own slot, matching vLLM's Triton path. A radiance caller declares the +// form as the op's `state_form` (ru_state_form); the raw C entry, which vLLM's radiance_gdn.py +// calls, has no op parameters and reads RADIANCE_GDN_ANCHOR, as that caller does. +static bool ru_anchor() { + static const bool v = [] { + const char* e = getenv("RADIANCE_GDN_ANCHOR"); + return e && e[0] == '1'; + }(); + return v; +} + +// STG: the q/k l2 scales are computed once per head and shared by the 128 v rows (bit-identical to +// per row). Folding the scales into the reductions instead is slower and moves about one output in +// 600 by a bf16 ULP. +// +// Flood size (MB of state a launch writes) up to which the non-temporal hint is used. It wins when +// the state would otherwise stay in the last-level cache and become the next GEMM's write-back +// (6.3 MB at one sequence: ~3% of a step) and loses when nothing survives anyway (50 MB at eight: +// ~2% slower). The threshold leaves cache room for the streaming weights. Under anchor state the +// hint nets about -100 us a step; under per-candidate state the flood is ~8x larger. (The gfx1201 +// figures.) +// +// gfx1151 (32 MB last-level cache, writes that go to DRAM either way): the hint never pays. On +// Flash-Next's decode (36 layers, anchor state, MTP 3) it costs the kernel 54 against 46 us at one +// sequence and 179 against 128 at four (--perfgdn), and with it off the engine's step is 0.5 ms +// shorter at one sequence and 0.6 at four (55.7 against 56.2, 64.7 against 65.4 ms; two runs each, +// interleaved). So the threshold is 0: no launch takes the hint. +#define RU_NT_MB 0 + +// `oq_i8` picks the folded quantiser's codes: E4M3 (0) or int8 (1); see the kernel's epilogue. +static int ru_update_launch( + const void* q, const void* k, const void* v, const void* a, const void* b, + long ab_stride, int ab_is_bf16, const void* A_log, const void* dt_bias, void* state, + long state_slot_stride, long state_head_stride, void* o, void* oq, void* os, + long oq_pitch, long os_ld, const void* cu, + const void* ssm_state_indices, long indices_stride, const void* num_accepted, + const void* z_gate, long z_pitch, const void* norm_weight, float norm_eps, int norm_act, + int N, int H, int Hg, int K, int V, float scale, float softplus_thr, int state_fp16, + void* stream, int oq_i8, bool anc) +{ + if (K != RU_K || V != RU_V) return -1; + if (H % Hg) return -2; + const int nm0 = (z_gate && norm_weight) ? 1 : 0; + // Fill the GPU: split a head's v rows until there are at least WGTARGET workgroups, at most + // four ways (64 threads, two waves). + int vs = 1; + if (!nm0) { const int want = (WGTARGET + N * H - 1) / (N * H); + vs = want >= 4 ? 4 : (want >= 2 ? 2 : 1); } + // The shift marker forbids splitting a head: with vs > 1 one workgroup could stamp this step's + // marker before another read the previous one, and they would disagree on the page shift. The + // wave count is the same either way. + if (anc && RU_ANC_MARK) vs = 1; + dim3 grid(N, H, vs), blk(RU_V / vs * 2); + // Every switch is a template parameter; the nested pick macros enumerate the instantiations. +#define RU_LAUNCH(AB, NM, VSC, NTC, ANCC, STGC, SDTC) \ + hipLaunchKernelGGL((r3dh_gdn_recurrent_update_kernel), \ + grid, blk, 0, (hipStream_t)stream, \ + (const unsigned short*)q, (const unsigned short*)k, \ + (const unsigned short*)v, a, b, ab_stride, \ + (const float*)A_log, (const float*)dt_bias, \ + (ru_state::T*)state, state_slot_stride, state_head_stride, \ + (unsigned short*)o, (unsigned char*)oq, (float*)os, oq_pitch, os_ld, \ + (const int*)cu, (const int*)ssm_state_indices, \ + indices_stride, (const int*)num_accepted, \ + (const unsigned short*)z_gate, z_pitch, (const float*)norm_weight, norm_eps, \ + norm_act, H, Hg, scale, softplus_thr, RuConv{}) +#define RU_PICKV(AB, NTC, ANCC, SDTC) \ + do { if (vs == 4) RU_LAUNCH(AB, 0, 4, NTC, ANCC, 0, SDTC); \ + else if (vs == 2) RU_LAUNCH(AB, 0, 2, NTC, ANCC, 0, SDTC); \ + else RU_LAUNCH(AB, 0, 1, NTC, ANCC, 0, SDTC); } while (0) +#define RU_PICKNM(AB, NTC, ANCC, SDTC) \ + do { if (oq_i8) RU_LAUNCH(AB, 2, 1, NTC, ANCC, 0, SDTC); \ + else RU_LAUNCH(AB, 1, 1, NTC, ANCC, 0, SDTC); } while (0) +#define RU_PICKAB(NTC, ANCC, SDTC) \ + do { if (ab_is_bf16) { if (nm0) RU_PICKNM(1, NTC, ANCC, SDTC); \ + else RU_PICKV(1, NTC, ANCC, SDTC); } \ + else { if (nm0) RU_PICKNM(0, NTC, ANCC, SDTC); \ + else RU_PICKV(0, NTC, ANCC, SDTC); } } while (0) +#define RU_PICKNT(ANCC, SDTC) \ + do { if (nt) RU_PICKAB(1, ANCC, SDTC); else RU_PICKAB(0, ANCC, SDTC); } while (0) +#define RU_PICKANC(SDTC) \ + do { if (anc) RU_PICKNT(1, SDTC); else RU_PICKNT(0, SDTC); } while (0) + + // The staged path (STG) is instantiated only for the decode shape: bf16 a/b, no fused row norm, + // VS 1. Everything else uses the per-row path (STG 0). + const int sdt = state_fp16 ? 1 : 0; + // Bytes of state this launch writes: one slot per sequence under the anchor, one per candidate + // without it. + const long slots_written = anc ? 1 : (long)indices_stride; + const long flood = (long)N * slots_written * state_slot_stride * (sdt ? 2 : 4); + const bool nt = flood <= (long)RU_NT_MB * 1024 * 1024; + // Anchor bounds: six columns are addressed (three anchor, three factor), and the factor block + // (indices_stride tokens of RU_FSTR) must fit in one head's slice of a slot. Keep these before + // the staged path, which returns early and is the shipped anchor path. + if (anc && indices_stride < 6) return -4; + if (anc && (long)indices_stride * RU_FSTR > state_head_stride) return -3; + if (ab_is_bf16 && !nm0 && vs == 1 && indices_stride <= RU_TMAX) { +#define RU_PICKSTG2(ANCC, SDTC) \ + do { if (nt) RU_LAUNCH(1, 0, 1, 1, ANCC, 1, SDTC); \ + else RU_LAUNCH(1, 0, 1, 0, ANCC, 1, SDTC); } while (0) +#define RU_PICKSTG(SDTC) do { if (anc) RU_PICKSTG2(1, SDTC); else RU_PICKSTG2(0, SDTC); } while (0) + if (sdt) RU_PICKSTG(1); else RU_PICKSTG(0); +#undef RU_PICKSTG +#undef RU_PICKSTG2 + return (int)hipGetLastError(); + } + if (sdt) RU_PICKANC(1); else RU_PICKANC(0); +#undef RU_PICKANC +#undef RU_PICKNT +#undef RU_PICKAB +#undef RU_PICKNM +#undef RU_PICKV +#undef RU_LAUNCH + return (int)hipGetLastError(); +} + +extern "C" int r3dh_gdn_recurrent_update_k128_v128_bf16_fp32state( + const void* q, const void* k, const void* v, const void* a, const void* b, + long ab_stride, int ab_is_bf16, const void* A_log, const void* dt_bias, void* state, + long state_slot_stride, long state_head_stride, void* o, void* oq, void* os, + long oq_pitch, long os_ld, const void* cu, + const void* ssm_state_indices, long indices_stride, const void* num_accepted, + const void* z_gate, long z_pitch, const void* norm_weight, float norm_eps, int norm_act, + int N, int H, int Hg, int K, int V, float scale, float softplus_thr, int state_fp16, + void* stream) +{ + return ru_update_launch(q, k, v, a, b, ab_stride, ab_is_bf16, A_log, dt_bias, state, + state_slot_stride, state_head_stride, o, oq, os, oq_pitch, os_ld, cu, + ssm_state_indices, indices_stride, num_accepted, z_gate, z_pitch, + norm_weight, norm_eps, norm_act, N, H, Hg, K, V, scale, softplus_thr, + state_fp16, stream, 0, ru_anchor()); +} + +// ============================================================== the folded convolution + +// Arrival counters for the folded convolution: one block per (stream, output), zeroed once and +// reset by the last arriver of each group. As with split_ctr in r3dh_gemm_fp8a8.hip, launches +// sharing a block must not overlap: different streams get different blocks, and launches on one +// stream sharing an output are ordered by their dependency. +constexpr unsigned kMaxConvCtr = 4096; + +static unsigned int* ru_conv_ctr(RadStream s, const void* out) { + static std::mutex m; + static std::map, unsigned int*> blocks; + std::lock_guard lk(m); + const auto key = std::make_pair(s, out); + if (auto it = blocks.find(key); it != blocks.end()) return it->second; + void* p = nullptr; + if (hipMalloc(&p, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess) return nullptr; + // Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished + // when it returns (core/device/aql.cpp); under HIP's own runtime (r3dh_selftest) it runs on the + // null stream, which a non-blocking stream does not wait for, so wait here. + if (hipMemset(p, 0, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess || + hipDeviceSynchronize() != hipSuccess) { + (void)hipFree(p); + return nullptr; + } + blocks.emplace(key, (unsigned int*)p); + return (unsigned int*)p; +} + +// The recurrent update with gdn_conv_update folded in, decode shape only (bf16 a/b, fused row +// norm, one workgroup per (sequence, value head)). State contract, non-temporal choice and +// factor-block bounds are as in ru_update_launch. +static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void* b, long ab_stride, + const void* A_log, const void* dt_bias, void* state, + long st_slot, long st_head, void* o, void* oq, void* os, + long oq_pitch, long os_ld, const void* cu, const void* sidx, + long sidx_stride, const void* nacc, const void* z, + long z_pitch, const void* nw, float neps, int nact, int N, + int H, int Hg, float scale, float thr, int state_fp16, + RadStream stream, int oq_i8, bool anc) { + if (anc && sidx_stride < 6) return RAD_E_SHAPE; + if (anc && sidx_stride * RU_FSTR > st_head) return RAD_E_SHAPE; + const int sdt = state_fp16 ? 1 : 0; + const long slots_written = anc ? 1 : sidx_stride; + const long flood = (long)N * slots_written * st_slot * (sdt ? 2 : 4); + const bool nt = flood <= (long)RU_NT_MB * 1024 * 1024; + const dim3 grid(N, H, 1), blk(RU_V * 2); +#define RC_LAUNCH(NTC, ANCC, SDTC) \ + do { if (oq_i8) RC_LAUNCH_NM(2, NTC, ANCC, SDTC); else RC_LAUNCH_NM(1, NTC, ANCC, SDTC); } \ + while (0) +#define RC_LAUNCH_NM(NM, NTC, ANCC, SDTC) \ + hipLaunchKernelGGL((r3dh_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, 1>), \ + grid, blk, 0, (hipStream_t)stream, nullptr, nullptr, nullptr, a, b, \ + ab_stride, (const float*)A_log, (const float*)dt_bias, \ + (ru_state::T*)state, st_slot, st_head, (unsigned short*)o, \ + (unsigned char*)oq, (float*)os, oq_pitch, os_ld, (const int*)cu, \ + (const int*)sidx, sidx_stride, (const int*)nacc, \ + (const unsigned short*)z, z_pitch, (const float*)nw, neps, nact, H, Hg, \ + scale, thr, cv) +#define RC_PICKNT(ANCC, SDTC) \ + do { if (nt) RC_LAUNCH(1, ANCC, SDTC); else RC_LAUNCH(0, ANCC, SDTC); } while (0) +#define RC_PICKANC(SDTC) \ + do { if (anc) RC_PICKNT(1, SDTC); else RC_PICKNT(0, SDTC); } while (0) + if (sdt) RC_PICKANC(1); else RC_PICKANC(0); +#undef RC_PICKANC +#undef RC_PICKNT +#undef RC_LAUNCH +#undef RC_LAUNCH_NM + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +// ============================================================== the plugin ABI entry points +// Shared operand helpers: r3dh_gdn_args.h. Operand enums use an OPD_ prefix because RU_K and RU_V +// are kernel constants. +/* ------------------------------------------------------------------ recurrent update */ + +enum { OPD_RU_Q = 0, OPD_RU_K, OPD_RU_V, OPD_RU_A, OPD_RU_B, OPD_RU_ALOG, OPD_RU_DTB, OPD_RU_STATE, OPD_RU_SIDX, OPD_RU_NACC, OPD_RU_CU, + OPD_RU_Z, OPD_RU_NORMW, OPD_RU_O, OPD_RU_OQ, OPD_RU_OS }; + +/* The op's `state_form`: 1 for anchor, 0 for per_candidate (also the default), -1 for a form this + * kernel does not implement. The pool behind `state` was sized for the declared form. */ +static int ru_state_form(const RadArgs* a) { + const char* sf = r3dh_gets(a, "state_form"); + if (!sf || std::strcmp(sf, "per_candidate") == 0) return 0; + return std::strcmp(sf, "anchor") == 0 ? 1 : -1; +} + +extern "C" int r3dh_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) { + if (gdn_dims_ok() != RAD_OK) return R3DH_NO(RAD_E_SHAPE); + const RadTensor* q = r3dh_opt(a, OPD_RU_Q); + const RadTensor* k = r3dh_opt(a, OPD_RU_K); + const RadTensor* v = r3dh_opt(a, OPD_RU_V); + const RadTensor* ta = r3dh_opt(a, OPD_RU_A); + const RadTensor* tb = r3dh_opt(a, OPD_RU_B); + const RadTensor* alog = r3dh_opt(a, OPD_RU_ALOG); + const RadTensor* dtb = r3dh_opt(a, OPD_RU_DTB); + const RadTensor* state = r3dh_opt(a, OPD_RU_STATE); + const RadTensor* sidx = r3dh_opt(a, OPD_RU_SIDX); + const RadTensor* nacc = r3dh_opt(a, OPD_RU_NACC); + const RadTensor* cu = r3dh_opt(a, OPD_RU_CU); + const RadTensor* z = r3dh_opt(a, OPD_RU_Z); + const RadTensor* nw = r3dh_opt(a, OPD_RU_NORMW); + const RadTensor* o = r3dh_opt(a, OPD_RU_O); + const RadTensor* oq = r3dh_opt(a, OPD_RU_OQ); + const RadTensor* os = r3dh_opt(a, OPD_RU_OS); + if (!q || !k || !v || !ta || !tb || !alog || !dtb || !state || !sidx || !cu || !o) + return R3DH_NO(RAD_E_INVAL); + if (q->rank != 3 || k->rank != 3 || v->rank != 3 || o->rank != 3) return R3DH_NO(RAD_E_SHAPE); + if (state->rank < 2 || sidx->rank < 1 || ta->rank != 2 || tb->rank != 2) return R3DH_NO(RAD_E_SHAPE); + + /* N comes from cu (the kernel reads cu[n + 1] for every n in the grid); state_idx is checked + * against it. */ + int N = 0; + int rc = seqs_of(cu, &N); + if (rc != RAD_OK) return rc; + if (sidx->shape[0] != N) return R3DH_NO(RAD_E_SHAPE); + + const long long ab_stride = r3dh_row_pitch(ta); + if (ab_stride < 0 || r3dh_row_pitch(tb) != ab_stride) return R3DH_NO(RAD_E_STRIDE); + if (!r3dh_contig(q) || !r3dh_contig(k) || !r3dh_contig(v) || !r3dh_contig(o)) + return R3DH_NO(RAD_E_STRIDE); + + const long long Hg = q->shape[1]; + const long long K = q->shape[2]; + const long long H = v->shape[1]; + const long long V = v->shape[2]; + if (H == 0 || Hg == 0 || H % Hg) return R3DH_NO(RAD_E_SHAPE); + + const int anc = ru_state_form(a); + if (anc < 0) return R3DH_NO(RAD_E_UNSUPPORTED); + + const float scale = (float)r3dh_getf(a, "scale", 1.0); + const float thr = (float)r3dh_getf(a, "softplus_thr", 20.0); + /* Folded gated norm parameters. */ + const float neps = (float)r3dh_getf(a, "eps", 0.0); + const int nact = r3dh_act_code(a, "act", "norm_act", 0); + if (nact < 0) return R3DH_NO(RAD_E_INVAL); + /* The l2 norm epsilon is compiled in, as in r3dh_rad_gdn_conv_prep. */ + if ((float)r3dh_getf(a, "l2_eps", 1e-6) != 1e-6f) return R3DH_NO(RAD_E_UNSUPPORTED); + /* State width from the cache's dtype, as in the chunk scan. */ + const int sfp16 = state->dtype == RAD_F16; + const int ab_is_bf16 = (ta->dtype == RAD_BF16) ? 1 : 0; + if (tb->dtype != ta->dtype) return R3DH_NO(RAD_E_DTYPE); + /* Optional n_head_v must agree with the value tensor. */ + const long long nhv = r3dh_geti_or(a, "n_head_v", 0); + if (nhv > 0 && nhv != H) return R3DH_NO(RAD_E_SHAPE); + + /* bf16 q/k/v/out/z; f32 or f16 state; fp32 A_log, dt_bias and norm weight. */ + R3DH_DT(q, RAD_BF16); R3DH_DT(k, RAD_BF16); R3DH_DT(v, RAD_BF16); R3DH_DT(o, RAD_BF16); + R3DH_DT(z, RAD_BF16); + if (state->dtype != RAD_F32 && state->dtype != RAD_F16) return R3DH_NO(RAD_E_DTYPE); + R3DH_DT(alog, RAD_F32); R3DH_DT(dtb, RAD_F32); R3DH_DT(nw, RAD_F32); + + /* The folded quantiser needs oq and os together, and the fused norm: without it a head's rows + * may be split across workgroups (VS > 1), and a group amax cannot span workgroups. */ + if ((oq != nullptr) != (os != nullptr)) return R3DH_NO(RAD_E_INVAL); + if (oq) { + if (!z || !nw) return R3DH_NO(RAD_E_UNSUPPORTED); + if (V != 128) return R3DH_NO(RAD_E_SHAPE); + if (oq->dtype != RAD_F8E4M3 && oq->dtype != RAD_I8) return R3DH_NO(RAD_E_DTYPE); + R3DH_DT(os, RAD_F32); + if (!r3dh_contig(oq)) return R3DH_NO(RAD_E_STRIDE); + } + + /* z may be a column view of the fused in-projection (rad_block_gdn_fp8.h): tokens are z_row + * elements apart, not H*V. */ + const long long z_row = z ? gn_row_pitch(z, H * V) : 0; + if (z && z_row < 0) return R3DH_NO(RAD_E_STRIDE); + + /* Slot and head strides come from the tensor, so a cache with padded slots is served too + * (see the header); the engine's own state cache is dense ([n_states, H, V, K] per layer). */ + return R3DH_RAW(ru_update_launch( + q->data, k->data, v->data, ta->data, tb->data, (long)ab_stride, ab_is_bf16, + alog->data, dtb->data, state->data, + (long)state->stride[0], (long)state->stride[1], + o->data, oq ? oq->data : nullptr, os ? os->data : nullptr, + oq ? (long)r3dh_row_pitch(oq) : 0, os ? (long)r3dh_row_pitch(os) : 0, + cu->data, sidx->data, (long)sidx->stride[0], + nacc ? nacc->data : nullptr, z ? z->data : nullptr, (long)z_row, + nw ? nw->data : nullptr, + neps, nact, N, (int)H, (int)Hg, (int)K, (int)V, scale, thr, sfp16, s, + oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0)); +} + + +/* ------------------------------------------------------------------ conv + recurrent update */ + +/* gdn_conv_update's inputs, then gdn_recurrent_update's minus q, k and v (never materialised). + * Inputs first, outputs last (docs/OPS.md). */ +enum { OPD_CR_X = 0, OPD_CR_CW, OPD_CR_CB, OPD_CR_CSTATE, OPD_CR_CIDX, OPD_CR_A, OPD_CR_B, + OPD_CR_ALOG, OPD_CR_DTB, OPD_CR_STATE, OPD_CR_SIDX, OPD_CR_NACC, OPD_CR_CU, OPD_CR_Z, + OPD_CR_NORMW, OPD_CR_O, OPD_CR_OQ, OPD_CR_OS }; + +extern "C" int r3dh_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s) { + if (gdn_dims_ok() != RAD_OK) return R3DH_NO(RAD_E_SHAPE); + const RadTensor* x = r3dh_opt(a, OPD_CR_X); + const RadTensor* cw = r3dh_opt(a, OPD_CR_CW); + const RadTensor* cb = r3dh_opt(a, OPD_CR_CB); + const RadTensor* cst = r3dh_opt(a, OPD_CR_CSTATE); + const RadTensor* cidx = r3dh_opt(a, OPD_CR_CIDX); + const RadTensor* ta = r3dh_opt(a, OPD_CR_A); + const RadTensor* tb = r3dh_opt(a, OPD_CR_B); + const RadTensor* alog = r3dh_opt(a, OPD_CR_ALOG); + const RadTensor* dtb = r3dh_opt(a, OPD_CR_DTB); + const RadTensor* state = r3dh_opt(a, OPD_CR_STATE); + const RadTensor* sidx = r3dh_opt(a, OPD_CR_SIDX); + const RadTensor* nacc = r3dh_opt(a, OPD_CR_NACC); + const RadTensor* cu = r3dh_opt(a, OPD_CR_CU); + const RadTensor* z = r3dh_opt(a, OPD_CR_Z); + const RadTensor* nw = r3dh_opt(a, OPD_CR_NORMW); + const RadTensor* o = r3dh_opt(a, OPD_CR_O); + const RadTensor* oq = r3dh_opt(a, OPD_CR_OQ); + const RadTensor* os = r3dh_opt(a, OPD_CR_OS); + /* The row norm is required: the fold is the decode shape, one workgroup per (sequence, value + * head). */ + if (!x || !cw || !cst || !cidx || !ta || !tb || !alog || !dtb || !state || !sidx || !cu || + !z || !nw || !o) + return R3DH_NO(RAD_E_INVAL); + if ((oq != nullptr) != (os != nullptr)) return R3DH_NO(RAD_E_INVAL); + if (x->rank != 2 || cst->rank != 3 || o->rank != 3 || ta->rank != 2 || tb->rank != 2) + return R3DH_NO(RAD_E_SHAPE); + if (state->rank < 2 || sidx->rank < 1 || cidx->rank < 1) return R3DH_NO(RAD_E_SHAPE); + + int N = 0; + int rc = seqs_of(cu, &N); + if (rc != RAD_OK) return rc; + if (sidx->shape[0] != N) return R3DH_NO(RAD_E_SHAPE); + + /* Head geometry from o ([tokens, H, V]) and x ([q | k | v] columns, 2 Hg K + H V wide). */ + const long long T = o->shape[0]; + const long long H = o->shape[1]; + const long long V = o->shape[2]; + const long long K = r3dh_geti_or(a, "head_k", 0); + if (K != RU_K || V != RU_V || r3dh_geti_or(a, "head_v", 0) != RU_V) return R3DH_NO(RAD_E_SHAPE); + if (x->shape[0] != T) return R3DH_NO(RAD_E_SHAPE); + const long long conv_dim = x->shape[1]; + if (H <= 0 || conv_dim <= H * V || (conv_dim - H * V) % (2 * K)) return R3DH_NO(RAD_E_SHAPE); + const long long Hg = (conv_dim - H * V) / (2 * K); + if (H % Hg) return R3DH_NO(RAD_E_SHAPE); + const long long nhv = r3dh_geti_or(a, "n_head_v", 0); + if (nhv > 0 && nhv != H) return R3DH_NO(RAD_E_SHAPE); + if ((long long)N * Hg > (long long)kMaxConvCtr) return R3DH_NO(RAD_E_SHAPE); + + const long long xpitch = r3dh_row_pitch(x); + if (xpitch < 0) return R3DH_NO(RAD_E_STRIDE); + if (!r3dh_contig(cw) || !r3dh_contig(o)) return R3DH_NO(RAD_E_STRIDE); + const long long ab_stride = r3dh_row_pitch(ta); + if (ab_stride < 0 || r3dh_row_pitch(tb) != ab_stride) return R3DH_NO(RAD_E_STRIDE); + + R3DH_DT(x, RAD_BF16); R3DH_DT(cw, RAD_BF16); R3DH_DT(cb, RAD_BF16); R3DH_DT(cst, RAD_BF16); + R3DH_DT(ta, RAD_BF16); R3DH_DT(tb, RAD_BF16); R3DH_DT(o, RAD_BF16); R3DH_DT(z, RAD_BF16); + R3DH_DT(alog, RAD_F32); R3DH_DT(dtb, RAD_F32); R3DH_DT(nw, RAD_F32); + if (state->dtype != RAD_F32 && state->dtype != RAD_F16) return R3DH_NO(RAD_E_DTYPE); + if (oq) { + if (oq->dtype != RAD_F8E4M3 && oq->dtype != RAD_I8) return R3DH_NO(RAD_E_DTYPE); + R3DH_DT(os, RAD_F32); + if (!r3dh_contig(oq)) return R3DH_NO(RAD_E_STRIDE); + } + + /* The window as in gdn_conv_update: max_query_len = state_len_max - (width - 2), and it must + * fit RU_CVT, since the fold holds the tokens in registers. */ + if (r3dh_geti_or(a, "conv_width", 0) != R3DH_GDN_CONV_W) return R3DH_NO(RAD_E_UNSUPPORTED); + const long long mql = cst->shape[2] - (R3DH_GDN_CONV_W - 2); + if (mql < 1) return R3DH_NO(RAD_E_SHAPE); + if (mql > RU_CVT) return R3DH_NO(RAD_E_UNSUPPORTED); + + /* The recurrent half's checks, as in r3dh_rad_gdn_recurrent_update. */ + const int anc = ru_state_form(a); + if (anc < 0) return R3DH_NO(RAD_E_UNSUPPORTED); + const float scale = (float)r3dh_getf(a, "scale", 1.0); + const float thr = (float)r3dh_getf(a, "softplus_thr", 20.0); + const float neps = (float)r3dh_getf(a, "eps", 0.0); + const int nact = r3dh_act_code(a, "act", "norm_act", 0); + if (nact < 0) return R3DH_NO(RAD_E_INVAL); + if ((float)r3dh_getf(a, "l2_eps", 1e-6) != 1e-6f) return R3DH_NO(RAD_E_UNSUPPORTED); + const long long z_row = gn_row_pitch(z, H * V); + if (z_row < 0) return R3DH_NO(RAD_E_STRIDE); + + RuConv cv{}; + cv.x = (const unsigned short*)x->data; cv.xpitch = (long)xpitch; + cv.w = (const unsigned short*)cw->data; cv.b = cb ? (const unsigned short*)cb->data : nullptr; + cv.cs = (unsigned short*)cst->data; + cv.cs_seq = (long)cst->stride[0]; cv.cs_dim = (long)cst->stride[1]; + cv.cs_tok = (long)cst->stride[2]; + cv.cidx = (const int*)cidx->data; cv.ci_stride = (long)cidx->stride[0]; + cv.ctr = ru_conv_ctr(s, o->data); + if (!cv.ctr) return R3DH_NO(RAD_E_NOMEM); + + return ru_conv_recurrent_launch( + cv, ta->data, tb->data, (long)ab_stride, alog->data, dtb->data, state->data, + (long)state->stride[0], (long)state->stride[1], o->data, oq ? oq->data : nullptr, + os ? os->data : nullptr, oq ? (long)r3dh_row_pitch(oq) : 0, + os ? (long)r3dh_row_pitch(os) : 0, cu->data, sidx->data, (long)sidx->stride[0], + nacc ? nacc->data : nullptr, z->data, (long)z_row, nw->data, neps, nact, N, (int)H, + (int)Hg, scale, thr, state->dtype == RAD_F16 ? 1 : 0, s, + oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0); +} diff --git a/libr3d/r3dh_gdn_wmma.h b/libr3d/r3dh_gdn_wmma.h new file mode 100644 index 00000000..3726f0e7 --- /dev/null +++ b/libr3d/r3dh_gdn_wmma.h @@ -0,0 +1,221 @@ +/* Ported from libhalo/halo_gdn_wmma.h, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Carried over from the strix-halo-vllm project's libhalo, where this layer was + * established and measured on the part; see libhalo/README.md. */ +// Fragment layer for the GDN kernels on gfx1151 / RDNA 3.5. +// +// This is the gfx11 counterpart of libr4d's r4d_gdn_wmma.h, and the difference is +// the whole reason the GDN kernels cannot simply be copied across: +// +// A/B per lane the k that lane's element e holds +// gfx1201 (RDNA4) 8 bf16 k = 8*(e>>2) + 4*(lane>>4) + (e&3) +// gfx1151 (RDNA3.5) 16 bf16 k = e +// +// RDNA 3.5 replicates each operand row across both halves of the wave, so a lane +// holds the WHOLE 16-wide k run. Established on the part itself by +// bench/wmma_layout_probe.hip; see r3dh_wmma.h. +// +// For this layer that is a simplification, not extra work: +// +// * a fragment is ONE 32-byte contiguous read of the row, so two dwordx4 rather +// than libr4d's two 8-byte groups sixteen bytes apart. All of its careful +// ds_read2_b32 / ds_load_2addr_b64 pairing notes are about making THAT split +// addressable in one register; there is no split here to pair. +// * the row pointer loses its k term entirely -- `4 * (lane >> 4)` disappears +// from rowP, rowG and rowGo, because the half-wave no longer selects k. +// +// What does NOT simplify is fragT, the transposed source: a lane needs 16 strided +// scalar reads instead of 8. +#pragma once +#include "r3dh_common.h" +#include "r3dh_wmma.h" + +// ---- the gated residual's own bf16 arithmetic ---------------------------------- +// libr4d's r4d_gdn_wmma.h carries these three and the kernels written against it use them +// (r3dh_ar_hc.h, r3dh_hc_bf16.hip); the port's header lost them, so they are restored here, in +// the same place and with the same rounding libr4d uses (round-half-away: one add + a shift, +// against RTNE's three instructions, and they differ only when the discarded bits are exactly +// 0x8000). halo::f32_to_bf16 is the RTNE form the WMMA helpers pack with; keep them apart. +__device__ __forceinline__ unsigned short f2bf(float f) { + return (unsigned short)((__builtin_bit_cast(unsigned, f) + 0x8000u) >> 16); +} +__device__ __forceinline__ unsigned f2bf2(float a, float b) { + const unsigned ua = __builtin_bit_cast(unsigned, a) + 0x8000u; + const unsigned ub = __builtin_bit_cast(unsigned, b) + 0x8000u; + return __builtin_amdgcn_perm(ub, ua, 0x07060302u); // {b_hi16, a_hi16} +} +__device__ __forceinline__ float bf2f(unsigned short h) { + return __builtin_bit_cast(float, (unsigned)h << 16); +} + +// K-contiguous fragment from a row pointer already advanced to this lane's row. +__device__ __forceinline__ v16bf fragP(const unsigned short* p) { + union { uint4 w[2]; v16bf f; } u; + u.w[0] = ((const uint4*)p)[0]; + u.w[1] = ((const uint4*)p)[1]; + return u.f; +} + +// Row pointer for the fragment above: LDS source, `pitch` in elements. No k term -- +// on gfx11 the lane's half does not select k. +__device__ __forceinline__ const unsigned short* rowP(const unsigned short* src, + int pitch, int base, int lane) { + return src + (size_t)(base + (lane & 15)) * pitch; +} + +// Row pointer for a global source; `lim` clamps so a partial last chunk cannot read +// past the tensor (those rows are discarded downstream). +__device__ __forceinline__ const unsigned short* rowG(const unsigned short* base, + size_t rowstride, int row0, + int lim, int lane) { + int r = row0 + (lane & 15); + r = r < lim ? r : lim; + return base + (size_t)r * rowstride; +} + +// 32-bit element offset for a global fragment source, split from a uniform base: +// keeps the whole k loop as global_load_dwordx4 vdst, voff, s[base] with an +// immediate, instead of rematerialising 64-bit address arithmetic per load. +__device__ __forceinline__ unsigned rowGo(unsigned rowstride, int row0, int lim, + int lane) { + int r = row0 + (lane & 15); + r = r < lim ? r : lim; + return (unsigned)r * rowstride; +} +__device__ __forceinline__ v16bf fragGo(const unsigned short* base, unsigned off) { + return fragP(base + off); +} + +// Fragment from a 32-bit LDS byte offset off the shared-block base. Holding the +// offset in one opaque register keeps the two dwordx4 as immediates rather than +// letting LLVM rematerialise a base add in front of every fragment. +__device__ __forceinline__ v16bf fragO(const char* sb, unsigned off) { + return fragP((const unsigned short*)(sb + off)); +} +#define LDSOPAQUE(x) asm("" : "+v"(x)) + +// K-contiguous fragment: src[idx][k], row pitch `pitch` (in elements) +__device__ __forceinline__ v16bf frag(const unsigned short* src, int pitch, + int base, int kbase, int lane) { + return fragP(rowP(src, pitch, base, lane) + kbase); +} + +// Same fragment, source stored transposed: src[k][idx]. 16 scalar reads on gfx11 +// against 8 on gfx12 -- the one place the wider fragment costs rather than saves. +__device__ __forceinline__ v16bf fragT(const unsigned short* src, int pitch, + int base, int kbase, int lane) { + const int idx = base + (lane & 15); + union { unsigned short h[16]; v16bf f; } u; +#pragma unroll + for (int e = 0; e < 16; ++e) u.h[e] = src[(size_t)(kbase + e) * pitch + idx]; + return u.f; +} + +// Fragment straight from global memory (no LDS staging). `lim` clamps the row so a +// partial last chunk cannot read past the tensor. +__device__ __forceinline__ v16bf fragG(const unsigned short* base, size_t rowstride, + int row0, int lim, int kbase, int lane) { + int r = row0 + (lane & 15); + r = r < lim ? r : lim; + return fragP(base + (size_t)r * rowstride + kbase); +} + +__device__ __forceinline__ v8f mma(v16bf a, v16bf b, v8f c) { + return halo::mma(a, b, c); +} + +// C[mt*16..][nt*16..] += A[M][KA] @ B[N][KA]^T over KSTEP 16-wide steps +template +__device__ __forceinline__ v8f gemm(const unsigned short* A, int Ap, int mt, + const unsigned short* B, int Bp, int nt, + int lane, v8f acc) { +#pragma unroll + for (int s = 0; s < KSTEP; ++s) + acc = mma(frag(A, Ap, mt * 16, s * 16, lane), + frag(B, Bp, nt * 16, s * 16, lane), acc); + return acc; +} + +// Where a result element lives. gfx11 wave32 puts D[2*e + (lane>>4)][lane & 15] in +// element e, which is NOT gfx12's mapping -- any kernel that writes an accumulator +// out by hand has to use these rather than the row/col arithmetic it came with. +__device__ __forceinline__ int accRow(int lane, int e) { return 2 * e + (lane >> 4); } +__device__ __forceinline__ int accCol(int lane) { return lane & 15; } + +// ---- writing an accumulator out ------------------------------------------------ +// gfx11 hands lane l element e the value D[2e + (l>>4)][l & 15]: eight rows of ONE +// column, stride two. libr4d's gfx12 mapping is D[8*(l>>4) + e][l & 15] -- eight +// CONSECUTIVE rows -- which is why every one of its accumulator write-outs is a +// single 16-byte store of a transposed tile. Ported naively that inverts into eight +// strided 2-byte stores. +// +// It need not. The partner lane l^16 holds exactly the eight rows interleaved +// between this lane's, so ONE cross-half exchange per dword reassembles sixteen +// consecutive rows, and each half-wave then owns eight of them -- the same single +// 16-byte store, for four v_permlanex16. +// +// Exchange the half the PARTNER needs rather than the half this lane owns: that is +// what keeps it at four shuffles instead of eight (a shuffle reads one VGPR for the +// whole wave, so the two halves cannot ask for different elements). +// +// v[] must ALREADY be scaled per element, because the two halves are scaling +// different rows -- see the gram store in r3dh_gdn_kkt_solve.hip. +__device__ __forceinline__ uint4 accPack(const float v[8], int lane) { + const int hi = lane >> 4; + uint32_t w[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const float mine = hi ? v[i + 4] : v[i]; // the row this lane already holds + const float send = hi ? v[i] : v[i + 4]; // the row the partner is missing + const float got = halo::swap16(send); + w[i] = hi ? halo::pk_bf16(got, mine) : halo::pk_bf16(mine, got); + } + return make_uint4(w[0], w[1], w[2], w[3]); +} +// First row of the eight accPack() returns for this lane. +__device__ __forceinline__ int accPackRow(int lane) { return 8 * (lane >> 4); } + +// accPack() with the same values and rounding, for a kernel where the write-out sits on the +// critical path. accPack() exchanges four floats per lane through halo::swap16 -- a __shfl_xor, +// so ds_bpermute_b32 and an LDS wait per dword -- and LLVM lowers its +// `hi ? pk(got, mine) : pk(mine, got)` to a divergent branch around each pack. This one rounds +// first (pk_bf16's round-to-nearest-even, the same bits), so the partner's four rows travel as two +// packed dwords over v_permlanex16, and the half-dependent order of the final pairs is a per-lane +// v_perm selector rather than a select per value: +// +// p[i] = {v[2i], v[2i+1]} rows {4i + hi, 4i + 2 + hi} +// lanes 0-15 keep p[0..1] and need the partner's p[0..1] (rows 1, 3, 5, 7) +// lanes 16-31 keep p[2..3] and need the partner's p[2..3] (rows 8, 10, 12, 14) +// +// Same precondition as accPack(): the whole wave is active. +__device__ __forceinline__ uint4 accPackX(const float v[8], int lane) { + const bool hi = (lane >> 4) != 0; + uint32_t r[8], p[4]; +#pragma unroll + for (int e = 0; e < 8; ++e) { // f32_to_bf16's rounding, the result in the high half + const uint32_t u = __builtin_bit_cast(uint32_t, v[e]); + r[e] = u + 0x7fffu + ((u >> 16) & 1u); + } +#pragma unroll + for (int i = 0; i < 4; ++i) p[i] = __builtin_amdgcn_perm(r[2 * i + 1], r[2 * i], 0x07060302u); + const uint32_t k0 = hi ? p[2] : p[0], k1 = hi ? p[3] : p[1]; // kept + const uint32_t g0 = r3dh_xor_lane_u32<16>(hi ? p[0] : p[2]); // got: the partner's kept + const uint32_t g1 = r3dh_xor_lane_u32<16>(hi ? p[1] : p[3]); + // {own, partner} below, {partner, own} above: low halves, then high halves. + const uint32_t sl = hi ? 0x01000504u : 0x05040100u, sh = hi ? 0x03020706u : 0x07060302u; + return make_uint4(__builtin_amdgcn_perm(g0, k0, sl), __builtin_amdgcn_perm(g0, k0, sh), + __builtin_amdgcn_perm(g1, k1, sl), __builtin_amdgcn_perm(g1, k1, sh)); +} + +// Byte offset, from the base of a shared block, of the fragment row this lane reads out +// of `buf[base + (lane&15)][...]` with the given row pitch in elements. +// +// This is the gfx11 form of libr4d's ROWO macro, and the difference is the whole port in +// one line: gfx12 adds `4 * (lane >> 4)` because the half-wave selects which quarter of +// the k run the lane holds, and gfx11 has no such term because the lane holds all of it. +// Every LDS fragment site in a ported kernel goes through here, so getting it wrong is a +// single-point failure rather than a scattered one. +__device__ __forceinline__ unsigned rowO(unsigned buf_off, int pitch, int base, int lane) { + return buf_off + (unsigned)(((base + (lane & 15)) * pitch) * 2); +} diff --git a/libr3d/r3dh_q8.h b/libr3d/r3dh_q8.h new file mode 100644 index 00000000..f16b171f --- /dev/null +++ b/libr3d/r3dh_q8.h @@ -0,0 +1,47 @@ +/* Ported from libhalo/halo_q8.h, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Derived from libr4d/r4d_q8.h by the libhalo rename transform (2026-10-26); + * see libhalo/README.md. Op schemas, row names and stored weight layouts are + * shared with libr4d by design. Everything else in this file is libhalo's own + * and diverges as it is measured on gfx1151. */ +// r3dh_q8.h -- the 8-bit activation codes the trunk GEMMs read, written by every quantising producer: +// E4M3 for the fp8a8 GEMMs, int8 for their int8 twins (gemm_i8a8_*). One scale per (row, 128 +// columns); only the largest code and the conversion differ. +// +// E4M3: scale `amax * (1 / 448)`, clamp to +-448, two packed conversions. The clamp is required: +// v_cvt_pk_fp8_f32 returns NaN for out-of-range input instead of saturating, and +// `amax * (1 / scale)` can land an ulp above 448. +// +// Int8: as quant_act_i8g (r3dh_quant_act_fp8.hip), scale `amax * (1 / 127)` and round-to-nearest- +// even into -127..127, so a fused producer writes the same codes as the standalone quantiser. +#pragma once +#include +#include +#include "r3dh_fp8_wmma.h" // r3dh_fp8::cvt_pk_fp8_f32 (no fp8-conversion-insts on gfx1151) + +template +__device__ __forceinline__ constexpr float q8_top() { + return I8 ? 127.0f : 448.0f; +} + +// Four values times `inv` (the reciprocal of the scale), as four codes in one dword, value 0 in +// the low byte. +template +__device__ __forceinline__ uint32_t q8_pack4(float a, float b, float c, float d, float inv) { + if constexpr (I8) { + const int ia = (int)rintf(fminf(fmaxf(a * inv, -127.0f), 127.0f)); + const int ib = (int)rintf(fminf(fmaxf(b * inv, -127.0f), 127.0f)); + const int ic = (int)rintf(fminf(fmaxf(c * inv, -127.0f), 127.0f)); + const int id = (int)rintf(fminf(fmaxf(d * inv, -127.0f), 127.0f)); + return ((uint32_t)ia & 0xFFu) | (((uint32_t)ib & 0xFFu) << 8) | + (((uint32_t)ic & 0xFFu) << 16) | (((uint32_t)id & 0xFFu) << 24); + } else { + int pk = 0; + pk = r3dh_fp8::cvt_pk_fp8_f32(fminf(fmaxf(a * inv, -448.0f), 448.0f), + fminf(fmaxf(b * inv, -448.0f), 448.0f), pk, false); + pk = r3dh_fp8::cvt_pk_fp8_f32(fminf(fmaxf(c * inv, -448.0f), 448.0f), + fminf(fmaxf(d * inv, -448.0f), 448.0f), pk, true); + return (uint32_t)pk; + } +} diff --git a/libr3d/r3dh_wmma.h b/libr3d/r3dh_wmma.h new file mode 100644 index 00000000..796fe8ce --- /dev/null +++ b/libr3d/r3dh_wmma.h @@ -0,0 +1,168 @@ +/* Ported from libhalo/halo_wmma.h, verbatim but for the halo_ -> r3dh_ rename, so libr3d builds and loads + * on its own. libhalo's gated-delta-net kernels are libr4d's ported to the gfx11 wave matrix and + * checked against libref on gfx1151 (rad-kbench); they compile for gfx11-generic unchanged. */ +/* Carried over from the strix-halo-vllm project's libhalo, where this layer was + * established and measured on the part; see libhalo/README.md. */ +// Wave32 WMMA fragment algebra for gfx1151 / RDNA 3.5. +// +// This is the gfx11 counterpart of libr4d's gfx12 fragment layer, and it exists +// because the two architectures do NOT agree on how a wave32 WMMA fragment is +// spread over the wave: +// +// A / B per lane the k a lane's element e holds +// gfx1201 (RDNA4) 8 bf16 (v[0:3]) k = 8*(e>>2) + 4*(lane>>4) + (e&3) +// gfx1151 (RDNA3.5) 16 bf16 (v[0:7]) k = e +// +// RDNA 3.5 replicates each operand row across both halves of the wave, so a lane +// holds the WHOLE 16-wide k run; RDNA4 splits it. Every fragment gather ported +// from libr4d therefore loses its half-wave term -- the port is a simplification +// at the gather sites, and a change of row mapping at the result. +// +// The layout below was established on the part itself by bench/wmma_layout_probe.hip, +// which tests candidate mappings against a host matmul and finds exactly one with +// zero error (the others are off by ~350 on the same data). Do not "fix" any of it +// from a vendor doc -- rerun the probe. +// +// A: lane l holds row (l & 15) of A; element e is k = e (lanes 16-31 replicate) +// B: lane l holds col (l & 15) of B; element e is k = e +// D: lane l, element e -> D[2*e + (l>>4)][l & 15] +// +// Note what the D mapping preserves: the COLUMN is still (lane & 15). libr4d's +// attention kernels are built around a transposed score matrix S^T = K.Q^T so that +// a fragment gives each lane exactly one query row and the softmax is lane-private. +// That property survives here unchanged, which is why those kernels are portable +// at all. +#pragma once +#include +#include +#include "r3dh_common.h" + +/* Byte order of stored fp8 weights along k, inside each group of four, and which + * e4m3 -> bf16 unpack deq16_e4m3 below compiles. In the vLLM libhalo these lived + * in its r3dh_common.h; here the stored layout is radiance's own (r3dh_layout.cpp + * chooses it at load), so the swizzled order is available when a relayout asks + * for it. Defaults: natural order, perm-input unpack. */ +#ifndef R3DH_FP8_SWIZ +#define R3DH_FP8_SWIZ 0 +#endif +#ifndef R3DH_FP8_DEQ +#define R3DH_FP8_DEQ 1 +#endif + +typedef __bf16 v16bf __attribute__((ext_vector_type(16))); +typedef __fp16 v16hf __attribute__((ext_vector_type(16))); // what the f16 WMMA builtin takes +typedef float v8f __attribute__((ext_vector_type(8))); +typedef float v2f __attribute__((ext_vector_type(2))); + +namespace halo { + +// ---- where a lane's data lives ------------------------------------------------ +__device__ __forceinline__ int a_row(int lane) { return lane & 15; } +__device__ __forceinline__ int b_col(int lane) { return lane & 15; } +__device__ __forceinline__ int d_col(int lane) { return lane & 15; } +__device__ __forceinline__ int d_row(int lane, int e) { return 2 * e + (lane >> 4); } +// The half a lane sits in. On gfx12 this selects which k it loads; here it selects +// only which D rows it receives, and the gather does not use it. +__device__ __forceinline__ int half(int lane) { return lane >> 4; } + +// ---- the instruction ---------------------------------------------------------- +__device__ __forceinline__ v8f mma(v16bf a, v16bf b, v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); +} +__device__ __forceinline__ v8f mma(v16hf a, v16hf b, v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +} + +// ---- building a fragment ------------------------------------------------------ +// From eight dwords, i.e. a lane's full 16-wide k run already packed as 16-bit +// pairs. This is the gfx11 replacement for libr4d's DT16::mk(uint2 lo, uint2 hi): +// twice the payload, and no half-wave selection. +template +__device__ __forceinline__ FRAG mk(const uint32_t w[8]) { + union { uint32_t u[8]; FRAG f; } q; +#pragma unroll + for (int i = 0; i < 8; ++i) q.u[i] = w[i]; + return q.f; +} + +// From a 32-byte-aligned pointer to 16 contiguous 16-bit values -- the common case +// once the half-wave split is gone, and two dwordx4 loads. +template +__device__ __forceinline__ FRAG mk_ldg(const void* p) { + union { uint4 v[2]; FRAG f; } q; + q.v[0] = *(const uint4*)p; + q.v[1] = *((const uint4*)p + 1); + return q.f; +} + +// f32 -> bf16, round-to-nearest-even. gfx1151 has no v_cvt_pk_bf16_f32 either, so +// this stays the software form libr4d uses. +__device__ __forceinline__ uint16_t f32_to_bf16(float f) { + uint32_t u = __builtin_bit_cast(uint32_t, f); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} +__device__ __forceinline__ uint32_t pk_bf16(float x, float y) { + return (uint32_t)f32_to_bf16(x) | ((uint32_t)f32_to_bf16(y) << 16); +} +// f16 packs in ONE instruction, which is why libr4d prefers it on the softmax path. +__device__ __forceinline__ uint32_t pk_f16(float x, float y) { + typedef __fp16 v2hf __attribute__((ext_vector_type(2))); // what cvt_pkrtz returns + union { v2hf h; uint32_t u; } q; + q.h = __builtin_amdgcn_cvt_pkrtz(x, y); + return q.u; +} + +// Exchange a value with the lane 16 away -- the two halves a D fragment splits its +// rows across. The one cross-lane step the transposed-score formulation needs. +__device__ __forceinline__ float swap16(float x) { return __shfl_xor(x, 16, 32); } +__device__ __forceinline__ uint32_t swap16_u(uint32_t x) { + return __builtin_bit_cast(uint32_t, swap16(__builtin_bit_cast(float, x))); +} + +// ---- e4m3 -> bf16, one B fragment (16 bytes) ---------------------------------- +// The single copy. It used to be inlined in r3dh_moe_fp8_group and again in +// r3dh_gemm_fp8_nt, and the two had already drifted; they are the same sixteen +// bytes becoming the same fragment, so they are the same function. +// +// A dword holds four e4m3 and must become two dwords of two bf16. Bytes 0 and 2 +// sit at bit 0 and bit 16, so ONE left shift moves both their payloads and one +// more moves both their signs; bytes 1 and 3 sit at bit 8 and 24 and one right +// shift serves both of theirs. Four instructions place all four values -- but +// that pairs k with k+2, and WMMA wants k with k+1. +// +// v_perm_b32 fixes the pairing on the INPUT for one instruction: reorder the +// dword to (b0, b2, b1, b3) and the natural output of the two shifts IS k +// order. Eight instructions per dword against the twelve the mask-and-restitch +// version needs (ten bit ops plus two v_mov_b16 the register allocator adds), +// and -- unlike doing it in storage -- it needs no change to the stored +// weights, which is what makes it shippable: the layout belongs to vLLM's +// Triton fused_experts, which reads the same tensors on every prefill. +// +// The exponent is NOT biased. Every value comes out low by exactly 2^-120, +// which the caller folds into the block scale as R3DH_FP8_FIX; see docs/31. +__device__ __forceinline__ v16bf deq16_e4m3(const uint32_t* __restrict__ w4) { + union { uint32_t u[8]; v16bf f; } q; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const uint32_t w = w4[d]; +#if !R3DH_FP8_DEQ + // The control: mask each byte in place, then restitch the halves into k + // order. Ten bit ops, and the allocator adds two v_mov_b16 on top. + const uint32_t lo = ((w & 0x007F007Fu) << 4) | ((w & 0x00800080u) << 8); + const uint32_t hi = ((w & 0x7F007F00u) >> 4) | (w & 0x80008000u); + q.u[d * 2 + 0] = (lo & 0x0000FFFFu) | (hi << 16); + q.u[d * 2 + 1] = (lo >> 16) | (hi & 0xFFFF0000u); +#else +#if R3DH_FP8_SWIZ + const uint32_t x = w; // stored (k0, k2, k1, k3): no perm needed +#else + const uint32_t x = __builtin_amdgcn_perm(w, w, 0x03010200u); +#endif + q.u[d * 2 + 0] = ((x << 8) & 0x80008000u) | ((x << 4) & 0x07F007F0u); + q.u[d * 2 + 1] = (x & 0x80008000u) | ((x >> 4) & 0x07F007F0u); +#endif + } + return q.f; +} + +} // namespace halo diff --git a/libr4d/r4d_attn_args.h b/libr4d/r4d_attn_args.h index 667abccc..7e6fc0ac 100644 --- a/libr4d/r4d_attn_args.h +++ b/libr4d/r4d_attn_args.h @@ -99,6 +99,8 @@ static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_d if (kv->stride[3] != 1) return R4D_NO(RAD_E_STRIDE); if (kv->stride[2] != row) return R4D_NO(RAD_E_STRIDE); if (kv->shape[3] != row) return R4D_NO(RAD_E_SHAPE); + /* The kernels divide q_heads by kv_heads for the GQA factor. */ + if (kv->shape[1] <= 0) return R4D_NO(RAD_E_SHAPE); /* 16-byte alignment for 128-bit loads. */ if (!r4d_aligned(q->data, 16) || !r4d_aligned(o->data, 16) || !r4d_aligned(kv->data, 16)) diff --git a/libr4d/r4d_encoder_bf16.hip b/libr4d/r4d_encoder_bf16.hip index b0fbd1f7..9fcc179d 100644 --- a/libr4d/r4d_encoder_bf16.hip +++ b/libr4d/r4d_encoder_bf16.hip @@ -354,6 +354,31 @@ __global__ __launch_bounds__(kThreads) void pool_cols_kernel( } } +// ---------------------------------------------------------------------------- point_fourier +// ref_point_fourier: row m of y is [x | sin(x_i f_j) | cos(x_i f_j)], f_j = 2^j (times pi), the +// sines then the cosines each i-major then j; f32 in and out. A thread an output column. +__global__ __launch_bounds__(kThreads) void point_fourier_kernel( + const float* __restrict__ x, float* __restrict__ y, uint32_t n, uint32_t F, uint32_t pi, + uint32_t x_ld, uint32_t y_ld, uint32_t M) { + const uint32_t w = n * (2 * F + 1); + const uint32_t c = blockIdx.x * kThreads + threadIdx.x; + if (c >= w) return; + for (uint32_t r = blockIdx.y; r < M; r += gridDim.y) { + float v; + if (c < n) { + v = x[(size_t)r * x_ld + c]; + } else { + const uint32_t k = c - n, half = n * F; + const uint32_t i = (k % half) / F, j = (k % half) % F; + const float f = pi ? (float)ldexp(3.14159265358979323846, (int)j) + : ldexpf(1.0f, (int)j); + const float t = x[(size_t)r * x_ld + i] * f; + v = k < half ? sinf(t) : cosf(t); + } + y[(size_t)r * y_ld + c] = v; + } +} + // ---------------------------------------------------------------------------- cast bf16 -> f32 __global__ __launch_bounds__(kThreads) void widen_kernel( const uint16_t* __restrict__ x, float* __restrict__ y, uint32_t n, uint32_t x_ld, @@ -923,6 +948,19 @@ extern "C" int r4d_pool_cols_bf16(long x, long y, int rows, int n, int k, float return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int r4d_point_fourier_f32(long x, long y, int rows, int n, int freqs, int pi, + int x_ld, int y_ld, long stream) { + if (!x || !y) return -1; + if (rows <= 0 || n <= 0 || freqs <= 0 || freqs > 30) return -2; + const uint32_t w = (uint32_t)(n * (2 * freqs + 1)); + hipLaunchKernelGGL(point_fourier_kernel, + dim3((w + kThreads - 1) / kThreads, grid_rows(rows)), + dim3(kThreads), 0, (hipStream_t)stream, (const float*)x, (float*)y, + (uint32_t)n, (uint32_t)freqs, (uint32_t)(pi != 0), (uint32_t)x_ld, + (uint32_t)y_ld, (uint32_t)rows); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + extern "C" int r4d_widen_bf16_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; @@ -1312,6 +1350,24 @@ extern "C" int r4d_rad_pool_cols(const RadArgs* a, RadStream s) { (long)(uintptr_t)s)); } +/* ------------------------------------------------------------------ point_fourier */ +extern "C" int r4d_rad_point_fourier(const RadArgs* a, RadStream s) { + const RadTensor* X = r4d_opt(a, 0); + const RadTensor* Y = r4d_opt(a, 1); + if (!X || !Y) return R4D_NO(RAD_E_INVAL); + if (X->dtype != RAD_F32 || Y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), F = r4d_geti_or(a, "freqs", 0); + if (n <= 0 || F <= 0 || F > 30) return R4D_NO(RAD_E_SHAPE); + long long M = 0, My = 0; + const long long x_ld = r4d_rows_pitch(X, n, &M); + const long long y_ld = r4d_rows_pitch(Y, n * (2 * F + 1), &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); + return enc_status(r4d_point_fourier_f32(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)F, + (int)r4d_geti_or(a, "pi", 0), (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); +} + /* ------------------------------------------------------------------ cast bf16 -> f32 */ extern "C" int r4d_rad_cast_widen(const RadArgs* a, RadStream s) { const RadTensor* x = r4d_opt(a, 0); diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 1c91c1df..615a4f48 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -796,6 +796,7 @@ int r4d_rad_cast_f16 (const RadArgs*, RadStream); int r4d_rad_cast_bf16 (const RadArgs*, RadStream); int r4d_rad_pool_rows (const RadArgs*, RadStream); int r4d_rad_pool_cols (const RadArgs*, RadStream); +int r4d_rad_point_fourier (const RadArgs*, RadStream); int r4d_rad_relu (const RadArgs*, RadStream); int r4d_rad_silu (const RadArgs*, RadStream); int r4d_rad_gelu (const RadArgs*, RadStream); diff --git a/libr4d/r4d_qsa_tail_store_bf16.hip b/libr4d/r4d_qsa_tail_store_bf16.hip index 82588658..ceb83fed 100644 --- a/libr4d/r4d_qsa_tail_store_bf16.hip +++ b/libr4d/r4d_qsa_tail_store_bf16.hip @@ -34,7 +34,7 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx, uint16_t* __restrict__ state, - int T, int n, int ring, int seqs, int k_ld, int s_slot, int s_row, int sidx_ld) { + int T, int n, int ring, int seqs, int slots, int k_ld, int s_slot, int s_row, int sidx_ld) { const int t = (int)blockIdx.x; if (t >= T) return; @@ -48,9 +48,10 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( /* Only the last `ring` tokens of this sequence's chunk -- see the header. */ if (t < cu[s + 1] - ring) return; - /* Column 0 is the committed slot; -1 marks a sequence with no state. */ + /* Column 0 is the committed slot; -1 marks a sequence with no state. A slot past the + * state plane's would write past its allocation. */ const int si = sidx[(size_t)s * sidx_ld]; - if (si < 0) return; + if (si < 0 || si >= slots) return; const int row = pos[t] % ring; const size_t src = (size_t)t * k_ld; @@ -67,17 +68,17 @@ __global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( // state [slots][ring][n] bf16, this layer's tail cache; written only, untargeted rows // keep their contents static int r4d_qsa_tail_store_bf16_emit(long k, long pos, long cu, long sidx, long state, int T, - int n, int ring, int seqs, int k_ld, int s_slot, int s_row, - int sidx_ld, RadStream stream) { + int n, int ring, int seqs, int slots, int k_ld, int s_slot, + int s_row, int sidx_ld, RadStream stream) { if (!k || !pos || !cu || !sidx || !state) return R4D_NO(RAD_E_INVAL); - if (T <= 0 || n <= 0 || ring <= 0 || seqs <= 0) return R4D_NO(RAD_E_SHAPE); + if (T <= 0 || n <= 0 || ring <= 0 || seqs <= 0 || slots <= 0) return R4D_NO(RAD_E_SHAPE); if (!k_ld) k_ld = n; if (!s_row) s_row = n; if (!sidx_ld) sidx_ld = 1; return R4D_EMIT(stream, qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), 0, (const uint16_t*)k, (const int32_t*)pos, (const int32_t*)cu, - (const int32_t*)sidx, (uint16_t*)state, T, n, ring, seqs, k_ld, s_slot, s_row, - sidx_ld); + (const int32_t*)sidx, (uint16_t*)state, T, n, ring, seqs, slots, k_ld, s_slot, + s_row, sidx_ld); } // ============================================================== the plugin ABI entry point @@ -114,7 +115,7 @@ extern "C" int r4d_rad_qsa_tail_store(const RadArgs* a, RadStream stream) { if (k->dtype != RAD_BF16 || st->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); return r4d_qsa_tail_store_bf16_emit(r4d_addr(k), r4d_addr(po), r4d_addr(cu), r4d_addr(sx), r4d_addr(st), (int)T, (int)n, (int)ring, (int)seqs, - (int)kp, (int)st->stride[0], (int)st->stride[2], - (int)sxp, stream); + (int)st->shape[0], (int)kp, (int)st->stride[0], + (int)st->stride[2], (int)sxp, stream); } diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index afcf16c3..00b03d8a 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1960,6 +1960,10 @@ static const RadParamSpec pQkNormRope[] = { static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), P_STR("dtype"), }; +/* `n` is the point's values; y has n (2 freqs + 1) columns. */ +static const RadParamSpec pPointFourier[] = { + P_INT("M"), P_INT("n"), P_INT("freqs"), P_INTO("pi"), P_STR("dtype"), +}; /* `positions` may be absent at `rotary_dim` 0 (the norm alone), and an absent gain is a unit * gain. */ static const RadOperandSpec oQkNormRope[] = { @@ -3048,6 +3052,10 @@ static const RadOpSchema kSchemas[] = { "Column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in f32 and " "rounded, then times `mult` and rounded again. n, the input width, is a multiple of k; " "y has n / k columns."), + SCHEMA("point_fourier", pPointFourier, oUnary, + "A point's Fourier features: row m of y is [x | sin(x_i f_j) | cos(x_i f_j)], f_j = 2^j " + "for j < freqs (times pi with `pi` 1), sines then cosines each i-major then j; y is " + "[M, n (2 freqs + 1)]."), SCHEMA("sigmoid", pMnDtype, oUnary, "y = 1 / (1 + exp(-x))."), SCHEMA("relu", pMnDtype, oUnary, "y = max(x, 0)."), SCHEMA("silu", pMnDtype, oUnary, "y = x * sigmoid(x)."), @@ -6047,6 +6055,15 @@ static const RadKernelInfo kKernels[] = { ROW(cBf16Row), NOTUNE, nullptr, nullptr, r4d_rad_pool_cols }, +{ "point_fourier_f32", "point_fourier", "elem", + "a point's Fourier features: x, then its sines and cosines at octaves (a shape decoder's query " + "embedding)", + "any n and freqs up to 30; a thread an output column", + "f32 in and out, the device's sinf and cosf", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_point_fourier }, + { "rmsnorm_bf16", "rmsnorm", "norm", "root-mean-square norm with a gain, two passes over the row", "any n; the sum of squares accumulates in f32 and only the store narrows", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index f146144a..30d0ff50 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -30236,6 +30236,40 @@ static void device_phase(const Plugin& pl) { return v; }; + /* point_fourier: a shape decoder's query points (three values, eight octaves, f32), past + * the 65535 rows one grid row a matrix row would reach, against libm's sinf and cosf. */ + if (sel("point_fourier_f32")) { + if (const RadKernelInfo* r = find(pl, "point_fourier_f32")) { + const int64_t M = 70001, n = 3, F = 8, W = n * (2 * F + 1); + std::vector x = randv((size_t)(M * n), 1.01f); + void* dx = dalloc(x.size() * 4); + void* dy = dalloc((size_t)(M * W) * 4); + if (dx) st_memcpy(dx, x.data(), x.size() * 4, hipMemcpyHostToDevice); + std::vector ts = { T(dx, RAD_F32, { M, n }), T(dy, RAD_F32, { M, W }) }; + std::vector ps = { PI("M", M), PI("n", n), PI("freqs", F), + PS("dtype", "f32") }; + run_case(r, ts, ps); + std::vector got((size_t)(M * W)); + st_memcpy(got.data(), dy, got.size() * 4, hipMemcpyDeviceToHost); + double worst = 0.0; + for (int64_t m = 0; m < M; ++m) + for (int64_t i = 0; i < n; ++i) { + const float v = x[(size_t)(m * n + i)]; + worst = std::max(worst, (double)std::fabs(got[(size_t)(m * W + i)] - v)); + for (int64_t j = 0; j < F; ++j) { + const float t = v * std::ldexp(1.0f, (int)j); + const float* g = &got[(size_t)(m * W)]; + const float es = g[n + i * F + j] - std::sin(t); + const float ec = g[n + n * F + i * F + j] - std::cos(t); + worst = std::max(worst, (double)std::max(std::fabs(es), std::fabs(ec))); + } + } + char d[96]; + std::snprintf(d, sizeof d, "max abs err %.3g", worst); + ok("point_fourier_f32 numerics", worst <= 1e-5, d); + } else ok("point_fourier_f32", false, "row absent"); + } + if (sel("relu_bf16") || sel("silu_bf16") || sel("clamp_bf16")) { const int64_t M = 5, n = 300; std::vector x = randv((size_t)(M * n), 2.0f); diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index abc369ef..84351bb8 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -8,6 +8,7 @@ #include "ref_ops.h" #include +#include #include using namespace ref; @@ -525,6 +526,42 @@ int ref_pool_cols(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ point_fourier */ +/* A point's Fourier features: row m of y is [x | sin(x_i f_j) | cos(x_i f_j)] over x's n values, + * the sines and the cosines each i-major then j, f_j = 2^j for j < freqs (times pi with `pi` 1), + * so y has n (2 freqs + 1) columns. The products are f32 (exact without pi: a power of two), the + * sine and cosine f32 and rounded once to y's dtype, as Hunyuan3D-2's shape VAE embeds a query + * point. */ +int ref_point_fourier(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0), F = p_int(a, "freqs", 0); + const bool pi = p_int(a, "pi", 0) != 0; + if (n <= 0 || F <= 0 || F > 30) return RAD_E_SHAPE; + const int64_t w = n * (2 * F + 1); + const int64_t M = rows_of(X, n); + if (M <= 0 || numel(Y) < M * w) return RAD_E_SHAPE; + float f[30]; + for (int64_t j = 0; j < F; ++j) + f[j] = pi ? (float)std::ldexp(3.14159265358979323846, (int)j) : std::ldexp(1.0f, (int)j); + + REF_PAR_FOR(M * w) + for (int64_t r = 0; r < M; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, w); + const int64_t xs = laststride(X), ys = laststride(Y); + for (int64_t i = 0; i < n; ++i) { + const float v = ldt(X, xb + i * xs); + stt(Y, yb + i * ys, v); + for (int64_t j = 0; j < F; ++j) { + const float t = v * f[j]; + stt(Y, yb + (n + i * F + j) * ys, std::sin(t)); + stt(Y, yb + (n + n * F + i * F + j) * ys, std::cos(t)); + } + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ relu */ /* y = max(x, 0) over [M, n], each operand at its own row pitch. */ int ref_relu(const RadArgs* a, RadStream) { diff --git a/libref/ref_ops.h b/libref/ref_ops.h index fcdb6679..bfa2a76c 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -91,6 +91,7 @@ int ref_seg_mean (const RadArgs*, RadStream); int ref_seg_softmax_pool (const RadArgs*, RadStream); int ref_pool_rows (const RadArgs*, RadStream); int ref_pool_cols (const RadArgs*, RadStream); +int ref_point_fourier (const RadArgs*, RadStream); int ref_relu (const RadArgs*, RadStream); int ref_clamp (const RadArgs*, RadStream); int ref_conv2d (const RadArgs*, RadStream); @@ -368,6 +369,7 @@ REF_SHAPE_FN(ref_seg_softmax_pool); REF_SHAPE_FN(ref_seg_mean_bf16_sum); REF_SHAPE_FN(ref_pool_rows); REF_SHAPE_FN(ref_pool_cols); +REF_SHAPE_FN(ref_point_fourier); REF_SHAPE_FN(ref_relu); REF_SHAPE_FN(ref_clamp); REF_SHAPE_FN(ref_conv2d); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index eb771ba0..13e4f15c 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -197,6 +197,9 @@ static const RadParamSpec pSegMean[] = { P_INT("M"), P_INT("n"), P_STR("dtype") static const RadOperandSpec oSegMean[] = { OPD("x"), OPD("cu_seqlens"), OUT("y") }; static const RadParamSpec pSegPool[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; static const RadOperandSpec oSegPool[] = { OPD("score"), OPD("v"), OPD("cu_seqlens"), OUT("y") }; +/* `n` is the point's values; y has n (2 freqs + 1) columns. */ +static const RadParamSpec pPointFourier[] = { P_INT("M"), P_INT("n"), P_INT("freqs"), P_INTO("pi"), + P_STR("dtype") }; /* `M` is the input row count, a multiple of `k`; y has M / k rows. */ static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), P_STR("dtype") }; @@ -1201,6 +1204,10 @@ static const RadOpSchema kSchemas[] = { "Column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in f32 and rounded " "to y's dtype, then times `mult` (default 1) and rounded again. n, the input width, is a " "multiple of k." }, +{ "point_fourier", ARR(pPointFourier), ARR(oUnary), + "A point's Fourier features: row m of y is [x | sin(x_i f_j) | cos(x_i f_j)] over x's n values, " + "sines then cosines each i-major then j, f_j = 2^j for j < freqs (times pi with `pi` 1); the " + "products f32, the sine and cosine f32 rounded once to y's dtype. y is [M, n (2 freqs + 1)]." }, { "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0), each operand at its own row pitch." }, { "clamp", ARR(pMnD), ARR(oClamp), "y = min(max(x, lo), hi), `lo` and `hi` WEIGHTS of one element each: a clipped linear's range." }, @@ -2289,6 +2296,8 @@ SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, DT_FLOAT, ref_pool_rows), SIMPLE("ref_pool_cols", "pool_cols", "elem", "mean of every k consecutive columns, then a " "multiplier", DT_FLOAT, ref_pool_cols), +SIMPLE("ref_point_fourier", "point_fourier", "elem", "a point's sines and cosines at octaves", + DT_FLOAT, ref_point_fourier), SIMPLE("ref_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, ref_relu), SIMPLE("ref_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, ref_clamp), SIMPLE("ref_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index d9421cb5..b8269311 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -634,6 +634,16 @@ int ref_pool_cols_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out return o.finish("pool_cols", operand, out); } +int ref_point_fourier_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), F = gi(p, n_p, "freqs", 0); + if (M <= 0 || n <= 0 || F <= 0 || F > 30) return RAD_E_UNSUPPORTED; + Opd o; + o.t(RAD_F32, { M, n }); /* x */ + o.t(D, { M, n * (2 * F + 1) }); /* y */ + return o.finish("point_fourier", operand, out); +} + int ref_relu_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 70b05801..ff3646c0 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -410,11 +410,13 @@ endif() # # libhalo serves gfx1151 behind libr4d's exact interface (libhalo/halo_parity.cpp): the same op # schemas and rows, so every model plugin runs on either. Host-only (the tables, no device calls); -# present when one build produces both plugins. +# present when one build produces both plugins. Labelled `parity`: it fails while libr4d has ops +# libhalo has not ported yet (every one printed as "only in libr4d"), which the image's test stage +# leaves out; a schema both declare must still agree, or the loader refuses the second library. if(TARGET halo_parity) add_test(NAME halo_parity COMMAND halo_parity ${RAD_PLUGIN_OUT}/kernels/libr4d.so ${RAD_PLUGIN_OUT}/kernels/libhalo.so) - set_tests_properties(halo_parity PROPERTIES LABELS "fast" TIMEOUT 60) + set_tests_properties(halo_parity PROPERTIES LABELS "fast;parity" TIMEOUT 60) endif() # ================================================================== the device layer without SVM diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 7ddfcaaa..2a5bdae9 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -1,8 +1,8 @@ -/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 32 and +/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 33 and * RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot * of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it * from the test's printout only together with a version bump. */ -{ "RadArchProbe", "", 0, 120 }, +{ "RadArchProbe", "", 0, 128 }, { "RadArchProbe", "draft_depth", 0, 4 }, { "RadArchProbe", "draft_depth_fixed", 4, 4 }, { "RadArchProbe", "shape_probe_ok", 8, 4 }, @@ -22,6 +22,7 @@ { "RadArchProbe", "tree_pays", 96, 8 }, { "RadArchProbe", "gen_max_pixels", 104, 8 }, { "RadArchProbe", "gen_max_refs", 112, 8 }, +{ "RadArchProbe", "gen_shape", 120, 4 }, { "RadArgs", "", 0, 64 }, { "RadArgs", "t", 0, 8 }, { "RadArgs", "n_t", 8, 4 }, @@ -32,7 +33,7 @@ { "RadArgs", "instance", 48, 8 }, { "RadArgs", "rank", 56, 4 }, { "RadArgs", "world_size", 60, 4 }, -{ "RadBatch", "", 0, 408 }, +{ "RadBatch", "", 0, 416 }, { "RadBatch", "phase", 0, 4 }, { "RadBatch", "step", 4, 4 }, { "RadBatch", "n_tok", 8, 8 }, @@ -89,6 +90,7 @@ { "RadBatch", "plugin_cu", 384, 8 }, { "RadBatch", "plugin_words_h", 392, 8 }, { "RadBatch", "plugin_cu_h", 400, 8 }, +{ "RadBatch", "sgen_b", 408, 8 }, { "RadBufDecl", "", 0, 80 }, { "RadBufDecl", "dtype", 0, 4 }, { "RadBufDecl", "rank", 4, 4 }, @@ -695,6 +697,44 @@ { "RadSampleParams", "mask_row", 84, 4 }, { "RadSampleParams", "flags", 88, 4 }, { "RadSampleParams", "dry_rep_limit", 92, 4 }, +{ "RadShapeGenBatch", "", 0, 112 }, +{ "RadShapeGenBatch", "lane", 0, 4 }, +{ "RadShapeGenBatch", "patches", 8, 8 }, +{ "RadShapeGenBatch", "step", 16, 4 }, +{ "RadShapeGenBatch", "n_steps", 20, 4 }, +{ "RadShapeGenBatch", "sigma", 24, 8 }, +{ "RadShapeGenBatch", "sigma_next", 32, 8 }, +{ "RadShapeGenBatch", "cfg", 40, 8 }, +{ "RadShapeGenBatch", "pair", 48, 8 }, +{ "RadShapeGenBatch", "lanes", 56, 8 }, +{ "RadShapeGenBatch", "flags", 64, 8 }, +{ "RadShapeGenBatch", "seed", 72, 8 }, +{ "RadShapeGenBatch", "lat_cu", 80, 8 }, +{ "RadShapeGenBatch", "n_query", 88, 8 }, +{ "RadShapeGenBatch", "query", 96, 8 }, +{ "RadShapeGenBatch", "query_cu", 104, 8 }, +{ "RadShapeGenDecl", "", 0, 200 }, +{ "RadShapeGenDecl", "name", 0, 8 }, +{ "RadShapeGenDecl", "canvas", 8, 8 }, +{ "RadShapeGenDecl", "border_ratio", 16, 8 }, +{ "RadShapeGenDecl", "enc_size", 24, 8 }, +{ "RadShapeGenDecl", "enc_patch", 32, 8 }, +{ "RadShapeGenDecl", "pix_mean", 40, 24 }, +{ "RadShapeGenDecl", "pix_std", 64, 24 }, +{ "RadShapeGenDecl", "latent_rows", 88, 8 }, +{ "RadShapeGenDecl", "latent_channels", 96, 8 }, +{ "RadShapeGenDecl", "step_rows", 104, 8 }, +{ "RadShapeGenDecl", "default_steps", 112, 8 }, +{ "RadShapeGenDecl", "max_steps", 120, 8 }, +{ "RadShapeGenDecl", "default_guidance", 128, 8 }, +{ "RadShapeGenDecl", "bounds", 136, 8 }, +{ "RadShapeGenDecl", "level", 144, 8 }, +{ "RadShapeGenDecl", "default_resolution", 152, 8 }, +{ "RadShapeGenDecl", "min_resolution", 160, 8 }, +{ "RadShapeGenDecl", "max_resolution", 168, 8 }, +{ "RadShapeGenDecl", "max_lanes", 176, 8 }, +{ "RadShapeGenDecl", "max_query", 184, 8 }, +{ "RadShapeGenDecl", "field_out", 192, 4 }, { "RadTensor", "", 0, 112 }, { "RadTensor", "data", 0, 8 }, { "RadTensor", "dtype", 8, 4 }, diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index a794307e..fa626180 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -59,7 +59,7 @@ std::vector cpp_rows() { } /* The layout at RAD_ABI_VERSION 32 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 32, kTableFormat = 2; +constexpr uint32_t kTableAbi = 33, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/oot_plugins.sh b/tests/oot_plugins.sh index 6e991c70..91ff0e6f 100644 --- a/tests/oot_plugins.sh +++ b/tests/oot_plugins.sh @@ -149,6 +149,13 @@ run "$W/logs/kbench.log" env HIP_VISIBLE_DEVICES=-1 RADIANCE_HOME="$HH" \ "$P/bin/rad-kbench" --fixture "$P/share/radiance/kernels.rkb" --max-cases 1 \ --max-bytes 2048 --op rmsnorm --op quant_act_fp8 --op silu_mul grep -E "passed|failed" "$W/logs/kbench.log" | tail -3 +# rad-kbench fails only on a case that ran and failed, so a replay that skipped every case would +# pass unseen: its summary must name at least one passed case and no failed one. +sum=$(grep -E '^[0-9]+ checked, [0-9]+ passed, [0-9]+ failed' "$W/logs/kbench.log" | tail -1) +n_pass=$(printf '%s\n' "$sum" | sed -nE 's/^[0-9]+ checked, ([0-9]+) passed, ([0-9]+) failed.*/\1/p') +n_fail=$(printf '%s\n' "$sum" | sed -nE 's/^[0-9]+ checked, ([0-9]+) passed, ([0-9]+) failed.*/\2/p') +[ -n "$n_pass" ] && [ "$n_pass" -gt 0 ] && [ "$n_fail" -eq 0 ] || + fail "the installed rad-kbench replay checked nothing or failed: '$sum' (log: $W/logs/kbench.log)" say "4. the installed rad-kbench replays fixture ops from the out-of-tree home: $(ls "$HH/kernels" | tr '\n' ' ')" # 5. The device library's machine code, against the tree's, object by object. A code object also diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index b6e2eea4..3fecd804 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -970,7 +970,8 @@ TEST(op_vocabulary) { "layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean", "seg_softmax_pool", "seg_mean_bf16_sum", - "pool_rows", "pool_cols", "relu", "clamp", "conv2d", "conv2d_unfold", "conv1d_dw", + "pool_rows", "pool_cols", "point_fourier", "relu", "clamp", "conv2d", "conv2d_unfold", + "conv1d_dw", "rel_sinusoid", "seg_sinusoid", "attn_local_rel", "gelu", "silu", "sigmoid", "logit_softcap", "scale", "fill", @@ -3508,6 +3509,30 @@ TEST(op_pool_cols) { CHECK(run("pool_cols", bad) < 0); } +/* point_fourier: [x | sin(x 2^j) | cos(x 2^j)], sines and cosines each value-major then octave; + * with `pi`, the octaves times pi. */ +TEST(op_point_fourier) { + T x(RAD_F32, {2, 2}); x.f({ 0.5f, -0.25f, 1.0f, 0.0f }); + T y(RAD_F32, {2, 10}); + A a; a.t(x).t(y).i("M", 2).i("n", 2).i("freqs", 2).s("dtype", "f32"); + CHECK_OK(run("point_fourier", a)); + const float v[2][2] = { { 0.5f, -0.25f }, { 1.0f, 0.0f } }; + for (int r = 0; r < 2; ++r) + for (int i = 0; i < 2; ++i) { + CHECK_EQ(y.at(r * 10 + i), v[r][i]); + for (int j = 0; j < 2; ++j) { + const float t = v[r][i] * (float)(1 << j); + CHECK_NEAR(y.at(r * 10 + 2 + i * 2 + j), std::sin(t), 1e-6); + CHECK_NEAR(y.at(r * 10 + 6 + i * 2 + j), std::cos(t), 1e-6); + } + } + A b; b.t(x).t(y).i("M", 2).i("n", 2).i("freqs", 2).i("pi", 1).s("dtype", "f32"); + CHECK_OK(run("point_fourier", b)); + CHECK_NEAR(y.at(3), std::sin(0.5f * 2.0f * 3.14159265f), 1e-6); + A bad; bad.t(x).t(y).i("M", 2).i("n", 2).i("freqs", 3).s("dtype", "f32"); + CHECK(run("point_fourier", bad) < 0); +} + /* rmsnorm with no gain: a unit gain. */ TEST(op_rmsnorm_no_gain) { T x(RAD_F32, {1, 2}); x.f({ 3, 4 }); @@ -9655,6 +9680,7 @@ std::vector geometries() { G("seg_mean_bf16_sum", "M", 6, a.i("M", R).i("n", 8).s("dtype", "bf16").i("n_seq", 2)), G("pool_rows", "M", 6, a.i("M", R).i("n", 8).i("k", 2).s("dtype", "f32")), G("pool_cols", "M", 6, a.i("M", R).i("n", 8).i("k", 2).s("dtype", "f32")), + G("point_fourier", "M", 3, a.i("M", R).i("n", 3).i("freqs", 2).s("dtype", "f32")), G("relu", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("clamp", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("conv2d", "M", 8, a.i("M", R).i("width", 4).i("cin", 2).i("cout", 3).i("kh", 3).i("kw", 3) diff --git a/tests/server_test.cpp b/tests/server_test.cpp index d1efe292..415c29c0 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -3720,6 +3720,25 @@ TEST(messages_refuse_a_field_they_do_not_know) { CHECK(f.sched.submitted.empty()); } +/* The chat path's history penalties and min-p are taken at the top level under the chat path's + * names and reach the sampler as there; out of range they are refused by name, as there. */ +TEST(messages_carry_the_penalties_and_min_p_to_the_sampler) { + Fixture f; + f.sched.reply = "fine"; + const HttpResponse r = post_messages(f, R"("presence_penalty":1.5,"frequency_penalty":0.25,)" + R"("repetition_penalty":1.05,"min_p":0.05,)" + R"("repeat_last_n":256)"); + CHECK_EQ(r.status, 200); + CHECK_NEAR(f.sched.last_sp.pres_penalty, 1.5f, 1e-6); + CHECK_NEAR(f.sched.last_sp.freq_penalty, 0.25f, 1e-6); + CHECK_NEAR(f.sched.last_sp.rep_penalty, 1.05f, 1e-6); + CHECK_NEAR(f.sched.last_sp.min_p, 0.05f, 1e-6); + CHECK_EQ(f.sched.last_sp.penalty_last_n, 256); + Fixture g; + CHECK(anthropic_refusal(post_messages(g, R"("presence_penalty":3)"), "presence_penalty")); + CHECK(g.sched.submitted.empty()); +} + /* What cannot change the answer here is taken and not acted on: capacity and placement, * prompt-cache control, and the inputs of Anthropic's own classifiers and fallbacks. */ TEST(messages_take_the_fields_that_change_nothing_here) { diff --git a/tests/shape_test.cpp b/tests/shape_test.cpp new file mode 100644 index 00000000..37a7038e --- /dev/null +++ b/tests/shape_test.cpp @@ -0,0 +1,464 @@ +/* shape_test.cpp -- the shape generator's host geometry (core/gen/shape.h) and its pass driver + * (core/gen/shape_driver.h). The plugin's side of each pass is played by the test: a query pass is + * answered with a sphere's field at the points the driver staged. + */ +#include "sched_fakes.h" + +using namespace sched_fake; + +#include "gen/shape_driver.h" +#include "rad_plugin.h" + +#include +#include +#include +#include +#include + +using namespace rad; + +namespace { + +/* A small declaration: a 28-pixel encoder picture in 14-pixel patches, a latent of 8 rows of 4, + * a step of both branches with 5 conditioning rows each. */ +RadShapeGenDecl decl_small() { + RadShapeGenDecl d{}; + d.canvas = 32; + d.border_ratio = 0.15; + d.enc_size = 28; + d.enc_patch = 14; + for (int c = 0; c < 3; ++c) { d.pix_mean[c] = 0.5; d.pix_std[c] = 0.25; } + d.latent_rows = 8; + d.latent_channels = 4; + d.step_rows = 2 * (5 + 8); + d.default_steps = 4; + d.max_steps = 8; + d.default_guidance = 5.0; + d.bounds = 1.0; + d.level = 0.0; + d.default_resolution = 64; + d.min_resolution = 8; + d.max_resolution = 128; + d.max_lanes = 2; + d.max_query = 4096; + d.field_out = 1; + return d; +} + +/* An RGBA picture w x h, opaque inside the box [x0, x1) x [y0, y1) and transparent elsewhere. */ +mm::FrameRGBA picture(int32_t w, int32_t h, int32_t x0, int32_t y0, int32_t x1, int32_t y1) { + mm::FrameRGBA f; + f.w = w; + f.h = h; + f.rgba.assign((size_t)w * h * 4, 0); + for (int32_t y = y0; y < y1; ++y) + for (int32_t x = x0; x < x1; ++x) { + uint8_t* p = &f.rgba[((size_t)y * w + x) * 4]; + p[0] = 200; p[1] = 50; p[2] = 10; p[3] = 255; + } + return f; +} + +gen::ShapeGenInfo info_small() { return gen::shape_info(decl_small(), "test"); } + +/* A sphere of radius `r` at the origin, as an occupancy logit: positive inside. */ +float sphere(float x, float y, float z, float r) { return r - std::sqrt(x * x + y * y + z * z); } + +/* The field of a sphere on level r's grid. */ +std::vector sphere_grid(int32_t r, double bounds, float radius) { + const std::vector ax = gen::shape_axis(bounds, r); + const int64_t n = (int64_t)r + 1; + std::vector f((size_t)(n * n * n)); + for (int64_t i = 0; i < n; ++i) + for (int64_t j = 0; j < n; ++j) + for (int64_t k = 0; k < n; ++k) + f[(size_t)((i * n + j) * n + k)] = sphere(ax[(size_t)i], ax[(size_t)j], + ax[(size_t)k], radius); + return f; +} + +struct ShapeFixture { + Program prog; + gen::ShapeDriver drv; + void build() { + prog.shape_gen = decl_small(); + prog.sgen_name = "test"; + prog.ctx.max_tok = 4096; + prog.ctx.max_seqs = 1; + } + int start() { return drv.init(prog, { gen::ShapeDriver::RankIO{} }); } + std::unique_ptr req(int32_t steps = 0, int32_t res = 16) { + auto r = std::make_unique(); + std::string why; + if (gen::shape_picture(info_small(), picture(40, 30, 5, 3, 30, 27), &r->patches, &why) < 0) + return nullptr; + r->steps = steps; + r->resolution = res; + r->seed = 7; + r->ticket = std::make_shared(); + return r; + } + /* The plugin's answer to a query pass: the sphere's field at each staged point, steepened + * `gain` times as an occupancy logit is (the model's cross zero within a cell or two). */ + void answer(const RadBatch* b, float radius, float gain = 20.0f) { + const RadShapeGenBatch* S = b->sgen_b; + for (const gen::IPassDriver::Readback& rb : drv.readbacks()) { + float* x = static_cast(rb.host); + for (int64_t i = 0; i < S->n_query; ++i) + x[i] = gain * sphere(S->query[3 * i], S->query[3 * i + 1], S->query[3 * i + 2], + radius); + } + } +}; + +char kind_of(int gen) { + switch (gen) { + case RAD_GEN_PASS_SCOND: return 'C'; + case RAD_GEN_PASS_SSTEP: return 'S'; + case RAD_GEN_PASS_SLATENT: return 'L'; + case RAD_GEN_PASS_SQUERY: return 'Q'; + default: return '?'; + } +} + +/* Every edge of a closed, consistently wound mesh is in exactly two faces, once each way. */ +bool watertight(const gen::ShapeMesh& m) { + std::map, int> e; + for (size_t t = 0; t + 2 < m.f.size(); t += 3) + for (int q = 0; q < 3; ++q) ++e[{ m.f[t + q], m.f[t + (q + 1) % 3] }]; + for (const auto& [k, n] : e) { + if (n != 1) return false; + auto it = e.find({ k.second, k.first }); + if (it == e.end() || it->second != 1) return false; + } + return !e.empty(); +} + +/* The signed volume of a closed mesh: positive when its faces wind counter-clockwise seen from + * outside. */ +double volume(const gen::ShapeMesh& m) { + double v = 0.0; + for (size_t t = 0; t + 2 < m.f.size(); t += 3) { + const float* a = &m.v[(size_t)m.f[t] * 3]; + const float* b = &m.v[(size_t)m.f[t + 1] * 3]; + const float* c = &m.v[(size_t)m.f[t + 2] * 3]; + v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0; + } + return v; +} + +} /* namespace */ + +/* The sampler's grid points are numpy's linspace(0, 1) in f32, the last exactly 1. */ +TEST(the_sigmas_are_linspace_from_noise_to_the_shape) { + const std::vector s = gen::shape_sigmas(50); + REQUIRE_EQ(s.size(), (size_t)50); + CHECK_EQ(s.front(), 0.0f); + CHECK_EQ(s.back(), 1.0f); + CHECK_EQ(s[1], (float)(1.0 / 49.0)); + CHECK_EQ(s[30], (float)(30 * (1.0 / 49.0))); + for (size_t i = 1; i < s.size(); ++i) CHECK(s[i] > s[i - 1]); + CHECK(gen::shape_sigmas(1).empty()); + CHECK_EQ(gen::shape_sigmas(2).size(), (size_t)2); +} + +/* The grid's levels: halved while at least 63, coarsest first; one level below 63. */ +TEST(the_grid_levels_halve_down_to_63) { + CHECK(gen::shape_levels(256) == (std::vector{ 64, 128, 256 })); + CHECK(gen::shape_levels(384) == (std::vector{ 96, 192, 384 })); + CHECK(gen::shape_levels(512) == (std::vector{ 64, 128, 256, 512 })); + CHECK(gen::shape_levels(63) == (std::vector{ 63 })); + CHECK(gen::shape_levels(32) == (std::vector{ 32 })); + CHECK(gen::shape_levels(130) == (std::vector{ 65, 130 })); + const std::vector a = gen::shape_axis(1.01, 4); + REQUIRE_EQ(a.size(), (size_t)5); + CHECK_EQ(a[0], -1.01f); + CHECK_EQ(a[2], (float)(2 * (2.02 / 4) - 1.01)); + CHECK_EQ(a[4], 1.01f); +} + +/* The finer level samples a shell around the coarse surface and nothing far from it. */ +TEST(refinement_samples_only_near_the_surface) { + const int32_t rp = 32, r = 64; + const float radius = 0.5f; + const std::vector coarse = sphere_grid(rp, 1.0, radius); + for (bool last : { false, true }) { + const std::vector pts = gen::shape_refine(coarse, rp, r, 0.0, last); + REQUIRE(!pts.empty()); + const std::vector ax = gen::shape_axis(1.0, r); + const int64_t n = r + 1; + double far = 0.0; + for (uint32_t p : pts) { + const float d = std::fabs(sphere(ax[p / (n * n)], ax[p / n % n], ax[p % n], radius)); + far = std::max(far, (double)d); + } + /* Within 0.95 of zero counts as near (the field here is a distance), plus the dilation. */ + CHECK(far < 0.95 + 4.0 * 2.0 / rp); + CHECK((int64_t)pts.size() < n * n * n); + /* Every fine cell the surface crosses has all eight corners sampled. */ + std::vector in((size_t)(n * n * n), 0); + for (uint32_t p : pts) in[p] = 1; + bool covered = true; + for (int64_t i = 0; i + 1 < n && covered; ++i) + for (int64_t j = 0; j + 1 < n && covered; ++j) + for (int64_t k = 0; k + 1 < n && covered; ++k) { + int pos = 0, neg = 0; + for (int c = 0; c < 8; ++c) { + const float v = sphere(ax[i + (c & 1)], ax[j + (c >> 1 & 1)], + ax[k + (c >> 2 & 1)], radius); + (v > 0 ? pos : neg)++; + } + if (!pos || !neg) continue; + for (int c = 0; c < 8; ++c) + covered = covered && + in[(size_t)(((i + (c & 1)) * n + j + (c >> 1 & 1)) * n + k + + (c >> 2 & 1))]; + } + CHECK(covered); + } +} + +/* Marching cubes over a sphere: a closed surface wound outwards, its vertices on the sphere + * (scaled by r / (r + 1), the reference's placement), its volume the ball's. */ +TEST(marching_cubes_makes_a_closed_outward_sphere) { + const int32_t r = 48; + const float radius = 0.6f; + gen::ShapeMesh m; + gen::shape_mesh(sphere_grid(r, 1.0, radius), r, 1.0, 0.0, &m); + REQUIRE(!m.f.empty()); + CHECK(watertight(m)); + const double scale = (double)r / (r + 1); + double worst = 0.0; + for (size_t i = 0; i + 2 < m.v.size(); i += 3) { + const double x = m.v[i] + 1.0 / (r + 1), y = m.v[i + 1] + 1.0 / (r + 1), + z = m.v[i + 2] + 1.0 / (r + 1); + worst = std::max(worst, std::fabs(std::sqrt(x * x + y * y + z * z) - radius * scale)); + } + CHECK(worst < 2.0 / r); + const double ball = 4.0 / 3.0 * M_PI * std::pow(radius * scale, 3); + CHECK(volume(m) > 0.0); + CHECK(std::fabs(volume(m) - ball) / ball < 0.02); +} + +/* Every inside/outside pattern of a cube gives a closed surface: a field of random signs. */ +TEST(marching_cubes_is_closed_for_every_cube_case) { + const int32_t r = 12; + const int64_t n = r + 1; + std::vector f((size_t)(n * n * n)); + uint32_t s = 12345; + for (float& v : f) { + s = s * 1664525u + 1013904223u; + v = (float)((s >> 8) & 0xffff) / 65535.0f - 0.5f; + } + /* A border outside the shape, so the surface closes inside the grid. */ + for (int64_t i = 0; i < n; ++i) + for (int64_t j = 0; j < n; ++j) + for (int64_t k = 0; k < n; ++k) + if (!i || !j || !k || i == r || j == r || k == r) + f[(size_t)((i * n + j) * n + k)] = -1.0f; + gen::ShapeMesh m; + gen::shape_mesh(f, r, 1.0, 0.0, &m); + REQUIRE(!m.f.empty()); + CHECK(watertight(m)); + CHECK(volume(m) > 0.0); +} + +/* A cube with a corner not sampled makes nothing, and an unsampled grid no surface. */ +TEST(marching_cubes_skips_unsampled_cubes) { + const int32_t r = 16; + std::vector f = sphere_grid(r, 1.0, 0.5f); + gen::ShapeMesh whole; + gen::shape_mesh(f, r, 1.0, 0.0, &whole); + std::vector holes = f; + const int64_t n = r + 1; + holes[(size_t)((8 * n + 8) * n + 4)] = NAN; /* a point on the sphere's surface band */ + gen::ShapeMesh m; + gen::shape_mesh(holes, r, 1.0, 0.0, &m); + CHECK(m.f.size() < whole.f.size()); + std::vector none(f.size(), NAN); + gen::shape_mesh(none, r, 1.0, 0.0, &m); + CHECK(m.f.empty()); +} + +/* The files: a GLB with its header and chunks sized, and the three others. */ +TEST(the_mesh_exports_as_glb_obj_ply_and_stl) { + gen::ShapeMesh m; + gen::shape_mesh(sphere_grid(16, 1.0, 0.5f), 16, 1.0, 0.0, &m); + REQUIRE(!m.f.empty()); + std::string bytes, mime, why; + CHECK_OK(gen::shape_export(m, "glb", &bytes, &mime, &why)); + CHECK_EQ(mime, std::string("model/gltf-binary")); + REQUIRE(bytes.size() > 28); + uint32_t hdr[5]; + std::memcpy(hdr, bytes.data(), sizeof hdr); + CHECK_EQ(hdr[0], 0x46546C67u); + CHECK_EQ(hdr[1], 2u); + CHECK_EQ(hdr[2], (uint32_t)bytes.size()); + CHECK_EQ(hdr[3] % 4, 0u); + CHECK_EQ(hdr[4], 0x4E4F534Au); + uint32_t bin[2]; + std::memcpy(bin, bytes.data() + 20 + hdr[3], sizeof bin); + CHECK_EQ(bin[1], 0x004E4942u); + CHECK_EQ((size_t)bin[0], m.v.size() * 4 * 2 + m.f.size() * 4); + CHECK_OK(gen::shape_export(m, "obj", &bytes, &mime, &why)); + CHECK(bytes.rfind("v ", 0) == 0); + CHECK_OK(gen::shape_export(m, "ply", &bytes, &mime, &why)); + CHECK(bytes.rfind("ply\n", 0) == 0); + CHECK_OK(gen::shape_export(m, "stl", &bytes, &mime, &why)); + CHECK_EQ(bytes.size(), (size_t)84 + m.f.size() / 3 * 50); + CHECK(gen::shape_export(m, "fbx", &bytes, &mime, &why) < 0); +} + +/* The picture: the alpha's box centred on white, normalised, cut into patches; an empty alpha + * refused. */ +TEST(the_picture_is_recentred_on_white_and_cut_into_patches) { + const gen::ShapeGenInfo g = info_small(); + std::vector p; + std::string why; + CHECK_OK(gen::shape_picture(g, picture(40, 30, 5, 3, 30, 27), &p, &why)); + REQUIRE_EQ(p.size(), (size_t)(2 * 2 * 3 * 14 * 14)); + /* The corners are white, (1 - 0.5) / 0.25 = 2 in every channel; the centre the colour. */ + const float white = (float)((1.0 - 0.5) / 0.25); + CHECK_NEAR(p[0], white, 1e-3); + CHECK_NEAR(p[(size_t)(2 * 14 * 14)], white, 1e-3); /* blue, pixel (0, 0) */ + const int64_t pd = 3 * 14 * 14; + /* Patch (1, 1) holds pixels (14.., 14..); its first pixel, red channel, is the box's colour. */ + CHECK_NEAR(p[(size_t)(3 * pd)], (float)((200.0 / 255.0 - 0.5) / 0.25), 0.1); + CHECK(gen::shape_picture(g, picture(20, 20, 0, 0, 0, 0), &p, &why) < 0); + CHECK(gen::shape_picture(g, picture(20, 20, 5, 5, 6, 15), &p, &why) < 0); +} + +/* A request runs its picture, its steps, the latent, then the grid level by level; the field the + * ticket hands back meshes into the sphere the queries were answered with. */ +TEST(a_request_runs_cond_steps_latent_and_the_grid_levels) { + ShapeFixture f; + f.build(); + CHECK_OK(f.start()); + auto r = f.req(4, 128); + REQUIRE(r != nullptr); + auto t = r->ticket; + std::string why; + CHECK_OK(f.drv.submit(std::move(r), &why)); + CHECK_EQ(t->steps, 3); + CHECK_EQ(t->resolution, 128); + std::string kinds; + const std::vector sig = gen::shape_sigmas(4); + int steps = 0; + for (int i = 0; i < 1000; ++i) { + const RadBatch* b = f.drv.next(i); + if (!b) break; + const RadShapeGenBatch* S = b->sgen_b; + REQUIRE(S != nullptr); + kinds += kind_of(b->gen); + CHECK_EQ(S->lanes[0], S->lane); + CHECK_EQ(S->lat_cu[2], 16); + if (b->gen == RAD_GEN_PASS_SCOND) CHECK_EQ(b->n_tok, (int64_t)4); + if (b->gen == RAD_GEN_PASS_SSTEP) { + CHECK_EQ(b->n_tok, (int64_t)26); + CHECK_EQ(S->sigma[0], sig[(size_t)steps]); + CHECK_EQ(S->sigma_next[0], sig[(size_t)steps + 1]); + CHECK_EQ(S->cfg[0], 5.0f); + CHECK_EQ(S->pair[0], 1); + CHECK_EQ(S->pair[1], -2); + CHECK_EQ(S->flags[0], steps == 0 ? (int32_t)RAD_GEN_F_FIRST : 0); + CHECK_EQ(S->flags[1], 0); + CHECK_EQ(S->seed[0], 7u); + ++steps; + } + if (b->gen == RAD_GEN_PASS_SQUERY) { + CHECK(S->n_query > 0 && S->n_query <= 4096); + CHECK_EQ(S->query_cu[1], (int32_t)S->n_query); + f.answer(b, 0.5f); + } + CHECK_OK(f.drv.done()); + } + /* 65^3 coarse points in passes of 4096, then the finer level's shell. */ + REQUIRE(kinds.size() > 5); + CHECK_EQ(kinds.substr(0, 5), std::string("CSSSL")); + CHECK(kinds.find_first_not_of('Q', 5) == std::string::npos); + CHECK((int64_t)(kinds.size() - 5) >= (65 * 65 * 65 + 4095) / 4096); + REQUIRE(t->finished()); + CHECK_OK(t->status()); + int32_t res = 0; + std::vector field = t->take_field(&res); + CHECK_EQ(res, 128); + gen::ShapeMesh m; + gen::shape_mesh(field, res, 1.0, 0.0, &m); + REQUIRE(!m.f.empty()); + CHECK(watertight(m)); + CHECK(volume(m) > 0.0); + /* Hierarchical sampling queried far fewer points than the dense grid has. */ + CHECK(t->points > 65 * 65 * 65); + CHECK(t->points < (int64_t)129 * 129 * 129 / 4); +} + +/* Dense sampling queries every point of the finest grid, in one level. */ +TEST(dense_sampling_queries_every_point_once) { + ShapeFixture f; + f.build(); + CHECK_OK(f.start()); + auto r = f.req(2, 20); + REQUIRE(r != nullptr); + r->dense = true; + auto t = r->ticket; + std::string why; + CHECK_OK(f.drv.submit(std::move(r), &why)); + for (int i = 0; i < 100; ++i) { + const RadBatch* b = f.drv.next(i); + if (!b) break; + if (b->gen == RAD_GEN_PASS_SQUERY) f.answer(b, 0.5f); + CHECK_OK(f.drv.done()); + } + REQUIRE(t->finished()); + CHECK_EQ(t->points, (int64_t)21 * 21 * 21); +} + +/* What a request may not name is refused at submit, with the range. */ +TEST(a_request_out_of_range_is_refused_at_submit) { + ShapeFixture f; + f.build(); + CHECK_OK(f.start()); + std::string why; + auto r = f.req(9); + CHECK(f.drv.submit(std::move(r), &why) < 0); + CHECK(why.find("num_inference_steps") != std::string::npos); + r = f.req(4, 200); + CHECK(f.drv.submit(std::move(r), &why) < 0); + CHECK(why.find("octree_resolution") != std::string::npos); + r = f.req(4); + r->guidance = -1.0; + CHECK(f.drv.submit(std::move(r), &why) < 0); + r = f.req(4); + r->patches.pop_back(); + CHECK(f.drv.submit(std::move(r), &why) < 0); +} + +/* A field that crosses the level nowhere finishes after the coarsest level. */ +TEST(a_field_without_a_surface_ends_after_its_first_level) { + ShapeFixture f; + f.build(); + CHECK_OK(f.start()); + auto r = f.req(2, 128); + auto t = r->ticket; + std::string why; + CHECK_OK(f.drv.submit(std::move(r), &why)); + int queries = 0; + for (int i = 0; i < 1000; ++i) { + const RadBatch* b = f.drv.next(i); + if (!b) break; + if (b->gen == RAD_GEN_PASS_SQUERY) { + f.answer(b, -5.0f); /* a sphere of negative radius: outside everywhere */ + ++queries; + } + CHECK_OK(f.drv.done()); + } + REQUIRE(t->finished()); + CHECK_EQ(queries, (65 * 65 * 65 + 4095) / 4096); + int32_t res = 0; + gen::ShapeMesh m; + gen::shape_mesh(t->take_field(&res), res, 1.0, 0.0, &m); + CHECK(m.f.empty()); +} + +RAD_TEST_MAIN() diff --git a/tests/shapes_test.cpp b/tests/shapes_test.cpp new file mode 100644 index 00000000..71cce1b4 --- /dev/null +++ b/tests/shapes_test.cpp @@ -0,0 +1,217 @@ +/* tests/shapes_test.cpp -- Hunyuan3D-2's API over a shape generator (core/server/shapes.cpp). + * + * The generator is faked here: it finishes every request on submit with a sphere's field on the + * request's grid, so these pin what the server owns: which requests are refused and under which + * field, the request it hands the generator (the prepared picture, the steps, the resolution, the + * guidance, the seed), the mesh file /generate answers with, and the background job seen through + * /send and /status. + */ +#include "server_fakes.h" + +#include "gen/shape.h" +#include "mm/media.h" +#include "server/oai.h" + +#include +#include + +namespace { + +struct FakeShapeGen : IShapeGen { + gen::ShapeGenInfo inf; + int finish_status = RAD_OK; + std::string finish_why; + /* What each request asked, kept after the request itself goes. */ + struct Seen { + int32_t steps, resolution; + double guidance; + uint64_t seed; + bool dense; + size_t n; + }; + std::vector got; + mutable std::mutex got_m; + + FakeShapeGen() { + RadShapeGenDecl d{}; + d.canvas = 32; + d.border_ratio = 0.15; + d.enc_size = 28; + d.enc_patch = 14; + for (int c = 0; c < 3; ++c) { d.pix_mean[c] = 0.5; d.pix_std[c] = 0.25; } + d.default_steps = 50; + d.max_steps = 200; + d.default_guidance = 5.0; + d.bounds = 1.01; + d.level = 0.0; + d.default_resolution = 24; + d.min_resolution = 8; + d.max_resolution = 48; + d.max_lanes = 2; + inf = gen::shape_info(d, "fake-shape"); + } + const gen::ShapeGenInfo& info() const override { return inf; } + int submit(std::unique_ptr r, std::string*) override { + std::lock_guard lk(got_m); + const int32_t res = r->resolution > 0 ? r->resolution : (int32_t)inf.default_resolution; + got.push_back({ r->steps, r->resolution, r->guidance, r->seed, r->dense, + r->patches.size() }); + gen::ShapeTicket& t = *r->ticket; + t.steps = (r->steps > 0 ? r->steps : 50) - 1; + t.resolution = res; + if (finish_status == RAD_OK) { + const std::vector ax = gen::shape_axis(inf.bounds, res); + const int64_t n = (int64_t)res + 1; + std::vector f((size_t)(n * n * n)); + for (int64_t i = 0; i < n; ++i) + for (int64_t j = 0; j < n; ++j) + for (int64_t k = 0; k < n; ++k) { + const float x = ax[(size_t)i], y = ax[(size_t)j], z = ax[(size_t)k]; + f[(size_t)((i * n + j) * n + k)] = 0.5f - std::sqrt(x * x + y * y + z * z); + } + t.set_field(std::move(f), res); + } + t.finish(finish_status, finish_why); + return RAD_OK; + } + int64_t queued() const override { return 0; } + int64_t running() const override { return 0; } + Seen last() const { + std::lock_guard lk(got_m); + return got.back(); + } +}; + +/* A 16 x 16 PNG, opaque inside [4, 12)^2 and transparent around it, as base64. */ +std::string picture_b64(bool opaque_anywhere = true) { + std::vector px((size_t)16 * 16 * 4, 0); + for (int y = 4; y < 12 && opaque_anywhere; ++y) + for (int x = 4; x < 12; ++x) { + uint8_t* p = &px[((size_t)y * 16 + x) * 4]; + p[0] = 30; p[1] = 120; p[2] = 220; p[3] = 255; + } + std::vector file; + std::string why; + if (mm::encode_image(px.data(), 16, 16, 4, "png", 0, &file, &why) < 0) return ""; + return base64_encode(file.data(), file.size()); +} + +struct Shapes { + FakeShapeGen gen; + std::unique_ptr f; + Shapes() { + f.reset(new Fixture(Fixture::Tweak{ [this](ServerOptions& o, Deps& d) { + d.shapes = &gen; + o.shape_model = true; + } })); + } + static json body(json extra = json::object()) { + json b = { { "image", picture_b64() } }; + for (auto it = extra.begin(); it != extra.end(); ++it) b[it.key()] = it.value(); + return b; + } + HttpResponse generate(const json& b) { return f->post("/generate", b.dump()); } + std::string refused(const json& b, int status = 400) { + HttpResponse r = generate(b); + CHECK_EQ(r.status, status); + return str_at(json::parse(r.body, nullptr, false)["error"], "param"); + } +}; + +} /* namespace */ + +/* A request that cannot be served is a 400 naming its field before anything is queued. */ +TEST(a_shape_request_that_cannot_be_served_names_its_field) { + if (!mm::decoder_available()) return; + Shapes s; + CHECK_EQ(s.refused(json::object()), std::string("image")); + CHECK_EQ(s.refused({ { "image", "not base64 !" } }), std::string("image")); + CHECK_EQ(s.refused({ { "image", picture_b64(false) } }), std::string("image")); + CHECK_EQ(s.refused(Shapes::body({ { "texture", true } })), std::string("texture")); + CHECK_EQ(s.refused(Shapes::body({ { "text", "a penguin" } })), std::string("text")); + CHECK_EQ(s.refused(Shapes::body({ { "mesh", "Z2xURg==" } })), std::string("mesh")); + CHECK_EQ(s.refused(Shapes::body({ { "type", "fbx" } })), std::string("type")); + CHECK_EQ(s.refused(Shapes::body({ { "num_inference_steps", 1 } })), + std::string("num_inference_steps")); + CHECK_EQ(s.refused(Shapes::body({ { "octree_resolution", 4096 } })), + std::string("octree_resolution")); + CHECK_EQ(s.refused(Shapes::body({ { "guidance_scale", -1 } })), std::string("guidance_scale")); + CHECK_EQ(s.refused(Shapes::body({ { "volume_decoding", "flashvdm" } })), + std::string("volume_decoding")); + CHECK_EQ(s.refused(Shapes::body({ { "mc_algo", "dmc" } })), std::string("mc_algo")); + CHECK_EQ(s.refused(Shapes::body({ { "temperature", 1 } })), std::string("temperature")); + CHECK_EQ(s.gen.got.size(), (size_t)0); +} + +/* The generator gets the prepared picture and the request's numbers; the answer is the mesh as + * the file `type` names. */ +TEST(generate_answers_with_the_mesh_file) { + if (!mm::decoder_available()) return; + Shapes s; + HttpResponse r = s.generate(Shapes::body({ { "num_inference_steps", 30 }, + { "octree_resolution", 32 }, + { "guidance_scale", 7.5 }, { "seed", 99 }, + { "face_count", 40000 }, { "mc_algo", "mc" } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(r.content_type, std::string("model/gltf-binary")); + REQUIRE(r.body.size() > 12); + CHECK_EQ(r.body.substr(0, 4), std::string("glTF")); + const FakeShapeGen::Seen q = s.gen.last(); + CHECK_EQ(q.steps, 30); + CHECK_EQ(q.resolution, 32); + CHECK_EQ(q.guidance, 7.5); + CHECK_EQ(q.seed, (uint64_t)99); + CHECK(!q.dense); + CHECK_EQ(q.n, (size_t)(2 * 2 * 3 * 14 * 14)); + /* The reference's defaults: seed 1234, the model's steps and resolution. */ + r = s.generate(Shapes::body({ { "type", "obj" }, { "volume_decoding", "dense" } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(r.content_type, std::string("model/obj")); + CHECK(r.body.rfind("v ", 0) == 0); + CHECK_EQ(s.gen.last().seed, (uint64_t)1234); + CHECK_EQ(s.gen.last().steps, 0); + CHECK(s.gen.last().dense); +} + +/* A failed shape is the generator's reason, not a file. */ +TEST(a_failed_shape_reports_the_reason) { + if (!mm::decoder_available()) return; + Shapes s; + s.gen.finish_status = RAD_E_STATE; + s.gen.finish_why = "the engine stopped"; + HttpResponse r = s.generate(Shapes::body()); + CHECK(r.status >= 400); + CHECK(r.body.find("the engine stopped") != std::string::npos); +} + +/* /send queues the shape and answers with its uid; /status reports it until the file is in + * `model_base64`, and an unknown uid is a 404. */ +TEST(send_and_status_make_the_shape_in_the_background) { + if (!mm::decoder_available()) return; + Shapes s; + HttpResponse r = s.f->post("/send", Shapes::body({ { "type", "stl" } }).dump()); + REQUIRE_EQ(r.status, 200); + const std::string uid = str_at(json::parse(r.body, nullptr, false), "uid"); + REQUIRE(!uid.empty()); + json o; + for (int i = 0; i < 400; ++i) { + o = json::parse(s.f->get(("/status/" + uid).c_str()).body, nullptr, false); + if (str_at(o, "status") != "processing") break; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + REQUIRE_EQ(str_at(o, "status"), std::string("completed")); + std::vector file; + REQUIRE(base64_decode(str_at(o, "model_base64"), &file)); + CHECK(file.size() > 84); + CHECK_EQ(s.f->get("/status/shape_nope").status, 404); +} + +/* A model that makes no shapes answers the routes with a 501. */ +TEST(the_shape_routes_need_a_shape_model) { + Fixture f; + CHECK_EQ(f.post("/generate", "{}").status, 501); + CHECK_EQ(f.post("/send", "{}").status, 501); + CHECK_EQ(f.get("/status/x").status, 501); +} + +RAD_TEST_MAIN() diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index d45e7dd3..978602de 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -95,7 +95,7 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { { "fishomni", "bsgemm-moe" }, { "flux3", "" }, { "flux3distilled", "" }, { "gemma3", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" }, { "glm5next", "" }, - { "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" }, + { "hunyuan3d2", "" }, { "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" }, { "laya", "" }, { "lfm2", "" }, { "llama", "" }, { "mistral3", "" }, { "llama", "fp8_e4m3" }, { "nomicbert", "" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, diff --git a/tools/ops_doc_check.sh b/tools/ops_doc_check.sh index e627bc65..67daa7df 100755 --- a/tools/ops_doc_check.sh +++ b/tools/ops_doc_check.sh @@ -37,6 +37,8 @@ function t_opd(t, q,w,io) { if (sub(/:inout$/, "", t)) io = ":inout" sub(/:(in|out)$/, "", t); return t w io q } # ---- doc notation: `name` followed by its annotations ------------------------------------- +# POSIX awk only: mawk, Debian's and Ubuntu's default awk, has no gensub. +function trim(t) { sub(/^ +/, "", t); sub(/ +$/, "", t); return t } function d_name(t, a) { a = index(substr(t, 2), "`"); return substr(t, 2, a - 1) } function d_rest(t, a) { a = index(substr(t, 2), "`"); return substr(t, a + 2) } function d_param(t, n,r,f,o) { @@ -63,9 +65,9 @@ FILENAME != doc { # ---- the doc rows -------------------------------------------------------------------------- /^\| `/ { n = split($0, c, "|") - op = d_name(gensub(/^ +| +$/, "", "g", c[2])); documented[op] = 1 + op = d_name(trim(c[2])); documented[op] = 1 if (n > 5) { exempt++; printf "exempt %-24s line %d -- %s\n", op, FNR, - gensub(/^ +| +$/, "", "g", c[5]); next } + trim(c[5]); next } pc = c[3]; oc = c[4]; gsub(/[,;]/, " ", pc); gsub(/[,;]|→/, " ", oc) ps = ""; np = split(pc, pa, /[ \t]+/) for (i = 1; i <= np; i++) { v = d_param(pa[i]); if (v != "") ps = ps (ps == "" ? "" : " ") v } diff --git a/tools/pad_tp.py b/tools/pad_tp.py index c1cf6b60..859fa478 100755 --- a/tools/pad_tp.py +++ b/tools/pad_tp.py @@ -20,7 +20,7 @@ does, so rank w-1 carries them. bf16 is handled as raw u16 (no arithmetic happens here), so numpy alone suffices. """ -import argparse, json, os, re, shutil, struct, sys +import argparse, json, os, re, shutil, struct, subprocess, sys import numpy as np DT = {"BF16": (np.uint16, 2), "F16": (np.float16, 2), "F32": (np.float32, 4), "I64": (np.int64, 8), @@ -111,6 +111,10 @@ def main(): os.makedirs(a.dst, exist_ok=True) idx_path = os.path.join(a.src, "model.safetensors.index.json") files = sorted(set(json.load(open(idx_path))["weight_map"].values())) if os.path.exists(idx_path) else ["model.safetensors"] + # Shard names come from the checkpoint's own index: each must be a bare file name in it. + for fn in files: + if not isinstance(fn, str) or not fn or fn != os.path.basename(fn) or fn in (".", ".."): + sys.exit(f"{idx_path}: shard name {fn!r} is not a file name in the checkpoint directory") def parts(w_, sizes, news, axis=0): """pad each consecutive segment of `sizes` along `axis` to `news` (zeros after the real rows).""" @@ -170,7 +174,8 @@ def main(): if a.sparse: dstf = os.path.join(a.dst, fn) if not os.path.exists(dstf): - r = os.system(f"cp --reflink=always '{os.path.join(a.src, fn)}' '{dstf}' 2>/dev/null") or 0 + r = subprocess.run(["cp", "--reflink=always", os.path.join(a.src, fn), dstf], + stderr=subprocess.DEVNULL).returncode if r: os.link(os.path.join(a.src, fn), dstf) # not btrfs/xfs: hard link, still no copy else: st_write_stream(os.path.join(a.dst, fn), meta, items); print(f" wrote {fn} ({len(items)} tensors)", flush=True) diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index 6d107e06..76c57de1 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -1253,6 +1253,9 @@ int main(int argc, char** argv) { w.abort(); return 1; } + } else if (meta_textless(ck.meta().get("radiance.text"))) { + RAD_INFO("vocab none: the model reads no text"); + vocab_textless(vb); } else if (file_exists(ck.tok_dir() + "/tokenizer.json")) { const std::string tj = ck.tok_dir() + "/tokenizer.json"; RAD_INFO("vocab %s", tj.c_str()); diff --git a/tools/rad_kbench.cpp b/tools/rad_kbench.cpp index 3cd38338..c177fcdb 100644 --- a/tools/rad_kbench.cpp +++ b/tools/rad_kbench.cpp @@ -2345,9 +2345,12 @@ int main(int argc, char** argv) { else if (a == "--coverage") ro.coverage_dir = next("--coverage"); else if (a == "--coverage-write") ro.coverage_write = true; else if (a == "--analysis") analysis_path = next("--analysis"); - else if (a == "--max-cases") max_cases = std::atoi(next("--max-cases")); + else if (a == "--max-cases") + max_cases = (int)rad_flag_int("rad-kbench", "--max-cases", next("--max-cases"), 0, + INT32_MAX); else if (a == "--max-bytes") - max_case_bytes = (int64_t)std::atoll(next("--max-bytes")) << 20; + max_case_bytes = rad_flag_int("rad-kbench", "--max-bytes", next("--max-bytes"), 1, + INT32_MAX) << 20; else if (a == "--no-fusion") fuse_check = false; else if (a == "--bench") bench = true; else if (a == "--timing-only") timing_only = true; diff --git a/tools/rad_schemas.cpp b/tools/rad_schemas.cpp index c6d7a4ae..c6a6e88c 100644 --- a/tools/rad_schemas.cpp +++ b/tools/rad_schemas.cpp @@ -9,6 +9,7 @@ * rad-schemas libr4d.so libref.so diff them, in hierarchy order */ #include "rad_abi.h" +#include "rad_abi_layout.h" #include #include @@ -72,6 +73,14 @@ int load(const char* path, Loaded* out) { fprintf(stderr, "%s: ABI %u, this build is %u\n", path, abi(), RAD_ABI_VERSION); return -1; } + /* One version can name two layouts; the engine refuses a mismatched fingerprint, and so does + * this tool, which reads the same structs. */ + auto layout = (uint64_t (*)(void))dlsym(out->h, "rad_plugin_abi_layout"); + if (!layout || layout() != rad_abi_layout()) { + fprintf(stderr, "%s: built against another layout of ABI %u, or exports no " + "rad_plugin_abi_layout\n", path, RAD_ABI_VERSION); + return -1; + } out->name = inf && inf()->name ? inf()->name : path; for (int i = 0, n = cnt(); i < n; ++i) { const RadOpSchema* s = at(i);