Archived
radiance 1.16.0
New models:
- Hunyuan3D-2 (hunyuan3d2): an untextured 3-D mesh from one picture of an object. DINOv2-giant
over the picture, a FLUX-shaped flow-matching DiT (16 double-stream and 32 single-stream blocks
of 1024) over 3072 latents with both guidance branches in one step, and the shape VAE's
geometry decoder. Converted from tencent/Hunyuan3D-2's hunyuan3d-dit-v2-0 folder with
data/recipes/hunyuan3d-2-bf16.recipe (fp16 cast to bf16, 4.4 GiB, one card). The licence
(Tencent Hunyuan 3D 2.0 Community License) does not cover the EU, the UK or South Korea
- Served on Hunyuan3D-2's own API server routes, so its Blender add-on and scripts work
unchanged: POST /generate answers with the mesh, POST /send runs it in the background and
GET /status/{uid} reports steps_done and then the file. GLB, OBJ, PLY or STL; the field is
sampled coarse to fine as FlashVDM's hierarchical decoding does, or densely with
"volume_decoding": "dense"; seed, steps, guidance and octree_resolution as the reference.
Texturing (Hunyuan3D-Paint) is refused for now (docs/GUIDE.md §5.17)
Merged:
- libr3d rewritten for RDNA3's wave matrix (@RikshaDriver): bf16, f16, int8-activation and vocab
GEMMs retiled to 16x128 blocks with a double-buffered k-walk; fp8, mxfp4a8, w2a8, w4a16, w5a16
and w8a8 quantised GEMMs and the gated form; grouped MoE GEMMs (bf16, fp8a8f32, mxfp4a8); the
norms and quantisers, the QSA state ops and the MoE router, scatter and gather. Brought onto the
op contract before release (13 schemas, the MoE GEMMs on weight tables with a_order and bf16
output, moe_gather's gate pitch, moe_scatter above 1024 slots, the mxfp4 m16 dispatch) and its
gated-delta-net kernels replaced by libhalo's; every op it serves now passes rad-kbench against
libref on a gfx1151, and r3d_selftest checks its MoE GEMMs by value
- Gemma 4 31B: asymmetric int5 linears (w5a8i8 above 64 rows, w5a16 up to 64, a scale per 128),
the norm, GELU and two-rank all-reduce junctions at quant_act_i8g's grid (rmsnorm_quant_i8g,
gelu_mul_quant_i8g, ar_rmsnorm_quant_i8g) so the prefill overlap runs on the i8a8, a4 and w5
trunks, and compose files for the 31B i8g, heretic-ara-i8g and w5 on two cards (@keptn42)
- The norms' lane sum reads eight at a time: TranslateGemma 27B decode is back from 225 to 239
tok/s a stream at four streams, bit for bit the same output (@mici81)
- The head-256 prefill softmax rescales each row by its own maximum, not by a vote of the wave, so
a row's rounding no longer depends on which rows share its launch (@gostar)
Anthropic Messages API:
- /v1/messages takes min_p, presence_penalty, frequency_penalty, repetition_penalty and
repeat_last_n as top-level fields with the chat path's names, ranges and meaning, so clients that
speak only the Anthropic format (Claude Code) can set a model card's sampling, such as Qwen's
presence_penalty 1.5. The penalties count the last repeat_last_n tokens of prompt and reply (64
by default, --repeat-last-n), as llama.cpp does
Plugin ABI 33:
- Shape generators: rad_declare_shape_generator, RadShapeGenBatch (RadBatch::sgen_b) and
RadArchProbe::gen_shape, with the SCOND, SSTEP, SLATENT and SQUERY passes. The layout
fingerprint table is regenerated; out-of-tree plugins rebuild against 33
- New op point_fourier ([x | sin(x 2^j) | cos(x 2^j)], times pi on request) in libref, libavx,
libr4d and libhalo
- A checkpoint for a model that reads no text gets a one-token vocabulary
More cards from the one image:
- stilldeadcode/radiance now carries libr3d (RDNA3: gfx11-generic, every gfx11 chip) and libhalo
(Strix Halo: gfx1151, preferred there over libr3d) beside libr4d (gfx1201). docker/build.sh and
the Dockerfile default to gfx1201;gfx11-generic;gfx1151
- libr3d loads only where the KFD topology lists a gfx11 card and libhalo only where it lists a
gfx1151; a process without /dev/kfd sees neither. On an RDNA4 card, or with no card at all,
the image therefore behaves exactly as before, and rad-convert lays weights out as before
- libhalo and libr3d now declare gemm_nt_q's w_rb, and libhalo gram_accum's upper, as libr4d
does. Before, any build carrying them refused both at load ("9 parameters vs 8"), so a build
for Strix Halo or RDNA3 had no device kernel library
- libhalo does not yet have every op libr4d added after it was ported (the IQR rows, Pixtral and
Ministral rope, the tree-attention and DFlash-tree rows, among others); halo_parity lists them
and is left out of the image's test stage until they are ported
Fixed -- container and checkpoint parsing:
- A .rad expert-1 entry inside or before expert 0 is refused; a vocab section whose count names
an array at offset 0 is refused rather than read from the file header; offset checks no longer
wrap; header tables must sit on their element alignment
- An imatrix array of arrays (unbounded recursion) and a safetensors header naming a tensor twice
are refused; a failed RadWriter undo says the container is damaged; a tune cache measured on
another machine is refused, as its format contract says
Fixed -- plugins:
- Two plugins declaring one op with different parameter roles are refused; before, the core
applied the first one's chunk/capacity roles to the other's rows
- Null tables behind nonzero counts, unknown roles, keyless parameters or constraints and more
operands than an issue carries are refused by name at load; on the host backend device rows are
dropped even when no fat binary was registered; rad-schemas checks the ABI layout fingerprint as
the engine does
Fixed -- device:
- Stream slots are recycled under a new generation: before, 1024 stream create/destroy cycles
(LoRA loads, lanes, uplinks) made every later rad_stream_create fail
- A stream whose drain fails keeps its queue and kernarg ring instead of freeing them under the
card; the kernarg ring no longer leaks when its access grant fails; a block over 1024 work-items
is refused
- rad_dev_free takes the allocation off the ledger the pin-cap check reads; the host backend
charges pages to the card the range was reserved for
Fixed -- engine and server:
- Two NDEBUG-only asserts (runtime-window totals, ring blocks per group) are refusals; a
plugin-declared lcm past int64 saturates so the quantum check refuses it; every share view rect
and part span is bounded by its entry
- Video: the timestep regions hold the refine rungs a schedule appends, a zero-frame encode is
refused, /v1/videos bounds each side before the area product, and a realtime session needs a
clip length to cut a turn at
Fixed -- kernels and quantisation:
- A trellis run shorter than a state's codes (tcq_rows=1, or N % tcq_rows == 1) read its seam
out of bounds; the encoder now refuses it as the decoder does, and tcq_rows below one state is
refused at parse
- qsa_tail_store bounds its slot index by the state plane (libr4d and libhalo); paged attention
refuses kv_heads <= 0; libavx row_amax skips a NaN as libref does
Fixed -- tools:
- pad_tp.py no longer runs cp through a shell with shard names from the checkpoint's index
(quote injection, path traversal): names must be bare file names
- ops_doc_check.sh runs under mawk (Ubuntu's awk); rad-kbench --max-cases/--max-bytes are checked
integers; oot_plugins fails unless the installed replay passed a case and failed none
Thanks to @RikshaDriver, @keptn42, @mici81 and @gostar.
This commit is contained in:
1 parent
cfa6a668f6
commit
769b4c64a6
122 files changed
+10092
-2203
No files matched your search
+4
-3
@@ -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()
|
||||
|
||||
+11
-8
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/hunyuan3d2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); 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)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
|
||||
+132
-12
@@ -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;
|
||||
|
||||
+53
-13
@@ -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<hsa_queue_t*> g_queue_by_id[kMaxQueues];
|
||||
std::atomic<uint32_t> g_next_queue_id{0};
|
||||
std::atomic<uint32_t> g_queue_id_at[kMaxQueues]; /* the id holding each slot now */
|
||||
std::mutex g_queue_slot_mu;
|
||||
std::vector<uint32_t> 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<char*>(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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<Tape*> 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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <cstdint>
|
||||
@@ -143,6 +144,26 @@ struct Ledger {
|
||||
std::atomic<int64_t> 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<void*, LiveAlloc> 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<std::mutex> lk(g_ledger_mu);
|
||||
g_ledger_live[p] = LiveAlloc{ bytes, kind };
|
||||
}
|
||||
void ledger_drop(void* p) {
|
||||
if (!p) return;
|
||||
std::lock_guard<std::mutex> 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;
|
||||
|
||||
+28
-3
@@ -20,6 +20,7 @@
|
||||
#include <condition_variable>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
@@ -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<const char*, VRange> g_vres;
|
||||
|
||||
int vmem_device_of(const void* addr) {
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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;
|
||||
}
|
||||
|
||||
|
||||
+46
-3
@@ -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<StallWatch> 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<StallWatch> 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<StallWatch> 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<StallWatch> 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<gen::ShapeDriver::RankIO> gio;
|
||||
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
|
||||
auto d = std::make_unique<gen::ShapeDriver>();
|
||||
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<gen::VideoDriver::RankIO> 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<gen::ShapeRequest> 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,
|
||||
|
||||
+7
-5
@@ -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::IPassDriver> 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. */
|
||||
|
||||
@@ -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). */
|
||||
|
||||
+8
-2
@@ -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 "";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <map>
|
||||
|
||||
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<std::pair<size_t, std::string>> 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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+55
-16
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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 <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
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<uint8_t> 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<uchar> 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<AreaTap> area_tab(int32_t ssize, int32_t dsize, double scale) {
|
||||
std::vector<AreaTap> 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<AreaTap> xt = area_tab(s.w, dw, sx), yt = area_tab(s.h, dh, sy);
|
||||
const int32_t ch = s.ch;
|
||||
std::vector<float> 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<int32_t> ofs;
|
||||
std::vector<int16_t> 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<int32_t> 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<int64_t>(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<int32_t> lo; std::vector<std::vector<float>> 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<float> 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<float>* 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<float> 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<float>& 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<float>& 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<float> shape_sigmas(int32_t steps) {
|
||||
std::vector<float> 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<int32_t> shape_levels(int32_t resolution) {
|
||||
std::vector<int32_t> 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<float> shape_axis(double bounds, int32_t r) {
|
||||
std::vector<float> 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<uint8_t>& m, int64_t n) {
|
||||
std::vector<uint8_t> t(m.size());
|
||||
auto pass = [&](const std::vector<uint8_t>& src, std::vector<uint8_t>& 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<uint32_t> shape_refine(const std::vector<float>& 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<uint8_t> 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<uint8_t> 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<uint32_t> 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<std::array<int, 2>> 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<bool> used(seg.size(), false);
|
||||
int nt = 0;
|
||||
for (size_t s0 = 0; s0 < seg.size(); ++s0) {
|
||||
if (used[s0]) continue;
|
||||
std::vector<int> 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<std::array<double, 3>> 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<float>& 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<int32_t> 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 <class T> 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<float> vertex_normals(const ShapeMesh& m) {
|
||||
std::vector<float> 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<float> 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<uint32_t>(out, 0x46546C67u); /* "glTF" */
|
||||
put_v<uint32_t>(out, 2);
|
||||
put_v<uint32_t>(out, (uint32_t)(12 + 8 + js.size() + 8 + bin.size()));
|
||||
put_v<uint32_t>(out, (uint32_t)js.size());
|
||||
put_v<uint32_t>(out, 0x4E4F534Au); /* "JSON" */
|
||||
out += js;
|
||||
put_v<uint32_t>(out, (uint32_t)bin.size());
|
||||
put_v<uint32_t>(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<uint8_t>(s, 3);
|
||||
for (int q = 0; q < 3; ++q) put_v<int32_t>(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<uint32_t>(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<uint16_t>(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<std::mutex> lk(mu_);
|
||||
steps_done_ = steps_done;
|
||||
points_done_ = points_done;
|
||||
}
|
||||
|
||||
void ShapeTicket::set_field(std::vector<float>&& field, int32_t r) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
field_ = std::move(field);
|
||||
r_ = r;
|
||||
}
|
||||
|
||||
void ShapeTicket::finish(int status, const std::string& why) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (done_) return;
|
||||
done_ = true;
|
||||
status_ = status;
|
||||
why_ = why;
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
|
||||
bool ShapeTicket::wait(int ms) {
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return done_; });
|
||||
return done_;
|
||||
}
|
||||
|
||||
bool ShapeTicket::finished() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return done_;
|
||||
}
|
||||
|
||||
int ShapeTicket::status() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return status_;
|
||||
}
|
||||
|
||||
std::string ShapeTicket::why() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return why_;
|
||||
}
|
||||
|
||||
std::vector<float> ShapeTicket::take_field(int32_t* r) {
|
||||
std::lock_guard<std::mutex> 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<std::mutex> lk(mu_);
|
||||
if (steps_done) *steps_done = steps_done_;
|
||||
if (points_done) *points_done = points_done_;
|
||||
}
|
||||
|
||||
} /* namespace gen */
|
||||
} /* namespace rad */
|
||||
@@ -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 <atomic>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<float>* 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<float> 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<int32_t> shape_levels(int32_t resolution);
|
||||
|
||||
/* One axis of a level's grid: numpy's linspace(-bounds, bounds, r + 1) in f32. */
|
||||
std::vector<float> 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<uint32_t> shape_refine(const std::vector<float>& 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<float> v;
|
||||
std::vector<uint32_t> 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<float>& 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<float>&& 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<float> take_field(int32_t* r);
|
||||
void progress_of(int32_t* steps_done, int32_t* points_done) const;
|
||||
|
||||
std::atomic<bool> 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<float> field_;
|
||||
int32_t r_ = 0;
|
||||
};
|
||||
|
||||
struct ShapeRequest {
|
||||
/* The picture, prepared (shape_picture). */
|
||||
std::vector<float> 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<ShapeTicket> ticket;
|
||||
};
|
||||
|
||||
} /* namespace gen */
|
||||
} /* namespace rad */
|
||||
@@ -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 <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
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<RankIO>& 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<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
|
||||
field_host_ = static_cast<float*>(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<ShapeRequest> 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<Job>();
|
||||
j->sigmas = shape_sigmas(steps);
|
||||
j->evals = steps - 1;
|
||||
j->cfg = (float)cfg;
|
||||
j->levels = r->dense ? std::vector<int32_t>{ 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<uint32_t>&& 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<int32_t>(R_LANES), lanes, sizeof lanes);
|
||||
std::memcpy(hptr<int32_t>(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<float>(ri, R_PATCH);
|
||||
S.step = j.step;
|
||||
S.n_steps = j.evals;
|
||||
S.sigma = dptr<float>(ri, R_SIGMA);
|
||||
S.sigma_next = dptr<float>(ri, R_SNEXT);
|
||||
S.cfg = dptr<float>(ri, R_CFG);
|
||||
S.pair = dptr<int32_t>(ri, R_PAIR);
|
||||
S.lanes = dptr<int32_t>(ri, R_LANES);
|
||||
S.flags = dptr<int32_t>(ri, R_FLAGS);
|
||||
S.seed = dptr<uint32_t>(ri, R_SEED);
|
||||
S.lat_cu = dptr<int32_t>(ri, R_LATCU);
|
||||
S.query = dptr<float>(ri, R_QUERY);
|
||||
S.query_cu = dptr<int32_t>(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<std::mutex> 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<float>(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<int64_t>(decl_.max_query, j.n_pts - j.next);
|
||||
const int64_t side = (int64_t)j.levels[j.level] + 1;
|
||||
float* q = hptr<float>(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<int32_t>(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<std::mutex> 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<float>().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<int64_t>(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<uint32_t> 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 */
|
||||
@@ -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 <deque>
|
||||
#include <mutex>
|
||||
|
||||
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<RankIO>& 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<ShapeRequest> 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<Readback>& 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<ShapeRequest> req;
|
||||
std::vector<float> 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<int32_t> levels;
|
||||
size_t level = 0;
|
||||
std::vector<float> field;
|
||||
std::vector<float> axis;
|
||||
std::vector<uint32_t> 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 <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
|
||||
template <class T> T* dptr(int rank, int r) const {
|
||||
return reinterpret_cast<T*>((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<uint32_t>&& 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<RankIO> ranks_;
|
||||
|
||||
char* host_ = nullptr; /* pinned, same layout as each slab */
|
||||
int64_t bytes_ = 0;
|
||||
std::vector<void*> dev_;
|
||||
Region reg_[R_N];
|
||||
float* field_host_ = nullptr;
|
||||
std::vector<Readback> rb_;
|
||||
|
||||
std::vector<RadBatch> out_; /* one per rank */
|
||||
std::vector<RadShapeGenBatch> sout_;
|
||||
Pass pass_;
|
||||
|
||||
mutable std::mutex mu_;
|
||||
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
|
||||
std::vector<int32_t> free_lanes_;
|
||||
uint64_t next_id_ = 1;
|
||||
bool closed_ = false;
|
||||
std::string closed_why_;
|
||||
int closed_status_ = RAD_E_STATE;
|
||||
};
|
||||
|
||||
} /* namespace gen */
|
||||
} /* namespace rad */
|
||||
@@ -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<int32_t>(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<float>(R_TV);
|
||||
float* ta = hptr<float>(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;
|
||||
}
|
||||
|
||||
+10
-6
@@ -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;
|
||||
|
||||
+55
-5
@@ -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<std::pair<const RadKernelInfo*, int>> keep;
|
||||
for (const auto& r : staged_rows)
|
||||
if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r);
|
||||
|
||||
+12
-1
@@ -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<int64_t> 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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
+16
-1
@@ -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<gen::ShapeRequest> r, std::string* why) = 0;
|
||||
virtual int64_t queued() const = 0;
|
||||
virtual int64_t running() const = 0;
|
||||
};
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
+11
-3
@@ -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");
|
||||
|
||||
|
||||
@@ -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<int64_t>(1, opt_.max_seqs);
|
||||
|
||||
@@ -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<HttpResponse> 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);
|
||||
|
||||
|
||||
@@ -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<Generation>& 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<ShapeJob> 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<std::shared_ptr<VideoJob>> videos_;
|
||||
std::vector<std::shared_ptr<VideoJob>> videos_gone_;
|
||||
/* The background shapes (/send), oldest first, and their threads (shapes.cpp). */
|
||||
std::mutex shapes_m_;
|
||||
std::vector<std::shared_ptr<ShapeJob>> shapes_;
|
||||
};
|
||||
|
||||
} /* namespace server */
|
||||
|
||||
@@ -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 <nlohmann/json.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <thread>
|
||||
|
||||
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<gen::ShapeRequest> 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<std::string>() == "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<bool>()) {
|
||||
*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<std::string>().empty())
|
||||
return bad("image", "'image' must be the picture as base64");
|
||||
std::string img = b["image"].get<std::string>();
|
||||
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:<type>;base64,...')");
|
||||
img = img.substr(comma + 1);
|
||||
}
|
||||
std::vector<uint8_t> 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<gen::ShapeRequest>();
|
||||
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<int64_t>() < lo || b[k].get<int64_t>() > 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<int64_t>();
|
||||
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<double>() >= 0.0) ||
|
||||
!std::isfinite(b["guidance_scale"].get<double>()))
|
||||
return bad("guidance_scale", "'guidance_scale' must be a finite number, not negative");
|
||||
r->guidance = b["guidance_scale"].get<double>();
|
||||
}
|
||||
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>()
|
||||
: (uint64_t)b["seed"].get<int64_t>();
|
||||
}
|
||||
if (b.contains("volume_decoding") && !b["volume_decoding"].is_null()) {
|
||||
const std::string v = b["volume_decoding"].is_string()
|
||||
? b["volume_decoding"].get<std::string>() : "";
|
||||
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<std::string>();
|
||||
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<gen::ShapeTicket>();
|
||||
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<float> field = t.take_field(&r);
|
||||
gen::ShapeMesh mesh;
|
||||
gen::shape_mesh(field, r, info.bounds, info.level, &mesh);
|
||||
std::vector<float>().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<gen::ShapeTicket> 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<gen::ShapeTicket> 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<ShapeJob> 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<std::mutex> 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<int64_t>(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<std::shared_ptr<ShapeJob>> all;
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<ShapeJob>();
|
||||
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<std::mutex> 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<std::mutex> 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 */
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<const RadFileHeader*>(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<const char*>(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<const rad_stroff*>(base + h->tok_text_off);
|
||||
out.tokens.resize(h->n_tokens);
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# hunyuan3d-2-bf16.recipe -- Hunyuan3D-2's shape model (hunyuan3d-dit-v2-0) served at bf16.
|
||||
#
|
||||
# rad-convert <Hunyuan3D-2>/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
|
||||
+3
-2
@@ -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=
|
||||
|
||||
@@ -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
|
||||
```
|
||||
+3
-2
@@ -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 <commit> # any other commit
|
||||
docker/build.sh --target build # stop at a stage, tagged radiance-<stage>
|
||||
```
|
||||
|
||||
+53
-4
@@ -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]
|
||||
|
||||
+18
@@ -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
|
||||
|
||||
@@ -105,6 +105,10 @@ std::vector<Case> 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));
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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) \
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
+3
-1
@@ -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`.
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+32
-6
@@ -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) {
|
||||
|
||||
@@ -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<float> 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<RadTensor> ts = { T(dx, RAD_F32, { M, n }), T(dy, RAD_F32, { M, W }) };
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PI("freqs", F),
|
||||
PS("dtype", "f32") };
|
||||
run_case(r, ts, ps);
|
||||
std::vector<float> 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<float> x = randv((size_t)(M * n), 2.0f);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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`.
|
||||
|
||||
+32
-17
@@ -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
|
||||
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_launch.h"
|
||||
#include "r3d_args.h"
|
||||
#include "r3d_codecs.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
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 <int SDT> 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 <int SDT, bool H0, bool HT>
|
||||
__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<SDT>::T* __restrict__ h0, unsigned short* __restrict__ o,
|
||||
typename cs_state<SDT>::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<SDT>::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<SDT>::T* p = ht + st_base;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < kNST; ++t) {
|
||||
typename cs_state<SDT>::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<SDT>::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<SDTC, H0C, HTC>)), 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<SDTC>::T*)h0, (unsigned short*)o, (cs_state<SDTC>::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;
|
||||
}
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_launch.h"
|
||||
#include "r3d_args.h"
|
||||
#include "r3d_codecs.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
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 <int KSTEP>
|
||||
__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 <int HG_RATIO>
|
||||
__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<R>)), 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);
|
||||
}
|
||||
@@ -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 <int NORM, int ABF16> 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 <hip/hip_runtime.h>
|
||||
|
||||
#include "r3d.h"
|
||||
#include "r3d_common.h"
|
||||
#include "r3d_launch.h"
|
||||
#include "r3d_args.h"
|
||||
#include "r3d_codecs.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
|
||||
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 <int NT>
|
||||
__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 <int NT>
|
||||
__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 <int ABF16>
|
||||
__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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+17
-13
@@ -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);
|
||||
|
||||
@@ -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<ACC>:
|
||||
__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<<<grid, blk, 0, (hipStream_t)s>>>( \
|
||||
(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);
|
||||
|
||||
@@ -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<MFS_ACC>(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)
|
||||
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
|
||||
@@ -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<<<grid, blk, 0, (hipStream_t)s>>>(
|
||||
(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();
|
||||
}
|
||||
|
||||
|
||||
+57
-57
@@ -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 <int ALU>
|
||||
__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><<<grid, blk, 0, (hipStream_t)s>>>(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><<<grid, blk, 0, (hipStream_t)s>>>(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><<<grid, blk, 0, (hipStream_t)s>>>(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><<<grid, blk, 0, (hipStream_t)s>>>(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); }
|
||||
|
||||
|
||||
+137
-61
@@ -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 <hip/hip_runtime.h>
|
||||
|
||||
@@ -142,29 +146,100 @@ __global__ __launch_bounds__(kScatWaves * kSortWave) void scatter_small_kernel(
|
||||
scatter_small_place<kScatWaves, INV>(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 <bool INV>
|
||||
__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<false>, 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<true>, 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<false>, 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<true>, 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<false>, 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<true>, 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"
|
||||
@@ -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 <cstring>
|
||||
|
||||
/* 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;
|
||||
}
|
||||
+10
-10
@@ -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);
|
||||
|
||||
+120
-73
@@ -48,8 +48,13 @@
|
||||
#define R3D_BUILD_TARGET "gfx1100 gfx1101 gfx1102 gfx1103 gfx1150 gfx1151"
|
||||
#endif
|
||||
|
||||
#include <dirent.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#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;
|
||||
}
|
||||
+349
-50
@@ -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<float> hA((size_t)M * (K / 128)), hW0((size_t)NE0 * (N / GR) * (K / 128)),
|
||||
hW1((size_t)NE1 * (N / GR) * (K / 128));
|
||||
std::vector<float> 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<uint8_t> 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<float> hA((size_t)M * (K / 128));
|
||||
std::vector<uint8_t> hW0((size_t)NE0 * (N / GR) * (K / 32)),
|
||||
hW1((size_t)NE1 * (N / GR) * (K / 32));
|
||||
std::vector<uint8_t> 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<uint16_t> 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<void*> 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<std::vector<uint8_t>>& ent, uint32_t dt, long long rows,
|
||||
long long cols) {
|
||||
std::vector<void*> 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<int32_t> 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<int32_t> 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<double>& ref, const std::vector<uint16_t>& 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<uint16_t> ha(AR * K);
|
||||
for (auto& x : ha) x = f32_to_bf16(rndf());
|
||||
std::vector<std::vector<uint8_t>> we(NE, std::vector<uint8_t>(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<uint16_t> y(T * N);
|
||||
hipDeviceSynchronize();
|
||||
hipMemcpy(y.data(), t[4].data, y.size() * 2, hipMemcpyDeviceToHost);
|
||||
std::vector<double> 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<uint8_t> ha(AR * K);
|
||||
std::vector<float> 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<std::vector<uint8_t>> wc(NE, std::vector<uint8_t>(wbytes)),
|
||||
ws(NE, std::vector<uint8_t>(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<double> 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<std::vector<uint8_t>> 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<uint16_t> 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;
|
||||
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
|
||||
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"
|
||||
@@ -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 <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
/* ================================================================== 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 */
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
|
||||
// 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 <int N>
|
||||
__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 <int N>
|
||||
__device__ __forceinline__ float r3dh_xor_lane(float v) {
|
||||
return __uint_as_float(r3dh_xor_lane_u32<N>(__float_as_uint(v)));
|
||||
}
|
||||
|
||||
// A 64-bit value's partner: the halves exchanged separately, as a 64-bit `__shfl_xor` does.
|
||||
template <int N>
|
||||
__device__ __forceinline__ unsigned long long r3dh_xor_lane_u64(unsigned long long v) {
|
||||
const uint32_t lo = r3dh_xor_lane_u32<N>((uint32_t)v);
|
||||
const uint32_t hi = r3dh_xor_lane_u32<N>((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 <int CTRL>
|
||||
__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 <int W>
|
||||
__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 <int W>
|
||||
__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;
|
||||
}
|
||||
@@ -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 <cstdint>
|
||||
|
||||
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
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
|
||||
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 <bool HI>
|
||||
__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
|
||||
@@ -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 */
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#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 <int SDT> 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 <int SDT, bool H0 = true, bool HT = true>
|
||||
__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<SDT>::T* __restrict__ h0, unsigned short* __restrict__ o,
|
||||
typename cs_state<SDT>::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<float (*)[FP]>(&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<SDT>::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<int, NTV>{});
|
||||
else if (np) mainloop(std::integral_constant<int, 1>{});
|
||||
else mainloop(std::integral_constant<int, 0>{});
|
||||
}
|
||||
{
|
||||
// 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<SDT>::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<SDTC, H0C, HTC>), 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<SDTC>::T*)h0, (unsigned short*)o, (cs_state<SDTC>::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));
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#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 <int HG_RATIO>
|
||||
__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<R>), 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));
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 <int KSTEP>
|
||||
__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);
|
||||
}
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
#include "r3dh_fp8_wmma.h" // r3dh_fp8::cvt_pk_fp8_f32 (no fp8-conversion-insts on gfx1151)
|
||||
|
||||
template <bool I8>
|
||||
__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 <bool I8>
|
||||
__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;
|
||||
}
|
||||
}
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
#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 <typename FRAG>
|
||||
__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 <typename FRAG>
|
||||
__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
|
||||
@@ -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))
|
||||
|
||||
@@ -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);
|
||||
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user