This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/core/build/rad_build.h
T
Deadcode 769b4c64a6 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.
2026-11-02 18:35:02 +01:00

273 lines
14 KiB
C++

/* rad_build.h -- the declare phase (spec §3.1): receives everything the architecture plugin will
* ever do.
*
* Declare always completes. A missing kernel does not stop the walk: every op, band and domain
* that resolved to nothing is collected with the constraint that refused it and reported at the
* end, which shows whether a plugin or a model is missing.
*
* Nothing is decided twice. After declare the model is static (every op, its kernel, the
* weights it touches, the order). The bucket table, weight manifest, buffer plan and KV block
* sizes are built once here, so the step path indexes tables.
*
* The kernel hierarchy, op schemas, constraint matching and bucket boundaries belong to
* core/plugin/. The Builder calls Registry::validate and Registry::build_bands rather than
* reimplementing them, so selector and builder cannot drift apart.
*
* Lifetime: every KernelRow, Resolved and RadOpSchema in the Program points into a plugin's static
* tables, which the Registry dlclose()s. Neither the Builder nor the Program may outlive the
* Registry.
*/
#pragma once
#include "plugin/registry.h"
#include <cstdio>
#include <functional>
#include <set>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
/* The plugin's handle. rad_builder.h only forward-declares it; as a base of rad::Builder, the C
* shims reach the Builder with a static_cast. */
struct RadBuilder { };
namespace rad {
/* Process-lifetime storage for declared names. RadNameMap and RadKernelInfo hold raw
* `const char*` and the Program outlives the Builder, so the strings are interned: a few thousand,
* deduplicated, never freed. Owning them in RadNameMap would be an ABI change. */
const char* intern(std::string_view s);
/* Names for the enums the graph dump prints; `bld_` prefixed to keep them apart from the
* planner's tier_name and site_name in rad_core.h. */
const char* bld_domain_name(int domain);
const char* bld_access_name(int access);
const char* bld_buf_kind_name(int kind);
const char* bld_kv_kind_name(int kind);
/* ------------------------------------------------------------------ the buffer plan */
/* Packing results for the --debug-graph report. `sum_bytes` (no sharing) and `peak_live` (a
* perfect packer) bracket the arena and show what the greedy pass left unused. */
struct BufPlanReport {
int64_t transient_bytes = 0; /* the packed, shared region */
int64_t persist_bytes = 0; /* PERSIST + DERIVED: their own non-overlapping region */
int64_t host_bytes = 0; /* domain=HOST buffers; a separate address space (see below) */
int64_t peak_live = 0; /* max over op index of the bytes live at it */
int64_t sum_bytes = 0; /* every transient, unshared */
int n_unknown_live = 0; /* transients whose liveness nothing declared */
};
/* Liveness must already be in BufferInfo::first_def / last_use; a transient with first_def < 0 is
* treated as live for the whole program, which is sound.
*
* Assigns BufferInfo::arena_offset for every buffer and sets Program::arena_bytes. Returns RAD_OK,
* or RAD_E_INVAL if a buffer could not be sized (a plugin-private dtype the core cannot measure). */
int plan_buffers(Program& p, BufPlanReport* rep = nullptr);
/* The arena layout for steps of at most `rows` tokens: the real plan's buffers, the fixed region
* unchanged, and the transients repacked, so the arena past `end` is unused by such a step and
* can be lent. `offset` and `decl` are indexed by buffer handle. */
struct ArenaLevel {
int64_t rows = 0;
int64_t end = 0;
std::vector<int64_t> offset;
std::vector<RadBufDecl> decl;
};
/* Lay out `probe`'s buffers (a sizing declare at `rows`) over `full`'s. Refused, with the reason
* in `why`, unless both declares describe the same buffers with only fewer rows; otherwise they
* cannot share the real plan's fixed region and kernels. */
int plan_level(const Program& full, const Program& probe, int64_t rows, ArenaLevel* out,
std::string* why);
/* Bytes a declared buffer occupies. 0 means the core cannot size it: a plugin-private dtype, legal
* for a weight (the kernel's layout hook sizes it) but not for an activation. */
int64_t buffer_bytes(const RadBufDecl& d);
/* ------------------------------------------------------------------ the model behind a declare */
/* What the model holds for a logical weight: its encoding and logical extents. rad_weight_encoding
* answers with it and every declaration is checked against it (spec §2.4). The engine answers from
* the container or checkpoint it loads, rad-convert from its recipe. `prog` is the declare so far,
* whose name map is used to search a checkpoint. RAD_OK, or RAD_E_NOTFOUND for a weight the model
* does not have. */
struct WeightSource {
RadEncoding enc{};
uint32_t rank = 0;
int64_t shape[RAD_MAX_RANK] = {0};
};
using WeightSourceFn = std::function<int(const std::string& name, const Program& prog,
WeightSource* out)>;
/* ------------------------------------------------------------------ the builder */
class Builder : public RadBuilder {
public:
/* The Registry must outlive the Builder and its Program (see the file header). */
Builder(Registry& reg, const RadModelMeta& meta, const RadBuildCtx& ctx);
/* Where rad_weight_encoding's answers come from. Unset (tests, synthetic tools), every source
* is RAD_E_NOTFOUND and a weight is read as plain in its declared dtype. */
void set_sources(WeightSourceFn f) { sources_ = std::move(f); }
/* The C surface, one method per rad_builder.h entry point. */
rad_weight decl_weight (const char* name, const RadWeightDecl* d);
int weight_encoding(const char* source, RadEncoding* out, int64_t* shape,
uint32_t* rank);
rad_buf decl_buffer (const char* name, const RadBufDecl* d);
rad_kvgroup decl_kv_group(const char* name, const RadKVGroupDecl* d);
int64_t kv_block_size(rad_kvgroup g);
int64_t kv_layer_bytes(rad_kvgroup g);
int bind_layer_kv(int layer, rad_kvgroup g);
rad_op decl_op (const char* op, const RadParam* p, int n_p,
const rad_weight* w, int n_w);
int op_resolved (rad_op h) const;
int op_declared (const char* op) const;
int decl_name_map(const RadNameMap* m);
int declare_logits(rad_buf b);
int declare_scores(rad_buf hidden, rad_weight table);
int declare_pooled(rad_buf b);
int declare_plugin_words(int64_t max_words);
int declare_drafter(const RadDrafterDecl* d);
int drafter_shared_kv(int pos_offset);
int lora_root(const char* native, const char* spellings);
int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
int64_t from_hi, int64_t to_lo);
int drafter_short_block(int64_t block);
int drafter_tree(rad_buf parents);
int declare_encoder(const RadEncoderDecl* d);
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
* buffer planner activation liveness. A transient no op names is live for the whole
* program; the --debug-graph buffer report counts those. */
int op_reads (rad_op h, const rad_buf* b, int n);
int op_writes(rad_op h, const rad_buf* b, int n);
int buf_concurrent(rad_buf b);
int lane1_window(bool end);
int weight_shard_span(rad_weight w, int64_t lo, int64_t hi);
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
const int64_t* total, int n);
int kv_group_zero(rad_kvgroup g);
int kv_group_dense_read(rad_kvgroup g);
int kv_group_replicated(rad_kvgroup g);
/* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns
* RAD_OK, or the first structural error class. Resolution misses are not errors here: an
* unresolved op returns a null handle and the plugin should offer a fallback (spec §2.3); it
* becomes an error only if the run phase issues it. */
int finish();
/* A sizing declare (RadBuildCtx::shape_probe): each op takes the bands `ref` resolved at the
* same position, and finish() initialises nothing. The plugin sees the real declare's answers
* (which ops resolved, each group's block size), so it declares the same graph and nothing is
* selected or set up twice. An op that differs from `ref`'s at that position is an error: a
* different graph cannot be laid over the real buffers. */
void set_reference(const Program* ref) { ref_ = ref; }
/* Off: finish() selects every kernel and initialises none, for callers that launch nothing.
* rad-convert needs only the kernels' layouts; a kernel's init depends on the running process
* (a ring, a peer's buffers), and libavx's n-gram gather refuses a process that cannot create
* an io_uring ring, which must not stop a sandboxed conversion. */
void set_instances(bool on) { instances_ = on; }
/* Runtime LoRA (core/lora/): the HF module leaves an adapter may target. Set before the plugin
* declares, so a fused GEMM over a targeted weight (the gated gate_up fold), which leaves no
* output for the delta, is declined as it is declared and the plugin emits the unfused chain it
* has for a library without the fused kernel. Null: nothing is declined. */
void set_lora_targets(const std::set<std::string>* t) { lora_targets_ = t; }
/* The read and write sets an op declared (rad_op_reads / rad_op_writes): the LoRA declare reads
* the dtypes of a targeted GEMM's activation and output from them. */
const std::vector<rad_buf>& op_read_set (rad_op h) const { return op_bufs_[h].reads; }
const std::vector<rad_buf>& op_write_set(rad_op h) const { return op_bufs_[h].writes; }
Program& program() { return prog_; }
const Program& program() const { return prog_; }
/* Structural failures (a bad schema, two ranged parameters, a duplicate name), all of them,
* like the miss list. */
const std::vector<std::string>& errors() const { return errors_; }
int status() const { return status_; }
const BufPlanReport& buf_report() const { return bufrep_; }
private:
/* Record a structural error and its class. Returns 0 so a decl_ function can
* `return err(...)` and yield a null handle. */
uint32_t err(int code, const char* f, ...) __attribute__((format(printf, 3, 4)));
std::string scoped(const char* name) const;
void resolve_bands(OpInfo& oi);
void record_tune_request(const Resolved& r);
/* init() for every surviving instance, after the whole graph has resolved, so a failing init
* cannot abort declare before the miss report is assembled. */
void finish_instances();
void fill_tune_instances();
int32_t find_kv_consumer(rad_kvgroup g);
void finish_layouts();
void finish_kv_groups();
void finish_weight_uses();
void finish_buffer_liveness();
Registry& reg_;
Program prog_;
const Program* ref_ = nullptr;
bool instances_ = true;
std::vector<std::string> errors_;
int status_ = RAD_OK;
bool finished_ = false;
std::string scope_;
/* Parallel to prog_.ops: the buffers each op declared it reads and writes. */
struct OpBufUse { std::vector<rad_buf> reads, writes; };
std::vector<OpBufUse> op_bufs_;
const std::set<std::string>* lora_targets_ = nullptr;
/* Buffers touched from the second lane (rad_buf_concurrent). Their declared op range does not
* bound when their bytes are in use, so they are live for the whole program. */
std::set<rad_buf> concurrent_bufs_;
/* The second lane's window (rad_lane1_window_begin), first and last op handle; -1 when none. */
int32_t lane1_w0_ = -1, lane1_w1_ = -1;
/* Parallel to prog_.kv_groups: where in the op list the group was declared, and the op found
* to consume it. Declaration order is the only link between an op and a group; see
* find_kv_consumer(). */
std::vector<int32_t> kv_decl_at_;
std::vector<int32_t> kv_consumer_;
/* Declared name -> index of its first prog_.name_map entry, so a repeated declaration is
* checked in constant time; a routed model declares tens of thousands of weights. */
std::unordered_map<std::string, size_t> name_map_first_;
/* Declared weight name -> handle, for the same reason (Flash-Next declares about 100K weights
* per rank). */
std::unordered_map<std::string, rad_weight> weight_by_name_;
/* tune_key() -> index in prog_.tune_requests: one request per kernel instantiation. */
std::unordered_map<std::string, size_t> tune_index_;
/* The model's answers, cached per source: a routed model declares each expert's codes and
* scales as two weights over one source, and a checkpoint lookup walks the name map. */
WeightSourceFn sources_;
std::unordered_map<std::string, std::pair<int, WeightSource>> source_cache_;
int lookup_source(const std::string& name, WeightSource* out);
BufPlanReport bufrep_;
};
/* ------------------------------------------------------------------ --debug-graph (spec §16) */
/* The entire declared graph: every op in declared order with its bucket table (one line per band:
* the resolving kernel, variant and plugin, the matched constraints, the weights touched and the
* buffer written); then the weight manifest, buffer plan, KV groups, tuning requests and miss
* report. The bucket-table block is exactly the format in spec §2.2. */
std::string dump_graph_str(const Program& p, const std::vector<std::string>* errors = nullptr);
/* The same walk as JSON, for the server's Model view, grouped by (op, band table): an op declared
* once per layer with one bucket table is one row with a count. */
std::string dump_graph_json(const Program& p);
} /* namespace rad */