radiance 1.10.0

LoRA for image and video generators:
- civitai and Hugging Face adapter files as published: kohya, ComfyUI and diffusers/PEFT key names;
  LoRA, LoCon, LoHa, LoKr and full-weight diffs; DoRA, OFT and Tucker are refused by name
- stacked per request with a strength each, through the `loras` field or <lora:name:strength> tags
  in the prompt; --lora-dir serves every file in a directory, GET /v1/loras lists them, and
  --max-loras / --max-lora-rank size the slots on the card (generators default to rank 64)
- Krea 2, Qwen-Image 2.1, FLUX.3 [klein], MiniMax H3, LTX-2.5, Anima and SDXL

New models:
- Anima (base, aesthetic and turbo): Cosmos-Predict2 DiT with the Qwen3-0.6B text encoder and the
  Qwen-Image VAE, on one card
- Stable Diffusion XL and its single-file finetunes (Illustrious, NoobAI including V-Pred, Pony),
  read as civitai ships them, with the Euler, Euler a and DPM++ 2M samplers

Recipes:
- q38-27b-mxfp4-df2: any bf16 Qwen3.8-27B or finetune at MXFP4 with the DFlash2 drafter
- Krea 2 finetunes from civitai: scripts/krea2_native.py reads Krea's own key names, and
  krea-2-fp8-unscaled keeps a plain-fp8 file's codes exactly

Changes: --max-num-batched-tokens defaults to 2048 (was 8192). Plugin ABI 25: out-of-tree plugins
must be rebuilt.
This commit is contained in:
Deadcode committed 2026-10-20 21:05:16 +02:00
1 parent 685ec5bd85
commit 4246a1dd04
124 files changed
+14326 -387

No files matched your search

+1 -1
View File
@@ -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.9.0 LANGUAGES C CXX)
project(radiance VERSION 1.10.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
+7
View File
@@ -45,7 +45,9 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, eight cards | `glm53-flash-mxfp4.rad` (171 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` |
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` |
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` |
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | `sdxl.yaml` |
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
| Anima Aesthetic FP8: anime and illustration, text to image, one card (Base and Turbo convert the same way) | `anima-aesthetic-fp8.rad` (3.0 GiB) | [convert](#convert-a-checkpoint) | `anima.yaml` |
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | — |
A container holds everything the server needs: the weights, the tokeniser, the chat template and
@@ -256,6 +258,11 @@ build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-
--draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2
build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \
--recipe data/recipes/q38-27b-w4a16.recipe
# Any single-file SDXL checkpoint (SDXL 1.0, Illustrious, NoobAI, Pony, a civitai finetune), with
# CLIP's tokenizer.json from openai/clip-vit-large-patch14
build/bin/rad-convert /srv/models/hf/OnomaAIResearch/Illustrious-XL-v2.0/Illustrious-XL-v2.0.safetensors \
-o illustrious-xl-v2.0-bf16.rad --recipe data/recipes/sdxl-bf16.recipe \
--tokenizer /srv/models/hf/openai/clip-vit-large-patch14/tokenizer.json
```
With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`.
+1 -1
View File
@@ -17,7 +17,7 @@ extern "C" {
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
* load with both versions printed. 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 24u
#define RAD_ABI_VERSION 25u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
+106 -5
View File
@@ -429,7 +429,7 @@ int rad_op_declared(RadBuilder* b, const char* op);
* convert-time fusions (q/k/v into one qkv, gate and up into gate_up). It is the only component
* that knows both sides, and rad-convert reads the map from it (spec §2.4). */
enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1, RAD_MAP_WNORM = 2, RAD_MAP_ROWS = 3,
RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5, RAD_MAP_TAP = 6 };
RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5, RAD_MAP_TAP = 6, RAD_MAP_COLS = 7 };
typedef struct RadNameMap {
const char* declared; /* the name given to rad_decl_weight */
@@ -445,7 +445,8 @@ typedef struct RadNameMap {
int src_index[8];
/* RAD_MAP_ROWS only: piece i is rows [src_index[i], src_index[i] + src_rows[i]) of the 2-D (or
* higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. */
* higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. RAD_MAP_COLS: columns
* [src_index[0], src_index[0] + src_rows[0]) of src[0]'s last dimension. */
int64_t src_rows[8];
} RadNameMap;
@@ -463,7 +464,13 @@ typedef struct RadNameMap {
*
* RAD_MAP_ROWS keeps only row ranges of its sources (see src_rows), joined: a head read over a
* fraction of a vocabulary (an audio model's codes, a few rows of a text model's 200K) stores that
* fraction rather than the whole table.
* fraction rather than the whole table. Successive ROWS maps for one name extend it in call order,
* as CONCAT maps do, so a weight may take more than eight pieces (an output projection whose rows
* are permuted, one piece a row).
*
* RAD_MAP_COLS keeps one column range of src[0] (see src_rows): a linear whose input carries
* channels the runtime never feeds (Cosmos's padding-mask channel, always zero) is read over the
* columns it is fed.
*
* RAD_MAP_TRANSPOSE swaps the last two dimensions of src[0] in each leading slice, [.., a, b] to
* [.., b, a]: a linear a checkpoint keeps as (in, out), where the GEMMs read (out, in).
@@ -478,7 +485,7 @@ typedef struct RadNameMap {
* run on a single frame reads only its last temporal tap, so [cout, cin, kt, kh, kw] read at tap -1
* of dimension 2 is the 2-D convolution it then is.
*
* TRANSPOSE, EMA and TAP are computed at convert in f32, like WNORM, and stored as the recipe
* TRANSPOSE, EMA, TAP and COLS are computed at convert in f32, like WNORM, and stored as the recipe
* says. */
int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
@@ -714,7 +721,8 @@ typedef struct RadGeneratorDecl {
/* The sampler: flow matching, Euler steps from sigma 1 towards 0.
* A fixed schedule: `n_sigmas` values, the terminal 0 implied; a request may not change the
* step count. Otherwise `default_steps` sigmas from 1 to 1/steps, shifted:
* step count. Otherwise `default_steps` sigmas from 1 to 1/steps (or off `sigma_grid`'s
* table), shifted:
* dyn_shift 0 sigma' = shift * s / (1 + (shift - 1) * s)
* dyn_shift 1 mu linear in the image's token count, 256 -> base_shift .. max_seq ->
* max_shift; shift_exp 1: exp(mu) / (exp(mu) + (1/s - 1)), 0: mu / (mu + ...)
@@ -755,10 +763,103 @@ typedef struct RadGeneratorDecl {
/* 1: a reference picture is shrunk to `ref_area` only when larger and cut to `size_multiple`
* by a centred crop; 0: resized to `ref_area` at its own aspect. */
int32_t ref_shrink_only;
/* ---- appended in ABI 25 (Anima, SDXL) */
/* `aux_tokens` nonzero: the conditioning also reads the user's prompt through the container's
* second tokenizer (rad-convert --tokenizer2), as that tokenizer encodes it alone, special
* tokens included, and the COND pass carries the ids (RadGenBatch::aux_ids). A prompt whose
* second tokenisation is longer than `aux_max_tokens` is refused. */
int64_t aux_max_tokens;
/* The unshifted sigmas of a schedule that is not fixed: 0 is diffusers' linspace(1, 1 / steps,
* steps); N > 0 picks them off a table of N timesteps as ComfyUI's `simple` scheduler does,
* step i at (N - floor(i N / steps)) / N, each an f32 quotient of the table's own. */
int32_t sigma_grid;
/* A prompt shorter than this many tokens after `drop_prefix` is padded with `pad_token` up to
* it, the padding read as prompt (a reference tokenizer's minimum length: an empty prompt is
* one padding token, and stays empty rather than becoming " "). 0: no minimum. */
int32_t min_tokens;
int32_t aux_tokens;
/* ---- a discrete-time denoiser (train_steps 0: the flow-matching sampler above)
* A model trained on `train_steps` timesteps of a variance-preserving schedule, betas from
* `beta_start` to `beta_end` (RAD_GEN_BETAS_*), sampled as k-diffusion samples it (Stable
* Diffusion's family). Its schedule is in sigmas, sigma_t = sqrt((1 - abar_t) / abar_t) for
* the cumulative product abar of 1 - beta; `zero_snr` rescales it to a zero terminal SNR
* (the last abar 4.8973451890853435e-08, as ComfyUI does). A request names a sampler
* (RAD_GEN_SAMPLER_*, one of those `samplers` holds as 1 << id, which the plugin's step
* serves) and a scheduler (RAD_GEN_SCHED_*), which places the request's steps between the
* table's largest and smallest sigma, 0 last. A DENOISE pass carries each entry's sigma,
* next and previous sigma in these units, the timestep the denoiser is conditioned on, the
* sampler and the step (RadGenBatch). n_sigmas, shift and the dynamic shift are unused. */
double beta_start, beta_end;
int32_t train_steps;
int32_t beta_schedule;
int32_t zero_snr;
uint32_t samplers;
int32_t default_sampler;
int32_t default_scheduler;
/* ---- the prompt in windows (a CLIP text encoder's fixed context)
* Nonzero: the prompt's tokens after `drop_prefix` are cut into runs of at most
* `chunk_tokens`, each laid out as `chunk_bos`, the run, `chunk_eos`, then `pad_token` up to
* chunk_tokens + 2 rows, the windows end to end; a prompt with no tokens is one window of
* the two markers and padding. The JOINT_STEP layout only, with `pad_multiple` 0, and
* `cond_rows` a whole number of windows. */
int32_t chunk_tokens;
int32_t chunk_bos, chunk_eos;
} RadGeneratorDecl;
/* RadGeneratorDecl::beta_schedule: betas linear in sqrt(beta) (Stable Diffusion's
* "scaled_linear"), or linear in beta. */
enum { RAD_GEN_BETAS_SCALED_LINEAR = 0, RAD_GEN_BETAS_LINEAR = 1 };
/* A discrete-time model's samplers, as k-diffusion (and ComfyUI) name and define them. */
enum {
RAD_GEN_SAMPLER_EULER = 0, /* "euler" */
RAD_GEN_SAMPLER_EULER_ANCESTRAL = 1, /* "euler_ancestral", eta 1 */
RAD_GEN_SAMPLER_DPMPP_2M = 2, /* "dpmpp_2m" */
RAD_GEN_SAMPLER_COUNT = 3
};
/* ... and its schedulers, ComfyUI's: "normal" (timesteps evenly spaced, the last at the smallest
* sigma), "karras" (rho 7), "exponential", "sgm_uniform" (normal without its last point) and
* "simple" (the table read at even strides). */
enum {
RAD_GEN_SCHED_NORMAL = 0,
RAD_GEN_SCHED_KARRAS = 1,
RAD_GEN_SCHED_EXPONENTIAL = 2,
RAD_GEN_SCHED_SGM_UNIFORM = 3,
RAD_GEN_SCHED_SIMPLE = 4,
RAD_GEN_SCHED_COUNT = 5
};
int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d);
/* ================================================================== adapter key names */
/* How LoRA files written for this model name its linears, for an image or video generator served
* with runtime adapters (--lora, --lora-dir, --max-loras; core/lora/). Adapter files from training
* tools and UIs name a module by the model's original code, not by the checkpoint the container
* was converted from, and wrap it in a prefix of their own: `diffusion_model.blocks.3.attn.wq`,
* kohya's `lora_unet_blocks_3_attn_wq`, a bare `blocks.3.attn.wq`. Both calls are optional,
* made before the GEMMs they cover are declared, and only a program that declares a root carries
* adapters at all. Additive exports; RAD_ABI_VERSION does not move.
*
* rad_lora_root declares one network the adapters may reach (the denoiser, a text encoder): every
* LoRA-capable GEMM over a checkpoint tensor whose name starts with `native` gets an adapter path.
* `spellings` lists, space separated, the prefixes adapter keys of this network start with in
* place of `native`; one ending in '_' is kohya's form, in which the rest of the key is the module
* path with every '.' written '_'. `native` itself is always accepted, and "-" stands for a key
* with no prefix at all. A key is tried against the longest matching spelling first.
*
* rad_lora_alias maps an adapter module that the checkpoint names differently. `from` and `to`
* are module paths relative to the root's prefixes (no ".weight"), '#' standing for a decimal
* index that `to` repeats in the same order. Rows [from_lo, from_hi) of the adapter module's
* output (its lora_B rows; from_hi 0 = all of them) land at rows from `to_lo` of the checkpoint
* module `to`. Several aliases with one `from` split a fused adapter module over separate
* checkpoint tensors (a `qkv` over `to_q`, `to_k`, `to_v`); several `from` into one `to` at
* different `to_lo` place separate adapter modules into one fused tensor. A module path that is
* the checkpoint's own needs no alias. */
int rad_lora_root(RadBuilder* b, const char* native, const char* spellings);
int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to,
int64_t from_lo, int64_t from_hi, int64_t to_lo);
/* ================================================================== the audio generator */
/* A program that makes audio from text: an autoregressive language model writes the piece frame by
* frame, with classifier-free guidance (each request runs a conditional and an unconditional
+15
View File
@@ -56,9 +56,16 @@ typedef struct RadFileHeader {
uint64_t prof_off, prof_count; /* RadFileProfile[] -- expert popularity */
uint64_t data_off, data_bytes; /* the blob; RAD_ALIGN_POOL-aligned */
/* reserved[RAD_HDR_AUX_VOCAB_OFF] and reserved[RAD_HDR_AUX_VOCAB_BYTES] place a second vocab
* section, laid out as the first (RadVocabHeader + its payload, its strings in the one string
* blob): a tokenizer a generator reads its prompt through beside the model's own
* (RadGeneratorDecl::aux_tokens). Both zero when there is none, as in a file written before
* the section existed; the rest are zero. */
uint64_t reserved[8];
} RadFileHeader;
enum { RAD_HDR_AUX_VOCAB_OFF = 0, RAD_HDR_AUX_VOCAB_BYTES = 1 };
/* ------------------------------------------------------------------ metadata */
typedef struct RadFileKV {
rad_stroff key;
@@ -124,9 +131,17 @@ enum { RAD_TOK_BPE = 1, RAD_TOK_UNIGRAM = 2, RAD_TOK_WORDPIECE = 3, RAD_TOK_RWKV
enum {
RAD_NORM_NFC = 1, RAD_NORM_NFKC = 2, RAD_NORM_NFD = 3, RAD_NORM_NFKD = 4,
RAD_NORM_LOWERCASE = 5, RAD_NORM_STRIP = 6, RAD_NORM_REPLACE = 7, RAD_NORM_PREPEND = 8,
RAD_NORM_PRECOMPILED = 9,
RAD_PRE_BYTELEVEL = 32, RAD_PRE_SPLIT = 33, RAD_PRE_METASPACE = 34,
RAD_PRE_WHITESPACE = 35, RAD_PRE_PUNCTUATION = 36, RAD_PRE_DIGITS = 37,
RAD_PRE_BYTE_FALLBACK = 38,
/* BPE's end-of-word suffix (arg0, CLIP's "</w>"): a word's last symbol carries it, so the
* merges and the vocabulary tell a word's end from its middle. */
RAD_PRE_END_OF_WORD = 39,
/* An added token matched in the normalised text rather than the raw one (tokenizers'
* `normalized`): arg0 its spelling, iarg its id. Cut out after the normalisers and before
* the other pre-tokenisers. */
RAD_PRE_ADDED_NORMALIZED = 40,
RAD_DEC_BYTELEVEL = 64, RAD_DEC_METASPACE = 65, RAD_DEC_REPLACE = 66,
RAD_DEC_STRIP = 67, RAD_DEC_FUSE = 68, RAD_DEC_BYTE_FALLBACK = 69
};
+26
View File
@@ -352,6 +352,32 @@ typedef struct RadGenBatch {
const int32_t* mode_ccu;
const int64_t* n_mode_h;
const float* mode_rope_f;
/* ---- appended in ABI 25 (Anima, SDXL) */
/* COND, for a generator that reads its prompt through a second tokenizer
* (RadGeneratorDecl::aux_tokens): the user's prompt as that tokenizer encodes it, `n_aux` ids
* on the device, and `aux_cu` {0, n_aux} on the device. 0 and null otherwise. */
int64_t n_aux;
const int32_t* aux_ids;
const int32_t* aux_cu;
/* ---- a discrete-time denoiser (RadGeneratorDecl::train_steps), DENOISE, one value per
* entry: the schedule's sigma before `sigma` (0 on an image's first step), `sigma` on the
* model's trained clock (the nearest of its timesteps, as ComfyUI conditions it), the
* request's sampler (RAD_GEN_SAMPLER_*) and the image's step, from 0. */
const float* sigma_prev;
const float* timestep;
const int32_t* sampler;
const int32_t* step;
/* DENOISE: [n_seq, 2] each entry's image height and width in pixels, f32 (a model
* conditioned on its size); `entry_h` [n_seq, 4] the same entries on the host: the
* conditioning's rows (JOINT_STEP), the height and width in pixels, and the branch (0 the
* prompt, 1 the negative prompt), for a plugin whose ops take an image's geometry from their
* operands and so issue each entry on its own. */
const float* size_px;
const int32_t* entry_h;
/* COND: the pass's token ids on the host ([n_tok]), for a plugin whose issue depends on
* where a window's end-of-text marker sits. */
const int32_t* tokens_h;
} RadGenBatch;
/* An entry's flags on a DENOISE pass. */
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/anima -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(anima LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(anima architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/anima.cpp)
+1367
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -432,6 +432,28 @@ inline int map_rows(RadBuilder* b, const char* declared, std::initializer_list<R
return rad_decl_name_map(b, &m);
}
/* How adapter files name a generator's modules (rad_lora_root, rad_lora_alias): one network
* under the checkpoint prefix `native`, the prefixes adapter keys use for it, and the module paths
* that differ, '#' standing for a block index. */
struct LoraName {
std::string from, to;
int64_t from_lo = 0, from_hi = 0, to_lo = 0;
};
inline int lora_names(RadBuilder* b, const char* native, const char* spellings,
const std::vector<LoraName>& names) {
const int s = rad_lora_root(b, native, spellings);
if (s < 0) return s;
for (const LoraName& n : names) {
const int a = rad_lora_alias(b, native, n.from.c_str(), n.to.c_str(), n.from_lo, n.from_hi,
n.to_lo);
if (a < 0) return a;
}
return RAD_OK;
}
/* The prefixes ComfyUI, kohya and bare-key adapter files put before a diffusion model's modules. */
inline const char* kLoraDiffusionSpellings = "diffusion_model. model.diffusion_model. lora_unet_ "
"base_model.model. -";
/* A weight-normalised checkpoint tensor folded into its plain weight (RAD_MAP_WNORM). */
inline int map_wnorm(RadBuilder* b, const char* declared, const char* g, const char* v) {
RadNameMap m = map_base(declared, RAD_MAP_WNORM);
+26
View File
@@ -937,6 +937,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_mask = decl_b(b, nm.f("lat_mask"), RAD_F32, { lane_rows, 1 }, RAD_BUF_PERSIST);
m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16,
{ 2 * (int64_t)kMaxLanes * cond_rows(), gd.n_embd }, RAD_BUF_PERSIST);
/* ---- adapter key names. LoRA files name the blocks by Black Forest Labs' modules, as
* ComfyUI loads them (comfy/ldm/flux3): `single_blocks.N.q_proj` or a fused `qkv`,
* `attn_out`, `mlp_in`, `mlp_out`, and the mode blocks under `content_mode_blocks`. */
{
const int64_t Q = gd.n_head_all * gd.head_dim;
std::vector<LoraName> n;
static const char* const kBlocks[][2] = {
{ "single_blocks.#.", "single_transformer_blocks.#." },
{ "txt_mode_blocks.#.", "txt_mode_blocks.#." },
{ "content_mode_blocks.image.#.", "mode_blocks.image.#." },
{ "content_mode_blocks.image_cond.#.", "mode_blocks.image_cond.#." },
};
for (const auto& bl : kBlocks) {
const std::string f = bl[0], t = bl[1];
n.push_back({ f + "q_proj", t + "attn.to_q" });
n.push_back({ f + "k_proj", t + "attn.to_k" });
n.push_back({ f + "v_proj", t + "attn.to_v" });
n.push_back({ f + "qkv", t + "attn.to_q", 0, Q, 0 });
n.push_back({ f + "qkv", t + "attn.to_k", Q, 2 * Q, 0 });
n.push_back({ f + "qkv", t + "attn.to_v", 2 * Q, 3 * Q, 0 });
n.push_back({ f + "attn_out", t + "attn.to_out.0" });
n.push_back({ f + "mlp_in", t + "ff.linear_in" });
n.push_back({ f + "mlp_out", t + "ff.linear_out" });
}
RAD_ARCH_TRY(lora_names(b, "transformer.", kLoraDiffusionSpellings, n));
}
RAD_ARCH_TRY(declare_te(b, meta, m));
RAD_ARCH_TRY(declare_encoder(b, meta, m));
RAD_ARCH_TRY(declare_dit(b, meta, m));
+31
View File
@@ -297,6 +297,36 @@ static int check_format(const RadModelMeta* meta) {
return RAD_OK;
}
/* ================================================================== adapter key names */
/* LoRA files for Krea 2 name the DiT and the text fusion by the reference code's modules
* (krea-ai/krea-2 mmdit.py): `blocks.N.attn.wq`, `txtfusion.refiner_blocks.N.mlp.up`, `tproj.1`;
* the container keeps diffusers' names. The language model takes no adapters. */
static int declare_lora_names(RadBuilder* b) {
std::vector<LoraName> n;
static const char* const kInner[][2] = {
{ "attn.wq", "attn.to_q" }, { "attn.wk", "attn.to_k" }, { "attn.wv", "attn.to_v" },
{ "attn.wo", "attn.to_out.0" }, { "attn.gate", "attn.to_gate" },
{ "mlp.gate", "ff.gate" }, { "mlp.up", "ff.up" }, { "mlp.down", "ff.down" },
};
static const char* const kBlocks[][2] = {
{ "blocks.#.", "transformer_blocks.#." },
{ "txtfusion.layerwise_blocks.#.", "text_fusion.layerwise_blocks.#." },
{ "txtfusion.refiner_blocks.#.", "text_fusion.refiner_blocks.#." },
};
for (const auto& bl : kBlocks)
for (const auto& in : kInner)
n.push_back({ std::string(bl[0]) + in[0], std::string(bl[1]) + in[1] });
n.push_back({ "txtfusion.projector", "text_fusion.projector" });
n.push_back({ "txtmlp.1", "txt_in.linear_1" });
n.push_back({ "txtmlp.3", "txt_in.linear_2" });
n.push_back({ "first", "img_in" });
n.push_back({ "last_linear", "final_layer.linear" });
n.push_back({ "tmlp.0", "time_embed.linear_1" });
n.push_back({ "tmlp.2", "time_embed.linear_2" });
n.push_back({ "tproj.1", "time_mod_proj" });
return lora_names(b, "transformer.", kLoraDiffusionSpellings, n);
}
/* ================================================================== declare */
static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
Geom& g = m.gt;
@@ -1059,6 +1089,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST);
m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16,
{ 2 * (int64_t)kMaxLanes * kCondRows, gd.n_embd }, RAD_BUF_PERSIST);
RAD_ARCH_TRY(declare_lora_names(b));
RAD_ARCH_TRY(declare_te(b, meta, m));
RAD_ARCH_TRY(declare_fusion(b, meta, m));
RAD_ARCH_TRY(declare_dit(b, meta, m));
+3
View File
@@ -3240,6 +3240,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- in issue order: the conditioning pass, the step, the frames, the soundtrack, the
* upscale */
/* LoRA files for LTX-2.5 name the DiT's modules as the checkpoint does (`transformer_blocks.N.
* attn1.to_q`, `ff.net.0.proj`), behind ComfyUI's or kohya's prefix. */
RAD_ARCH_TRY(lora_names(b, "transformer.", kLoraDiffusionSpellings, {}));
RAD_ARCH_TRY(declare_te(b, meta, m));
{
const int64_t wz = std::max<int64_t>(rad_meta_geti(meta, "connectors.video_hidden_dim", 0),
+36
View File
@@ -705,6 +705,41 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
return m.op_embed ? RAD_OK : RAD_E_INVAL;
}
/* ================================================================== adapter key names */
/* LoRA files for H3 name the DiT by ComfyUI's modules (comfy/ldm/minimax): one fused
* `attn.qkv_proj` (q, k, v), `attn.out_proj`, and `mlp.fc1` with the SwiGLU's gate half first,
* where the checkpoint keeps the value half first in `ff.net.0.proj`. */
static int declare_lora_names(RadBuilder* b, const Model& m) {
std::vector<LoraName> n;
const int64_t Q = m.gd.n_head_all * m.gd.head_dim, KV = m.gd.n_head_kv_all * m.gd.head_dim;
const int64_t F = m.gd.n_ff_all;
static const char* const kBlocks[][2] = {
{ "blocks.#.", "transformer_blocks.#." },
{ "token_refiner.blocks.#.", "token_refiner.refiner_blocks.#." },
};
for (const auto& bl : kBlocks) {
const std::string f = bl[0], t = bl[1];
n.push_back({ f + "attn.qkv_proj", t + "attn.to_q", 0, Q, 0 });
n.push_back({ f + "attn.qkv_proj", t + "attn.to_k", Q, Q + KV, 0 });
n.push_back({ f + "attn.qkv_proj", t + "attn.to_v", Q + KV, Q + 2 * KV, 0 });
n.push_back({ f + "attn.out_proj", t + "attn.to_out.0" });
n.push_back({ f + "attn.to_gate_compress", t + "attn.to_gate_compress" });
n.push_back({ f + "mlp.fc1", t + "ff.net.0.proj", 0, F, F });
n.push_back({ f + "mlp.fc1", t + "ff.net.0.proj", F, 2 * F, 0 });
n.push_back({ f + "mlp.fc2", t + "ff.net.2" });
}
n.push_back({ "blocks.#.adaln_proj.linear", "transformer_blocks.#.adaln_proj.linear" });
n.push_back({ "video_patch_proj", "proj_in" });
n.push_back({ "audio_patch_proj", "audio_proj_in" });
n.push_back({ "condition_proj", "context_embedder" });
n.push_back({ "time_embedder.proj_in", "time_embedder.linear_1" });
n.push_back({ "time_embedder.proj_out", "time_embedder.linear_2" });
n.push_back({ "final_layer.video_out", "proj_out" });
n.push_back({ "final_layer.audio_out", "audio_proj_out" });
n.push_back({ "final_layer.adaln_proj.linear", "norm_out.linear" });
return lora_names(b, "transformer.", kLoraDiffusionSpellings, n);
}
/* ================================================================== the token refiner */
/* `context_embedder` (5120 -> 5376, bf16, replicated), two plain blocks with full attention over
* the prompt and no rotary, and the final RMSNorm into the lane's prompt rows. The feed-forward is
@@ -1924,6 +1959,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- in issue order: the conditioning pass, the step, the soundtrack, the frames */
m.b_text = decl_b(b, nm.f("lane.text"), RAD_BF16, { (int64_t)kMaxLanes * kMaxText, m.D },
RAD_BUF_PERSIST);
RAD_ARCH_TRY(declare_lora_names(b, m));
RAD_ARCH_TRY(declare_te(b, meta, m));
RAD_ARCH_TRY(declare_refiner(b, meta, m));
RAD_ARCH_TRY(declare_tables(b, meta, m));
+11
View File
@@ -911,6 +911,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* (Vae says why the order matters.) */
m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, m.gt.n_embd, kGrpVision, true));
/* ---- adapter key names. The DiT's LoRA files use the checkpoint's own names, or
* ComfyUI's, which join the SwiGLU's gate and up projections as `img_mlp.gate_up` [gate; up]
* (comfy/ldm/qwen_image21). */
{
const int64_t F = gd.n_ff_all;
RAD_ARCH_TRY(lora_names(b, "transformer.", kLoraDiffusionSpellings,
{ { "transformer_blocks.#.img_mlp.gate_up",
"transformer_blocks.#.img_mlp.gate_layer", 0, F, 0 },
{ "transformer_blocks.#.img_mlp.gate_up",
"transformer_blocks.#.img_mlp.proj", F, 2 * F, 0 } }));
}
RAD_ARCH_TRY(declare_te(b, meta, m));
RAD_ARCH_TRY(declare_encoder(b, meta, m));
RAD_ARCH_TRY(declare_dit(b, meta, m));
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/sdxl -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(sdxl LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(sdxl architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/sdxl.cpp)
+1236
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -125,6 +125,9 @@ public:
int declare_pooled(rad_buf b);
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 declare_encoder(const RadEncoderDecl* d);
int declare_generator(const RadGeneratorDecl* d);
int declare_audio_generator(const RadAudioGenDecl* d);
+135 -10
View File
@@ -942,7 +942,7 @@ int Builder::decl_name_map(const RadNameMap* m) {
}
if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM &&
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA &&
m->mode != RAD_MAP_TAP) {
m->mode != RAD_MAP_TAP && m->mode != RAD_MAP_COLS) {
err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode);
return RAD_E_INVAL;
}
@@ -953,9 +953,11 @@ int Builder::decl_name_map(const RadNameMap* m) {
: "the magnitude and the direction", m->n_src);
return RAD_E_INVAL;
}
if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP) && m->n_src != 1) {
if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP || m->mode == RAD_MAP_COLS) &&
m->n_src != 1) {
err(RAD_E_INVAL, "name map for '%s': a %s map names one source, not %d", m->declared,
m->mode == RAD_MAP_TAP ? "tap" : "transpose", m->n_src);
m->mode == RAD_MAP_TAP ? "tap" : m->mode == RAD_MAP_COLS ? "column" : "transpose",
m->n_src);
return RAD_E_INVAL;
}
@@ -984,14 +986,20 @@ int Builder::decl_name_map(const RadNameMap* m) {
m->declared, i, m->src_index[i], (long long)m->src_rows[i]);
return RAD_E_INVAL;
}
if (m->mode == RAD_MAP_COLS && (m->src_index[0] < 0 || m->src_rows[0] <= 0)) {
err(RAD_E_INVAL, "name map for '%s': the column range starts at %d and holds %lld columns",
m->declared, m->src_index[0], (long long)m->src_rows[0]);
return RAD_E_INVAL;
}
/* A CONCAT map may be declared in pieces; any other repeat is an error.
/* A CONCAT, ROWS or EMA map may be declared in pieces; any other repeat is an error.
*
* `src[8]` is the ABI's cap, and a sharded checkpoint exceeds it: Qwen3.8-Flash-Next stores
* its n-gram embedding as 128 tensors `...ngram_embedding.shard_K.weight`. Growing the array
* would cost ~80 MB of Program (one map per declared weight, ~50K weights). So successive
* CONCAT maps for one name extend it in call order, and rad-convert joins their sources end
* to end (map_concat_shards() in arch/common/rad_arch.h).
* to end (map_concat_shards() in arch/common/rad_arch.h). ROWS maps extend the same way (a
* row permutation is one piece a row).
*
* Other repeats are refused: a lookup built with std::map::emplace would silently keep the
* first, so a copy-paste mistake would convert weights from the wrong tensors. */
@@ -999,11 +1007,12 @@ int Builder::decl_name_map(const RadNameMap* m) {
if (seen != name_map_first_.end()) {
const RadNameMap& first = prog_.name_map[seen->second];
const bool joins = (c.mode == RAD_MAP_CONCAT && first.mode == RAD_MAP_CONCAT) ||
(c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA);
(c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA) ||
(c.mode == RAD_MAP_ROWS && first.mode == RAD_MAP_ROWS);
if (!joins) {
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT or EMA map may "
"be extended -- a repeated COPY map means two sources for one weight, "
"and which one wins is not something a declaration can express",
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT, ROWS or EMA "
"map may be extended -- a repeated COPY map means two sources for one "
"weight, and which one wins is not something a declaration can express",
c.declared);
return RAD_E_INVAL;
}
@@ -1232,7 +1241,32 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
(long long)d->default_height, (long long)d->max_lanes);
return RAD_E_INVAL;
}
if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
if (d->train_steps < 0) {
err(RAD_E_INVAL, "declare_generator '%s': train_steps %d is negative", nm,
(int)d->train_steps);
return RAD_E_INVAL;
}
if (d->train_steps > 0) {
/* A discrete-time denoiser: its own schedule, a sampler it serves by default. */
const uint32_t all = (1u << RAD_GEN_SAMPLER_COUNT) - 1;
if (d->train_steps < 2 || !(d->beta_start > 0) || !(d->beta_end > d->beta_start) ||
!(d->beta_end < 1) ||
(d->beta_schedule != RAD_GEN_BETAS_SCALED_LINEAR &&
d->beta_schedule != RAD_GEN_BETAS_LINEAR) ||
d->n_sigmas != 0 || d->default_steps <= 0 || (d->samplers & ~all) || !d->samplers ||
d->default_sampler < 0 || d->default_sampler >= RAD_GEN_SAMPLER_COUNT ||
!(d->samplers & (1u << d->default_sampler)) || d->default_scheduler < 0 ||
d->default_scheduler >= RAD_GEN_SCHED_COUNT ||
!(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0))) {
err(RAD_E_INVAL, "declare_generator '%s': the discrete-time sampler is incomplete (%d "
"timesteps, betas %g..%g kind %d, %lld default steps, samplers 0x%x "
"default %d, scheduler %d, %d fixed sigmas, guidance %g)", nm,
(int)d->train_steps, d->beta_start, d->beta_end, (int)d->beta_schedule,
(long long)d->default_steps, (unsigned)d->samplers, (int)d->default_sampler,
(int)d->default_scheduler, (int)d->n_sigmas, d->default_cfg);
return RAD_E_INVAL;
}
} else if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
(d->n_sigmas == 0 && d->default_steps <= 0) ||
!(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0)) ||
(d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) ||
@@ -1244,6 +1278,23 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
d->shift_terminal, d->default_cfg);
return RAD_E_INVAL;
}
if (d->sigma_grid < 0 || d->min_tokens < 0 || (d->aux_tokens && d->aux_max_tokens <= 0)) {
err(RAD_E_INVAL, "declare_generator '%s': sigma_grid %d, min_tokens %d and a second "
"tokenizer of at most %lld tokens are not a schedule and a prompt it can "
"read", nm, (int)d->sigma_grid, (int)d->min_tokens,
(long long)d->aux_max_tokens);
return RAD_E_INVAL;
}
if (d->chunk_tokens < 0 ||
(d->chunk_tokens > 0 &&
(!joint || d->pad_multiple != 0 || d->pad_token < 0 || d->chunk_bos < 0 ||
d->chunk_eos < 0 || d->cond_rows % (d->chunk_tokens + 2) != 0))) {
err(RAD_E_INVAL, "declare_generator '%s': a prompt in windows of %d tokens needs the joint "
"layout without pad_multiple, bos, eos and pad tokens, and cond_rows a "
"whole number of windows (cond_rows %lld)", nm, (int)d->chunk_tokens,
(long long)d->cond_rows);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_sigmas; ++i)
if (!(d->sigmas[i] > 0.0 && d->sigmas[i] <= 1.0) ||
(i > 0 && !(d->sigmas[i] < d->sigmas[i - 1]))) {
@@ -1764,6 +1815,69 @@ int Builder::drafter_shared_kv(int pos_offset) {
return RAD_OK;
}
int Builder::lora_root(const char* native, const char* spellings) {
if (finished_) {
err(RAD_E_STATE, "lora_root after declare finished");
return RAD_E_STATE;
}
if (!native || !*native) {
err(RAD_E_INVAL, "lora_root: an empty checkpoint prefix would put every tensor in one "
"network; name the prefix the network's tensors share");
return RAD_E_INVAL;
}
for (const LoraRoot& r : prog_.lora_roots)
if (r.native == native) {
err(RAD_E_INVAL, "lora_root '%s' declared twice", native);
return RAD_E_INVAL;
}
LoraRoot r;
r.native = native;
std::string cur;
for (const char* p = spellings ? spellings : "";; ++p) {
if (*p && *p != ' ') { cur += *p; continue; }
if (!cur.empty()) r.spellings.push_back(cur == "-" ? std::string() : cur);
cur.clear();
if (!*p) break;
}
prog_.lora_roots.push_back(std::move(r));
return RAD_OK;
}
int Builder::lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
int64_t from_hi, int64_t to_lo) {
if (finished_) {
err(RAD_E_STATE, "lora_alias after declare finished");
return RAD_E_STATE;
}
bool root = false;
for (const LoraRoot& r : prog_.lora_roots) root = root || (native && r.native == native);
if (!root) {
err(RAD_E_INVAL, "lora_alias '%s': its root '%s' is not declared (rad_lora_root first)",
from ? from : "", native ? native : "");
return RAD_E_INVAL;
}
if (!from || !*from || !to || !*to) {
err(RAD_E_INVAL, "lora_alias under '%s': an empty module path", native);
return RAD_E_INVAL;
}
auto hashes = [](const char* s) { int n = 0; for (; *s; ++s) n += *s == '#'; return n; };
if (hashes(from) != hashes(to)) {
err(RAD_E_INVAL, "lora_alias '%s' -> '%s': %d index placeholders against %d", from, to,
hashes(from), hashes(to));
return RAD_E_INVAL;
}
if (from_lo < 0 || to_lo < 0 || (from_hi != 0 && from_hi <= from_lo)) {
err(RAD_E_INVAL, "lora_alias '%s' -> '%s': rows [%lld, %lld) to %lld", from, to,
(long long)from_lo, (long long)from_hi, (long long)to_lo);
return RAD_E_INVAL;
}
LoraAlias a;
a.root = native; a.from = from; a.to = to;
a.from_lo = from_lo; a.from_hi = from_hi; a.to_lo = to_lo;
prog_.lora_aliases.push_back(std::move(a));
return RAD_OK;
}
void Builder::note_v(const char* f, va_list ap) {
char msg[1024];
vsnprintf(msg, sizeof msg, f ? f : "", ap);
@@ -2228,6 +2342,17 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) {
return B(b)->drafter_shared_kv(pos_offset);
}
int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) {
if (!b) return RAD_E_INVAL;
return B(b)->lora_root(native, spellings);
}
int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to,
int64_t from_lo, int64_t from_hi, int64_t to_lo) {
if (!b) return RAD_E_INVAL;
return B(b)->lora_alias(native, from, to, from_lo, from_hi, to_lo);
}
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_encoder(d);
+25 -16
View File
@@ -23,6 +23,7 @@
#include <fstream>
#include <set>
#include <sstream>
#include <sys/stat.h>
namespace rad {
@@ -103,13 +104,20 @@ static const Flag g_flags[] = {
" or host memory (default 3600). 0 keeps it until the memory\n"
" is wanted" },
{ "--lora", "ADAPTER", "NAME=PATH: serve a PEFT LoRA adapter beside the base model,\n"
" as model NAME (repeatable). The base stays as it is; each\n"
" request picks its adapter by `model`"},
{ "--lora", "ADAPTER", "NAME=PATH: serve a LoRA adapter beside the base model\n"
" (repeatable). A text model takes a PEFT directory and\n"
" serves it as model NAME; an image or video generator takes\n"
" a .safetensors file (kohya, ComfyUI, PEFT, LyCORIS) that\n"
" a request names in `loras`. The base stays as it is"},
{ "--lora-dir", "DIR", "image and video generators: a request may name any\n"
" NAME.safetensors under DIR in `loras`, opened when first\n"
" asked for"},
{ "--max-loras", "N", "adapter slots resident at once (default: the number of\n"
" --lora). Each slot holds one adapter's A/B on the card"},
{ "--max-lora-rank", "R", "the rank each slot is sized for (default 16); a smaller\n"
" adapter is zero-padded, a larger one refused"},
" --lora, 2 with --lora-dir alone). A text model's slot holds\n"
" one adapter, a generator's one request's combination"},
{ "--max-lora-rank", "R", "the rank each slot is sized for (default 16 for a text\n"
" model, 64 for a generator); a text model's larger adapter is\n"
" refused, a generator's larger combination truncated"},
{ "--lora-target-modules", "LIST", "comma-separated HF module leaf names adapters may\n"
" target (q_proj,k_proj,...). Default: what the --lora\n"
" adapters target. Needed with --max-loras and no --lora"},
@@ -520,6 +528,7 @@ int config_parse(int argc, char** argv, Config* c) {
}
c->lora.adapters.emplace_back(std::string(v, eq), std::string(eq + 1));
}
else if (S("--lora-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->lora.dir = v; }
else if (S("--max-loras")) { if (!num(0, 64, &c->lora.max_loras)) return RAD_E_INVAL; }
else if (S("--max-lora-rank")) { if (!num(1, 512, &c->lora.max_rank)) return RAD_E_INVAL; }
else if (S("--lora-target-modules")) {
@@ -881,21 +890,18 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("--lora names the adapter '%s' twice", name.c_str());
return RAD_E_INVAL;
}
if (L.max_loras > 0 && L.max_loras < (int)L.adapters.size()) {
RAD_ERR("--max-loras %d holds fewer adapters than the %zu that --lora names",
L.max_loras, L.adapters.size());
return RAD_E_INVAL;
}
const bool rank_given = c->given.count("--max-lora-rank") != 0;
if (!L.enabled() && (rank_given || !L.targets.empty())) {
RAD_ERR("%s sizes runtime LoRA slots, and there are none: give --lora or --max-loras",
rank_given ? "--max-lora-rank" : "--lora-target-modules");
return RAD_E_INVAL;
}
if (L.adapters.empty() && L.max_loras > 0 && L.targets.empty()) {
RAD_ERR("--max-loras with no --lora names no module an adapter may target; give "
"--lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)");
return RAD_E_INVAL;
if (!L.dir.empty()) {
struct stat sb{};
if (stat(L.dir.c_str(), &sb) != 0 || !S_ISDIR(sb.st_mode)) {
RAD_ERR("--lora-dir '%s' is not a directory", L.dir.c_str());
return RAD_E_INVAL;
}
}
if (!c->kld_lora.empty() && !c->kld()) {
RAD_ERR("--kld-lora scores through an adapter in KL mode; give --kld-record or "
@@ -1019,9 +1025,12 @@ const ShowRow kShow[] = {
std::string o;
for (const auto& [n, p] : c.lora.adapters) o += (o.empty() ? "" : ", ") + n + "=" + p;
return o.empty() ? std::string("none") : o; } },
{ "--lora-dir", [](const Config& c) {
return c.lora.dir.empty() ? std::string("none") : c.lora.dir; } },
{ "--max-loras", [](const Config& c) {
return c.lora.enabled() ? num(c.lora.slots()) : std::string("0 (off)"); } },
{ "--max-lora-rank", [](const Config& c) { return num(c.lora.max_rank); } },
{ "--max-lora-rank", [](const Config& c) {
return c.lora.max_rank > 0 ? num(c.lora.max_rank) : std::string("auto (16 text, 64 generator)"); } },
{ "--lora-target-modules", [](const Config& c) {
std::string o;
for (const std::string& t : c.lora.targets) o += (o.empty() ? "" : ",") + t;
+48 -1
View File
@@ -2113,7 +2113,23 @@ int Engine::run_server() {
o.graph_json = [this] { return dump_graph_json(ranks_[0]->program); };
/* Per request, from a reading at most a second old (Engine::diagnostics_json). */
o.diagnostics_json = [this] { return diagnostics_json(); };
if (cfg_.lora.enabled()) {
if (cfg_.lora.enabled() && ranks_[0]->program.is_pass_driven()) {
/* A generator's request names its adapters in `loras`; `model` stays the model. */
o.gen_lora_acquire = [this](const std::vector<std::pair<std::string, double>>& u,
int32_t* slot, std::shared_ptr<void>* hold, std::string* note,
std::string* e) {
std::vector<LoraUse> uses;
for (const auto& [n, w] : u) uses.push_back({ n, w });
return gen_lora_acquire(uses, slot, hold, note, e);
};
o.gen_lora_names = [this] { return gen_lora_names(); };
o.lora_load = [this](const std::string& n, const std::string& d, std::string* e) {
return lora_load(n, d, e);
};
o.lora_unload = [this](const std::string& n, std::string* e, int* in_flight) {
return lora_unload(n, e, in_flight);
};
} else if (cfg_.lora.enabled()) {
/* `model` picks the adapter, and the served model's own name picks the base. */
for (const auto& [name, dir] : cfg_.lora.adapters)
if (name == o.model_id) {
@@ -2347,7 +2363,14 @@ int Engine::run_server() {
gen::Driver* drv = nullptr;
const mm::Processor* proc = nullptr;
server::ImageGenInfo inf;
Tokenizer aux;
bool has_aux = false;
const server::ImageGenInfo& info() const override { return inf; }
int encode_aux(const std::string& text, std::vector<int32_t>* out) const override {
if (!has_aux) return RAD_E_UNSUPPORTED;
out->clear();
return aux.encode(text, *out, /*add_special=*/true, /*parse_special=*/true);
}
int submit(std::unique_ptr<gen::Request> r, std::string* why) override {
return drv->submit(std::move(r), why);
}
@@ -2393,6 +2416,27 @@ int Engine::run_server() {
in.cfg_original = gd.cfg_original != 0;
in.has_default_negative = pg.gen_str.has_default_negative;
in.default_negative = pg.gen_str.default_negative;
in.min_tokens = gd.min_tokens;
in.pad_token = gd.pad_token;
in.aux_tokens = gd.aux_tokens != 0;
in.aux_max_tokens = gd.aux_max_tokens;
if (in.aux_tokens) {
if (!aux_vocab_) {
RAD_ERR("images: '%s' reads its prompt through a second tokenizer and %s carries "
"none; convert it with rad-convert --tokenizer2", in.name.c_str(),
cfg_.model.c_str());
return RAD_E_FORMAT;
}
RAD_TRY(image_bridge.aux.init(aux_vocab_));
image_bridge.has_aux = true;
}
in.samplers = gd.train_steps > 0 ? gd.samplers : 0;
in.default_sampler = gd.default_sampler;
in.default_scheduler = gd.default_scheduler;
in.chunk_tokens = gd.chunk_tokens;
in.chunk_bos = gd.chunk_bos;
in.chunk_eos = gd.chunk_eos;
in.chunk_pad = gd.pad_token;
image_bridge.drv = img_gen_;
image_bridge.proc = mm_proc.get();
d.images = &image_bridge;
@@ -2407,6 +2451,9 @@ int Engine::run_server() {
(long long)in.default_height, (long long)in.max_tokens, (long long)in.max_refs,
in.fixed_schedule ? (std::to_string(in.fixed_steps) + " fixed steps").c_str()
: (std::to_string(in.default_steps) + " steps by default").c_str());
if (in.samplers)
RAD_INFO("images: sampler %s, scheduler %s by default", gen::sampler_name(in.default_sampler),
gen::scheduler_name(in.default_scheduler));
}
/* An audio generator's endpoint: the driver's queue, the declared prompt and limits, and the
+28
View File
@@ -31,6 +31,7 @@
#include "text/tokenizer.h"
#include "format/radfile.h"
#include "format/table_copy.h"
#include "lora/adapter.h"
#include "lora/slots.h"
#include <atomic>
@@ -155,6 +156,30 @@ public:
int lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid,
std::shared_ptr<void>* hold);
std::vector<std::string> lora_names() const;
/* A generator's adapters: a request names one or more adapter files at their strengths, and
* gets the slot holding exactly that combination, composed into a free (or the least recently
* used idle) slot when none holds it yet. `note` says what the composition left out or
* approximated, for the reply. RAD_E_NOTFOUND names an adapter neither --lora nor --lora-dir
* provides; RAD_E_FULL means every slot is held by running requests. */
struct LoraUse { std::string name; double weight = 1.0; };
int gen_lora_acquire(const std::vector<LoraUse>& uses, int32_t* slot,
std::shared_ptr<void>* hold, std::string* note, std::string* err);
/* The adapter files a generator request may name: --lora's and those under --lora-dir. */
std::vector<std::string> gen_lora_names() const;
bool gen_lora_enabled() const { return lora_gen_; }
private:
/* A generator's adapter files by name (--lora, POST /v1/load_lora_adapter, --lora-dir), opened
* once and kept mapped; compositions read them when a combination is put in a slot. */
int gen_lora_open(const std::string& name, std::shared_ptr<const lora::AdapterFile>* out,
std::string* err);
int gen_lora_start();
/* Every rank's packed bytes into `slot` of its pools, each rank on a stream of its own. */
int lora_copy(int slot, const std::vector<std::vector<lora::PackedSite>>& packed,
std::string* err);
bool lora_gen_ = false;
std::unique_ptr<lora::KeyMap> lora_keys_;
mutable std::mutex lora_lib_mu_;
std::map<std::string, std::pair<std::string, std::shared_ptr<const lora::AdapterFile>>> lora_lib_;
private:
std::atomic<uint64_t> lora_epoch_{0}; /* step-loop iterations, for slot reuse */
lora::SlotTable lora_table_; /* reads lora_epoch_, so declared after it */
@@ -216,6 +241,9 @@ private:
* which references `vocab_` and must not outlive it. */
std::shared_ptr<const Vocab> vocab_;
std::unique_ptr<VocabView> vocab_view_;
/* The container's second vocabulary (rad-convert --tokenizer2), which an image generator that
* declares `aux_tokens` reads its prompt through; null without one. */
std::shared_ptr<const Vocab> aux_vocab_;
/* The chunk geometry, resolved once and shared: the prefix cache needs the checkpoint interval
* at configure time and the scheduler the whole geometry at init. Resolving it separately
+8
View File
@@ -3663,6 +3663,14 @@ int Engine::load_vocab() {
auto v = std::make_shared<Vocab>();
RAD_TRY(v->load(std::move(vb)));
vocab_ = v;
if (file_ && file_->aux_vocab()) {
VocabBuild ab;
RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), file_->aux_vocab().h, ab));
auto av = std::make_shared<Vocab>();
RAD_TRY(av->load(std::move(ab)));
aux_vocab_ = av;
RAD_INFO("vocab: a second vocabulary of %d tokens", aux_vocab_->n_tokens());
}
auto view = std::make_unique<TokenView>();
RAD_TRY(view->init(vocab_));
+3
View File
@@ -43,6 +43,8 @@ int Engine::gen_loop() {
return fail_loop(st);
};
while (!stopping_.load(std::memory_order_acquire)) {
/* A round of the loop, idle or not: what lets a freed adapter slot cool (lora/slots.h). */
lora_epoch_.fetch_add(1, std::memory_order_acq_rel);
const RadBatch* b = gen_->next(step);
if (!b) {
step_batch_.store(nullptr, std::memory_order_release);
@@ -52,6 +54,7 @@ int Engine::gen_loop() {
}
idle = 0;
if (const int ps = prepare_release(b); ps < 0) return stop(ps);
for (auto& rk : ranks_) rk->ctx.set_gen_lora_slot(gen_->lora_slot());
issue_what_.store(kIssueModel, std::memory_order_release);
step_batch_.store(b, std::memory_order_release);
barrier_->arrive_and_wait(); /* release the ranks */
+321 -13
View File
@@ -4,16 +4,25 @@
* A load packs the adapter for each rank (lora::load_adapter, host only), refuses a module no rank
* placed, copies each rank's bytes into the slot on a stream of its own, waits, and only then
* publishes the name. A request can name the adapter only after the publish, so no step reads a
* slot while it is written. */
* slot while it is written.
*
* A generator keeps its adapter files in a library instead (--lora, --lora-dir, the load
* endpoint), and a slot holds one combination of them at given strengths, named by the
* combination: the first request that asks for it composes it (lora/adapter.h) into a free slot,
* or the least recently used one no request holds, and later ones find it there. */
#include "engine_priv.h"
#include "lora/lora.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstring>
#include <dirent.h>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
#include <thread>
namespace rad {
@@ -50,13 +59,41 @@ int read_targets(const std::string& dir, std::set<std::string>* out, std::string
return RAD_OK;
}
/* A generator's adapter name: a file stem under --lora-dir, possibly in a subdirectory, never
* leaving it. */
bool valid_name(const std::string& n) {
if (n.empty() || n.size() > 200 || n[0] == '/' || n[0] == '.') return false;
if (n.find("..") != std::string::npos || n.find("//") != std::string::npos) return false;
for (char c : n)
if (!(std::isalnum((unsigned char)c) || c == '_' || c == '-' || c == '.' || c == '/' ||
c == ' ' || c == '(' || c == ')' || c == '+' || c == ','))
return false;
return true;
}
bool is_file(const std::string& p) {
struct stat sb{};
return stat(p.c_str(), &sb) == 0 && S_ISREG(sb.st_mode);
}
/* The combination's slot name: the adapters sorted by name, each at its strength. */
std::string combo_key(const std::vector<Engine::LoraUse>& uses) {
std::string k;
for (const Engine::LoraUse& u : uses) k += fmt("%s%s*%.6g", k.empty() ? "" : "+", u.name.c_str(), u.weight);
return k;
}
} /* namespace */
int Engine::lora_targets() {
if (!cfg_.lora.enabled()) return RAD_OK;
lora_targets_ = std::set<std::string>(cfg_.lora.targets.begin(), cfg_.lora.targets.end());
if (lora_targets_.empty()) {
/* A PEFT directory names its targets; an adapter file (a generator's) and a directory of
* them do not, and a generator's default is every plain GEMM under its declared roots. A
* text model refuses "*" at declare. */
for (const auto& [name, dir] : cfg_.lora.adapters) {
if (is_file(dir)) { lora_targets_.insert("*"); continue; }
std::string err;
const int s = read_targets(dir, &lora_targets_, &err);
if (s < 0) {
@@ -64,6 +101,7 @@ int Engine::lora_targets() {
return s;
}
}
if (cfg_.lora.adapters.empty()) lora_targets_.insert("*");
}
lora_table_.reset(cfg_.lora.slots(), &lora_epoch_);
return RAD_OK;
@@ -71,6 +109,12 @@ int Engine::lora_targets() {
int Engine::lora_start() {
if (!cfg_.lora.enabled()) return RAD_OK;
lora_gen_ = ranks_[0]->program.is_pass_driven();
if (!lora_gen_ && cfg_.lora.slots() < (int)cfg_.lora.adapters.size()) {
RAD_ERR("lora: --max-loras %d holds fewer adapters than the %zu that --lora names",
cfg_.lora.slots(), cfg_.lora.adapters.size());
return RAD_E_INVAL;
}
size_t n_sites = 0;
for (const auto& r : ranks_) n_sites += r->program.lora_sites.size();
if (n_sites == 0) {
@@ -82,7 +126,7 @@ int Engine::lora_start() {
}
/* Every target is a module some rank carries adapters on. A leaf the model lacks, or holds
* only outside the trunk (embedding, lm_head, a tower, the drafter), would target nothing. */
{
if (!lora_targets_.count("*")) {
std::set<std::string> carried;
for (const auto& r : ranks_)
for (const lora::Site& site : r->lora_sites)
@@ -117,9 +161,10 @@ int Engine::lora_start() {
for (const std::string& x : lora_targets_) t += (t.empty() ? "" : ",") + x;
RAD_INFO("lora: %zu GEMMs over %zu weights carry adapters on rank 0 (%s); %d slots of rank "
"%d, %s a slot, %s on the card", P.lora_sites.size(), P.lora_pools.size(), t.c_str(),
cfg_.lora.slots(), cfg_.lora.max_rank, humanb(slot_bytes).c_str(),
cfg_.lora.slots(), cfg_.lora.rank(lora_gen_), humanb(slot_bytes).c_str(),
humanb(slot_bytes * cfg_.lora.slots()).c_str());
}
if (lora_gen_) return gen_lora_start();
for (const auto& [name, dir] : cfg_.lora.adapters) {
std::string err;
const int s = lora_load(name, dir, &err);
@@ -135,6 +180,37 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
std::lock_guard<std::mutex> lk(lora_mu_);
if (!cfg_.lora.enabled()) { *err = "the engine was started without adapters"; return RAD_E_STATE; }
if (name.empty()) { *err = "an adapter needs a name"; return RAD_E_INVAL; }
if (lora_gen_) {
/* A generator's adapter goes into the library; a slot takes it when a request asks. */
if (!valid_name(name)) { *err = "'" + name + "' is not an adapter name"; return RAD_E_INVAL; }
{
std::lock_guard<std::mutex> lk2(lora_lib_mu_);
if (lora_lib_.count(name)) { *err = "an adapter named '" + name + "' is already loaded"; return RAD_E_INVAL; }
}
auto f = std::make_shared<lora::AdapterFile>();
RAD_TRY(f->open(dir, err));
int placed = 0, rank = 0;
std::string first;
for (const lora::FileModule& m : f->modules()) {
std::string why;
if (!lora_keys_->resolve(m.key, &why).empty()) { ++placed; continue; }
if (first.empty()) first = m.key + ": " + why;
}
for (const lora::FileModule& m : f->modules())
if (m.kind == lora::FileModule::LORA && m.t[0]) rank = std::max(rank, (int)m.t[0]->shape[0]);
if (placed == 0) {
*err = fmt("none of its %zu modules is a module of this model (%s)", f->modules().size(),
first.c_str());
return RAD_E_NOTFOUND;
}
RAD_INFO("lora: '%s' -- %s, %d of %zu modules on this model%s%s%s", name.c_str(),
f->kind_name(), placed, f->modules().size(),
rank ? fmt(", rank %d", rank).c_str() : "", first.empty() ? "" : "; not placed: ",
first.c_str());
std::lock_guard<std::mutex> lk2(lora_lib_mu_);
lora_lib_[name] = { dir, f };
return RAD_OK;
}
/* A slot that is still cooling (lora/slots.h) is waited for here rather than answered with a
* retry: the step loop goes round idle or busy, so the wait is milliseconds, and a hot swap
* (unload, then load at once) would otherwise fail under traffic. Only other loads wait on
@@ -155,7 +231,7 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
std::vector<lora::AdapterInfo> infos(ranks_.size());
std::vector<std::vector<lora::PackedSite>> packed(ranks_.size());
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
const int s = lora::load_adapter(dir, ranks_[ri]->lora_sites, cfg_.lora.max_rank, &infos[ri],
const int s = lora::load_adapter(dir, ranks_[ri]->lora_sites, cfg_.lora.rank(false), &infos[ri],
&packed[ri], err);
if (s < 0) {
if (ranks_.size() > 1) *err = fmt("rank %zu: ", ri) + *err;
@@ -167,7 +243,19 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
if (s < 0) return s;
}
/* ---- copy, per rank, on a stream of its own (the compute stream may be recording a pass) */
RAD_TRY(lora_copy(slot, packed, err));
lora_table_.publish(slot, name, dir);
const lora::AdapterInfo& a = infos[0];
RAD_INFO("lora: '%s' in slot %d -- %zu modules, rank %lld, alpha %g%s, base %s", name.c_str(),
slot, a.modules.size(), (long long)a.max_module_rank, a.alpha, a.rslora ? " (rsLoRA)" : "",
a.base_model.empty() ? "(unnamed)" : a.base_model.c_str());
return RAD_OK;
}
int Engine::lora_copy(int slot, const std::vector<std::vector<lora::PackedSite>>& packed,
std::string* err) {
/* Each rank on a stream of its own: the compute stream may be recording a pass. */
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
Rank& r = *ranks_[ri];
const Program& P = r.program;
@@ -218,12 +306,6 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
return rc;
}
}
lora_table_.publish(slot, name, dir);
const lora::AdapterInfo& a = infos[0];
RAD_INFO("lora: '%s' in slot %d -- %zu modules, rank %lld, alpha %g%s, base %s", name.c_str(),
slot, a.modules.size(), (long long)a.max_module_rank, a.alpha, a.rslora ? " (rsLoRA)" : "",
a.base_model.empty() ? "(unnamed)" : a.base_model.c_str());
return RAD_OK;
}
@@ -233,11 +315,237 @@ int Engine::lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid,
}
int Engine::lora_unload(const std::string& name, std::string* err, int* in_flight) {
return lora_table_.unload(name, in_flight, err);
if (!lora_gen_) return lora_table_.unload(name, in_flight, err);
/* A generator's adapter leaves the library, and every combination holding it its slot (at
* once when idle, after its requests otherwise). */
{
std::lock_guard<std::mutex> lk(lora_lib_mu_);
if (!lora_lib_.erase(name)) {
*err = "no adapter named '" + name + "' is loaded";
return RAD_E_NOTFOUND;
}
}
*in_flight = 0;
for (const std::string& k : lora_table_.names()) {
bool uses = false;
size_t at = 0;
while (at <= k.size()) {
const size_t plus = std::min(k.find('+', at), k.size());
const std::string part = k.substr(at, plus - at);
if (part.substr(0, part.rfind('*')) == name) uses = true;
at = plus + 1;
}
if (!uses) continue;
int n = 0;
std::string e;
lora_table_.unload(k, &n, &e);
*in_flight += n;
}
return RAD_OK;
}
std::vector<std::string> Engine::lora_names() const {
return lora_table_.names();
return lora_gen_ ? gen_lora_names() : lora_table_.names();
}
/* ================================================================== generator adapters */
int Engine::gen_lora_start() {
/* Every slot's run of the slot-row table holds its own index (Program::lora_rows). */
for (auto& rp : ranks_) {
Rank& r = *rp;
const Program& P = r.program;
if (!P.lora_rows || P.lora_rows_n <= 0) continue;
const int S = cfg_.lora.slots();
std::vector<int32_t> v((size_t)(S * P.lora_rows_n));
for (int s = 0; s < S; ++s)
std::fill(v.begin() + (int64_t)s * P.lora_rows_n, v.begin() + (int64_t)(s + 1) * P.lora_rows_n, s);
void* d = P.buffers[P.lora_rows].ptr;
if (!d || rad_dev_set(r.device) < 0) {
RAD_ERR("lora: rank %d: the slot-row table has no address", r.index);
return RAD_E_STATE;
}
RadStream st{};
if (rad_stream_create(&st, 0) < 0) return RAD_E_DEVICE;
const int rc = rad_memcpy_async(d, v.data(), (int64_t)v.size() * 4, st);
const int sy = rad_stream_sync(st);
rad_stream_destroy(st);
if (rc < 0 || sy < 0) return RAD_E_DEVICE;
}
lora_keys_ = std::make_unique<lora::KeyMap>(ranks_[0]->program, ranks_[0]->lora_sites);
for (const auto& [name, path] : cfg_.lora.adapters) {
std::string err;
const int s = lora_load(name, path, &err);
if (s < 0) {
RAD_ERR("lora: adapter '%s' (%s): %s", name.c_str(), path.c_str(), err.c_str());
return s;
}
}
if (!cfg_.lora.dir.empty())
RAD_INFO("lora: requests may name the %zu adapter files under %s", gen_lora_names().size(),
cfg_.lora.dir.c_str());
return RAD_OK;
}
int Engine::gen_lora_open(const std::string& name, std::shared_ptr<const lora::AdapterFile>* out,
std::string* err) {
{
std::lock_guard<std::mutex> lk(lora_lib_mu_);
auto it = lora_lib_.find(name);
if (it != lora_lib_.end()) { *out = it->second.second; return RAD_OK; }
}
const std::string path = cfg_.lora.dir + "/" + name + ".safetensors";
if (cfg_.lora.dir.empty() || !valid_name(name) || !is_file(path)) {
*err = "no adapter named '" + name + "'" +
(cfg_.lora.dir.empty() ? std::string(" is loaded")
: " is loaded or under --lora-dir (GET /v1/loras lists them)");
return RAD_E_NOTFOUND;
}
/* lora_load takes lora_mu_, which the caller holds: open here, as lora_load would. */
auto f = std::make_shared<lora::AdapterFile>();
RAD_TRY(f->open(path, err));
RAD_INFO("lora: '%s' opened from --lora-dir -- %s, %zu modules", name.c_str(), f->kind_name(),
f->modules().size());
std::lock_guard<std::mutex> lk(lora_lib_mu_);
lora_lib_[name] = { path, f };
*out = f;
return RAD_OK;
}
std::vector<std::string> Engine::gen_lora_names() const {
std::set<std::string> n;
{
std::lock_guard<std::mutex> lk(lora_lib_mu_);
for (const auto& [k, v] : lora_lib_) n.insert(k);
}
if (!cfg_.lora.dir.empty()) {
/* Two levels: the directory and its subdirectories, as a UI's lora folder is laid out. */
std::vector<std::string> dirs{ "" };
for (size_t i = 0; i < dirs.size(); ++i) {
const std::string rel = dirs[i];
DIR* d = opendir((cfg_.lora.dir + "/" + rel).c_str());
if (!d) continue;
while (dirent* e = readdir(d)) {
const std::string fn = e->d_name;
if (fn.empty() || fn[0] == '.') continue;
const std::string p = rel + fn;
struct stat sb{};
if (stat((cfg_.lora.dir + "/" + p).c_str(), &sb) != 0) continue;
if (S_ISDIR(sb.st_mode)) { if (rel.empty()) dirs.push_back(p + "/"); continue; }
const size_t k = fn.size();
if (k > 12 && fn.compare(k - 12, 12, ".safetensors") == 0) {
const std::string stem = p.substr(0, p.size() - 12);
if (valid_name(stem)) n.insert(stem);
}
}
closedir(d);
}
}
return std::vector<std::string>(n.begin(), n.end());
}
int Engine::gen_lora_acquire(const std::vector<LoraUse>& uses_in, int32_t* slot,
std::shared_ptr<void>* hold, std::string* note, std::string* err) {
*slot = -1;
hold->reset();
if (note) note->clear();
if (!lora_gen_) { *err = "this model takes no adapters (start it with --lora or --lora-dir)"; return RAD_E_STATE; }
/* One entry per adapter, strengths of a repeated name summed; strength 0 is no adapter. */
std::map<std::string, double> by;
for (const LoraUse& u : uses_in) {
if (!std::isfinite(u.weight) || std::fabs(u.weight) > 16.0) {
*err = fmt("adapter '%s': strength %g is outside [-16, 16]", u.name.c_str(), u.weight);
return RAD_E_INVAL;
}
by[u.name] += u.weight;
}
std::vector<LoraUse> uses;
for (const auto& [n, w] : by) if (w != 0.0) uses.push_back({ n, w });
if (uses.empty()) return RAD_OK;
if (uses.size() > 16) { *err = fmt("%zu adapters in one request; at most 16", uses.size()); return RAD_E_INVAL; }
const std::string key = combo_key(uses);
uint64_t uid = 0;
if (lora_table_.acquire(key, slot, &uid, hold) == RAD_OK) return RAD_OK;
std::lock_guard<std::mutex> lk(lora_mu_);
if (lora_table_.acquire(key, slot, &uid, hold) == RAD_OK) return RAD_OK;
const auto t0 = std::chrono::steady_clock::now();
std::vector<lora::Strength> ss;
for (const LoraUse& u : uses) {
lora::Strength s;
s.name = u.name;
s.weight = u.weight;
RAD_TRY(gen_lora_open(u.name, &s.file, err));
ss.push_back(std::move(s));
}
/* A slot: free, or freed from the least recently used combination no request holds. */
const auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds(2);
int sl = -1;
for (;;) {
bool cooling = false;
const int s = lora_table_.reserve(key, &sl, &cooling, err);
if (s >= 0) break;
if (s == RAD_E_FULL && !cooling) {
std::string ev;
if (lora_table_.evict_idle(&ev) == RAD_OK) continue;
*err = fmt("all %d adapter slots are held by running requests with other adapters "
"(--max-loras); retry when one finishes", cfg_.lora.slots());
return RAD_E_FULL;
}
if (s != RAD_E_FULL || stopping_.load(std::memory_order_acquire) ||
std::chrono::steady_clock::now() >= give_up)
return s;
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
const int rank = cfg_.lora.rank(true);
std::map<std::string, lora::Composite> comp;
lora::ComposeReport rep;
RAD_TRY(lora::compose(*lora_keys_, ss, rank, &comp, &rep, err));
if (rep.modules == 0) {
*err = "none of the adapters' modules is a module of this model" +
(rep.unplaced.empty() ? std::string() : " (" + rep.unplaced[0] + ")");
return RAD_E_NOTFOUND;
}
const std::map<std::string, lora::AdModule> mods = lora::as_modules(comp, *lora_keys_);
std::vector<std::vector<lora::PackedSite>> packed(ranks_.size());
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
lora::AdapterInfo info;
const int s = lora::pack_modules(ranks_[ri]->lora_sites, rank, mods, &info, &packed[ri], err,
/*compact=*/true);
if (s < 0) {
if (ranks_.size() > 1) *err = fmt("rank %zu: ", ri) + *err;
return s;
}
/* Pools past the last one a site names hold nothing (lora_declare's dropped GEMMs). */
packed[ri].resize(ranks_[ri]->program.lora_pools.size());
}
RAD_TRY(lora_copy(sl, packed, err));
/* The ranks each pool takes in this slot, before a pass can name the slot (the publish). */
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
Program& P = ranks_[ri]->program;
const size_t S = (size_t)cfg_.lora.slots();
for (size_t p = 0; p < P.lora_pools.size() && p < packed[ri].size(); ++p)
if (p * S + (size_t)sl < P.lora_rused.size())
P.lora_rused[p * S + (size_t)sl] = packed[ri][p].empty ? 0 : (int32_t)packed[ri][p].r_used;
}
lora_table_.publish(sl, key, "");
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
std::string n;
if (!rep.unplaced.empty())
n += fmt("%zu adapter module%s not on this model (%s)", rep.unplaced.size(),
rep.unplaced.size() == 1 ? "" : "s", rep.unplaced[0].c_str());
if (rep.exact < rep.modules)
n += fmt("%s%lld module%s past rank %d were truncated to it, keeping at worst %.1f%% of the "
"delta (%s)", n.empty() ? "" : "; ", (long long)(rep.modules - rep.exact),
rep.modules - rep.exact == 1 ? "" : "s", rank, 100.0 * rep.worst_kept,
rep.worst_module.c_str());
RAD_INFO("lora: slot %d <- %s: %lld modules (%lld exact) in %.0f ms%s%s", sl, key.c_str(),
(long long)rep.modules, (long long)rep.exact, ms, n.empty() ? "" : "; ", n.c_str());
if (note) *note = n;
if (lora_table_.acquire(key, slot, &uid, hold) != RAD_OK) {
*err = "the combination's slot was taken back before the request could hold it; retry";
return RAD_E_STATE;
}
return RAD_OK;
}
} /* namespace rad */
+232 -7
View File
@@ -628,6 +628,191 @@ int Checkpoint::open_diffusers() {
return RAD_OK;
}
/* 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
*
* model.diffusion_model.* the UNet, under the names it is trained and adapted
* (LoRA) under, kept as they are;
* conditioner.embedders.0.transformer.* CLIP ViT-L's text model, already in transformers'
* CLIPTextModel names, kept;
* conditioner.embedders.1.model.* OpenCLIP ViT-bigG's text tower in open_clip's names,
* read as transformers' CLIPTextModelWithProjection
* under conditioner.embedders.1.transformer.: each
* block's fused in_proj split into q/k/v_proj (row
* views, nothing copied), c_fc / c_proj as fc1 / fc2,
* ln_1 / ln_2 / ln_final as layer_norm1 / layer_norm2 /
* final_layer_norm, and the (in, out) text_projection
* transposed into a linear's (out, in)
* `text_projection.weight`;
* first_stage_model.* the VAE, its decoder read in diffusers' AutoencoderKL
* names under vae. (its 1 x 1 attention convolutions
* keep their rank-4 shape).
*
* A `v_pred` tensor marks a v-prediction model and `ztsnr` one trained to a zero terminal SNR
* (ComfyUI's convention): they become the `sdxl.prediction` and `sdxl.zero_snr` keys. The
* architecture is `sdxl`. The checkpoint holds no tokenizer; rad-convert takes CLIP's with
* --tokenizer. */
int Checkpoint::open_sgm() {
kind_ = SafeT;
RAD_TRY(add_shard(path_));
bool vpred = false, zsnr = false;
std::vector<SrcTensor> add;
std::vector<std::string> drop;
auto rename = [&](const SrcTensor& t, const std::string& name) {
SrcTensor v = t;
v.name = name;
add.push_back(std::move(v));
drop.push_back(t.name);
};
const std::string g_old = "conditioner.embedders.1.model.";
const std::string g_new = "conditioner.embedders.1.transformer.";
const std::string tm = g_new + "text_model.";
const std::string v_old = "first_stage_model.";
for (const SrcTensor& t : tensors_) {
const std::string& n = t.name;
if (n == "v_pred") { vpred = true; continue; }
if (n == "ztsnr") { zsnr = true; continue; }
if (n.rfind(g_old, 0) == 0) {
const std::string r = n.substr(g_old.size());
if (r == "token_embedding.weight") {
rename(t, tm + "embeddings.token_embedding.weight");
} else if (r == "positional_embedding") {
rename(t, tm + "embeddings.position_embedding.weight");
} else if (r.rfind("ln_final.", 0) == 0) {
rename(t, tm + "final_layer_norm." + r.substr(std::strlen("ln_final.")));
} else if (r == "text_projection") {
/* x @ P in open_clip; a linear's weight is P^T. */
if (t.shape.size() != 2 || !t.data ||
(t.rad_dtype != RAD_F16 && t.rad_dtype != RAD_BF16 && t.rad_dtype != RAD_F32)) {
RAD_ERR("%s: '%s' is not a 2-D float matrix", path_.c_str(), n.c_str());
return RAD_E_FORMAT;
}
const int64_t a = t.shape[0], b = t.shape[1];
const int64_t es = rad_dtype_bytes(t.rad_dtype, 1);
owned_.push_back(std::make_unique<uint8_t[]>((size_t)(a * b * es)));
uint8_t* dst = owned_.back().get();
const uint8_t* src = (const uint8_t*)t.data;
for (int64_t i = 0; i < a; ++i)
for (int64_t j = 0; j < b; ++j)
std::memcpy(dst + (size_t)((j * a + i) * es),
src + (size_t)((i * b + j) * es), (size_t)es);
SrcTensor v = t;
v.name = g_new + "text_projection.weight";
v.shape = { b, a };
v.data = dst;
add.push_back(std::move(v));
drop.push_back(n);
} else if (r.rfind("transformer.resblocks.", 0) == 0) {
/* transformer.resblocks.N.<rest> */
const size_t p0 = std::strlen("transformer.resblocks.");
const size_t dot = r.find('.', p0);
if (dot == std::string::npos) continue;
const std::string layer = tm + "encoder.layers." + r.substr(p0, dot - p0) + ".";
const std::string rest = r.substr(dot + 1);
if (rest == "attn.in_proj_weight" || rest == "attn.in_proj_bias") {
const bool w = rest == "attn.in_proj_weight";
if (t.shape.empty() || t.shape[0] % 3 || !t.data) {
RAD_ERR("%s: '%s' does not split into q, k and v", path_.c_str(),
n.c_str());
return RAD_E_FORMAT;
}
const int64_t d = t.shape[0] / 3, rb = t.bytes / t.shape[0];
const char* part[3] = { "q_proj", "k_proj", "v_proj" };
for (int k = 0; k < 3; ++k) {
SrcTensor v = t;
v.name = layer + "self_attn." + part[k] + (w ? ".weight" : ".bias");
v.shape[0] = d;
v.bytes = rb * d;
v.data = (const uint8_t*)t.data + (size_t)(k * d * rb);
add.push_back(std::move(v));
}
drop.push_back(n);
} else {
static const std::pair<const char*, const char*> kMap[] = {
{ "attn.out_proj.", "self_attn.out_proj." }, { "ln_1.", "layer_norm1." },
{ "ln_2.", "layer_norm2." }, { "mlp.c_fc.", "mlp.fc1." },
{ "mlp.c_proj.", "mlp.fc2." } };
for (const auto& [from, to] : kMap)
if (rest.rfind(from, 0) == 0) {
rename(t, layer + to + rest.substr(std::strlen(from)));
break;
}
}
}
continue;
}
if (n.rfind(v_old + "decoder.", 0) == 0 || n.rfind(v_old + "post_quant_conv.", 0) == 0) {
/* diffusers' convert_ldm_vae_checkpoint, the decoder's half. */
std::string r = n.substr(v_old.size());
auto sub = [&](const std::string& from, const std::string& to) {
const size_t at = r.find(from);
if (at != std::string::npos) r.replace(at, from.size(), to);
};
sub("decoder.mid.block_1.", "decoder.mid_block.resnets.0.");
sub("decoder.mid.block_2.", "decoder.mid_block.resnets.1.");
sub("decoder.mid.attn_1.norm.", "decoder.mid_block.attentions.0.group_norm.");
sub("decoder.mid.attn_1.q.", "decoder.mid_block.attentions.0.to_q.");
sub("decoder.mid.attn_1.k.", "decoder.mid_block.attentions.0.to_k.");
sub("decoder.mid.attn_1.v.", "decoder.mid_block.attentions.0.to_v.");
sub("decoder.mid.attn_1.proj_out.", "decoder.mid_block.attentions.0.to_out.0.");
sub("decoder.norm_out.", "decoder.conv_norm_out.");
if (r.rfind("decoder.up.", 0) == 0) {
/* up.i runs at the i-th resolution from the bottom of the encoder's pyramid;
* up_blocks count in the order the decoder runs them. */
const size_t p0 = std::strlen("decoder.up."), dot = r.find('.', p0);
if (dot == std::string::npos) continue;
const int i = std::atoi(r.substr(p0, dot - p0).c_str());
std::string rest = r.substr(dot + 1);
if (rest.rfind("block.", 0) == 0) rest = "resnets." + rest.substr(6);
else if (rest.rfind("upsample.", 0) == 0) rest = "upsamplers.0." + rest.substr(9);
r = "decoder.up_blocks." + std::to_string(3 - i) + "." + rest;
}
sub(".nin_shortcut.", ".conv_shortcut.");
rename(t, "vae." + r);
}
}
for (const std::string& n : drop) index_.erase(n);
for (SrcTensor& v : add) {
if (index_.count(v.name)) {
RAD_ERR("%s: '%s' is read from two tensors", path_.c_str(), v.name.c_str());
return RAD_E_FORMAT;
}
index_.emplace(v.name, tensors_.size());
tensors_.push_back(std::move(v));
}
meta_.arch = "sdxl";
const size_t slash = path_.find_last_of('/');
meta_.name = slash == std::string::npos ? path_ : path_.substr(slash + 1);
meta_.kv("sdxl.prediction", vpred ? "v" : "eps");
meta_.kv("sdxl.zero_snr", zsnr ? "1" : "0");
/* The typed dimensions are the conditioning network's, OpenCLIP bigG's text tower (as a
* diffusers pipeline's are its text encoder's), read off its tensors. */
{
RadModelMeta& m = meta_.m;
const SrcTensor* tok = find(tm + "embeddings.token_embedding.weight");
const SrcTensor* fc1 = find(tm + "encoder.layers.0.mlp.fc1.weight");
int64_t layers = 0;
while (find(tm + "encoder.layers." + std::to_string(layers) + ".layer_norm1.weight"))
++layers;
if (!tok || tok->shape.size() != 2 || !fc1 || fc1->shape.size() != 2 || !layers) {
RAD_ERR("%s: OpenCLIP bigG's text tower is incomplete", path_.c_str());
return RAD_E_FORMAT;
}
m.n_layers = layers;
m.n_embd = tok->shape[1];
m.head_dim = 64;
m.n_head = m.n_head_kv = m.n_embd / 64;
m.n_ff = fc1->shape[0];
m.n_vocab = tok->shape[0];
m.n_ctx_train = 77;
m.rms_eps = 1e-5f;
m.rope_theta = 10000.0f;
m.rope_scale = 1.0f;
}
meta_.finish();
return RAD_OK;
}
int Checkpoint::open_safetensors(const std::string& path) {
kind_ = SafeT;
/* One shard, an index, or the directory holding either, as one namespace. */
@@ -644,15 +829,29 @@ int Checkpoint::open_safetensors(const std::string& path) {
return open_diffusers();
if (is_file) {
shards.push_back(path);
/* A single-file Stable Diffusion XL checkpoint, as Stability and every SDXL finetune
* ship one: read by its own importer. */
SafeTensorsFile probe;
if (probe.open(path) == RAD_OK) {
bool unet = false, bigg = false;
for (const auto& t : probe.tensors()) {
unet = unet || t.name == "model.diffusion_model.label_emb.0.0.weight";
bigg = bigg ||
t.name.rfind("conditioner.embedders.1.model.transformer.resblocks.", 0) == 0;
}
if (unet && bigg) return open_sgm();
}
} else {
RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json",
is_index, &shards, &owner));
}
for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner));
RAD_TRY(meta_from_config_json(dir_, &meta_));
RAD_TRY(meta_merge_generation_config(dir_, &meta_));
RAD_TRY(meta_merge_preprocessor_configs(dir_, &meta_));
const std::string& md = meta_dir_.empty() ? dir_ : meta_dir_;
RAD_TRY(meta_from_config_json(md, &meta_));
RAD_TRY(meta_merge_generation_config(md, &meta_));
RAD_TRY(meta_merge_preprocessor_configs(md, &meta_));
if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_;
if (!is_file && !is_index) RAD_TRY(add_companions());
/* FP8's block, where the checkpoint states one. */
if (const char* bs = meta_.get("quantization_config.weight_block_size")) {
@@ -1301,6 +1500,17 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
return RAD_OK;
}
int Checkpoint::add_file(const std::string& path) {
if (kind_ != SafeT) {
RAD_ERR("%s is merged into a safetensors checkpoint's namespace; %s is not one",
path.c_str(), path_.c_str());
return RAD_E_UNSUPPORTED;
}
RAD_TRY(add_shard(path));
meta_.finish();
return RAD_OK;
}
const SrcTensor* Checkpoint::find(const std::string& n) const {
auto it = index_.find(n);
return it == index_.end() ? nullptr : &tensors_[it->second];
@@ -1565,8 +1775,9 @@ static int resolve_wnorm(Checkpoint& ck, const RadNameMap& m, bool optional, Ckp
}
/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]), RAD_MAP_EMA (src[0] the embedding
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)) and
* RAD_MAP_TAP (one index of one dimension of src[0]), computed in f32 into `derived`. */
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)), RAD_MAP_TAP
* (one index of one dimension of src[0]) and RAD_MAP_COLS (one column range of src[0]), computed in
* f32 into `derived`. */
static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>& maps,
bool optional, CkptWeight* out, std::string* why) {
auto refuse = [&](int rc, std::string msg) {
@@ -1630,7 +1841,21 @@ static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>&
return refuse(RAD_E_FORMAT, "'" + a->name + "' cannot be read as f32");
out->rank = (uint32_t)rank;
for (size_t i = 0; i < rank; ++i) out->shape[i] = a->shape[i];
if (m.mode == RAD_MAP_TAP) {
if (m.mode == RAD_MAP_COLS) {
const int64_t cb = a->shape[rank - 1], c0 = m.src_index[0], nc = m.src_rows[0];
if (c0 < 0 || nc <= 0 || c0 + nc > cb)
return refuse(RAD_E_SHAPE, "columns [" + std::to_string(c0) + ", " +
std::to_string(c0 + nc) + ") of '" + a->name + "', which "
"has " + std::to_string(cb));
const int64_t outer = n / cb;
out->derived.resize((size_t)(outer * nc));
for (int64_t o = 0; o < outer; ++o)
std::memcpy(&out->derived[(size_t)(o * nc)], &src[(size_t)(o * cb + c0)],
(size_t)nc * sizeof(float));
out->shape[rank - 1] = nc;
out->why = "it is columns [" + std::to_string(c0) + ", " + std::to_string(c0 + nc) +
") of '" + a->name + "', at convert -- a recipe rule stores it";
} else if (m.mode == RAD_MAP_TAP) {
const int d = m.concat_dim;
if (d < 0 || (size_t)d >= rank || rank < 3)
return refuse(RAD_E_SHAPE, "'" + a->name + "' has rank " + std::to_string(rank) +
@@ -1709,7 +1934,7 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
if (maps.front()->mode == RAD_MAP_WNORM)
return resolve_wnorm(ck, *maps.front(), optional, out, why);
if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA ||
maps.front()->mode == RAD_MAP_TAP)
maps.front()->mode == RAD_MAP_TAP || maps.front()->mode == RAD_MAP_COLS)
return resolve_derived(ck, maps, optional, out, why);
struct Src1 { const char* name; int index; int64_t rows; };
std::vector<Src1> srcs;
+11 -2
View File
@@ -120,6 +120,14 @@ public:
* borrows the target's embedding and head, so it goes into the target's container with its
* tensors and config.json keys under `draft.`. */
int add_draft(const std::string& dir, const std::string& prefix);
/* Merge one more safetensors file, its tensor names kept: a release that ships its networks
* as separate single files (ComfyUI's split_files: a diffusion model, a text encoder and a
* VAE). A name already present is refused. */
int add_file(const std::string& path);
/* Before open(): read config.json, generation_config.json and the tokenizer from `dir` rather
* than from beside the checkpoint, for a single-file checkpoint that ships none of them (the
* text encoder's repository describes such a release). */
void set_meta_dir(const std::string& dir) { meta_dir_ = dir; }
const SrcTensor* find(const std::string& n) const;
const std::vector<SrcTensor>& tensors() const { return tensors_; }
@@ -177,12 +185,13 @@ private:
const std::unordered_map<std::string, std::string>* owner = nullptr);
int open_safetensors(const std::string& path);
int open_diffusers();
int open_sgm();
int add_companions();
int open_gguf(const std::string& path);
void detect_import();
enum Kind { None, Gguf, SafeT } kind_ = None;
std::string path_, dir_, tok_dir_;
std::string path_, dir_, tok_dir_, meta_dir_;
GgufFile gguf_;
MetaOwn meta_;
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
@@ -249,7 +258,7 @@ struct CkptWeight {
* (the values change), so a recipe rule stores it. */
bool wnorm = false;
std::vector<float> wnorm_scale;
/* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, RAD_MAP_EMA): its f32
/* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, EMA, TAP, COLS): its f32
* values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule
* stores it. */
std::vector<float> derived;
+90 -51
View File
@@ -40,6 +40,7 @@ void RadFile::close() {
hdr_ = nullptr; meta_ = nullptr; dir_ = nullptr; planes_ = nullptr; encs_ = nullptr;
prof_ = nullptr;
vocab_ = VocabSection{};
aux_vocab_ = VocabSection{};
groups_.clear();
by_name_.clear();
path_.clear();
@@ -197,6 +198,9 @@ int RadFile::validate() {
if (!need(span_n(hdr_->prof_off, hdr_->prof_count, sizeof(RadFileProfile)),
"the expert profile")) return RAD_E_FORMAT;
if (!need(span_ok(hdr_->vocab_off, hdr_->vocab_bytes), "the vocab section")) return RAD_E_FORMAT;
if (!need(span_ok(hdr_->reserved[RAD_HDR_AUX_VOCAB_OFF],
hdr_->reserved[RAD_HDR_AUX_VOCAB_BYTES]), "the second vocab section"))
return RAD_E_FORMAT;
if (!need(span_ok(hdr_->data_off, hdr_->data_bytes), "the data blob")) return RAD_E_FORMAT;
if (hdr_->data_bytes && (hdr_->data_off % RAD_ALIGN_POOL) != 0) {
@@ -312,22 +316,29 @@ int RadFile::validate() {
}
/* ---------------------------------------------------------------- vocab */
if (hdr_->vocab_bytes >= sizeof(RadVocabHeader)) {
/* The section is read in place through typed pointers, so the header and every array must
* be aligned to their element (the writer guarantees it). */
if (hdr_->vocab_off % alignof(RadVocabHeader) != 0) {
RAD_ERR("%s: the vocab section starts at %llu, which is not %zu-aligned", path_.c_str(),
(unsigned long long)hdr_->vocab_off, alignof(RadVocabHeader));
/* The vocab section, and the second one a generator may read its prompt through: the same
* layout, each checked against its own extent. */
auto read_vocab = [&](uint64_t voff, uint64_t vbytes, const char* what,
VocabSection* out) -> int {
if (vbytes == 0) return RAD_OK;
if (vbytes < sizeof(RadVocabHeader)) {
RAD_ERR("%s: the %s section is %llu bytes, shorter than its own header (%zu)",
path_.c_str(), what, (unsigned long long)vbytes, sizeof(RadVocabHeader));
return RAD_E_FORMAT;
}
const RadVocabHeader* v = (const RadVocabHeader*)(base_ + hdr_->vocab_off);
/* The section is read in place through typed pointers, so the header and every array must
* be aligned to their element (the writer guarantees it). */
if (voff % alignof(RadVocabHeader) != 0) {
RAD_ERR("%s: the %s section starts at %llu, which is not %zu-aligned", path_.c_str(),
what, (unsigned long long)voff, alignof(RadVocabHeader));
return RAD_E_FORMAT;
}
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 >= hdr_->vocab_off &&
off - hdr_->vocab_off <= hdr_->vocab_bytes &&
bytes <= hdr_->vocab_bytes - (off - hdr_->vocab_off) &&
(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;
@@ -336,47 +347,50 @@ int RadFile::validate() {
!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))) {
RAD_ERR("%s: the vocab section's arrays do not fit inside it, or one is not aligned "
"to its element", path_.c_str());
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);
return RAD_E_FORMAT;
}
vocab_.h = v;
vocab_.tok_text = (nt && v->tok_text_off) ? (const rad_stroff*)(base_ + v->tok_text_off) : nullptr;
vocab_.tok_score = (nt && v->tok_score_off) ? (const float*)(base_ + v->tok_score_off) : nullptr;
vocab_.tok_type = (nt && v->tok_type_off) ? (const uint8_t*)(base_ + v->tok_type_off) : nullptr;
vocab_.merges = (nm && v->merge_off) ? (const uint32_t*)(base_ + v->merge_off) : nullptr;
vocab_.steps = (ns && v->step_off) ? (const RadVocabStep*)(base_ + v->step_off) : nullptr;
VocabSection& vs = *out;
vs.h = v;
vs.tok_text = (nt && v->tok_text_off) ? (const rad_stroff*)(base_ + v->tok_text_off) : nullptr;
vs.tok_score = (nt && v->tok_score_off) ? (const float*)(base_ + v->tok_score_off) : nullptr;
vs.tok_type = (nt && v->tok_type_off) ? (const uint8_t*)(base_ + v->tok_type_off) : nullptr;
vs.merges = (nm && v->merge_off) ? (const uint32_t*)(base_ + v->merge_off) : nullptr;
vs.steps = (ns && v->step_off) ? (const RadVocabStep*)(base_ + v->step_off) : nullptr;
if (vocab_.tok_text)
if (vs.tok_text)
for (uint64_t i = 0; i < nt; ++i)
if (!str_ok(vocab_.tok_text[i])) {
RAD_ERR("%s: vocab token %llu points outside the string blob", path_.c_str(),
(unsigned long long)i);
if (!str_ok(vs.tok_text[i])) {
RAD_ERR("%s: %s token %llu points outside the string blob", path_.c_str(),
what, (unsigned long long)i);
return RAD_E_FORMAT;
}
if (vocab_.steps)
if (vs.steps)
for (uint64_t i = 0; i < ns; ++i)
if (!str_ok(vocab_.steps[i].arg0) || !str_ok(vocab_.steps[i].arg1)) {
RAD_ERR("%s: vocab step %llu points outside the string blob", path_.c_str(),
if (!str_ok(vs.steps[i].arg0) || !str_ok(vs.steps[i].arg1)) {
RAD_ERR("%s: %s step %llu points outside the string blob", path_.c_str(), what,
(unsigned long long)i);
return RAD_E_FORMAT;
}
if (vocab_.merges)
if (vs.merges)
for (uint64_t i = 0; i < nm * 2; ++i)
if (vocab_.merges[i] >= nt) {
RAD_ERR("%s: merge %llu names token %u of %llu", path_.c_str(),
(unsigned long long)(i / 2), vocab_.merges[i], (unsigned long long)nt);
if (vs.merges[i] >= nt) {
RAD_ERR("%s: %s merge %llu names token %u of %llu", path_.c_str(), what,
(unsigned long long)(i / 2), vs.merges[i], (unsigned long long)nt);
return RAD_E_FORMAT;
}
if (!str_ok(v->chat_template)) {
RAD_ERR("%s: the chat template offset is outside the string blob", path_.c_str());
RAD_ERR("%s: the %s section's chat template offset is outside the string blob",
path_.c_str(), what);
return RAD_E_FORMAT;
}
} else if (hdr_->vocab_bytes != 0) {
RAD_ERR("%s: the vocab section is %llu bytes, shorter than its own header (%zu)",
path_.c_str(), (unsigned long long)hdr_->vocab_bytes, sizeof(RadVocabHeader));
return RAD_E_FORMAT;
}
return RAD_OK;
};
RAD_TRY(read_vocab(hdr_->vocab_off, hdr_->vocab_bytes, "vocab", &vocab_));
RAD_TRY(read_vocab(hdr_->reserved[RAD_HDR_AUX_VOCAB_OFF],
hdr_->reserved[RAD_HDR_AUX_VOCAB_BYTES], "second vocab", &aux_vocab_));
return RAD_OK;
}
@@ -956,6 +970,29 @@ int RadWriter::check_complete() const {
return RAD_OK;
}
/* A serialised vocab section's arrays rebased from section-relative to file offsets. */
static void rebase_vocab(std::vector<uint8_t>& blob, uint64_t at) {
auto* vh = (RadVocabHeader*)blob.data();
if (vh->tok_text_off) vh->tok_text_off += at;
if (vh->tok_score_off) vh->tok_score_off += at;
if (vh->tok_type_off) vh->tok_type_off += at;
if (vh->merge_off) vh->merge_off += at;
if (vh->step_off) vh->step_off += at;
}
int RadWriter::set_aux_vocab_section(const void* blob, int64_t bytes) {
std::vector<uint8_t> keep;
keep.swap(vocab_blob_);
const bool had = have_vocab_;
const int s = set_vocab_section(blob, bytes);
keep.swap(vocab_blob_);
have_vocab_ = had;
if (s < 0) return s;
aux_vocab_blob_.assign((const uint8_t*)blob, (const uint8_t*)blob + bytes);
have_aux_vocab_ = true;
return RAD_OK;
}
int RadWriter::set_vocab_section(const void* blob, int64_t bytes) {
if (!began_ || sealed_) return RAD_E_STATE;
if (!blob || bytes < (int64_t)sizeof(RadVocabHeader)) {
@@ -1049,6 +1086,10 @@ void RadWriter::layout(RadFileHeader* hp) {
h.enc_count = encs_.size();
h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size());
h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0;
if (have_aux_vocab_) {
h.reserved[RAD_HDR_AUX_VOCAB_OFF] = (uint64_t)place8((int64_t)aux_vocab_blob_.size());
h.reserved[RAD_HDR_AUX_VOCAB_BYTES] = aux_vocab_blob_.size();
}
h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile)));
h.prof_count = prof_.size();
@@ -1095,14 +1136,8 @@ int RadWriter::finish() {
* aligned within the blob, so alignment is preserved. */
for (auto& e : dir_) e.offset += h.data_off;
for (auto& p : planes_) p.offset += h.data_off;
if (have_vocab_) {
auto* vh = (RadVocabHeader*)vocab_blob_.data();
if (vh->tok_text_off) vh->tok_text_off += h.vocab_off;
if (vh->tok_score_off) vh->tok_score_off += h.vocab_off;
if (vh->tok_type_off) vh->tok_type_off += h.vocab_off;
if (vh->merge_off) vh->merge_off += h.vocab_off;
if (vh->step_off) vh->step_off += h.vocab_off;
}
if (have_vocab_) rebase_vocab(vocab_blob_, h.vocab_off);
if (have_aux_vocab_) rebase_vocab(aux_vocab_blob_, h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
int st = RAD_OK;
int64_t at = 0;
@@ -1120,6 +1155,9 @@ int RadWriter::finish() {
emit(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), (int64_t)h.plane_off);
emit(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), (int64_t)h.enc_off);
if (have_vocab_) emit(vocab_blob_.data(), (int64_t)vocab_blob_.size(), (int64_t)h.vocab_off);
if (have_aux_vocab_)
emit(aux_vocab_blob_.data(), (int64_t)aux_vocab_blob_.size(),
(int64_t)h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
emit(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), (int64_t)h.prof_off);
if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; }
@@ -1249,6 +1287,10 @@ int RadWriter::finish_append() {
h.enc_count = encs_.size();
h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size());
h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0;
if (have_aux_vocab_) {
h.reserved[RAD_HDR_AUX_VOCAB_OFF] = (uint64_t)place8((int64_t)aux_vocab_blob_.size());
h.reserved[RAD_HDR_AUX_VOCAB_BYTES] = aux_vocab_blob_.size();
}
h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile)));
h.prof_count = prof_.size();
@@ -1264,14 +1306,8 @@ int RadWriter::finish_append() {
if (!dir_abs_[i])
for (uint32_t k = 0; k < dir_[i].n_planes; ++k)
planes_[dir_[i].plane_first + k].offset += (uint64_t)append_base_;
if (have_vocab_) {
auto* vh = (RadVocabHeader*)vocab_blob_.data();
if (vh->tok_text_off) vh->tok_text_off += h.vocab_off;
if (vh->tok_score_off) vh->tok_score_off += h.vocab_off;
if (vh->tok_type_off) vh->tok_type_off += h.vocab_off;
if (vh->merge_off) vh->merge_off += h.vocab_off;
if (vh->step_off) vh->step_off += h.vocab_off;
}
if (have_vocab_) rebase_vocab(vocab_blob_, h.vocab_off);
if (have_aux_vocab_) rebase_vocab(aux_vocab_blob_, h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
int st = RAD_OK;
auto put = [&](const void* p, int64_t bytes, uint64_t at) {
@@ -1283,6 +1319,9 @@ int RadWriter::finish_append() {
put(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), h.plane_off);
put(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), h.enc_off);
if (have_vocab_) put(vocab_blob_.data(), (int64_t)vocab_blob_.size(), h.vocab_off);
if (have_aux_vocab_)
put(aux_vocab_blob_.data(), (int64_t)aux_vocab_blob_.size(),
h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
put(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), h.prof_off);
if (st >= 0 && ::ftruncate(fd_out_, (off_t)off) != 0) st = RAD_E_IO;
/* Make everything durable before the new header names it. */
+7 -1
View File
@@ -141,6 +141,8 @@ public:
/* ------------------------------------------------------------ vocab and profile */
VocabSection vocab() const { return vocab_; }
/* The second vocab section, or an empty one (RAD_HDR_AUX_VOCAB_OFF in rad_format.h). */
VocabSection aux_vocab() const { return aux_vocab_; }
int64_t profile_count() const { return (int64_t)hdr_->prof_count; }
const RadFileProfile* profile() const { return prof_; }
@@ -161,7 +163,7 @@ private:
const RadFileProfile* prof_ = nullptr;
uint64_t str_bytes_ = 1;
VocabSection vocab_;
VocabSection vocab_, aux_vocab_;
std::vector<ExpertGroup> groups_;
std::unordered_map<std::string_view, int64_t> by_name_;
};
@@ -244,6 +246,8 @@ public:
/* The serialised vocab section. Its internal offsets must be section-relative (serialise with
* section_file_off 0); finish() rebases them, as it does the directory. */
int set_vocab_section(const void* blob, int64_t bytes);
/* The second vocab section (RAD_HDR_AUX_VOCAB_OFF), serialised the same way. */
int set_aux_vocab_section(const void* blob, int64_t bytes);
void add_profile(int32_t layer, int32_t expert, float share);
@@ -301,6 +305,8 @@ private:
/* The vocab section, assembled in memory and appended verbatim. */
std::vector<uint8_t> vocab_blob_;
bool have_vocab_ = false;
std::vector<uint8_t> aux_vocab_blob_;
bool have_aux_vocab_ = false;
int64_t blob_bytes_ = 0; /* the blob's reserved length */
+87 -4
View File
@@ -23,7 +23,7 @@ int64_t ref_tokens_max(const RadGeneratorDecl& d) {
}
struct Sizes {
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0;
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0, AX = 0;
bool joint = false;
};
@@ -43,6 +43,7 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2;
z.NT = d.max_tokens;
z.NB = block_size > 0 ? (z.P + block_size - 1) / block_size : 0;
z.AX = d.aux_tokens ? d.aux_max_tokens : 0;
return z;
}
@@ -85,6 +86,12 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
{ 0, J * z.T * I }, /* R_MSRC */
{ 0, J * 3 * (z.S + 1) * I }, /* R_MCCU */
{ 0, J * 4 * z.T * 4 }, /* R_MROPE */
{ 0, (z.AX ? z.AX + 2 : 0) * I }, /* R_AUX: a COND's {0, n} and second-tokenizer ids */
{ 0, z.S * 4 }, /* R_SIGP */
{ 0, z.S * 4 }, /* R_TSTEP */
{ 0, z.S * I }, /* R_SAMP */
{ 0, z.S * I }, /* R_STEPI */
{ 0, 2 * z.S * 4 }, /* R_SIZE */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -113,6 +120,14 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>&
fixed_ = prog.gen_str.sigmas;
kv_ = kv;
ranks_ = ranks;
table_ = DiscreteTable{};
if (discrete()) {
std::string why;
if (discrete_table(decl_, &table_, &why) < 0) {
RAD_ERR("image generator: %s", why.c_str());
return RAD_E_INVAL;
}
}
/* Exactly one paged full-attention KV group, holding the conditioning; none in the joint
* layout, where the conditioning rides in the steps. Group handles start at 1 (group 0 is the
* null handle); the KV manager and a batch both index by handle. */
@@ -216,6 +231,10 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
return no("at most " + std::to_string(d.max_refs) + " pictures a request");
for (const Branch* b : { &r->pos, &r->neg }) {
if (b == &r->neg && !r->has_neg) continue;
if (d.aux_tokens && (b->aux.empty() || (int64_t)b->aux.size() > d.aux_max_tokens))
return no("the prompt is " + std::to_string(b->aux.size()) + " tokens to the "
"model's second tokenizer, which reads 1.." +
std::to_string(d.aux_max_tokens));
if ((int64_t)b->tokens.size() > max_tok_)
return no("the prompt is " + std::to_string(b->tokens.size()) + " tokens with its "
"pictures; a conditioning pass carries " + std::to_string(max_tok_));
@@ -235,6 +254,10 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
r->inp_src.h != r->height))
return no("the mask's picture is not at the size being made");
if (r->previews < 0 || r->previews > 3) return no("partial_images must be 0..3");
if (discrete() && (r->sampler < 0 || r->sampler >= RAD_GEN_SAMPLER_COUNT ||
!(decl_.samplers & (1u << r->sampler)) || r->scheduler < 0 ||
r->scheduler >= RAD_GEN_SCHED_COUNT))
return no("the sampler or scheduler is not one this model serves");
r->ticket->t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
@@ -373,7 +396,13 @@ int Driver::admit_locked() {
release_kv_locked(j);
break;
}
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
if (discrete()) {
j.sigmas = schedule_discrete(decl_, table_, r.scheduler, r.steps);
j.tsteps.clear();
for (float sg : j.sigmas) j.tsteps.push_back(sg > 0 ? (float)table_.timestep(sg) : 0.0f);
} else {
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
}
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
for (int b = 0; b < j.n_branch; ++b) {
Cond& c = j.cond[b];
@@ -491,6 +520,16 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
G.mode_ccu = nullptr;
G.n_mode_h = nullptr;
G.mode_rope_f = nullptr;
G.n_aux = 0;
G.aux_ids = nullptr;
G.aux_cu = nullptr;
G.sigma_prev = nullptr;
G.timestep = nullptr;
G.sampler = nullptr;
G.step = nullptr;
G.size_px = nullptr;
G.entry_h = nullptr;
G.tokens_h = nullptr;
}
}
@@ -529,15 +568,18 @@ const RadBatch* Driver::next(int step) {
for (int b = 0; b < j.n_branch; ++b)
if (!j.cond[b].encoded) return build_cond(j, b, step);
}
/* 3. A denoise step over what is in flight, oldest request first. */
/* 3. A denoise step over what is in flight, oldest request first, with the oldest one's
* adapters: a pass runs one runtime LoRA slot in every row. */
std::vector<int32_t> take;
int64_t rows = 0, entries = 0;
int32_t lora = -2;
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed) continue;
bool ready = true;
for (int b = 0; b < j.n_branch; ++b) ready = ready && j.cond[b].encoded;
if (!ready) continue;
if (lora != -2 && j.req->lora_slot != lora) continue;
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
for (int32_t l : j.lanes) {
const Lane& ln = lanes_[(size_t)l];
@@ -548,10 +590,13 @@ const RadBatch* Driver::next(int step) {
rows += need;
entries += j.n_branch;
take.push_back(l);
lora = j.req->lora_slot;
}
}
if (take.empty()) return nullptr;
return build_denoise(take, step);
const RadBatch* b = build_denoise(take, step);
pass_.lora_slot = lora;
return b;
}
const RadBatch* Driver::batch_for(int rank) const {
@@ -704,6 +749,15 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
/* The conditioning is modulated at t = 0. */
hptr<float>(R_SIG)[0] = 0.0f;
reg_[R_SIG].used = 4;
/* The prompt through the second tokenizer, for a model that reads it. */
const int64_t n_aux = decl_.aux_tokens ? (int64_t)br.aux.size() : 0;
if (n_aux) {
int32_t* ax = hptr<int32_t>(R_AUX);
ax[0] = 0;
ax[1] = (int32_t)n_aux;
std::memcpy(ax + 2, br.aux.data(), (size_t)n_aux * 4);
reg_[R_AUX].used = (n_aux + 2) * 4;
}
/* Host-side arrays the plugin reads (segment kinds, pixel blocks, lanes), owned by the driver
* for the life of the pass. */
host_bidi_ = c.lay.bidi;
@@ -758,6 +812,10 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
G.n_lane = (int64_t)host_lanes_.size();
G.lane_h = host_lanes_.data();
G.lane = G.n_lane ? dptr<int32_t>(ri, R_LANE) : nullptr;
G.n_aux = n_aux;
G.aux_cu = n_aux ? dptr<int32_t>(ri, R_AUX) : nullptr;
G.aux_ids = n_aux ? dptr<int32_t>(ri, R_AUX) + 2 : nullptr;
G.tokens_h = hptr<int32_t>(R_TOK);
if (joint()) {
B.n_kv_groups = 0;
B.kv = nullptr;
@@ -771,6 +829,7 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
}
pass_.kind = RAD_GEN_PASS_COND;
pass_.job = j.id;
pass_.lora_slot = j.req->lora_slot;
pass_.branch = branch;
return &out_[0];
}
@@ -821,6 +880,12 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
uint32_t* seed = hptr<uint32_t>(R_SEED);
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
float* sigp = hptr<float>(R_SIGP);
float* tstep = hptr<float>(R_TSTEP);
int32_t* samp = hptr<int32_t>(R_SAMP);
int32_t* stepi = hptr<int32_t>(R_STEPI);
float* size = hptr<float>(R_SIZE);
host_entry_.assign((size_t)(4 * S), 0);
int64_t row = 0;
cu[0] = 0;
pass_.lanes.clear();
@@ -866,6 +931,16 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
cu[i + 1] = (int32_t)row;
sig[i] = j.sigmas[(size_t)ln.step];
sign[i] = j.sigmas[(size_t)ln.step + 1];
sigp[i] = ln.step > 0 ? j.sigmas[(size_t)ln.step - 1] : 0.0f;
tstep[i] = discrete() ? j.tsteps[(size_t)ln.step] : 0.0f;
samp[i] = j.req->sampler;
stepi[i] = ln.step;
size[2 * i] = (float)j.req->height;
size[2 * i + 1] = (float)j.req->width;
host_entry_[(size_t)(4 * i)] = joint() ? (int32_t)c.lay.rows : 0;
host_entry_[(size_t)(4 * i + 1)] = j.req->height;
host_entry_[(size_t)(4 * i + 2)] = j.req->width;
host_entry_[(size_t)(4 * i + 3)] = e.branch;
const bool neg = e.branch == 1;
cfg[i] = neg ? 0.0f : (j.n_branch > 1 ? j.req->cfg : 1.0f);
pair[i] = neg ? -2 : (j.n_branch > 1 ? (int32_t)(i + 1) : -1);
@@ -930,6 +1005,8 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
reg_[R_GROPE].used = 3 * n_tok * 4;
}
reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4;
reg_[R_SIGP].used = reg_[R_TSTEP].used = reg_[R_SAMP].used = reg_[R_STEPI].used = S * 4;
reg_[R_SIZE].used = 2 * S * 4;
reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4;
reg_[R_SEED].used = 2 * S * 4;
reg_[R_BT].used = joint() ? 0 : S * pitch * 4;
@@ -954,6 +1031,12 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
G.lane_h = nullptr;
G.rope = joint() ? nullptr : dptr<int32_t>(ri, R_GROPE);
G.lane_dh = hptr<int32_t>(R_LANE);
G.sigma_prev = dptr<float>(ri, R_SIGP);
G.timestep = dptr<float>(ri, R_TSTEP);
G.sampler = dptr<int32_t>(ri, R_SAMP);
G.step = dptr<int32_t>(ri, R_STEPI);
G.size_px = dptr<float>(ri, R_SIZE);
G.entry_h = host_entry_.data();
if (joint()) {
G.src = dptr<int32_t>(ri, R_SRC);
G.n_img = n_img;
+11 -1
View File
@@ -60,6 +60,7 @@ public:
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
int32_t lora_slot() const override { return pass_.lora_slot; }
/* A decode pass's pixels: `image_out` into the pinned image buffer. */
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
@@ -85,6 +86,8 @@ private:
int32_t h_lat = 0, w_lat = 0;
int64_t tokens = 0;
std::vector<float> sigmas;
/* A discrete-time model's: each step's timestep, beside `sigmas`. */
std::vector<float> tsteps;
std::vector<int32_t> lanes;
std::vector<std::pair<int32_t, int32_t>> ref_hw;
int32_t images_done = 0;
@@ -112,13 +115,15 @@ private:
bool preview = false;
std::vector<int32_t> lanes; /* DENOISE: the lanes it stepped, one per image */
std::vector<char> marks; /* ... and whether each was marked for a preview */
int32_t lora_slot = -1; /* every image of a pass runs with the same adapters */
};
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE,
R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED,
R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE, R_N };
R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE,
R_AUX, R_SIGP, R_TSTEP, R_SAMP, R_STEPI, R_SIZE, R_N };
int layout_regions();
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
@@ -147,6 +152,9 @@ private:
RadGeneratorDecl decl_{};
std::vector<double> fixed_;
/* A discrete-time model's sigma table (RadGeneratorDecl::train_steps), empty otherwise. */
DiscreteTable table_;
bool discrete() const { return decl_.train_steps > 0; }
int64_t max_tok_ = 0, max_seqs_ = 0, max_enc_ = 0, patch_dim_ = 0;
int64_t max_rows_ = 0; /* the longest conditioning sequence */
int64_t max_px_ = 0; /* pixels the staging holds */
@@ -170,6 +178,8 @@ private:
Pass pass_;
/* Host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */
std::vector<int32_t> host_bidi_, host_px_, host_lanes_;
/* A DENOISE pass's per-entry host array (RadGenBatch::entry_h). */
std::vector<int32_t> host_entry_;
int64_t host_nmode_[3] = { 0, 0, 0 };
mutable std::mutex mu_;
+131
View File
@@ -67,6 +67,16 @@ std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>
std::vector<float> s;
if (!fixed.empty()) {
for (double v : fixed) s.push_back((float)v);
} else if (d.sigma_grid > 0) {
/* ComfyUI's `simple` scheduler: the model's table holds t = k / N for k = 1..N (an f32
* quotient), and step i reads entry N - 1 - floor(i N / n), the floor of a Python float. */
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
const int64_t N = d.sigma_grid;
const double ss = (double)N / (double)n;
for (int32_t i = 0; i < n; ++i) {
const int64_t k = N - (int64_t)((double)i * ss);
s.push_back((float)k / (float)N);
}
} else {
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
/* np.linspace(1.0, 1 / n, n) in f64, then astype(f32). */
@@ -94,6 +104,127 @@ std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>
return s;
}
/* ================================================================== a discrete-time schedule */
float DiscreteTable::sigma_at(double t) const {
const double hi = (double)(log_sigmas.size() - 1);
t = t < 0.0 ? 0.0 : t > hi ? hi : t;
const size_t lo = (size_t)std::floor(t), up = (size_t)std::ceil(t);
const float w = (float)(t - std::floor(t));
return std::exp((1.0f - w) * log_sigmas[lo] + w * log_sigmas[up]);
}
int32_t DiscreteTable::timestep(float sigma) const {
const float l = std::log(sigma);
int32_t best = 0;
float bd = std::fabs(l - log_sigmas[0]);
for (size_t i = 1; i < log_sigmas.size(); ++i) {
const float d = std::fabs(l - log_sigmas[i]);
if (d < bd) { bd = d; best = (int32_t)i; }
}
return best;
}
int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why) {
const int32_t n = d.train_steps;
if (n < 2 || !(d.beta_start > 0) || !(d.beta_end > d.beta_start) || d.beta_end >= 1 ||
(d.beta_schedule != RAD_GEN_BETAS_SCALED_LINEAR && d.beta_schedule != RAD_GEN_BETAS_LINEAR)) {
if (why) *why = "the discrete schedule needs two or more timesteps and betas rising in (0, 1)";
return RAD_E_INVAL;
}
std::vector<double> sig((size_t)n);
double abar = 1.0;
const bool sq = d.beta_schedule == RAD_GEN_BETAS_SCALED_LINEAR;
const double a = sq ? std::sqrt(d.beta_start) : d.beta_start;
const double b = sq ? std::sqrt(d.beta_end) : d.beta_end;
for (int32_t i = 0; i < n; ++i) {
const double v = a + (b - a) * (double)i / (double)(n - 1);
abar *= 1.0 - (sq ? v * v : v);
sig[(size_t)i] = std::sqrt((1.0 - abar) / abar);
}
if (d.zero_snr) {
/* ComfyUI's rescale_zero_terminal_snr_sigmas: sqrt(abar) shifted to end at 0 and scaled
* to keep its start, the last abar then set to a small positive value. */
std::vector<double> s((size_t)n);
for (int32_t i = 0; i < n; ++i) s[(size_t)i] = std::sqrt(1.0 / (sig[(size_t)i] * sig[(size_t)i] + 1.0));
const double s0 = s.front(), sT = s.back();
for (int32_t i = 0; i < n; ++i) {
double v = (s[(size_t)i] - sT) * (s0 / (s0 - sT));
double ab = v * v;
if (i == n - 1) ab = 4.8973451890853435e-08;
sig[(size_t)i] = std::sqrt((1.0 - ab) / ab);
}
}
out->sigmas.resize((size_t)n);
out->log_sigmas.resize((size_t)n);
for (int32_t i = 0; i < n; ++i) {
out->sigmas[(size_t)i] = (float)sig[(size_t)i];
out->log_sigmas[(size_t)i] = (float)std::log(sig[(size_t)i]);
}
return RAD_OK;
}
std::vector<float> schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t,
int32_t scheduler, int32_t steps) {
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
std::vector<float> s;
const double smin = t.sigma_min(), smax = t.sigma_max();
/* A point i of n evenly spaced from `a` to `b`, both ends included. */
auto lin = [](double a, double b, int32_t i, int32_t cnt) {
return cnt <= 1 ? a : a + (b - a) * (double)i / (double)(cnt - 1);
};
switch (scheduler) {
case RAD_GEN_SCHED_KARRAS: {
const double rho = 7.0, lo = std::pow(smin, 1.0 / rho), hi = std::pow(smax, 1.0 / rho);
for (int32_t i = 0; i < n; ++i) s.push_back((float)std::pow(lin(hi, lo, i, n), rho));
break;
}
case RAD_GEN_SCHED_EXPONENTIAL:
for (int32_t i = 0; i < n; ++i)
s.push_back((float)std::exp(lin(std::log(smax), std::log(smin), i, n)));
break;
case RAD_GEN_SCHED_SIMPLE: {
const double stride = (double)t.sigmas.size() / (double)n;
for (int32_t i = 0; i < n; ++i)
s.push_back(t.sigmas[t.sigmas.size() - 1 - (size_t)((double)i * stride)]);
break;
}
case RAD_GEN_SCHED_SGM_UNIFORM:
case RAD_GEN_SCHED_NORMAL:
default: {
/* Timesteps from the largest sigma's to the smallest's, evenly spaced; sgm_uniform
* spaces n + 1 and drops the last. The model's clock ends at 0. */
const double a = (double)t.timestep(t.sigma_max()), b = (double)t.timestep(t.sigma_min());
const bool sgm = scheduler == RAD_GEN_SCHED_SGM_UNIFORM;
const int32_t cnt = sgm ? n + 1 : n;
for (int32_t i = 0; i < n; ++i) s.push_back(t.sigma_at(lin(a, b, i, cnt)));
break;
}
}
s.push_back(0.0f);
return s;
}
namespace {
const char* const kSamplers[RAD_GEN_SAMPLER_COUNT] = { "euler", "euler_ancestral", "dpmpp_2m" };
const char* const kScheds[RAD_GEN_SCHED_COUNT] = { "normal", "karras", "exponential",
"sgm_uniform", "simple" };
} /* namespace */
const char* sampler_name(int32_t id) {
return id >= 0 && id < RAD_GEN_SAMPLER_COUNT ? kSamplers[id] : "";
}
const char* scheduler_name(int32_t id) {
return id >= 0 && id < RAD_GEN_SCHED_COUNT ? kScheds[id] : "";
}
int32_t sampler_id(const std::string& name) {
for (int32_t i = 0; i < RAD_GEN_SAMPLER_COUNT; ++i) if (name == kSamplers[i]) return i;
return -1;
}
int32_t scheduler_id(const std::string& name) {
for (int32_t i = 0; i < RAD_GEN_SCHED_COUNT; ++i) if (name == kScheds[i]) return i;
return -1;
}
/* ================================================================== the sequence */
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total) {
const int32_t h0 = -(h - h / 2), w0 = -(w - w / 2);
+34
View File
@@ -48,6 +48,9 @@ struct Branch {
std::vector<int32_t> tokens;
std::shared_ptr<mm::PromptMedia> media; /* null for a prompt with no pictures */
int32_t n_drop = 0;
/* The user's prompt through the model's second tokenizer (RadGeneratorDecl::aux_tokens);
* empty otherwise. */
std::vector<int32_t> aux;
};
/* One finished image, or a preview of one. */
@@ -99,6 +102,8 @@ struct Request {
float cfg = 1.0f;
int32_t width = 0, height = 0; /* pixels, whole multiples of the declared multiple */
int32_t steps = 0; /* 0: the model's default (or its fixed schedule) */
/* A discrete-time model's sampler and scheduler (RAD_GEN_SAMPLER_*, RAD_GEN_SCHED_*). */
int32_t sampler = 0, scheduler = 0;
int32_t n = 1;
uint64_t seed = 0; /* image i draws its noise from seed + i */
int32_t previews = 0; /* partial images per image, 0..3 */
@@ -109,6 +114,10 @@ struct Request {
bool inpaint = false;
Pixels inp_src;
std::vector<float> inp_mask;
/* The runtime LoRA slot every pass of the request runs with (Engine::gen_lora_acquire), -1
* for none, and the hold that keeps the slot's adapters in it until the request is done. */
int32_t lora_slot = -1;
std::shared_ptr<void> lora_hold;
std::shared_ptr<Ticket> ticket;
};
@@ -119,6 +128,31 @@ struct Request {
std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>& fixed,
int32_t steps, int64_t tokens);
/* ================================================================== a discrete-time schedule */
/* The sigma table of a model trained on discrete timesteps (RadGeneratorDecl::train_steps), as
* ComfyUI's ModelSamplingDiscrete builds it: betas in f64, their cumulative product, sigma_t =
* sqrt((1 - abar_t) / abar_t), then f32, and the f32 logs. */
struct DiscreteTable {
std::vector<float> sigmas; /* [train_steps], ascending: sigmas[t] is timestep t's */
std::vector<float> log_sigmas;
float sigma_min() const { return sigmas.front(); }
float sigma_max() const { return sigmas.back(); }
/* sigma at a fractional timestep: the logs interpolated linearly, t clamped to the table. */
float sigma_at(double t) const;
/* The timestep a sigma is conditioned at: the table's nearest in log sigma. */
int32_t timestep(float sigma) const;
};
/* RAD_E_INVAL with `why` for a declaration whose schedule cannot be built. */
int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why);
/* The n + 1 sigmas `scheduler` places for `steps` (0: the default) steps, the last 0. */
std::vector<float> schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t,
int32_t scheduler, int32_t steps);
/* The names a request spells samplers and schedulers by, and their ids (-1: none). */
const char* sampler_name(int32_t id);
const char* scheduler_name(int32_t id);
int32_t sampler_id(const std::string& name);
int32_t scheduler_id(const std::string& name);
/* ================================================================== the generator's sequence */
/* One conditioning sequence as the generator sees it (RadGeneratorDecl::layout): the prompt row or
* reference latent row behind each row, rotary positions, segments, and the output image's frame. */
+2
View File
@@ -29,6 +29,8 @@ struct IPassDriver {
* `step` is the engine's pass counter, carried into RadBatch::step. */
virtual const RadBatch* next(int step) = 0;
virtual const RadBatch* batch_for(int rank) const = 0;
/* The runtime LoRA slot every row of the staged pass runs with, -1 for none. */
virtual int32_t lora_slot() const { return -1; }
/* What the staged pass's results are, valid until done(). */
virtual const std::vector<Readback>& readbacks() const = 0;
/* The pass has run on every rank, its streams are drained and the readbacks have landed. */
+5
View File
@@ -95,6 +95,11 @@ struct VideoRequest {
std::vector<uint8_t> image;
/* The decoder (RadVideoGenDecl::decoders) by its index; 0 the model's default. */
int32_t decoder = 0;
/* The runtime LoRA slot the request's conditioning and denoising passes run with
* (Engine::gen_lora_acquire), -1 for none, and the hold that keeps it until the request is
* done. */
int32_t lora_slot = -1;
std::shared_ptr<void> lora_hold;
std::shared_ptr<VideoTicket> ticket;
};
+2
View File
@@ -809,6 +809,7 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
if (j.auto_len) rb_.assign(1, Readback{ decl_.duration_out, 4, duration_host_ });
pass_.kind = RAD_GEN_PASS_VCOND;
pass_.job = j.id;
pass_.lora_slot = j.req->lora_slot;
return &out_[0];
}
@@ -858,6 +859,7 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) {
for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP;
pass_.kind = RAD_GEN_PASS_VSTEP;
pass_.job = j.id;
pass_.lora_slot = j.req->lora_slot;
return &out_[0];
}
+2
View File
@@ -53,6 +53,7 @@ public:
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
int32_t lora_slot() const override { return pass_.lora_slot; }
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
@@ -99,6 +100,7 @@ private:
int kind = 0;
uint64_t job = 0;
int32_t n_frames = 0;
int32_t lora_slot = -1;
};
/* Staging regions: their offsets in the host span and every rank's slab. */
+986
View File
@@ -0,0 +1,986 @@
/* lora/adapter.cpp -- see adapter.h. Host code only. */
#include "adapter.h"
#include "rad_plugin.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <map>
#include <regex>
#include <thread>
#include <unordered_map>
namespace rad {
namespace lora {
namespace {
#define TRY(x) do { const int s_ = (x); if (s_ < 0) return s_; } while (0)
std::string fmt(const char* f, ...) __attribute__((format(printf, 1, 2)));
std::string fmt(const char* f, ...) {
char buf[2048];
va_list ap;
va_start(ap, f);
vsnprintf(buf, sizeof buf, f, ap);
va_end(ap);
return buf;
}
int fail(std::string* err, int code, const std::string& m) {
if (err) *err = m;
return code;
}
bool ends_with(const std::string& s, const char* p) {
const size_t n = std::strlen(p);
return s.size() >= n && s.compare(s.size() - n, n, p) == 0;
}
std::string shape_str(const std::vector<int64_t>& s) {
std::string r = "[";
for (size_t i = 0; i < s.size(); ++i) r += (i ? ", " : "") + std::to_string(s[i]);
return r + "]";
}
/* ---------------------------------------------------------------- tensors as f32 */
bool float_dtype(uint32_t dt) { return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; }
float elem(const StTensor& t, int64_t i) {
switch (t.dtype) {
case RAD_BF16: { uint16_t v; std::memcpy(&v, t.data + 2 * i, 2); return rad_bf16_to_f32(v); }
case RAD_F16: { uint16_t v; std::memcpy(&v, t.data + 2 * i, 2); return rad_f16_to_f32(v); }
default: { float v; std::memcpy(&v, t.data + 4 * i, 4); return v; }
}
}
/* A tensor as a row-major matrix [shape[0], product of the rest]. */
int as_matrix(const StTensor* t, const char* what, int64_t* rows, int64_t* cols,
std::vector<float>* out, std::string* err) {
if (!t) return fail(err, RAD_E_FORMAT, fmt("no %s tensor", what));
if (!float_dtype(t->dtype))
return fail(err, RAD_E_DTYPE, fmt("%s is %s; expected BF16, F16 or F32", t->name.c_str(),
t->dtype_str.c_str()));
if (t->shape.size() < 2 || !t->data)
return fail(err, RAD_E_SHAPE, fmt("%s has shape %s; expected a matrix", t->name.c_str(),
shape_str(t->shape).c_str()));
*rows = t->shape[0];
*cols = t->numel() / (t->shape[0] ? t->shape[0] : 1);
if (out) {
out->resize((size_t)(*rows * *cols));
for (int64_t i = 0; i < *rows * *cols; ++i) (*out)[(size_t)i] = elem(*t, i);
}
return RAD_OK;
}
/* The trailing dims past the first two, all 1 (an up projection of a convolution is 1 x 1). */
bool trailing_ones(const StTensor* t) {
for (size_t i = 2; i < t->shape.size(); ++i) if (t->shape[i] != 1) return false;
return true;
}
/* One number: shape [] (numel() counts it as no element) or [1], a float or (as some trainers
* write an alpha) an integer or F64. */
int scalar(const StTensor* t, double* v, std::string* err) {
const int64_t n = t->shape.empty() ? 1 : t->numel();
if (n != 1 || !t->data)
return fail(err, RAD_E_FORMAT, fmt("%s is not one number", t->name.c_str()));
if (float_dtype(t->dtype)) {
*v = elem(*t, 0);
} else if (t->dtype == RAD_I64 && t->bytes >= 8) {
int64_t x; std::memcpy(&x, t->data, 8); *v = (double)x;
} else if (t->dtype == RAD_I32 && t->bytes >= 4) {
int32_t x; std::memcpy(&x, t->data, 4); *v = (double)x;
} else if (t->dtype_str == "F64" && t->bytes >= 8) {
std::memcpy(v, t->data, 8);
} else {
return fail(err, RAD_E_FORMAT, fmt("%s is %s, not a number this reader knows",
t->name.c_str(), t->dtype_str.c_str()));
}
return std::isfinite(*v) ? RAD_OK : fail(err, RAD_E_FORMAT, t->name + " is not finite");
}
/* ---------------------------------------------------------------- dense f32 kernels */
/* C[m, n] (+)= A[m, k] B[k, n], row-major. */
void mm(const float* A, const float* B, float* C, int64_t m, int64_t k, int64_t n, bool add = false) {
if (!add) std::fill(C, C + m * n, 0.0f);
for (int64_t i = 0; i < m; ++i) {
float* c = C + i * n;
for (int64_t p = 0; p < k; ++p) {
const float a = A[i * k + p];
if (a == 0.0f) continue;
const float* b = B + p * n;
for (int64_t j = 0; j < n; ++j) c[j] += a * b[j];
}
}
}
/* C[m, n] (+)= A[k, m]^T B[k, n]. */
void mm_tn(const float* A, const float* B, float* C, int64_t m, int64_t k, int64_t n, bool add = false) {
if (!add) std::fill(C, C + m * n, 0.0f);
for (int64_t p = 0; p < k; ++p) {
const float* a = A + p * m;
const float* b = B + p * n;
for (int64_t i = 0; i < m; ++i) {
const float x = a[i];
if (x == 0.0f) continue;
float* c = C + i * n;
for (int64_t j = 0; j < n; ++j) c[j] += x * b[j];
}
}
}
/* Orthonormalise the l columns of Y [n, l] in place (modified Gram-Schmidt, twice). A column
* that vanishes is left zero. */
void orth(float* Y, int64_t n, int64_t l) {
std::vector<double> col((size_t)n);
for (int64_t j = 0; j < l; ++j) {
for (int pass = 0; pass < 2; ++pass)
for (int64_t i = 0; i < j; ++i) {
double d = 0.0;
for (int64_t r = 0; r < n; ++r) d += (double)Y[r * l + i] * Y[r * l + j];
for (int64_t r = 0; r < n; ++r) Y[r * l + j] -= (float)(d * Y[r * l + i]);
}
double nn = 0.0;
for (int64_t r = 0; r < n; ++r) nn += (double)Y[r * l + j] * Y[r * l + j];
const double inv = nn > 1e-30 ? 1.0 / std::sqrt(nn) : 0.0;
for (int64_t r = 0; r < n; ++r) Y[r * l + j] = (float)(Y[r * l + j] * inv);
}
}
/* Eigen-decomposition of a symmetric l x l matrix (cyclic Jacobi): eigenvalues in `w`, sorted
* descending, and eigenvectors as the columns of V [l, l]. */
void sym_eig(std::vector<double> G, int64_t l, std::vector<double>* w, std::vector<double>* V) {
V->assign((size_t)(l * l), 0.0);
for (int64_t i = 0; i < l; ++i) (*V)[(size_t)(i * l + i)] = 1.0;
for (int sweep = 0; sweep < 60; ++sweep) {
double off = 0.0, tot = 0.0;
for (int64_t i = 0; i < l; ++i)
for (int64_t j = 0; j < l; ++j) {
const double g = G[(size_t)(i * l + j)];
tot += g * g;
if (i != j) off += g * g;
}
if (off <= 1e-24 * (tot > 0 ? tot : 1.0)) break;
for (int64_t p = 0; p < l; ++p)
for (int64_t q = p + 1; q < l; ++q) {
const double gpq = G[(size_t)(p * l + q)];
if (std::fabs(gpq) < 1e-300) continue;
const double gpp = G[(size_t)(p * l + p)], gqq = G[(size_t)(q * l + q)];
const double th = (gqq - gpp) / (2.0 * gpq);
const double t = (th >= 0 ? 1.0 : -1.0) / (std::fabs(th) + std::sqrt(th * th + 1.0));
const double c = 1.0 / std::sqrt(t * t + 1.0), s = t * c;
for (int64_t k = 0; k < l; ++k) {
const double gkp = G[(size_t)(k * l + p)], gkq = G[(size_t)(k * l + q)];
G[(size_t)(k * l + p)] = c * gkp - s * gkq;
G[(size_t)(k * l + q)] = s * gkp + c * gkq;
}
for (int64_t k = 0; k < l; ++k) {
const double gpk = G[(size_t)(p * l + k)], gqk = G[(size_t)(q * l + k)];
G[(size_t)(p * l + k)] = c * gpk - s * gqk;
G[(size_t)(q * l + k)] = s * gpk + c * gqk;
}
for (int64_t k = 0; k < l; ++k) {
const double vkp = (*V)[(size_t)(k * l + p)], vkq = (*V)[(size_t)(k * l + q)];
(*V)[(size_t)(k * l + p)] = c * vkp - s * vkq;
(*V)[(size_t)(k * l + q)] = s * vkp + c * vkq;
}
}
}
std::vector<int64_t> ord((size_t)l);
for (int64_t i = 0; i < l; ++i) ord[(size_t)i] = i;
std::sort(ord.begin(), ord.end(), [&](int64_t a, int64_t b) {
return G[(size_t)(a * l + a)] > G[(size_t)(b * l + b)];
});
std::vector<double> V2((size_t)(l * l));
w->resize((size_t)l);
for (int64_t c = 0; c < l; ++c) {
(*w)[(size_t)c] = G[(size_t)(ord[(size_t)c] * l + ord[(size_t)c])];
for (int64_t r = 0; r < l; ++r) V2[(size_t)(r * l + c)] = (*V)[(size_t)(r * l + ord[(size_t)c])];
}
*V = std::move(V2);
}
/* ||B A||_F^2 for B [n, r], A [r, k]: trace((B^T B)(A A^T)). */
double lowrank_energy(const std::vector<float>& B, const std::vector<float>& A, int64_t n, int64_t r,
int64_t k) {
std::vector<double> bb((size_t)(r * r), 0.0), aa((size_t)(r * r), 0.0);
for (int64_t i = 0; i < n; ++i)
for (int64_t p = 0; p < r; ++p) {
const double x = B[(size_t)(i * r + p)];
if (x == 0.0) continue;
for (int64_t q = 0; q < r; ++q) bb[(size_t)(p * r + q)] += x * B[(size_t)(i * r + q)];
}
for (int64_t p = 0; p < r; ++p)
for (int64_t q = p; q < r; ++q) {
double d = 0.0;
for (int64_t j = 0; j < k; ++j) d += (double)A[(size_t)(p * k + j)] * A[(size_t)(q * k + j)];
aa[(size_t)(p * r + q)] = aa[(size_t)(q * r + p)] = d;
}
double e = 0.0;
for (size_t i = 0; i < bb.size(); ++i) e += bb[i] * aa[i];
return e;
}
/* ---------------------------------------------------------------- the key suffixes */
struct Suffix {
const char* s;
int kind; /* FileModule::Kind, or -1 alpha, -2 refused, -3 skipped */
int slot;
const char* why;
};
const Suffix kSuffix[] = {
{ ".lora_down.weight", FileModule::LORA, 0, nullptr },
{ ".lora_up.weight", FileModule::LORA, 1, nullptr },
{ ".lora_A.default.weight", FileModule::LORA, 0, nullptr },
{ ".lora_B.default.weight", FileModule::LORA, 1, nullptr },
{ ".lora_A.weight", FileModule::LORA, 0, nullptr },
{ ".lora_B.weight", FileModule::LORA, 1, nullptr },
{ ".lora_linear_layer.down.weight", FileModule::LORA, 0, nullptr },
{ ".lora_linear_layer.up.weight", FileModule::LORA, 1, nullptr },
{ ".lora.down.weight", FileModule::LORA, 0, nullptr },
{ ".lora.up.weight", FileModule::LORA, 1, nullptr },
{ ".hada_w1_a", FileModule::LOHA, 0, nullptr },
{ ".hada_w1_b", FileModule::LOHA, 1, nullptr },
{ ".hada_w2_a", FileModule::LOHA, 2, nullptr },
{ ".hada_w2_b", FileModule::LOHA, 3, nullptr },
{ ".lokr_w1", FileModule::LOKR, 0, nullptr },
{ ".lokr_w1_a", FileModule::LOKR, 1, nullptr },
{ ".lokr_w1_b", FileModule::LOKR, 2, nullptr },
{ ".lokr_w2", FileModule::LOKR, 3, nullptr },
{ ".lokr_w2_a", FileModule::LOKR, 4, nullptr },
{ ".lokr_w2_b", FileModule::LOKR, 5, nullptr },
{ ".diff", FileModule::FULL, 0, nullptr },
{ ".alpha", -1, 0, nullptr },
{ ".lora_alpha", -1, 0, nullptr },
{ ".dora_scale", -2, 0, "a DoRA magnitude, which rescales the base weight's columns" },
{ ".lora_magnitude_vector.default.weight", -2, 0, "a DoRA magnitude, which rescales the base "
"weight's columns" },
{ ".lora_magnitude_vector.weight", -2, 0, "a DoRA magnitude, which rescales the base weight's "
"columns" },
{ ".lora_magnitude_vector", -2, 0, "a DoRA magnitude, which rescales the base weight's columns" },
{ ".hada_t1", -2, 0, "a LoHa Tucker core" },
{ ".hada_t2", -2, 0, "a LoHa Tucker core" },
{ ".lokr_t2", -2, 0, "a LoKr Tucker core" },
{ ".lora_mid.weight", -2, 0, "a LoCon Tucker core" },
{ ".oft_blocks", -2, 0, "an OFT rotation" },
{ ".oft_diag", -2, 0, "an OFT rotation" },
{ ".oft_R.weight", -2, 0, "an OFT rotation" },
{ ".boft_R", -2, 0, "a BOFT rotation" },
{ ".diff_b", -3, 0, "a bias delta" },
{ ".w_norm", -3, 0, "a norm's weight delta" },
{ ".b_norm", -3, 0, "a norm's bias delta" },
{ ".lora_B.bias", -3, 0, "a bias on lora_B" },
{ ".lora_up.bias", -3, 0, "a bias on lora_up" },
{ ".set_weight", -2, 0, "a replacement weight" },
};
} /* namespace */
/* ================================================================== the file */
int AdapterFile::open(const std::string& path, std::string* err) {
mods_.clear();
skipped_.clear();
if (st_.open(path) != RAD_OK) return fail(err, RAD_E_IO, path + ": cannot open as safetensors");
std::map<std::string, FileModule> by;
std::map<std::string, const StTensor*> alphas;
for (const StTensor& t : st_.tensors()) {
const Suffix* hit = nullptr;
for (const Suffix& s : kSuffix)
if (ends_with(t.name, s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s;
if (!hit) {
skipped_.push_back({ t.name, "not an adapter tensor" });
continue;
}
const std::string key = t.name.substr(0, t.name.size() - std::strlen(hit->s));
if (hit->kind == -2)
return fail(err, RAD_E_UNSUPPORTED, fmt("%s: %s is %s; that kind of adapter is not "
"served", path.c_str(), t.name.c_str(), hit->why));
if (hit->kind == -3) { skipped_.push_back({ t.name, hit->why }); continue; }
if (hit->kind == -1) { alphas[key] = &t; continue; }
FileModule& m = by[key];
if (m.key.empty()) { m.key = key; m.kind = (FileModule::Kind)hit->kind; }
else if (m.kind != hit->kind)
return fail(err, RAD_E_FORMAT, fmt("%s: module %s mixes adapter kinds", path.c_str(),
key.c_str()));
if (m.t[hit->slot])
return fail(err, RAD_E_FORMAT, fmt("%s: module %s has two %s tensors", path.c_str(),
key.c_str(), hit->s));
m.t[hit->slot] = &t;
}
for (auto& [k, a] : alphas) {
auto it = by.find(k);
if (it == by.end()) { skipped_.push_back({ a->name, "an alpha of no module" }); continue; }
it->second.alpha = a;
}
for (auto& [k, m] : by) {
const char* missing = nullptr;
switch (m.kind) {
case FileModule::LORA:
if (!m.t[0] || !m.t[1]) missing = m.t[0] ? "up/B" : "down/A";
break;
case FileModule::LOHA:
if (!m.t[0] || !m.t[1] || !m.t[2] || !m.t[3]) missing = "a hada_w factor";
break;
case FileModule::LOKR:
if (!m.t[0] && !(m.t[1] && m.t[2])) missing = "lokr_w1 (or lokr_w1_a and _b)";
else if (!m.t[3] && !(m.t[4] && m.t[5])) missing = "lokr_w2 (or lokr_w2_a and _b)";
break;
case FileModule::FULL: break;
}
if (missing)
return fail(err, RAD_E_FORMAT, fmt("%s: module %s has no %s", path.c_str(), k.c_str(),
missing));
mods_.push_back(m);
}
if (mods_.empty()) return fail(err, RAD_E_FORMAT, path + ": no adapter modules in the file");
return RAD_OK;
}
const char* AdapterFile::kind_name() const {
int n[4] = { 0, 0, 0, 0 };
for (const FileModule& m : mods_) ++n[m.kind];
const int k = (int)(std::max_element(n, n + 4) - n);
static const char* const kName[] = { "LoRA", "LoHa", "LoKr", "full" };
return kName[k];
}
/* ================================================================== deltas */
int module_delta(const FileModule& m, double w, Delta* out, std::string* err) {
*out = Delta{};
double alpha = 0.0;
const bool has_alpha = m.alpha != nullptr;
if (has_alpha) TRY(scalar(m.alpha, &alpha, err));
if (m.kind == FileModule::LORA) {
int64_t r = 0, K = 0, N = 0, r2 = 0;
std::vector<float> A, B;
TRY(as_matrix(m.t[0], "down", &r, &K, &A, err));
TRY(as_matrix(m.t[1], "up", &N, &r2, &B, err));
if (!trailing_ones(m.t[1]) || r2 != r)
return fail(err, RAD_E_SHAPE, fmt("module %s: down %s and up %s are not one rank-%lld "
"pair", m.key.c_str(), shape_str(m.t[0]->shape).c_str(),
shape_str(m.t[1]->shape).c_str(), (long long)r));
const double s = w * (has_alpha && r > 0 ? alpha / (double)r : 1.0);
for (float& x : B) x = (float)(x * s);
out->N = N; out->K = K; out->r = r; out->rank_bound = r; out->low_rank = true;
out->A = std::move(A); out->B = std::move(B);
out->energy = lowrank_energy(out->B, out->A, N, r, K);
return RAD_OK;
}
if (m.kind == FileModule::LOHA) {
int64_t N1 = 0, r1 = 0, r1b = 0, K1 = 0, N2 = 0, r2 = 0, r2b = 0, K2 = 0;
std::vector<float> w1a, w1b, w2a, w2b;
TRY(as_matrix(m.t[0], "hada_w1_a", &N1, &r1, &w1a, err));
TRY(as_matrix(m.t[1], "hada_w1_b", &r1b, &K1, &w1b, err));
TRY(as_matrix(m.t[2], "hada_w2_a", &N2, &r2, &w2a, err));
TRY(as_matrix(m.t[3], "hada_w2_b", &r2b, &K2, &w2b, err));
if (r1 != r1b || r2 != r2b || N1 != N2 || K1 != K2)
return fail(err, RAD_E_SHAPE, fmt("module %s: LoHa factors %s %s %s %s do not pair",
m.key.c_str(), shape_str(m.t[0]->shape).c_str(),
shape_str(m.t[1]->shape).c_str(),
shape_str(m.t[2]->shape).c_str(),
shape_str(m.t[3]->shape).c_str()));
/* (w1a w1b) o (w2a w2b) = sum over (i, j) of (w1a[:, i] o w2a[:, j]) (w1b[i] o w2b[j]):
* exactly rank r1 r2. */
const double s = w * (has_alpha && r1 > 0 ? alpha / (double)r1 : 1.0);
const int64_t R = r1 * r2, N = N1, K = K1;
out->B.assign((size_t)(N * R), 0.0f);
out->A.assign((size_t)(R * K), 0.0f);
for (int64_t n = 0; n < N; ++n)
for (int64_t i = 0; i < r1; ++i)
for (int64_t j = 0; j < r2; ++j)
out->B[(size_t)(n * R + i * r2 + j)] =
(float)(s * w1a[(size_t)(n * r1 + i)] * w2a[(size_t)(n * r2 + j)]);
for (int64_t i = 0; i < r1; ++i)
for (int64_t j = 0; j < r2; ++j)
for (int64_t k = 0; k < K; ++k)
out->A[(size_t)((i * r2 + j) * K + k)] = w1b[(size_t)(i * K + k)] * w2b[(size_t)(j * K + k)];
out->N = N; out->K = K; out->r = R; out->rank_bound = R; out->low_rank = true;
out->energy = lowrank_energy(out->B, out->A, N, R, K);
return RAD_OK;
}
if (m.kind == FileModule::LOKR) {
/* kron(w1 [a, b], w2 [c, e]) is [a c, b e]: element (i1 c + i2, j1 e + j2) is
* w1[i1, j1] w2[i2, j2]. A convolution's w2 [c, d, kh, kw] flattens to e = d kh kw, which
* is the flattened kron of the 4-D tensors. */
int64_t a = 0, b = 0, dim = 0;
std::vector<float> W1;
if (m.t[0]) {
TRY(as_matrix(m.t[0], "lokr_w1", &a, &b, &W1, err));
} else {
int64_t r = 0, r2 = 0;
std::vector<float> x, y;
TRY(as_matrix(m.t[1], "lokr_w1_a", &a, &r, &x, err));
TRY(as_matrix(m.t[2], "lokr_w1_b", &r2, &b, &y, err));
if (r != r2) return fail(err, RAD_E_SHAPE, "module " + m.key + ": lokr_w1_a/_b ranks differ");
W1.resize((size_t)(a * b));
mm(x.data(), y.data(), W1.data(), a, r, b);
dim = r;
}
int64_t c = 0, e = 0, r2 = 0;
auto W2 = std::make_shared<std::vector<float>>();
auto W2a = std::make_shared<std::vector<float>>();
auto W2b = std::make_shared<std::vector<float>>();
if (m.t[3]) {
TRY(as_matrix(m.t[3], "lokr_w2", &c, &e, W2.get(), err));
} else {
int64_t rr = 0;
TRY(as_matrix(m.t[4], "lokr_w2_a", &c, &r2, W2a.get(), err));
TRY(as_matrix(m.t[5], "lokr_w2_b", &rr, &e, W2b.get(), err));
if (rr != r2) return fail(err, RAD_E_SHAPE, "module " + m.key + ": lokr_w2_a/_b ranks differ");
dim = r2;
}
const double s = w * (has_alpha && dim > 0 ? alpha / (double)dim : 1.0);
for (float& x : W1) x = (float)(x * s);
auto w1 = std::make_shared<std::vector<float>>(std::move(W1));
const int64_t N = a * c, K = b * e;
out->N = N; out->K = K;
out->rank_bound = std::min(a, b) * (r2 ? r2 : std::min(c, e));
const bool full2 = !W2->empty();
/* ||kron(w1, w2)|| = ||w1|| ||w2|| */
{
double e1 = 0.0;
for (float x : *w1) e1 += (double)x * x;
double e2 = 0.0;
if (full2) for (float x : *W2) e2 += (double)x * x;
else e2 = lowrank_energy(*W2a, *W2b, c, r2, e);
out->energy = e1 * e2;
}
/* Column x of X [K, l], as the matrix [b, e]: kron(w1, w2) x = w1 X w2^T, read as [a, c]. */
out->apply = [=](const float* X, int64_t l, float* Y) {
std::vector<float> xm((size_t)(b * e)), t((size_t)(b * c)), y((size_t)(a * c)), u;
for (int64_t col = 0; col < l; ++col) {
for (int64_t k = 0; k < K; ++k) xm[(size_t)k] = X[k * l + col];
if (full2) {
/* t[j1, i2] = sum_j2 xm[j1, j2] w2[i2, j2] */
for (int64_t j1 = 0; j1 < b; ++j1)
for (int64_t i2 = 0; i2 < c; ++i2) {
float d = 0.0f;
const float* xr = xm.data() + j1 * e;
const float* wr = W2->data() + i2 * e;
for (int64_t j2 = 0; j2 < e; ++j2) d += xr[j2] * wr[j2];
t[(size_t)(j1 * c + i2)] = d;
}
} else {
u.assign((size_t)(b * r2), 0.0f);
for (int64_t j1 = 0; j1 < b; ++j1)
for (int64_t p = 0; p < r2; ++p) {
float d = 0.0f;
const float* xr = xm.data() + j1 * e;
const float* wr = W2b->data() + p * e;
for (int64_t j2 = 0; j2 < e; ++j2) d += xr[j2] * wr[j2];
u[(size_t)(j1 * r2 + p)] = d;
}
for (int64_t j1 = 0; j1 < b; ++j1)
for (int64_t i2 = 0; i2 < c; ++i2) {
float d = 0.0f;
for (int64_t p = 0; p < r2; ++p) d += u[(size_t)(j1 * r2 + p)] * (*W2a)[(size_t)(i2 * r2 + p)];
t[(size_t)(j1 * c + i2)] = d;
}
}
mm(w1->data(), t.data(), y.data(), a, b, c);
for (int64_t n = 0; n < N; ++n) Y[n * l + col] = y[(size_t)n];
}
};
/* The transpose: kron(w1, w2)^T y = w1^T Y w2, Y the column as [a, c], read as [b, e]. */
out->apply_t = [=](const float* Yin, int64_t l, float* X) {
std::vector<float> ym((size_t)(a * c)), t((size_t)(b * c)), x((size_t)(b * e)), u;
for (int64_t col = 0; col < l; ++col) {
for (int64_t n = 0; n < N; ++n) ym[(size_t)n] = Yin[n * l + col];
mm_tn(w1->data(), ym.data(), t.data(), b, a, c); /* [b, c] */
if (full2) {
mm(t.data(), W2->data(), x.data(), b, c, e);
} else {
u.assign((size_t)(b * r2), 0.0f);
mm(t.data(), W2a->data(), u.data(), b, c, r2);
mm(u.data(), W2b->data(), x.data(), b, r2, e);
}
for (int64_t k = 0; k < K; ++k) X[k * l + col] = x[(size_t)k];
}
};
return RAD_OK;
}
/* FULL */
int64_t N = 0, K = 0;
auto D = std::make_shared<std::vector<float>>();
TRY(as_matrix(m.t[0], "diff", &N, &K, D.get(), err));
for (float& x : *D) x = (float)(x * w);
out->N = N; out->K = K; out->rank_bound = std::min(N, K);
out->energy = 0.0;
for (float x : *D) out->energy += (double)x * x;
out->apply = [D, N, K](const float* X, int64_t l, float* Y) { mm(D->data(), X, Y, N, K, l); };
out->apply_t = [D, N, K](const float* Yin, int64_t l, float* X) { mm_tn(D->data(), Yin, X, K, N, l); };
return RAD_OK;
}
void truncate(const Delta& d, int64_t r, std::vector<float>* B, std::vector<float>* A, double* kept) {
const int64_t N = d.N, K = d.K;
r = std::max<int64_t>(0, std::min({ r, N, K, d.rank_bound > 0 ? d.rank_bound : r }));
if (kept) *kept = 1.0;
if (d.low_rank && d.r <= r) { *B = d.B; *A = d.A; return; }
auto fwd = [&](const float* X, int64_t l, float* Y) {
if (!d.low_rank) { d.apply(X, l, Y); return; }
std::vector<float> t((size_t)(d.r * l));
mm(d.A.data(), X, t.data(), d.r, K, l);
mm(d.B.data(), t.data(), Y, N, d.r, l);
};
auto bwd = [&](const float* Y, int64_t l, float* X) {
if (!d.low_rank) { d.apply_t(Y, l, X); return; }
std::vector<float> t((size_t)(d.r * l));
mm_tn(d.B.data(), Y, t.data(), d.r, N, l);
mm_tn(d.A.data(), t.data(), X, K, d.r, l);
};
const int64_t l = std::min({ r + 8, N, K });
/* A fixed sketch: the same adapter composes to the same bytes on every rank and every load. */
std::vector<float> Om((size_t)(K * l));
uint64_t st = 0x2545F4914F6CDD1Dull ^ (uint64_t)(N * 1315423911ull + K);
for (float& x : Om) {
st ^= st << 13; st ^= st >> 7; st ^= st << 17;
x = (float)((double)(st >> 11) / (double)(1ull << 53) - 0.5);
}
std::vector<float> Y((size_t)(N * l)), Z((size_t)(K * l));
fwd(Om.data(), l, Y.data());
orth(Y.data(), N, l);
for (int it = 0; it < 2; ++it) {
bwd(Y.data(), l, Z.data());
orth(Z.data(), K, l);
fwd(Z.data(), l, Y.data());
orth(Y.data(), N, l);
}
/* C^T = D^T Q [K, l]; the SVD of C = Q^T D from the eigen-decomposition of C C^T. */
bwd(Y.data(), l, Z.data());
std::vector<double> G((size_t)(l * l), 0.0);
for (int64_t k = 0; k < K; ++k)
for (int64_t i = 0; i < l; ++i) {
const double x = Z[(size_t)(k * l + i)];
if (x == 0.0) continue;
for (int64_t j = i; j < l; ++j) G[(size_t)(i * l + j)] += x * Z[(size_t)(k * l + j)];
}
for (int64_t i = 0; i < l; ++i)
for (int64_t j = 0; j < i; ++j) G[(size_t)(i * l + j)] = G[(size_t)(j * l + i)];
std::vector<double> w, V;
sym_eig(G, l, &w, &V);
double tot = 0.0, top = 0.0;
for (int64_t i = 0; i < l; ++i) tot += std::max(0.0, w[(size_t)i]);
for (int64_t i = 0; i < r; ++i) top += std::max(0.0, w[(size_t)i]);
if (d.energy > 0.0) tot = std::max(tot, d.energy);
if (kept) *kept = tot > 0.0 ? std::min(1.0, top / tot) : 1.0;
B->assign((size_t)(N * r), 0.0f);
A->assign((size_t)(r * K), 0.0f);
for (int64_t i = 0; i < r; ++i) {
const double sg = std::sqrt(std::max(0.0, w[(size_t)i]));
if (sg <= 1e-20) continue;
/* B[:, i] = Q V[:, i] sigma_i; A[i] = V[:, i]^T C / sigma_i. */
for (int64_t n = 0; n < N; ++n) {
double acc = 0.0;
for (int64_t j = 0; j < l; ++j) acc += (double)Y[(size_t)(n * l + j)] * V[(size_t)(j * l + i)];
(*B)[(size_t)(n * r + i)] = (float)(acc * sg);
}
for (int64_t k = 0; k < K; ++k) {
double acc = 0.0;
for (int64_t j = 0; j < l; ++j) acc += V[(size_t)(j * l + i)] * Z[(size_t)(k * l + j)];
(*A)[(size_t)(i * K + k)] = (float)(acc / sg);
}
}
}
/* ================================================================== the key map */
namespace {
std::string underscored(std::string s) {
for (char& c : s) if (c == '.') c = '_';
return s;
}
std::regex pattern(const std::string& from, bool kohya) {
std::string re = "^";
for (char c : kohya ? underscored(from) : from) {
if (c == '#') re += "([0-9]+)";
else if (std::strchr(".^$|()[]{}*+?\\", c)) { re += '\\'; re += c; }
else re += c;
}
return std::regex(re + "$", std::regex::ECMAScript | std::regex::optimize);
}
std::string module_of(const std::string& src) {
return ends_with(src, ".weight") ? src.substr(0, src.size() - 7) : std::string();
}
} /* namespace */
KeyMap::KeyMap(const Program& prog, const std::vector<Site>& sites) : prog_(&prog) {
for (const Site& s : sites)
for (size_t i = 0; i < s.sources.size(); ++i) {
const SiteSource& src = s.sources[i];
if (!src.targeted) continue;
const size_t at = src.module.find('@');
if (at != std::string::npos) {
/* A row piece: the module stays adaptable, its rows open (the adapter's say). */
Piece p;
p.name = src.module;
p.lo = std::strtoll(src.module.c_str() + at + 1, nullptr, 10);
const size_t plus = src.module.find('+', at);
p.n = plus == std::string::npos ? 0 : std::strtoll(src.module.c_str() + plus + 1, nullptr, 10);
const std::string real = src.module.substr(0, at);
std::vector<Piece>& ps = pieces_[real];
bool dup = false;
for (const Piece& q : ps) dup = dup || q.name == p.name;
if (!dup) ps.push_back(p);
adaptable_[real] = { -1, s.K_full > 0 ? s.K_full : -1 };
continue;
}
whole_.insert(src.module);
int64_t rows = -1;
if (src.part_lo >= 0) {
rows = 0;
for (int g = src.part_lo; g < src.part_hi; ++g) {
const int64_t t = s.part_total[(size_t)g];
if (t <= 0) { rows = -1; break; }
rows += t;
}
} else if (s.sources.size() == 1 && s.part_total.size() == 1 && s.part_total[0] > 0) {
rows = s.part_total[0];
}
adaptable_[src.module] = { rows, s.K_full > 0 ? s.K_full : -1 };
}
for (const LoraRoot& r : prog.lora_roots) {
Root R;
R.native = r.native;
R.spellings = r.spellings;
R.spellings.push_back(r.native);
std::sort(R.spellings.begin(), R.spellings.end(),
[](const std::string& a, const std::string& b) { return a.size() > b.size(); });
R.spellings.erase(std::unique(R.spellings.begin(), R.spellings.end()), R.spellings.end());
roots_.push_back(std::move(R));
}
for (const RadNameMap& m : prog.name_map)
for (int k = 0; k < m.n_src && k < 8; ++k) {
if (!m.src[k]) continue;
const std::string mod = module_of(m.src[k]);
if (mod.empty()) continue;
for (Root& R : roots_) {
if (mod.compare(0, R.native.size(), R.native) != 0) continue;
if (!adaptable_.count(mod) && !known_.count(mod))
known_[mod] = "the base reads it with an op no adapter path follows (a fused "
"activation, a rotated input, or not a GEMM)";
const std::string u = underscored(mod.substr(R.native.size()));
auto it = R.kohya.find(u);
if (it == R.kohya.end()) R.kohya[u] = mod;
else if (it->second != mod) it->second.clear(); /* ambiguous */
}
}
for (const LoraAlias& a : prog.lora_aliases) {
for (size_t ri = 0; ri < roots_.size(); ++ri) {
if (roots_[ri].native != a.root) continue;
Alias x;
x.root = ri;
x.from = a.from; x.to = a.to;
x.from_lo = a.from_lo; x.from_hi = a.from_hi; x.to_lo = a.to_lo;
x.dotted = pattern(a.from, false);
x.kohya = pattern(a.from, true);
aliases_.push_back(std::move(x));
}
}
}
int64_t KeyMap::rows(const std::string& module) const {
auto it = adaptable_.find(module);
return it == adaptable_.end() ? -1 : it->second.first;
}
const std::vector<KeyMap::Piece>& KeyMap::pieces(const std::string& module) const {
static const std::vector<Piece> none;
auto it = pieces_.find(module);
return it == pieces_.end() ? none : it->second;
}
int64_t KeyMap::cols(const std::string& module) const {
auto it = adaptable_.find(module);
return it == adaptable_.end() ? -1 : it->second.second;
}
bool KeyMap::lookup(const Root& r, const std::string& rel, bool kohya, std::vector<Target>* out,
std::string* why) const {
auto take = [&](const std::string& mod, int64_t lo, int64_t hi, int64_t to) {
if (adaptable_.count(mod)) {
Target t;
t.module = mod; t.from_lo = lo; t.from_hi = hi; t.to_lo = to;
out->push_back(t);
return true;
}
auto k = known_.find(mod);
if (k != known_.end() && why) *why = mod + ": " + k->second;
return false;
};
if (kohya) {
auto it = r.kohya.find(rel);
if (it != r.kohya.end()) {
if (it->second.empty()) { if (why) *why = "its kohya name matches two modules of the base"; }
else if (take(it->second, 0, 0, 0)) return true;
}
} else if (take(r.native + rel, 0, 0, 0)) {
return true;
}
const size_t ri = (size_t)(&r - roots_.data());
for (const Alias& a : aliases_) {
if (a.root != ri) continue;
std::smatch m;
if (!std::regex_match(rel, m, kohya ? a.kohya : a.dotted)) continue;
std::string to;
size_t g = 1;
for (char c : a.to) {
if (c == '#' && g < m.size()) to += m[g++].str();
else to += c;
}
take(r.native + to, a.from_lo, a.from_hi, a.to_lo);
}
return !out->empty();
}
std::vector<Target> KeyMap::resolve(const std::string& key, std::string* why) const {
struct Cand { size_t root; size_t len; bool kohya; };
std::vector<Cand> cs;
for (size_t ri = 0; ri < roots_.size(); ++ri)
for (const std::string& sp : roots_[ri].spellings)
if (key.compare(0, sp.size(), sp) == 0)
cs.push_back({ ri, sp.size(), !sp.empty() && sp.back() == '_' });
std::stable_sort(cs.begin(), cs.end(), [](const Cand& a, const Cand& b) { return a.len > b.len; });
std::vector<Target> out;
std::string first_why;
for (const Cand& c : cs) {
std::string w;
if (lookup(roots_[c.root], key.substr(c.len), c.kohya, &out, &w)) return out;
if (first_why.empty()) first_why = w;
}
if (why) *why = !first_why.empty() ? first_why
: cs.empty() ? std::string("its prefix names no network of this model")
: std::string("no module of this model is named so");
return out;
}
/* ================================================================== composition */
namespace {
struct Part {
std::shared_ptr<Delta> d;
int64_t from_lo = 0, n = 0, to_lo = 0;
};
} /* namespace */
int compose(const KeyMap& km, const std::vector<Strength>& ads, int max_rank,
std::map<std::string, Composite>* out, ComposeReport* rep, std::string* err) {
out->clear();
*rep = ComposeReport{};
std::map<std::string, std::vector<Part>> by;
for (const Strength& s : ads) {
if (!s.file) return fail(err, RAD_E_INVAL, "adapter '" + s.name + "' is not open");
for (const auto& [t, why] : s.file->skipped()) rep->skipped.push_back(s.name + ": " + t + ": " + why);
if (s.weight == 0.0) continue;
for (const FileModule& fm : s.file->modules()) {
std::string why;
const std::vector<Target> ts = km.resolve(fm.key, &why);
if (ts.empty()) { rep->unplaced.push_back(s.name + ": " + fm.key + ": " + why); continue; }
auto d = std::make_shared<Delta>();
std::string e;
if (module_delta(fm, s.weight, d.get(), &e) < 0)
return fail(err, RAD_E_FORMAT, s.name + ": " + e);
for (const Target& t : ts) {
Part p;
p.d = d;
p.from_lo = t.from_lo;
p.n = (t.from_hi > 0 ? t.from_hi : d->N) - t.from_lo;
p.to_lo = t.to_lo;
if (p.n <= 0 || t.from_lo + p.n > d->N)
return fail(err, RAD_E_SHAPE, fmt("%s: %s has %lld output rows; the base's alias "
"takes rows [%lld, %lld) of it for %s",
s.name.c_str(), fm.key.c_str(), (long long)d->N,
(long long)t.from_lo, (long long)(t.from_lo + p.n),
t.module.c_str()));
by[t.module].push_back(p);
}
}
}
std::vector<std::string> names;
for (auto& [k, v] : by) { names.push_back(k); (*out)[k]; }
std::vector<std::string> errs(names.size());
std::vector<double> kept(names.size(), 1.0);
std::vector<char> exact(names.size(), 1);
std::atomic<size_t> next{ 0 };
auto work = [&]() {
for (size_t i; (i = next.fetch_add(1)) < names.size();) {
const std::string& mod = names[i];
const std::vector<Part>& ps = by.find(mod)->second;
Composite& c = out->find(mod)->second;
int64_t rows = km.rows(mod), K = km.cols(mod);
int64_t extent = 0;
for (const Part& p : ps) extent = std::max(extent, p.to_lo + p.n);
for (const KeyMap::Piece& pc : km.pieces(mod)) extent = std::max(extent, pc.lo + pc.n);
if (rows < 0) rows = extent;
if (K < 0) K = ps[0].d->K;
bool lr = true;
int64_t R = 0, bound = 0;
for (const Part& p : ps) {
if (p.d->K != K) {
errs[i] = fmt("%s: an adapter's delta has %lld input columns, the base's module "
"%lld", mod.c_str(), (long long)p.d->K, (long long)K);
break;
}
if (p.to_lo + p.n > rows) {
errs[i] = fmt("%s: an adapter's delta reaches row %lld of a module of %lld rows",
mod.c_str(), (long long)(p.to_lo + p.n), (long long)rows);
break;
}
lr = lr && p.d->low_rank;
R += p.d->low_rank ? p.d->r : 0;
bound += p.d->rank_bound;
}
if (!errs[i].empty()) continue;
c.rows = rows; c.K = K;
if (lr && R <= max_rank) {
/* Side by side: every delta its own block of ranks. */
c.r = R;
c.B.assign((size_t)(rows * R), 0.0f);
c.A.assign((size_t)(R * K), 0.0f);
int64_t o = 0;
for (const Part& p : ps) {
const Delta& d = *p.d;
for (int64_t row = 0; row < p.n; ++row)
std::memcpy(&c.B[(size_t)((p.to_lo + row) * R + o)],
&d.B[(size_t)((p.from_lo + row) * d.r)], (size_t)d.r * 4);
std::memcpy(&c.A[(size_t)(o * K)], d.A.data(), (size_t)(d.r * K) * 4);
o += d.r;
}
continue;
}
/* The sum, as one operator over the module's rows, truncated to the slot's rank. */
exact[i] = 0;
Delta sum;
sum.N = rows; sum.K = K; sum.rank_bound = bound;
/* One whole delta's energy is known; a sum's or a row slice's is what the sketch
* holds, exact when its rank is within the sketch's. */
sum.energy = ps.size() == 1 && ps[0].from_lo == 0 && ps[0].n == ps[0].d->N
? ps[0].d->energy : -1.0;
sum.apply = [&ps, rows](const float* X, int64_t l, float* Y) {
std::fill(Y, Y + rows * l, 0.0f);
for (const Part& p : ps) {
const Delta& d = *p.d;
std::vector<float> y((size_t)(d.N * l));
if (d.low_rank) {
std::vector<float> t((size_t)(d.r * l));
mm(d.A.data(), X, t.data(), d.r, d.K, l);
mm(d.B.data(), t.data(), y.data(), d.N, d.r, l);
} else {
d.apply(X, l, y.data());
}
for (int64_t row = 0; row < p.n; ++row)
for (int64_t j = 0; j < l; ++j)
Y[(p.to_lo + row) * l + j] += y[(size_t)((p.from_lo + row) * l + j)];
}
};
sum.apply_t = [&ps, K](const float* Yin, int64_t l, float* X) {
std::fill(X, X + K * l, 0.0f);
std::vector<float> x((size_t)(K * l));
for (const Part& p : ps) {
const Delta& d = *p.d;
std::vector<float> y((size_t)(d.N * l), 0.0f);
for (int64_t row = 0; row < p.n; ++row)
for (int64_t j = 0; j < l; ++j)
y[(size_t)((p.from_lo + row) * l + j)] = Yin[(p.to_lo + row) * l + j];
if (d.low_rank) {
std::vector<float> t((size_t)(d.r * l));
mm_tn(d.B.data(), y.data(), t.data(), d.r, d.N, l);
mm_tn(d.A.data(), t.data(), x.data(), d.K, d.r, l);
} else {
d.apply_t(y.data(), l, x.data());
}
for (int64_t k = 0; k < K * l; ++k) X[k] += x[(size_t)k];
}
};
truncate(sum, max_rank, &c.B, &c.A, &kept[i]);
c.r = (int64_t)(c.A.size() / (size_t)(K > 0 ? K : 1));
/* Kept energy is exact when the sum is low-rank: ||B A||^2 of the parts side by side. */
if (lr) {
std::vector<float> Bc((size_t)(rows * R), 0.0f), Ac((size_t)(R * K), 0.0f);
int64_t o = 0;
for (const Part& p : ps) {
const Delta& d = *p.d;
for (int64_t row = 0; row < p.n; ++row)
std::memcpy(&Bc[(size_t)((p.to_lo + row) * R + o)],
&d.B[(size_t)((p.from_lo + row) * d.r)], (size_t)d.r * 4);
std::memcpy(&Ac[(size_t)(o * K)], d.A.data(), (size_t)(d.r * K) * 4);
o += d.r;
}
const double tot = lowrank_energy(Bc, Ac, rows, R, K);
const double got = lowrank_energy(c.B, c.A, rows, c.r, K);
kept[i] = tot > 0.0 ? std::min(1.0, got / tot) : 1.0;
}
}
};
const unsigned hw = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
std::vector<std::thread> th;
for (unsigned t = 1; t < hw && t < names.size(); ++t) th.emplace_back(work);
work();
for (std::thread& t : th) t.join();
for (size_t i = 0; i < names.size(); ++i) {
if (!errs[i].empty()) return fail(err, RAD_E_SHAPE, errs[i]);
++rep->modules;
/* Held exactly: side by side, or an operator whose rank fits (LoKr, LoHa within R). */
if (exact[i] || kept[i] >= 0.9999) ++rep->exact;
else if (kept[i] < rep->worst_kept) { rep->worst_kept = kept[i]; rep->worst_module = names[i]; }
}
return RAD_OK;
}
std::map<std::string, AdModule> as_modules(std::map<std::string, Composite>& c, const KeyMap& km) {
std::map<std::string, AdModule> m;
for (auto& [name, x] : c) {
if (x.r <= 0) continue;
const std::vector<KeyMap::Piece>& pcs = km.pieces(name);
x.tPieces.assign(pcs.size(), StTensor{});
x.tA = StTensor{};
x.tA.name = name + ".A";
x.tA.dtype = RAD_F32;
x.tA.dtype_str = "F32";
x.tA.shape = { x.r, x.K };
x.tA.bytes = x.A.size() * 4;
x.tA.data = (const uint8_t*)x.A.data();
x.tB = StTensor{};
x.tB.name = name + ".B";
x.tB.dtype = RAD_F32;
x.tB.dtype_str = "F32";
x.tB.shape = { x.rows, x.r };
x.tB.bytes = x.B.size() * 4;
x.tB.data = (const uint8_t*)x.B.data();
AdModule a;
a.name = name;
a.A = &x.tA;
a.B = &x.tB;
a.rank = x.r;
a.alpha = (double)x.r;
a.scale = 1.0f;
if (pcs.empty() || km.whole(name)) m[name] = a;
for (size_t i = 0; i < pcs.size(); ++i) {
StTensor& t = x.tPieces[i];
t = x.tB;
t.name = pcs[i].name + ".B";
t.shape = { pcs[i].n, x.r };
t.bytes = (uint64_t)(pcs[i].n * x.r) * 4;
t.data = (const uint8_t*)(x.B.data() + pcs[i].lo * x.r);
AdModule p = a;
p.name = pcs[i].name;
p.B = &t;
m[p.name] = p;
}
}
return m;
}
} /* namespace lora */
} /* namespace rad */
+183
View File
@@ -0,0 +1,183 @@
/* lora/adapter.h -- adapter files as image and video generators receive them, and the bytes of a
* slot holding one or several of them at chosen strengths.
*
* An adapter for a generator is one safetensors file, written by whichever tool trained or
* converted it, so the same delta arrives under several spellings:
*
* LoRA `<m>.lora_down.weight` / `<m>.lora_up.weight` (+ `<m>.alpha`): kohya, ComfyUI;
* `<m>.lora_A[.default].weight` / `<m>.lora_B[...]` (+ `.alpha`): PEFT, diffusers, ai-toolkit;
* `<m>.lora.down.weight` / `<m>.lora.up.weight`; `<m>.lora_linear_layer.down/up.weight`.
* delta = alpha / rank * up @ down; no alpha is a scale of 1. A convolution's down is
* [rank, cin, kh, kw] and its up [cout, rank, 1, 1], read as the flattened matrices.
* LoHa `<m>.hada_w1_a/_w1_b/_w2_a/_w2_b` (+ alpha): delta = alpha / rank1 *
* (w1_a @ w1_b) * (w2_a @ w2_b), elementwise; exactly a rank1 * rank2 product of
* row-wise Kronecker factors.
* LoKr `<m>.lokr_w1` or `_w1_a`/`_w1_b`, `<m>.lokr_w2` or `_w2_a`/`_w2_b` (+ alpha):
* delta = scale * kron(w1, w2), scale alpha / rank of a decomposed factor, else 1.
* full `<m>.diff`: the delta itself.
*
* Every module becomes a Delta, a linear map with its strength folded in. A slot holds, for each
* checkpoint module the adapters reach, the sum of the deltas that land there: the low-rank ones
* side by side while their ranks fit the slot's rank (exact), otherwise the sum's best rank-R
* approximation (a randomized SVD; the fraction of the delta's energy it keeps is reported).
*
* Where a module lands is the generator's own declaration (rad_lora_root, rad_lora_alias): a
* key's prefix names the network, its path the checkpoint module directly or through an alias,
* kohya's underscore form matched against the same names. */
#pragma once
#include "lora.h"
#include "../format/safetensors.h"
#include <functional>
#include <map>
#include <memory>
#include <regex>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
namespace rad {
namespace lora {
/* One module of an adapter file, before it is mapped onto the base. */
struct FileModule {
enum Kind { LORA, LOHA, LOKR, FULL };
std::string key; /* the module as the file spells it, tensor suffix removed */
Kind kind = LORA;
/* LORA: down, up. LOHA: w1_a, w1_b, w2_a, w2_b. LOKR: w1, w1_a, w1_b, w2, w2_a, w2_b.
* FULL: diff. */
const StTensor* t[6] = {};
const StTensor* alpha = nullptr;
};
class AdapterFile {
public:
/* Opens and groups the file's tensors by module. Refuses a file holding a form whose effect
* this engine cannot reproduce (DoRA's magnitude, OFT, Tucker cores), naming it. */
int open(const std::string& path, std::string* err);
const std::string& path() const { return st_.path(); }
const std::vector<FileModule>& modules() const { return mods_; }
/* Tensors that change no linear (a trained bias, a norm's weight), with why; reported, not
* applied. */
const std::vector<std::pair<std::string, std::string>>& skipped() const { return skipped_; }
/* The most common kind among the modules, for messages ("LoRA", "LoHa", ...). */
const char* kind_name() const;
private:
SafeTensorsFile st_;
std::vector<FileModule> mods_;
std::vector<std::pair<std::string, std::string>> skipped_;
};
/* A module's delta as a linear map [N, K] with its scale and strength folded in. Low-rank forms
* keep their factors (B [N, r] and A [r, K], row-major); the rest are applied as operators to
* blocks of `l` column vectors (X [K, l] -> Y [N, l], and the transpose), all f32. */
struct Delta {
int64_t N = 0, K = 0;
int64_t rank_bound = 0;
double energy = -1.0; /* ||delta||_F^2, -1 when not known */
bool low_rank = false;
int64_t r = 0;
std::vector<float> B, A;
std::function<void(const float* X, int64_t l, float* Y)> apply, apply_t;
};
/* The delta of one module at strength `w`. RAD_E_SHAPE / RAD_E_DTYPE / RAD_E_FORMAT name the
* tensor. */
int module_delta(const FileModule& m, double w, Delta* out, std::string* err);
/* Rank-`r` factors of a delta given as an operator (randomized range finder, two power
* iterations): B [N, r], A [r, K]. `kept` is the fraction of the squared Frobenius norm kept, of
* Delta::energy when known and of what the sketch holds otherwise (1 when the delta's rank is at
* most r). */
void truncate(const Delta& d, int64_t r, std::vector<float>* B, std::vector<float>* A,
double* kept);
/* Where an adapter module lands in the base: rows [from_lo, from_hi) of its output (from_hi 0 =
* all) at rows from `to_lo` of the checkpoint module `module`. */
struct Target {
std::string module;
int64_t from_lo = 0, from_hi = 0, to_lo = 0;
};
/* The generator's key names over one rank's Program and sites. */
class KeyMap {
public:
KeyMap(const Program& prog, const std::vector<Site>& sites);
/* The targets of a file's module key; empty with `why` when it lands nowhere adaptable. */
std::vector<Target> resolve(const std::string& key, std::string* why) const;
/* A checkpoint module's full rows and columns as the sites record them, or -1 when the
* declaration leaves them open. */
int64_t rows(const std::string& module) const;
int64_t cols(const std::string& module) const;
/* The row pieces a module is cut into (RAD_MAP_ROWS; core/lora/lora.cpp names each
* `<module>@<first row>+<rows>`), empty for a module the sites read whole; and whether a site
* also reads it whole. */
struct Piece { std::string name; int64_t lo = 0, n = 0; };
const std::vector<Piece>& pieces(const std::string& module) const;
bool whole(const std::string& module) const { return whole_.count(module) != 0; }
private:
struct Root {
std::string native;
std::vector<std::string> spellings;
std::unordered_map<std::string, std::string> kohya; /* underscored rel -> module */
};
struct Alias {
size_t root;
std::string from, to;
int64_t from_lo, from_hi, to_lo;
std::regex dotted, kohya;
};
bool lookup(const Root& r, const std::string& rel, bool kohya, std::vector<Target>* out,
std::string* why) const;
const Program* prog_;
std::vector<Root> roots_;
std::vector<Alias> aliases_;
std::unordered_map<std::string, std::pair<int64_t, int64_t>> adaptable_; /* -> rows, cols */
std::unordered_map<std::string, std::string> known_; /* module -> why not adaptable */
std::unordered_map<std::string, std::vector<Piece>> pieces_;
std::set<std::string> whole_;
};
/* One adapter at a strength, for compose(). */
struct Strength {
std::string name;
std::shared_ptr<const AdapterFile> file;
double weight = 1.0;
};
/* What compose() did, for the log and the client. */
struct ComposeReport {
int64_t modules = 0; /* checkpoint modules the slot carries */
int64_t exact = 0; /* ... held exactly */
double worst_kept = 1.0; /* lowest kept energy among the truncated */
std::string worst_module;
std::vector<std::string> unplaced; /* "<adapter>: <key>: why" */
std::vector<std::string> skipped; /* "<adapter>: <tensor>: why" */
};
/* The factors of a composite, per checkpoint module: B [rows, r] and A [r, K], f32, held by the
* caller while the packer reads them. */
struct Composite {
int64_t rows = 0, K = 0, r = 0;
std::vector<float> B, A;
StTensor tA, tB;
std::vector<StTensor> tPieces; /* B's row ranges, one per piece of the module */
};
/* The sum of the adapters' deltas per checkpoint module, at most `max_rank` each. Unplaced
* modules are reported, not refused, as UIs do. RAD_E_SHAPE when a module's shape disagrees with
* the base's. */
int compose(const KeyMap& km, const std::vector<Strength>& ads, int max_rank,
std::map<std::string, Composite>* out, ComposeReport* rep, std::string* err);
/* The packer's view of a composite (scale 1: the strengths and alphas are folded into B): a
* module under its own name where a site reads it whole, and each of its row pieces under the
* piece's name. */
std::map<std::string, AdModule> as_modules(std::map<std::string, Composite>& c, const KeyMap& km);
} /* namespace lora */
} /* namespace rad */
+26 -11
View File
@@ -1,9 +1,14 @@
/* lora/config.h -- what runtime LoRA was started with (--lora, --max-loras, --max-lora-rank,
* --lora-target-modules). Read by declare (which sites and pools exist), by the adapter manager
* (what may be loaded into them) and by nothing else.
/* lora/config.h -- what runtime LoRA was started with (--lora, --lora-dir, --max-loras,
* --max-lora-rank, --lora-target-modules). Read by declare (which sites and pools exist), by the
* adapter manager (what may be loaded into them) and by nothing else.
*
* Off unless asked for: with no adapter named and no --max-loras, `enabled()` is false, declare
* appends nothing, the program has no pool and no extra op, and no step carries an adapter slot. */
* Off unless asked for: with no adapter named, no --lora-dir and no --max-loras, `enabled()` is
* false, declare appends nothing, the program has no pool and no extra op, and no step carries an
* adapter slot.
*
* A text model's slot holds one adapter; a generator's holds the combination one request asks for
* (several adapter files at their strengths, core/lora/adapter.h), so its slots are not tied to
* the number of adapters named. */
#pragma once
#include <string>
#include <utility>
@@ -12,20 +17,30 @@
namespace rad {
struct LoraConfig {
/* NAME=PATH pairs to load at startup, in the order given. */
/* NAME=PATH pairs to load at startup, in the order given: a PEFT directory, or for a
* generator one .safetensors file. */
std::vector<std::pair<std::string, std::string>> adapters;
/* Adapter slots resident at once. 0 with adapters named means "as many as were named". */
/* A generator's adapter directory: a request may name any NAME.safetensors under it. */
std::string dir;
/* Adapter slots resident at once. 0: as many as were named, and two with --lora-dir alone. */
int max_loras = 0;
/* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. */
int max_rank = 16;
/* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. 0: the
* default, kDefaultRank for a text model and kDefaultGenRank for a generator, whose adapter
* files run to rank 32 and are stacked. */
int max_rank = 0;
static constexpr int kDefaultRank = 16, kDefaultGenRank = 64;
int rank(bool generator) const {
return max_rank > 0 ? max_rank : generator ? kDefaultGenRank : kDefaultRank;
}
/* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for, sorted
* and unique. Empty: the union of the startup adapters' target_modules. */
std::vector<std::string> targets;
bool enabled() const { return max_loras > 0 || !adapters.empty(); }
bool enabled() const { return max_loras > 0 || !adapters.empty() || !dir.empty(); }
int slots() const {
const int named = (int)adapters.size();
return max_loras > 0 ? (max_loras > named ? max_loras : named) : named;
if (max_loras > 0) return max_loras;
return named > 0 ? named : (dir.empty() ? 0 : 2);
}
};
+99 -12
View File
@@ -3,6 +3,7 @@
#include "build/rad_build.h"
#include "rad_internal.h"
#include <algorithm>
#include <cstring>
#include <map>
#include <string>
@@ -73,23 +74,36 @@ rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32
} /* namespace */
/* A generator pass's adapter ops run over at most this many rows at a time: large enough that the
* kernels' row tiles are all busy, small enough that `t` for the largest rank is a few MiB. */
constexpr int64_t kGenChunk = 8192;
int lora_declare(Builder& b, const LoraDeclare& d) {
if (!d.cfg || !d.cfg->enabled()) return RAD_OK;
Program& P = b.program();
/* Adapters are chosen per request and applied on the token steps of a model that writes
* logits; a generator's passes and an embedding model's requests carry no adapter. */
if (P.is_pass_driven() || P.pooled_buf != RAD_NULL_HANDLE ||
P.logits_buf == RAD_NULL_HANDLE) {
RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, and this one %s",
P.is_pass_driven() ? "is an image, audio or video generator"
* logits, or on every pass of a generator that names its adapter keys (rad_lora_root); an
* embedding model's requests carry no adapter. */
const bool gen = P.is_pass_driven();
if (gen ? P.lora_roots.empty()
: (P.pooled_buf != RAD_NULL_HANDLE || P.logits_buf == RAD_NULL_HANDLE)) {
RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, or a generator "
"that declares how adapter files name its modules, and this one %s",
gen ? "is a generator that declares no adapter "
"key names (rad_lora_root)"
: P.pooled_buf != RAD_NULL_HANDLE ? "makes embeddings"
: "declares no logits");
return RAD_E_UNSUPPORTED;
}
if (!gen && d.targets.count("*")) {
RAD_ERR("lora: an adapter without adapter_config.json names no target modules, and a "
"text model has no default set; give them with --lora-target-modules");
return RAD_E_UNSUPPORTED;
}
const int S = d.cfg->slots();
const int max_rank = d.cfg->max_rank;
const int max_rank = d.cfg->rank(gen);
const int64_t max_tok = P.ctx.max_tok;
if (S <= 0 || max_rank <= 0 || max_tok <= 0) {
if (S <= 0 || max_rank <= 0 || (!gen && max_tok <= 0)) {
RAD_ERR("lora: %d slots of rank %d over steps of %lld tokens is not a configuration", S,
max_rank, (long long)max_tok);
return RAD_E_INVAL;
@@ -150,6 +164,26 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
}
}
/* ---- a token step's rows are its tokens; a generator pass's are each GEMM's own, issued in
* chunks of at most kGenChunk rows (Ctx::issue_lora), so `t` holds one chunk. */
int64_t rows = max_tok;
if (gen) {
rows = 0;
for (const lora::Site& x : sites)
if (x.gemm > 0 && x.gemm < P.ops.size()) rows = std::max(rows, P.ops[x.gemm].range_hi);
rows = std::min<int64_t>(rows, kGenChunk);
}
/* On the real declare, what the adapters cost: the pools are persistent buffers, so the
* arena plan (and with it what is left for weights and the KV cache) holds them. */
if (d.sites_out) {
int64_t slot_bytes = 0;
for (const LoraPool& p : P.lora_pools) slot_bytes += 2 * p.R * p.K + 2 * p.N * p.R + 4 * p.N;
RAD_INFO("lora: %zu weights carry adapters, %d slots of rank %d, %s a slot on this rank, "
"%s in all (--max-loras, --max-lora-rank)", P.lora_pools.size(), S, max_rank,
humanb(slot_bytes).c_str(), humanb(slot_bytes * S).c_str());
}
/* ---- t = A.x, one f32 plane per capacity R and lane. Persistent, not transient: the ops that
* use it run at the GEMM's position, but the buffer plan would place a transient at the
* appended ops' own position, the end of the program, and share its bytes with buffers live
@@ -160,7 +194,7 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
if (t_by_r.count(x.R)) continue;
LoraScratch sc;
sc.R = x.R;
const int64_t sh[2] = { max_tok, x.R };
const int64_t sh[2] = { rows, x.R };
for (int l = 0; l < 2; ++l) {
sc.lane[l] = decl_persist(b, fmt("lora.t.r%lld.lane%d", (long long)x.R, l), RAD_F32, 2, sh);
if (!sc.lane[l]) return RAD_E_STATE;
@@ -169,9 +203,21 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
P.lora_t.push_back(sc);
}
/* ---- a generator pass's slot operand: elements [s rows, (s + 1) rows) of an [S rows] i32
* buffer, every one s (filled when the engine starts adapters) */
P.lora_rows = 0;
P.lora_rows_n = 0;
if (gen && rows > 0) {
const int64_t sh[1] = { S * rows };
P.lora_rows = decl_persist(b, "lora.slot_rows", RAD_I32, 1, sh);
if (!P.lora_rows) return RAD_E_STATE;
P.lora_rows_n = rows;
}
/* ---- the two ops behind each targeted GEMM */
P.lora_sites.clear();
int n_refused = 0;
std::vector<char> dropped(sites.size(), 0);
for (lora::Site& x : sites) {
const uint32_t gh = x.gemm;
if (gh == 0 || gh >= P.ops.size()) return RAD_E_STATE;
@@ -186,7 +232,15 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
const int oa = opd_index(g, "a"), oas = opd_index(g, "a_scale"), oy = opd_index(g, "y");
const std::vector<rad_buf> reads = b.op_read_set(gh), writes = b.op_write_set(gh);
/* A text model's targeted GEMM that cannot carry the ops is refused; a generator's, whose
* every plain GEMM is a candidate, stays the base and its modules are reported unplaced. */
auto refuse = [&](const std::string& why) {
if (gen) {
RAD_WARN("lora: op %u '%s' over '%s' carries no adapter: %s", gh, gop.c_str(),
x.weight.c_str(), why.c_str());
dropped[(size_t)(&x - sites.data())] = 1;
return;
}
RAD_ERR("lora: op %u '%s' over '%s': %s", gh, gop.c_str(), x.weight.c_str(), why.c_str());
++n_refused;
};
@@ -223,9 +277,14 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
sp[n_sp++] = RAD_STR("dtype", rad_dtype_name(a_dt));
const rad_op hs = b.decl_op("lora_shrink", sp, n_sp, nullptr, 0);
const RadParam ep[5] = { RAD_RANGE("M", lo, hi), RAD_INT("N", x.N_r), RAD_INT("R", x.R),
RAD_INT("S", S), RAD_STR("dtype", rad_dtype_name(y_dt)) };
const rad_op he = b.decl_op("lora_expand", ep, 5, nullptr, 0);
RadParam ep[5] = { RAD_RANGE("M", lo, hi), RAD_INT("N", x.N_r), RAD_INT("R", x.R),
RAD_INT("S", S), RAD_STR("dtype", rad_dtype_name(y_dt)) };
/* A generator's passes are many rows of one adapter: its expand runs on the WMMA
* (lora_expand_mm) where a library has it. A token step keeps the exact row, whose bytes
* do not depend on the batch. */
const char* expand_op = gen && b.op_declared("lora_expand_mm") ? "lora_expand_mm"
: "lora_expand";
const rad_op he = b.decl_op(expand_op, ep, 5, nullptr, 0);
if (!hs || !he) {
refuse(fmt("no kernel resolves lora_%s for an activation of %s and an output of %s",
!hs ? "shrink" : "expand", rad_dtype_name(a_dt), rad_dtype_name(y_dt)));
@@ -233,6 +292,28 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
}
LoraIssueSite is;
/* A generator's slot packs its ranks from 0 (lora::pack_modules, compact): pairs that read
* the first half and quarter of R, so a rank-16 adapter in a slot sized 64 a module costs
* a quarter. Multiples of 16, the WMMA's step. */
if (gen) {
int64_t prev = x.R;
for (int v = 0; v < 2; ++v) {
const int64_t rv = ((x.R >> (v + 1)) + 15) / 16 * 16;
if (rv < 16 || rv >= prev) break;
RadParam vs[6];
for (int i = 0; i < n_sp; ++i) vs[i] = sp[i];
vs[2] = RAD_INT("R", rv);
ep[2] = RAD_INT("R", rv);
const rad_op vs_op = b.decl_op("lora_shrink", vs, n_sp, nullptr, 0);
const rad_op ve_op = b.decl_op(expand_op, ep, 5, nullptr, 0);
if (!vs_op || !ve_op) break;
P.ops[vs_op].anchor = (int32_t)gh;
P.ops[ve_op].anchor = (int32_t)gh;
is.shrink_v[v] = vs_op; is.expand_v[v] = ve_op; is.R_v[v] = rv;
is.n_v = (int8_t)(v + 1);
prev = rv;
}
}
is.gemm = gh; is.shrink = hs; is.expand = he;
is.opd_a = (int8_t)oa;
is.opd_a_scale = (int8_t)(coded ? oas : -1);
@@ -248,7 +329,13 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
}
if (n_refused) return RAD_E_UNSUPPORTED;
if (d.sites_out) *d.sites_out = std::move(sites);
if (gen) P.lora_rused.assign(P.lora_pools.size() * (size_t)S, 0);
if (d.sites_out) {
std::vector<lora::Site> kept;
for (size_t i = 0; i < sites.size(); ++i)
if (!dropped[i]) kept.push_back(std::move(sites[i]));
*d.sites_out = std::move(kept);
}
return RAD_OK;
}
+108 -32
View File
@@ -88,8 +88,13 @@ bool excluded_source(const std::string& src) {
return false;
}
/* A generator that declared adapter key names (rad_lora_root): its scope is those roots, every
* matrix under one of them, and none of the token model's rules below apply. */
bool gen_scope(const Program& prog) { return !prog.lora_roots.empty(); }
const char* excluded_weight(const Program& prog, const WeightInfo& w) {
if (w.decl.access == RAD_ACCESS_VOCAB) return "a vocabulary weight (embedding / lm_head)";
if (gen_scope(prog)) return w.decl.rank == 2 ? nullptr : "not a matrix";
if (w.decl.access == RAD_ACCESS_PER_REQUEST) return "an encoder tower weight (per-request access)";
if (prog.meta.n_layers > 0 && w.decl.group.layer >= prog.meta.n_layers)
return "a drafter / MTP layer (layer group at or above meta.n_layers)";
@@ -121,8 +126,23 @@ void scan_maps(const Program& prog, const std::string& declared,
struct MapIndex {
std::unordered_map<std::string, std::vector<const RadNameMap*>> by;
explicit MapIndex(const Program& prog) {
for (const RadNameMap& m : prog.name_map)
if (m.declared) by[m.declared].push_back(&m);
/* An entry repeated whole (a plugin's encoding probe maps the weight it then declares) is
* one entry. */
auto same = [](const RadNameMap& a, const RadNameMap& b) {
if (a.mode != b.mode || a.n_src != b.n_src || a.concat_dim != b.concat_dim) return false;
for (int k = 0; k < a.n_src && k < 8; ++k)
if (std::strcmp(a.src[k] ? a.src[k] : "", b.src[k] ? b.src[k] : "") != 0 ||
a.src_index[k] != b.src_index[k] || a.src_rows[k] != b.src_rows[k])
return false;
return true;
};
for (const RadNameMap& m : prog.name_map) {
if (!m.declared) continue;
std::vector<const RadNameMap*>& v = by[m.declared];
bool dup = false;
for (const RadNameMap* x : v) dup = dup || same(*x, m);
if (!dup) v.push_back(&m);
}
}
const std::vector<const RadNameMap*>* find(const std::string& d) const {
auto it = by.find(d);
@@ -130,19 +150,27 @@ struct MapIndex {
}
};
/* Is checkpoint tensor `src` an adapter target? A token model: its leaf is in the target list and
* it is in the trunk. A generator: it is under a declared root, and its leaf is in the list or the
* list is "*". */
bool source_targeted(const Program& prog, const TargetSet& targets, const std::string& src) {
std::string leaf;
if (module_of(src, &leaf).empty()) return false;
if (!gen_scope(prog)) return targets.count(leaf) && !excluded_source(src);
if (!targets.count("*") && !targets.count(leaf)) return false;
for (const LoraRoot& r : prog.lora_roots)
if (src.compare(0, r.native.size(), r.native) == 0) return true;
return false;
}
/* weight_targeted(), over the maps already found. */
bool targeted_core(const Program& prog, const WeightInfo& w,
const std::vector<const RadNameMap*>& maps, const TargetSet& targets) {
if (targets.empty() || maps.empty()) return false;
if (excluded_weight(prog, w)) return false;
for (const RadNameMap* m : maps)
for (int k = 0; k < m->n_src && k < 8; ++k) {
if (!m->src[k]) continue;
const std::string src = m->src[k];
std::string leaf;
if (module_of(src, &leaf).empty()) continue;
if (targets.count(leaf) && !excluded_source(src)) return true;
}
for (int k = 0; k < m->n_src && k < 8; ++k)
if (m->src[k] && source_targeted(prog, targets, m->src[k])) return true;
return false;
}
@@ -464,40 +492,46 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
if (!maps || maps->empty())
return fail(err, RAD_E_NOTFOUND, fmt("weight '%s' has no name-map entry", W.name.c_str()));
std::vector<std::string> srcs;
/* A row piece of a checkpoint tensor (RAD_MAP_ROWS) is a source of its own, named
* `<module>@<first row>+<rows>`: the adapter's B rows it takes are that range of the
* module's. */
std::vector<std::string> piece;
const bool alternatives = maps->size() == 1 && (*maps)[0]->mode == RAD_MAP_COPY &&
(*maps)[0]->n_src > 1;
for (const RadNameMap* m : *maps)
for (int k = 0; k < m->n_src && k < 8; ++k) {
if (m->src_index[k] >= 0)
const bool rows = m->mode == RAD_MAP_ROWS;
if (!rows && m->src_index[k] >= 0)
return fail(err, RAD_E_UNSUPPORTED,
fmt("weight '%s' is slice %d of the stacked checkpoint tensor %s; a "
"LoRA on a stacked (expert) tensor is not supported",
W.name.c_str(), m->src_index[k], m->src[k]));
srcs.push_back(m->src[k] ? m->src[k] : "");
piece.push_back(rows ? fmt("@%d+%lld", m->src_index[k], (long long)m->src_rows[k]) : "");
}
if (alternatives) {
/* COPY with alternatives: the first one the container holds is the weight, and which one
* that is is not recorded. Usable only when exactly one alternative is targeted. */
std::vector<std::string> hit;
for (const std::string& x : srcs) {
std::string leaf;
if (!module_of(x, &leaf).empty() && targets.count(leaf) && !excluded_source(x))
hit.push_back(x);
}
for (const std::string& x : srcs)
if (source_targeted(prog, targets, x)) hit.push_back(x);
if (hit.size() != 1)
return fail(err, RAD_E_UNSUPPORTED,
fmt("weight '%s' is one of %zu alternative checkpoint tensors and %zu of "
"them are targeted; which one the container holds is not recorded",
W.name.c_str(), srcs.size(), hit.size()));
srcs = hit;
piece.assign(srcs.size(), "");
}
int slot = 0;
for (const std::string& x : srcs) {
for (size_t si = 0; si < srcs.size(); ++si) {
const std::string& x = srcs[si];
SiteSource ss;
std::string leaf;
ss.module = module_of(x, &leaf);
if (ss.module.empty()) ss.module = x;
ss.targeted = !leaf.empty() && targets.count(leaf) && !excluded_source(x);
ss.module += piece[si];
ss.targeted = source_targeted(prog, targets, x);
if (ss.targeted) ss.slot = slot++;
s.sources.push_back(ss);
}
@@ -544,6 +578,8 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
/* ================================================================== predicates */
bool weight_targeted(const Program& prog, rad_weight w, const TargetSet& targets) {
if (targets.empty() || w == 0 || w >= prog.weights.size()) return false;
/* A generator's fused GEMMs are kept: its scope is the plain GEMMs (build_sites). */
if (gen_scope(prog)) return false;
const WeightInfo& wi = prog.weights[w];
if (excluded_weight(prog, wi)) return false;
std::vector<const RadNameMap*> maps;
@@ -598,7 +634,7 @@ bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::s
int find_unsupported_uses(const Program& prog, const TargetSet& targets,
std::vector<UnsupportedUse>* out) {
if (out) out->clear();
if (targets.empty()) return 0;
if (targets.empty() || gen_scope(prog)) return 0;
const MapIndex mi(prog);
int n = 0;
for (size_t i = 1; i < prog.ops.size(); ++i) {
@@ -642,14 +678,47 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
if (max_rank <= 0) return fail(err, RAD_E_INVAL, fmt("max LoRA rank %d", max_rank));
if (targets.empty()) return RAD_OK;
const MapIndex mi(prog);
/* A generator's weight carries an adapter only when every op reading it is a site over it; one
* read elsewhere (a fused GEMM, a non-GEMM op) stays the base everywhere. */
std::set<std::string> other_reader;
if (gen_scope(prog))
for (size_t i = 1; i < prog.ops.size(); ++i) {
const OpInfo& op = prog.ops[i];
if (op.weights.empty() || !op_live(op)) continue;
rad_weight b = 0;
const bool site = op_is_site(prog, op, &b, nullptr);
for (rad_weight h : op.weights)
if (h && h < prog.weights.size() &&
(!site || !b || prog.weights[b].source != prog.weights[h].source))
other_reader.insert(prog.weights[h].source);
}
std::map<rad_weight, int32_t> pool_of;
std::vector<size_t> first_site;
for (size_t i = 1; i < prog.ops.size(); ++i) {
rad_weight b = 0;
if (!op_live(prog.ops[i]) || !op_is_site(prog, prog.ops[i], &b, nullptr)) continue;
if (!targeted_idx(prog, mi, b, targets)) continue;
if (other_reader.count(prog.weights[b].source)) continue;
if (gen_scope(prog)) {
/* Checkpoint tensors copied, joined, transposed or cut into row pieces carry a
* generator's adapter; a folded or derived one (weight norm, EMA) stays the base. */
bool whole = true;
if (const auto* maps = mi.find(prog.weights[b].source))
for (const RadNameMap* m : *maps)
whole = whole && (m->mode == RAD_MAP_COPY || m->mode == RAD_MAP_CONCAT ||
m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_ROWS);
if (!whole) continue;
}
Site s;
const int st = make_site(prog, mi, targets, max_rank, (uint32_t)i, b, &s, err);
if (st < 0 && gen_scope(prog)) {
/* A generator's every plain GEMM is a candidate; one whose geometry cannot be told
* stays the base, as a fused one does. */
RAD_WARN("lora: '%s' carries no adapter: %s", prog.weights[b].name.c_str(),
err ? err->c_str() : "");
if (err) err->clear();
continue;
}
if (st < 0) return st;
auto it = pool_of.find(b);
if (it == pool_of.end()) {
@@ -729,15 +798,6 @@ std::string explain_module(const Program& prog, const TargetSet& targets, const
/* ================================================================== the adapter */
namespace {
struct AdModule {
std::string name;
const StTensor* A = nullptr;
const StTensor* B = nullptr;
int64_t rank = 0;
double alpha = 0.0;
float scale = 0.0f;
};
struct Slot { int32_t pool; int32_t source; };
} /* namespace */
@@ -937,6 +997,12 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
info->leaves.insert(d == std::string::npos ? am.name : am.name.substr(d + 1));
}
return pack_modules(sites, max_rank, mods, info, packed, err);
}
int pack_modules(const std::vector<Site>& sites, int max_rank,
const std::map<std::string, AdModule>& mods, AdapterInfo* info,
std::vector<PackedSite>* packed, std::string* err, bool compact) {
/* ---- the sites, by pool: the representative of each pool and where its modules sit. */
int32_t n_pools = 0;
for (const Site& s : sites) {
@@ -955,7 +1021,9 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
}
std::unordered_map<std::string, std::vector<Slot>> where;
for (int32_t p = 0; p < n_pools; ++p) {
if (!rep[(size_t)p]) return fail(err, RAD_E_INVAL, fmt("pool %d has no site", p));
/* A pool whose only GEMM could carry no adapter ops (lora_declare drops it) holds
* nothing. */
if (!rep[(size_t)p]) continue;
const Site& s = *rep[(size_t)p];
for (size_t i = 0; i < s.sources.size(); ++i)
if (s.sources[i].targeted) where[s.sources[i].module].push_back({ p, (int32_t)i });
@@ -1001,9 +1069,10 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
/* ---- pack, pool by pool */
packed->resize((size_t)n_pools);
for (int32_t p = 0; p < n_pools; ++p) {
const Site& s = *rep[(size_t)p];
PackedSite& out = (*packed)[(size_t)p];
out.pool = p;
if (!rep[(size_t)p]) continue;
const Site& s = *rep[(size_t)p];
out.a.assign((size_t)(s.R * s.K_r), 0);
out.b.assign((size_t)(s.N_r * s.R), 0);
out.scale.assign((size_t)s.N_r, 0.0f);
@@ -1135,12 +1204,19 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
}
/* Pack. A: rows t_off.. of the module's block; B: rows y_col.., columns t_off..; scale on
* the module's rows. */
* the module's rows. Compact: the modules' ranks one after another from 0. */
std::vector<int64_t> off(n, 0);
int64_t used = 0;
for (size_t i = 0; i < n; ++i) {
off[i] = compact ? used : (int64_t)s.sources[i].slot * max_rank;
if (am[i]) used += am[i]->rank;
}
out.r_used = compact ? used : s.R;
for (size_t i = 0; i < n; ++i) {
if (!am[i]) continue;
const StTensor& A = *am[i]->A;
const int64_t r = am[i]->rank, kc = A.shape[1];
const int64_t t0 = (int64_t)s.sources[i].slot * max_rank;
const int64_t t0 = off[i];
for (int64_t j = 0; j < r; ++j)
for (int64_t k = 0; k < s.K_r; ++k)
out.a[(size_t)((t0 + j) * s.K_r + k)] = elem_bf16(A, j * kc + s.k_lo + k);
@@ -1156,7 +1232,7 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
if (yr < 0 || yr >= s.N_r)
return fail(err, RAD_E_STATE, fmt("weight '%s': a part lands outside y", s.weight.c_str()));
for (int64_t j = 0; j < r; ++j)
out.b[(size_t)(yr * s.R + sp.t_off + j)] = elem_bf16(B, row * r + j);
out.b[(size_t)(yr * s.R + off[i] + j)] = elem_bf16(B, row * r + j);
out.scale[(size_t)yr] = am[i]->scale;
}
}
+24
View File
@@ -19,12 +19,14 @@
#include "../rad_core.h"
#include <cstdint>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
namespace rad {
struct StTensor;
namespace lora {
/* HF module leaf names, ordered so every caller builds the same set. Empty targets nothing. */
@@ -82,6 +84,8 @@ struct PackedSite {
std::vector<float> scale; /* [N_r]: the module's alpha/r (alpha/sqrt(r) rsLoRA) on its rows */
int32_t pool = -1;
bool empty = true; /* no module of this adapter lands in this pool */
/* Packed compact (pack_modules): the ranks the modules take, from j = 0; R otherwise. */
int64_t r_used = 0;
};
/* What an adapter is, independent of the name it is served under. */
@@ -157,6 +161,26 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max_rank,
AdapterInfo* info, std::vector<PackedSite>* packed, std::string* err);
/* One module's factors as the packer reads them: lora_A [rank, K] and lora_B [rows, rank] in any
* dtype a safetensors tensor carries (BF16, F16, F32), and the scale its rows run at. `name` is the
* module path the base's name map spells (without ".weight"). */
struct AdModule {
std::string name;
const StTensor* A = nullptr;
const StTensor* B = nullptr;
int64_t rank = 0;
double alpha = 0.0;
float scale = 0.0f;
};
/* load_adapter's second half, for any source of factors: `mods` (by name) packed into one
* PackedSite per pool of `sites`, in the slot layout of the pool's sites. Fills info->modules and
* info->absent. `compact`: the modules of a pool take consecutive ranks from j = 0, in source
* order, instead of a block of max_rank each, so a pass may run only the first r_used of them. */
int pack_modules(const std::vector<Site>& sites, int max_rank,
const std::map<std::string, AdModule>& mods, AdapterInfo* info,
std::vector<PackedSite>* packed, std::string* err, bool compact = false);
/* After load_adapter on every rank: refuse a module that no rank placed. With `prog`/`targets`
* (any one rank's) the message says why it is not a site (base lacks it, scope, target list, op). */
int check_placed(const std::vector<AdapterInfo>& per_rank, std::string* err,
+16 -1
View File
@@ -60,6 +60,7 @@ uint64_t SlotTable::publish(int slot, const std::string& name, const std::string
s.uid = next_uid_++;
s.used = true;
s.draining = false;
s.last_use = ++uses_;
return s.uid;
}
@@ -69,10 +70,11 @@ int SlotTable::acquire(const std::string& name, int32_t* slot, uint64_t* uid,
{
std::lock_guard<std::mutex> lk(mu_);
for (size_t i = 0; i < slots_.size() && !u; ++i) {
const Slot& x = slots_[i];
Slot& x = slots_[i];
if (x.uid == 0 || x.draining || x.name != name) continue;
u = x.uid;
*slot = (int32_t)i;
x.last_use = ++uses_;
++refs_[u];
}
}
@@ -125,6 +127,19 @@ int SlotTable::unload(const std::string& name, int* in_flight, std::string* err)
return RAD_E_NOTFOUND;
}
int SlotTable::evict_idle(std::string* evicted) {
std::lock_guard<std::mutex> lk(mu_);
Slot* best = nullptr;
for (Slot& x : slots_) {
if (x.uid == 0 || x.draining || refs_.count(x.uid)) continue;
if (!best || x.last_use < best->last_use) best = &x;
}
if (!best) return RAD_E_FULL;
if (evicted) *evicted = best->name;
free_slot(*best, " to make room");
return RAD_OK;
}
std::vector<std::string> SlotTable::names() const {
std::lock_guard<std::mutex> lk(mu_);
std::vector<std::string> out;
+6
View File
@@ -61,6 +61,10 @@ public:
* RAD_E_NOTFOUND: nothing of that name is loaded. */
int unload(const std::string& name, int* in_flight, std::string* err);
/* Free the least recently acquired loaded slot that no request holds, for a load that found
* none free; its name in *evicted. RAD_E_FULL when every loaded slot is held. */
int evict_idle(std::string* evicted);
/* The loaded adapters a request may name, in slot order: not the draining ones. */
std::vector<std::string> names() const;
/* Requests holding the adapter `name` (draining or not), 0 for none or no such adapter. */
@@ -73,6 +77,7 @@ private:
bool used = false; /* ever held an adapter, so `freed_at` means something */
bool draining = false;
uint64_t freed_at = 0; /* `epoch` when it was last freed */
uint64_t last_use = 0; /* acquire counter at its last acquire or publish */
};
void free_slot(Slot& s, const char* how); /* under mu_ */
void release(uint64_t uid); /* a hold's deleter */
@@ -82,6 +87,7 @@ private:
std::vector<Slot> slots_;
std::map<uint64_t, int> refs_; /* uid -> holds */
uint64_t next_uid_ = 1;
uint64_t uses_ = 0;
const std::atomic<uint64_t>* epoch_ = nullptr;
};
+27 -1
View File
@@ -310,6 +310,11 @@ struct LoraIssueSite {
int32_t pool = -1; /* index into Program::lora_pools */
int32_t t = -1; /* index into Program::lora_t */
int64_t R = 0, K = 0, N = 0;
/* A generator's narrower pairs: the same pools read to rank R_v[i] < R, the pass taking the
* narrowest that holds its slot's ranks (Program::lora_rused). */
uint32_t shrink_v[2] = { 0, 0 }, expand_v[2] = { 0, 0 };
int64_t R_v[2] = { 0, 0 };
int8_t n_v = 0;
};
/* One targeted weight's adapter slots: A [S, R, K], B [S, N, R] bf16 and the per-column scale
* [S, N] f32, persistent buffers, so the arena plan (and with it the KV budget) holds them. */
@@ -323,6 +328,16 @@ struct LoraScratch {
int64_t R = 0;
rad_buf lane[2] = { 0, 0 };
};
/* A generator's adapter key names (rad_lora_root, rad_lora_alias in rad_builder.h). */
struct LoraRoot {
std::string native; /* checkpoint prefix of the network's tensors */
std::vector<std::string> spellings; /* adapter-side prefixes; "" is a bare key */
};
struct LoraAlias {
std::string root; /* LoraRoot::native it is relative to */
std::string from, to; /* module paths, '#' a decimal index */
int64_t from_lo = 0, from_hi = 0, to_lo = 0;
};
/* Everything declare produced. The core owns it; the plugin only ever sees handles into it. */
class Program {
@@ -349,6 +364,17 @@ public:
std::vector<LoraIssueSite> lora_sites;
std::vector<LoraPool> lora_pools;
std::vector<LoraScratch> lora_t;
/* A generator's adapter key names: declared by the plugin whether or not adapters are on. A
* generator that declares no root carries no adapters. */
std::vector<LoraRoot> lora_roots;
std::vector<LoraAlias> lora_aliases;
/* A generator's pass runs with one adapter in every row: `lora_rows` is [S * lora_rows_n]
* i32, run s all s, so a pass's slot operand is run s of it. 0 on a token-step program. */
rad_buf lora_rows = 0;
int64_t lora_rows_n = 0;
/* A generator's slots pack each combination's ranks from j = 0: the ranks pool p takes in
* slot s at [p * S + s], 0 for a pool the combination does not reach (no adapter op runs). */
std::vector<int32_t> lora_rused;
/* The declared draft head (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when none, the
* normal case: the engine then speculates with the scheduler's prompt-lookup drafter or not at
@@ -716,7 +742,7 @@ struct Config {
* slower. `on` forces P2P and stops startup naming the refused pairs instead of falling
* back. */
int p2p = RAD_P2P_AUTO; /* --p2p auto|on|off */
int64_t max_tok = 8192; /* --max-num-batched-tokens */
int64_t max_tok = 2048; /* --max-num-batched-tokens */
/* --busy-prefill-chunk: how much of a step a prefill chunk may take when other work is
* pending in it (decode rows, another prefill, a request waiting for admission). -1 = auto:
* leave those their rows plus a share for admission, but keep at least the smallest pass the
+4
View File
@@ -201,6 +201,9 @@ public:
/* Call once on the rank thread before its first run_step: the backend's current device is
* thread-local, and init may have run on another thread. */
int bind_thread();
/* The runtime LoRA slot every row of the generator passes that follow runs with, -1 for none
* (Ctx::issue_lora). Set by the pass loop before it releases the rank for a pass. */
void set_gen_lora_slot(int32_t s) { gen_lora_slot_ = s; }
/* ---------------------------------------------------------- run-phase queries */
const RadBatch* batch() const { return batch_; }
@@ -350,6 +353,7 @@ private:
int bind_weights();
int bind_ops();
int issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n);
int32_t gen_lora_slot_ = -1;
int bind_routing();
int bind_profiling();
int check_domain(rad_op h, int domain) const;
+76 -24
View File
@@ -424,17 +424,21 @@ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* A row-parallel gemm's y is this rank's partial sum and the plugin reduces it after this returns,
* so the delta rides the same reduction (B.A.x is linear in x's shards). Nothing is issued on a
* step with no adapter row (RadBatch::lora_slot null), which is then the pass an engine without
* adapters runs, nor on a draft pass, whose proposals the trunk verifies. An encoder or generator
* pass never reaches a site: such a weight is outside the targets' scope rule (core/lora/lora.h),
* so reaching one here is refused rather than run without its delta. */
* adapters runs, nor on a draft pass, whose proposals the trunk verifies. An encoder pass never
* reaches a site: such a weight is outside the targets' scope rule (core/lora/lora.h), so reaching
* one here is refused rather than run without its delta.
*
* A generator's pass runs one adapter in all its rows (gen_lora_slot_, -1 for none), whatever the
* rows are -- a stream's tokens, a text encoder's taps, a video's patches -- so its slot operand
* is row `slot` of Program::lora_rows, the gemm's first n rows of it. */
int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
if (!batch_) return RAD_OK;
if (batch_->enc != 0 || batch_->gen != 0)
const bool gen = batch_->gen != 0;
if (batch_->enc != 0)
return abort_step_msg(h, RAD_E_UNSUPPORTED,
"a LoRA-targeted gemm was issued by an encoder or generator pass, "
"which runtime LoRA does not reach; leave its module out of "
"--lora-target-modules");
if (!batch_->lora_slot || batch_->draft_pass != 0) return RAD_OK;
"a LoRA-targeted gemm was issued by an encoder pass, which runtime "
"LoRA does not reach; leave its module out of --lora-target-modules");
if (gen ? gen_lora_slot_ < 0 : (!batch_->lora_slot || batch_->draft_pass != 0)) return RAD_OK;
const OpPlan& p = plans_[h];
const LoraIssueSite& s = program_->lora_sites[(size_t)p.lora_site];
if (n == RAD_N_BATCH) n = batch_->n_tok;
@@ -467,13 +471,15 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
rad_dtype_name(xd.dtype), rad_dtype_name(yd.dtype)));
const int64_t yw = yd.rank >= 2 ? yd.shape[yd.rank - 1] : 0;
if (yw <= 0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output has no width");
if (ya.cols == 0 && ya.offset % yw != 0)
/* A token step reads each row's slot at the row the gemm wrote, so the views must name token
* rows; a generator pass's one slot holds for any rows. */
if (!gen && ya.cols == 0 && ya.offset % yw != 0)
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output view starts inside a "
"row, so its token rows cannot be told");
const int64_t r0 = ya.offset / yw;
const int64_t r0 = gen ? 0 : ya.offset / yw;
/* The activation must start at the same row: shrink reads x's row m and expand writes y's row
* m with one slot. */
{
if (!gen) {
const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0;
if (xw <= 0 || (xa.cols == 0 && xa.offset % xw != 0) || xa.offset / xw != r0)
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's activation and output "
@@ -483,26 +489,72 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
(int)op_domain_[s.expand].load(std::memory_order_relaxed) != dom)
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed in "
"another domain than the gemm they follow");
if (r0 < 0 || r0 + n > batch_->n_tok)
if (!gen && (r0 < 0 || r0 + n > batch_->n_tok))
return abort_step_msg(h, RAD_E_STATE,
fmt("LoRA site: the gemm wrote rows [%lld, %lld) of a %lld-token step",
(long long)r0, (long long)(r0 + n), (long long)batch_->n_tok));
if (gen && (!program_->lora_rows || gen_lora_slot_ >= program_->lora_pools[(size_t)s.pool].S))
return abort_step_msg(h, RAD_E_STATE,
fmt("LoRA site: a generator pass in slot %d of %lld", gen_lora_slot_,
(long long)program_->lora_pools[(size_t)s.pool].S));
/* Each row's adapter is the step batch's (RadBatch::lora_slot), rewritten in stream order
* before each step's kernels, so the pointer this launch records is the one a replay of it
* reads. */
* reads. A generator pass is never recorded, so its run of the slot table is named directly,
* and it runs the pair over chunks of at most lora_rows_n rows: a video's passes run to
* hundreds of thousands of rows, and `t` and the slot run are sized for one chunk. */
const LoraPool& pool = program_->lora_pools[(size_t)s.pool];
const rad_buf t = program_->lora_t[(size_t)s.t].lane[lane_ ? 1 : 0];
RadOperand slot = RAD_P_T(batch_->lora_slot + r0, RAD_I32);
slot.rows = n;
const RadOperand tv = RAD_B_N(t, 0, n);
const RadOperand sh[5] = { xa,
s.opd_a_scale >= 0 && s.opd_a_scale < n_opd ? opd[s.opd_a_scale]
: RAD_NONE,
slot, RAD_B(pool.a), tv };
int rc = issue_body((rad_op)s.shrink, sh, 5, n);
if (rc < 0) return rc;
const RadOperand ex[5] = { tv, slot, RAD_B(pool.b), RAD_B(pool.scale), ya };
return issue_body((rad_op)s.expand, ex, 5, n);
/* A generator's slot holds its ranks from 0 (Program::lora_rused): no pair where it holds
* none, the narrowest declared pair that holds them otherwise. */
uint32_t sh_op = s.shrink, ex_op = s.expand;
int64_t rv = s.R;
if (gen) {
const size_t ui = (size_t)s.pool * (size_t)pool.S + (size_t)gen_lora_slot_;
const int64_t used = ui < program_->lora_rused.size() ? program_->lora_rused[ui] : s.R;
if (used <= 0) return RAD_OK;
for (int v = 0; v < s.n_v; ++v)
if (s.R_v[v] >= used) { sh_op = s.shrink_v[v]; ex_op = s.expand_v[v]; rv = s.R_v[v]; }
}
RadOperand xs = s.opd_a_scale >= 0 && s.opd_a_scale < n_opd ? opd[s.opd_a_scale]
: RAD_NONE;
const int64_t step = gen ? program_->lora_rows_n : n;
if (step <= 0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: no slot rows");
int64_t sw = 0; /* a_scale's row stride, for a chunk past the first */
if (n > step && xs.kind != RAD_OPK_NONE) {
if (xs.kind != RAD_OPK_BUF || (size_t)xs.handle >= program_->buffers.size())
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: a generator pass's activation "
"scale is not a declared buffer, so its "
"rows cannot be chunked");
const RadBufDecl& sd = program_->buffers[xs.handle].decl;
sw = sd.rank >= 2 ? sd.shape[sd.rank - 1] : 1;
}
const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0;
for (int64_t c = 0; c < n; c += step) {
const int64_t nc = std::min(step, n - c);
RadOperand x = xa, y = ya, a_s = xs;
if (c > 0) {
x.offset += c * xw;
y.offset += c * yw;
if (a_s.kind == RAD_OPK_BUF) a_s.offset += c * sw;
}
if (n > step) {
x.rows = nc;
y.rows = nc;
if (a_s.kind == RAD_OPK_BUF) a_s.rows = nc;
}
RadOperand slot = gen ? RAD_B(program_->lora_rows) : RAD_P_T(batch_->lora_slot + r0, RAD_I32);
if (gen) slot.offset = (int64_t)gen_lora_slot_ * program_->lora_rows_n;
slot.rows = nc;
RadOperand tv = RAD_B_N(t, 0, nc);
if (rv < s.R) tv.cols = rv;
const RadOperand sh[5] = { x, a_s, slot, RAD_B(pool.a), tv };
int rc = issue_body((rad_op)sh_op, sh, 5, nc);
if (rc < 0) return rc;
const RadOperand ex[5] = { tv, slot, RAD_B(pool.b), RAD_B(pool.scale), y };
rc = issue_body((rad_op)ex_op, ex, 5, nc);
if (rc < 0) return rc;
}
return RAD_OK;
}
int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
+23
View File
@@ -599,6 +599,22 @@ struct ImageGenInfo {
/* A reference picture is shrunk to `ref_area` only when larger, then centre-cropped to the
* size multiple; otherwise resized to `ref_area` at its aspect. */
bool ref_shrink_only = false;
/* A prompt of fewer tokens after the drop prefix is padded with `pad_token` up to this many
* (RadGeneratorDecl::min_tokens); 0: no minimum. */
int64_t min_tokens = 0;
int32_t pad_token = 0;
/* The prompt is also read through the model's second tokenizer (IImageGen::encode_aux), at
* most `aux_max_tokens` ids of it. */
bool aux_tokens = false;
int64_t aux_max_tokens = 0;
/* A discrete-time model (RadGeneratorDecl::train_steps): the samplers it serves (1 << id)
* and the sampler and scheduler a request gets when it names none. 0 samplers: flow
* matching, which takes neither field. */
uint32_t samplers = 0;
int32_t default_sampler = 0, default_scheduler = 0;
/* The prompt in windows (RadGeneratorDecl::chunk_tokens): tokens a window, its markers and
* its padding token; 0 for a prompt read whole. */
int32_t chunk_tokens = 0, chunk_bos = 0, chunk_eos = 0, chunk_pad = 0;
};
class IImageGen {
@@ -612,6 +628,13 @@ public:
virtual int picture(const mm::Frame& f, std::shared_ptr<mm::Item>* out, std::string* why) = 0;
virtual int64_t queued() const = 0;
virtual int64_t running() const = 0;
/* The user's prompt through the model's second tokenizer (ImageGenInfo::aux_tokens), with the
* special tokens that tokenizer adds; RAD_E_UNSUPPORTED for a model without one. */
virtual int encode_aux(const std::string& text, std::vector<int32_t>* out) const {
(void)text;
(void)out;
return RAD_E_UNSUPPORTED;
}
};
/* The audio generator (core/gen/audio_driver.h), for a model that makes music or other audio from
+111 -6
View File
@@ -21,6 +21,7 @@
* `.completed` event per image.
*/
#include "server.h"
#include "loras.h"
#include "oai.h"
#include "gen/gen.h"
@@ -58,6 +59,7 @@ struct ImgReq {
bool has_neg = false;
double cfg = 1.0;
int32_t w = 0, h = 0, n = 1, steps = 0, previews = 0;
int32_t sampler = 0, scheduler = 0;
bool seed_given = false;
uint64_t seed = 0;
std::string background = "auto", format = "png", quality = "auto";
@@ -89,6 +91,11 @@ json form_value(const std::string& key, const std::string& v) {
if (v == "true" || v == "1") return json(true);
if (v == "false" || v == "0") return json(false);
}
/* `loras` as JSON text, or one adapter's name. */
if ((key == "loras" || key == "lora") && !v.empty() && (v[0] == '[' || v[0] == '{')) {
json j = json::parse(v, nullptr, false);
if (!j.is_discarded()) return j;
}
return json(v);
}
@@ -235,7 +242,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
"output_compression", "response_format", "stream", "partial_images", "moderation",
"style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale",
"guidance_scale",
"num_inference_steps", "width", "height",
"num_inference_steps", "width", "height", "loras", "lora", "sampler", "scheduler",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
@@ -262,7 +269,20 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
return error_response(err_bad("prompt", "expected a string"), req.peer);
if (!body.contains("prompt"))
return error_response(err_bad("prompt", "the prompt is required"), req.peer);
if (r.prompt.empty()) r.prompt = " ";
/* Runtime LoRA adapters: `loras` and <lora:...> tags, which leave the prompt. */
std::vector<std::pair<std::string, double>> loras;
{
std::string field, why;
if (parse_loras(body, &r.prompt, &loras, &field, &why) < 0)
return error_response(err_bad(field.c_str(), why), req.peer);
if (!loras.empty() && !opt_.gen_lora_acquire)
return error_response(err_unsupported(field.c_str(), "this server was started without "
"adapters (--lora, --lora-dir)"),
req.peer);
}
/* An empty prompt becomes " ", as in the diffusers pipelines, unless the model pads a short
* prompt itself (ImageGenInfo::min_tokens), as ComfyUI's tokenizers do. */
if (r.prompt.empty() && info.min_tokens == 0) r.prompt = " ";
std::string rf;
if (str("response_format", &rf) < 0 || (!rf.empty() && rf != "b64_json" && rf != "url"))
return error_response(err_bad("response_format", "expected b64_json"), req.peer);
@@ -335,6 +355,39 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
else if (r.quality == "medium") steps = std::max<int64_t>(1, info.default_steps * 3 / 4);
}
r.steps = (int32_t)steps;
/* A discrete-time model's sampler and scheduler, by ComfyUI's names. */
{
std::string sname, kname;
if (str("sampler", &sname) < 0)
return error_response(err_bad("sampler", "expected a string"), req.peer);
if (str("scheduler", &kname) < 0)
return error_response(err_bad("scheduler", "expected a string"), req.peer);
if (!info.samplers && (!sname.empty() || !kname.empty()))
return error_response(err_unsupported(sname.empty() ? "scheduler" : "sampler",
"this model samples with flow-matching Euler "
"on its own schedule"), req.peer);
r.sampler = info.default_sampler;
r.scheduler = info.default_scheduler;
if (!sname.empty()) {
r.sampler = gen::sampler_id(sname);
if (r.sampler < 0 || !(info.samplers & (1u << r.sampler))) {
ApiError e = err_bad("sampler", "'" + sname + "' is not a sampler this model serves");
for (int32_t i = 0; i < RAD_GEN_SAMPLER_COUNT; ++i)
if (info.samplers & (1u << i)) e.supported.push_back(gen::sampler_name(i));
return error_response(e, req.peer);
}
}
if (!kname.empty()) {
r.scheduler = gen::scheduler_id(kname);
if (r.scheduler < 0) {
ApiError e = err_bad("scheduler", "'" + kname + "' is not a scheduler this model "
"serves");
for (int32_t i = 0; i < RAD_GEN_SCHED_COUNT; ++i)
e.supported.push_back(gen::scheduler_name(i));
return error_response(e, req.peer);
}
}
}
/* -1 asks for a random seed, as llama-server and the chat endpoints read it. */
if (body.contains("seed") && !body["seed"].is_null()) {
if (!body["seed"].is_number_integer())
@@ -365,12 +418,12 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
"..30"), req.peer);
}
/* Guidance needs a scale past its off value and a negative prompt: the request's (empty
* becomes " ", as in the reference pipeline), or the model's own. */
* becomes " " as the prompt does), or the model's own. */
const bool guided = r.cfg > cfg_off;
const bool named_neg = body.contains("negative_prompt") && !body["negative_prompt"].is_null();
r.has_neg = guided && (named_neg || info.has_default_negative);
if (r.has_neg && !named_neg) r.negative = info.default_negative;
else if (r.has_neg && r.negative.empty()) r.negative = " ";
else if (r.has_neg && r.negative.empty() && info.min_tokens == 0) r.negative = " ";
if (guided && !r.has_neg)
return error_response(err_bad(cfg_key, "guidance needs a negative_prompt"), req.peer);
@@ -470,6 +523,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
g->height = r.h;
g->n = r.n;
g->steps = r.steps;
g->sampler = r.sampler;
g->scheduler = r.scheduler;
g->seed = r.seed;
g->previews = r.previews;
/* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is
@@ -585,6 +640,41 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
return RAD_E_STATE;
}
out->n_drop = (int32_t)drop.size();
/* The reference tokenizer's minimum length: an empty prompt is padding the model reads. */
while ((int64_t)out->tokens.size() - out->n_drop < info.min_tokens)
out->tokens.push_back(info.pad_token);
if (info.aux_tokens) {
if (deps_.images->encode_aux(prompt, &out->aux) < 0) {
*err = err_internal("the prompt could not be read by the model's second "
"tokenizer");
return RAD_E_STATE;
}
if ((int64_t)out->aux.size() > info.aux_max_tokens) {
*err = err_bad("prompt", "the prompt is " + std::to_string(out->aux.size()) +
" tokens to this model's second tokenizer, which "
"reads at most " +
std::to_string(info.aux_max_tokens));
return RAD_E_INVAL;
}
}
/* A prompt read in windows: runs of at most chunk_tokens after the prefix, each between
* its markers and padded to the window. */
if (info.chunk_tokens > 0) {
const size_t W = (size_t)info.chunk_tokens;
std::vector<int32_t> win(out->tokens.begin(), out->tokens.begin() + out->n_drop);
const size_t n_body = out->tokens.size() - (size_t)out->n_drop;
size_t at = 0;
do {
const size_t take = std::min(W, n_body - at);
win.push_back(info.chunk_bos);
win.insert(win.end(), out->tokens.begin() + out->n_drop + (std::ptrdiff_t)at,
out->tokens.begin() + out->n_drop + (std::ptrdiff_t)(at + take));
win.push_back(info.chunk_eos);
win.resize(win.size() + (W - take), info.chunk_pad);
at += take;
} while (at < n_body);
out->tokens = std::move(win);
}
if ((int64_t)out->tokens.size() > info.max_cond_tokens) {
*err = err_bad("prompt", "the prompt is " + std::to_string(out->tokens.size()) +
" tokens with its pictures; this deployment conditions on "
@@ -600,6 +690,19 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
return error_response(err, req.peer);
}
/* ---- the adapters' slot, held until the request is done */
std::string lora_note;
if (!loras.empty()) {
std::string why;
const int s = opt_.gen_lora_acquire(loras, &g->lora_slot, &g->lora_hold, &lora_note, &why);
if (s < 0) {
ApiError e = err_bad("loras", why);
if (s == RAD_E_NOTFOUND) { e.status = 404; e.type = "not_found_error"; }
else if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
return error_response(e, req.peer);
}
}
/* ---- admitted and queued */
if (auto no = admit(1, req.peer)) return *no;
std::shared_ptr<gen::Ticket> ticket = g->ticket;
@@ -613,9 +716,11 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
return error_response(e, req.peer);
}
}
RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s", edit ? "edit" : "generation", r.w,
std::string lora_s;
for (const auto& [n, w] : loras) lora_s += (lora_s.empty() ? " loras=" : ",") + n + fmt(":%g", w);
RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s%s", edit ? "edit" : "generation", r.w,
r.h, r.n, r.steps, (unsigned long long)r.seed, r.has_neg ? " guided" : "",
r.has_mask ? " masked" : "", r.stream ? " streamed" : "");
r.has_mask ? " masked" : "", r.stream ? " streamed" : "", lora_s.c_str());
/* ---- one finished picture to a file */
const std::string size_s = std::to_string(r.w) + "x" + std::to_string(r.h);
+117
View File
@@ -0,0 +1,117 @@
/* loras.cpp -- see loras.h. */
#include "loras.h"
#include "rad_internal.h"
#include <cmath>
#include <cstdlib>
namespace rad {
namespace server {
namespace {
/* "name" or "name:strength" (the last ':' splits, so a name may hold one). */
bool split_entry(const std::string& s, std::string* name, double* w) {
*w = 1.0;
const size_t c = s.rfind(':');
if (c != std::string::npos && c + 1 < s.size()) {
char* end = nullptr;
const double v = std::strtod(s.c_str() + c + 1, &end);
if (end && *end == '\0' && std::isfinite(v)) {
*name = s.substr(0, c);
*w = v;
return !name->empty();
}
}
*name = s;
return !name->empty();
}
} /* namespace */
int parse_loras(const nlohmann::json& body, std::string* prompt,
std::vector<std::pair<std::string, double>>* out, std::string* field,
std::string* why) {
out->clear();
const char* key = body.contains("loras") ? "loras" : "lora";
if (body.contains(key) && !body[key].is_null()) {
*field = key;
const nlohmann::json& v = body[key];
auto entry = [&](const nlohmann::json& e) -> bool {
std::string name;
double w = 1.0;
if (e.is_string()) {
if (!split_entry(e.get<std::string>(), &name, &w)) return false;
} else if (e.is_object()) {
if (!e.contains("name") || !e["name"].is_string()) return false;
name = e["name"].get<std::string>();
for (const char* k : { "weight", "strength", "scale" })
if (e.contains(k) && !e[k].is_null()) {
if (!e[k].is_number()) return false;
w = e[k].get<double>();
}
} else {
return false;
}
if (name.empty() || !std::isfinite(w)) return false;
out->push_back({ name, w });
return true;
};
if (v.is_array()) {
for (const nlohmann::json& e : v)
if (!entry(e)) {
*why = "each entry is a name, \"name:strength\" or {\"name\", \"weight\"}";
return RAD_E_INVAL;
}
} else if (v.is_object() && !v.contains("name")) {
for (auto it = v.begin(); it != v.end(); ++it) {
if (!it.value().is_number() || !std::isfinite(it.value().get<double>())) {
*why = "a {name: strength} object's strengths are numbers";
return RAD_E_INVAL;
}
out->push_back({ it.key(), it.value().get<double>() });
}
} else if (!entry(v)) {
*why = "expected a list of adapters (names, \"name:strength\" or {\"name\", \"weight\"})";
return RAD_E_INVAL;
}
}
/* <lora:name[:strength]> tags in the prompt. */
if (prompt) {
std::string p;
size_t at = 0;
for (;;) {
const size_t open = prompt->find("<lora:", at);
if (open == std::string::npos) { p += prompt->substr(at); break; }
const size_t close = prompt->find('>', open);
if (close == std::string::npos) { p += prompt->substr(at); break; }
std::string name;
double w = 1.0;
if (!split_entry(prompt->substr(open + 6, close - open - 6), &name, &w)) {
*field = "prompt";
*why = "a <lora:...> tag names no adapter";
return RAD_E_INVAL;
}
out->push_back({ name, w });
p += prompt->substr(at, open - at);
at = close + 1;
}
if (p.size() != prompt->size()) {
/* Tidy the gaps the tags leave: runs of spaces, and commas with nothing between. */
std::string t;
for (char c : p) {
if (c == ' ' && (t.empty() || t.back() == ' ')) continue;
t += c;
}
for (size_t k; (k = t.find(", ,")) != std::string::npos;) t.erase(k, 2);
for (size_t k; (k = t.find(",,")) != std::string::npos;) t.erase(k, 1);
while (!t.empty() && (t[0] == ' ' || t[0] == ',')) t.erase(0, 1);
while (!t.empty() && (t.back() == ' ' || t.back() == ',')) t.pop_back();
*prompt = t.empty() ? std::string(" ") : t;
}
}
return RAD_OK;
}
} /* namespace server */
} /* namespace rad */
+30
View File
@@ -0,0 +1,30 @@
/* loras.h -- which runtime LoRA adapters an image or video request asks for, and at what strength.
*
* Two spellings, merged:
*
* `loras` in the body: a list whose entries are a name, "name:strength", or an object
* {"name": ..., "weight" | "strength" | "scale": ...}; or an object {name: strength}.
* `lora` is the same field.
*
* <lora:name> or <lora:name:strength> in the prompt, as Stable Diffusion web UIs write it: the
* tag is taken out of the prompt, the text around it kept.
*
* A strength not given is 1. */
#pragma once
#include <nlohmann/json.hpp>
#include <string>
#include <utility>
#include <vector>
namespace rad {
namespace server {
/* RAD_OK with the adapters in `out` (possibly none) and their tags removed from *prompt;
* RAD_E_INVAL with `why` for a malformed entry. `field` receives the field the error is about. */
int parse_loras(const nlohmann::json& body, std::string* prompt,
std::vector<std::pair<std::string, double>>* out, std::string* field,
std::string* why);
} /* namespace server */
} /* namespace rad */
+17
View File
@@ -132,6 +132,7 @@ void Server::register_routes() {
return r;
});
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
router_.get ("/v1/loras", [this](const HttpRequest& q) { return handle_loras(q); });
router_.get ("/v1/models/*id", [this](const HttpRequest& q) { return handle_models(q); });
router_.post("/v1/load_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, true); });
router_.post("/v1/unload_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, false); });
@@ -1864,6 +1865,22 @@ HttpResponse Server::handle_models(const HttpRequest& req) {
/* Runtime LoRA admin, vLLM's routes and bodies: {"lora_name", "lora_path"} to load, {"lora_name"}
* to unload. The path is read on this machine, so without --api-key only a loopback client may
* ask, the rule /diagnostics follows. */
/* A generator's adapter files: what `loras` and <lora:...> tags may name. */
HttpResponse Server::handle_loras(const HttpRequest& req) {
using json = nlohmann::json;
if (!opt_.gen_lora_names) {
ApiError e;
e.status = 404;
e.type = "not_found_error";
e.message = "this server takes no adapters in image or video requests (--lora, --lora-dir)";
return error_response(e, req.peer);
}
json data = json::array();
for (const std::string& n : opt_.gen_lora_names()) data.push_back({ { "id", n }, { "object", "lora" } });
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{ { "object", "list" }, { "data", std::move(data) } }));
}
HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
using json = nlohmann::json;
auto fail = [&](int status, const char* type, const std::string& msg) {
+7
View File
@@ -141,6 +141,12 @@ struct ServerOptions {
* of an adapter requests still use drains it: RAD_OK with *in_flight > 0 (Engine::lora_unload). */
std::function<int(const std::string&, const std::string&, std::string*)> lora_load;
std::function<int(const std::string&, std::string*, int*)> lora_unload;
/* A generator's adapters (Engine::gen_lora_acquire): the images and videos endpoints' `loras`
* and <lora:...> tags get a slot holding that combination, a hold on it and a note on what was
* left out; `gen_lora_names` is GET /v1/loras. Unset without adapters. */
std::function<int(const std::vector<std::pair<std::string, double>>&, int32_t*,
std::shared_ptr<void>*, std::string*, std::string*)> gen_lora_acquire;
std::function<std::vector<std::string>()> gen_lora_names;
std::string api_key;
bool cors = true;
@@ -240,6 +246,7 @@ private:
void realtime_run(RealtimeSession& s, WsConn& ws);
bool realtime_loop(RealtimeSession& s, WsConn& ws);
HttpResponse handle_models(const HttpRequest& req);
HttpResponse handle_loras(const HttpRequest& req);
HttpResponse handle_metrics(const HttpRequest& req);
std::optional<HttpResponse> refuse_text(const std::string& peer,
ApiShape shape = ApiShape::OpenAI);
+26 -3
View File
@@ -39,6 +39,7 @@
* special tokens and the prompt without, so a caller cannot write control tokens into it.
*/
#include "server.h"
#include "loras.h"
#include "oai.h"
#include "gen/video.h"
@@ -168,7 +169,9 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"),
req.peer);
json v = p.data;
if (p.name == "target" || p.name == "conditions") {
if (p.name == "target" || p.name == "conditions" ||
((p.name == "loras" || p.name == "lora") && !p.data.empty() &&
(p.data[0] == '[' || p.data[0] == '{'))) {
v = json::parse(p.data, nullptr, false);
if (v.is_discarded())
return error_response(err_bad(p.name, "expected JSON"), req.peer);
@@ -183,7 +186,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
static const char* kKnown[] = {
"model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps",
"task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps",
"negative_prompt", "decoder",
"negative_prompt", "decoder", "loras", "lora",
/* RadVideoGenBatch::guidance_h's order */
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale",
@@ -210,7 +213,17 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
if (!has(body, "prompt") || !body["prompt"].is_string() ||
body["prompt"].get<std::string>().find_first_not_of(" \t\r\n") == std::string::npos)
return bad("prompt", "the prompt is required, as a non-empty string");
const std::string prompt = body["prompt"].get<std::string>();
std::string prompt = body["prompt"].get<std::string>();
/* Runtime LoRA adapters: `loras` and <lora:...> tags, which leave the prompt. */
std::vector<std::pair<std::string, double>> loras;
{
std::string field, why;
if (parse_loras(body, &prompt, &loras, &field, &why) < 0) return bad(field.c_str(), why);
if (!loras.empty() && !opt_.gen_lora_acquire)
return error_response(err_unsupported(field.c_str(), "this server was started without "
"adapters (--lora, --lora-dir)"),
req.peer);
}
if (has(body, "input_reference")) {
/* JSON: a data URL, as a string or an image_url object. */
const json& v = body["input_reference"];
@@ -497,6 +510,16 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
}
/* ---- admitted and queued: the job holds its place until its file is written */
if (!loras.empty()) {
std::string why, note;
const int s = opt_.gen_lora_acquire(loras, &r->lora_slot, &r->lora_hold, &note, &why);
if (s < 0) {
ApiError e = err_bad("loras", why);
if (s == RAD_E_NOTFOUND) { e.status = 404; e.type = "not_found_error"; }
else if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
return error_response(e, req.peer);
}
}
if (auto no = admit(1, req.peer)) return *no;
auto j = std::make_shared<VideoJob>();
j->id = new_video_id();
+150 -27
View File
@@ -1,5 +1,6 @@
#include "text/tokenizer.h"
#include "text/tokenizer_bpe.h"
#include "text/tokenizer_grapheme.h"
#include "text/tokenizer_nfc.h"
#include "text/tokenizer_regex.h"
#include "text/unicode_norm.h"
@@ -388,6 +389,8 @@ struct TokEncoder {
/* Split, a regex Replace, ByteLevel with use_regex, and the character-class
* pre-tokenisers; `re2` is BertPreTokenizer's punctuation after its whitespace split. */
std::unique_ptr<TokRegex> re, re2;
/* Precompiled: the decoded character map. */
std::unique_ptr<PrecompiledMap> pmap;
};
std::vector<Step> norm, pre;
uint32_t kind = RAD_TOK_BPE;
@@ -403,6 +406,12 @@ struct TokEncoder {
TokTable text; /* token text -> lowest id */
TokTable raw; /* raw bytes a byte-level token stands for -> id */
int32_t byte_sym[256]; /* raw byte -> id of its byte-level character */
/* BPE's end-of-word suffix (RAD_PRE_END_OF_WORD), empty without one. A word's last symbol
* is its text with the suffix: `raw_eow` holds the tokens ending in it by the raw bytes
* before it, and `byte_sym_eow` a byte's character with it. */
std::string eow;
TokTable raw_eow;
int32_t byte_sym_eow[256];
int32_t byte_tok[256]; /* raw byte -> id of "<0xNN>" */
MergeTable merges;
std::vector<uint8_t> types;
@@ -419,6 +428,10 @@ struct TokEncoder {
std::unique_ptr<std::atomic<uint8_t>[]> self_merges;
SpecialMatcher specials;
/* The added tokens matched in the normalised text (RAD_PRE_ADDED_NORMALIZED); `specials`
* holds the rest. */
SpecialMatcher nspecials;
bool has_nspecials = false;
mutable SegmentCache cache;
int build(const VocabBuild& b, const std::vector<int32_t>& special);
@@ -443,11 +456,19 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
for (const VocabStep& s : b.steps) {
if (step_is_norm(s.kind)) {
Step st{ s, nullptr, nullptr };
Step st{ s, nullptr, nullptr, nullptr };
if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) RAD_TRY(compile(s.arg0, "Replace", &st.re));
if (s.kind == RAD_NORM_PRECOMPILED) {
st.pmap = std::make_unique<PrecompiledMap>();
std::string why;
if (st.pmap->load(s.arg0, &why) < 0) {
RAD_ERR("vocab: the Precompiled normaliser's map: %s", why.c_str());
return RAD_E_FORMAT;
}
}
norm.push_back(std::move(st));
} else if (step_is_pre(s.kind)) {
Step st{ s, nullptr, nullptr };
Step st{ s, nullptr, nullptr, nullptr };
if (s.kind == RAD_PRE_SPLIT) RAD_TRY(compile(s.arg0, "Split", &st.re));
if (s.kind == RAD_PRE_WHITESPACE) {
RAD_TRY(compile(s.flags == kPreWhitespace ? k_word_runs : k_space_runs,
@@ -462,6 +483,7 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
if (s.flags & 2) RAD_TRY(compile(k_gpt2_pattern, "ByteLevel", &st.re));
}
if (s.kind == RAD_PRE_BYTE_FALLBACK) byte_fallback = true;
if (s.kind == RAD_PRE_END_OF_WORD) eow = s.arg0;
if (s.kind == RAD_PRE_METASPACE && s.iarg == 1) prepend_first = true;
pre.push_back(std::move(st));
}
@@ -469,7 +491,7 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
if (kind == RAD_TOK_BPE) {
for (size_t k = pre.size(); k-- > 0; ) {
const uint32_t sk = pre[k].step.kind;
if (sk == RAD_PRE_BYTE_FALLBACK) continue;
if (sk == RAD_PRE_BYTE_FALLBACK || sk == RAD_PRE_END_OF_WORD) continue;
if (sk == RAD_PRE_BYTELEVEL) defer_bytelevel = (int)k;
break;
}
@@ -490,12 +512,20 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
const char buf[7] = { '<', '0', 'x', hex[c >> 4], hex[c & 15], '>', 0 };
byte_tok[c] = text.find(buf);
byte_sym[c] = text.find(a.to_utf8[c]);
byte_sym_eow[c] = eow.empty() ? -1 : text.find(a.to_utf8[c] + eow);
}
if (defer_bytelevel >= 0) {
raw.reserve(n);
std::string r;
for (size_t i = 0; i < n; ++i)
if (!b.tokens[i].empty() && byte_decode_strict(b.tokens[i], &r)) raw.insert(r, (int32_t)i);
for (size_t i = 0; i < n; ++i) {
const std::string& t = b.tokens[i];
if (t.empty()) continue;
if (!eow.empty() && t.size() > eow.size() &&
t.compare(t.size() - eow.size(), eow.size(), eow) == 0 &&
byte_decode_strict(t.substr(0, t.size() - eow.size()), &r))
raw_eow.insert(r, (int32_t)i);
if (byte_decode_strict(t, &r)) raw.insert(r, (int32_t)i);
}
}
/* Keyed by the pair as the vocab lists it; the lowest rank wins a duplicate. A symbol's id is
@@ -511,7 +541,17 @@ int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special)
merges.insert((int32_t)l, (int32_t)rr, (uint32_t)r, text.find(cat));
}
specials.build(special, b.tokens, b.types);
/* Each matcher keeps the priority order of `special` (longest first). */
std::vector<int32_t> raw_special, norm_special;
for (int32_t id : special) {
bool normalized = false;
for (const VocabStep& s : b.steps)
normalized |= s.kind == RAD_PRE_ADDED_NORMALIZED && s.iarg == id;
(normalized ? norm_special : raw_special).push_back(id);
}
specials.build(raw_special, b.tokens, b.types);
nspecials.build(norm_special, b.tokens, b.types);
has_nspecials = !norm_special.empty();
self_merges.reset(new std::atomic<uint8_t>[n]());
/* A byte-level BPE never looks text up by its mapped spelling once `raw` exists. */
if (defer_bytelevel >= 0) text = TokTable();
@@ -541,8 +581,8 @@ int Vocab::load(VocabBuild b) {
* so a vocabulary that declares one does not load. */
for (const VocabStep& s : b_.steps) {
const uint32_t k = s.kind;
if ((k >= RAD_NORM_NFC && k <= RAD_NORM_PREPEND) ||
(k >= RAD_PRE_BYTELEVEL && k <= RAD_PRE_BYTE_FALLBACK) ||
if ((k >= RAD_NORM_NFC && k <= RAD_NORM_PRECOMPILED) ||
(k >= RAD_PRE_BYTELEVEL && k <= RAD_PRE_ADDED_NORMALIZED) ||
(k >= RAD_DEC_BYTELEVEL && k <= RAD_DEC_BYTE_FALLBACK))
continue;
RAD_ERR("vocab: %s is not implemented", step_describe(s).c_str());
@@ -570,6 +610,19 @@ int Vocab::load(VocabBuild b) {
if (s.kind == RAD_DEC_STRIP && fused) fused_strip = true;
}
}
/* A token matched in the normalised text is one of the vocabulary's added tokens, spelt as
* the step says. */
for (const VocabStep& s : b_.steps) {
if (s.kind != RAD_PRE_ADDED_NORMALIZED) continue;
const int32_t id = (int32_t)s.iarg;
if (s.iarg < 0 || s.iarg >= (int64_t)b_.tokens.size() || s.arg0.empty() ||
b_.tokens[(size_t)id] != s.arg0 ||
(!b_.types.empty() && b_.types[(size_t)id] != RAD_TT_CONTROL &&
b_.types[(size_t)id] != RAD_TT_USER_DEFINED)) {
RAD_ERR("vocab: %s names no added token of that spelling", step_describe(s).c_str());
return RAD_E_FORMAT;
}
}
if (b_.types.empty()) b_.types.assign(b_.tokens.size(), (uint8_t)RAD_TT_NORMAL);
if (b_.types.size() != b_.tokens.size()) {
RAD_ERR("vocab: %zu tokens but %zu token types", b_.tokens.size(), b_.types.size());
@@ -781,6 +834,8 @@ std::string step_describe(const VocabStep& s) {
return fmt("Replace(%s '%s' -> '%s')", (s.flags & 1) ? "regex" : "literal",
s.arg0.c_str(), s.arg1.c_str());
case RAD_NORM_PREPEND: return fmt("Prepend('%s')", s.arg0.c_str());
case RAD_NORM_PRECOMPILED:
return fmt("Precompiled(%zu base64 bytes)", s.arg0.size());
case RAD_PRE_BYTELEVEL:
return fmt("ByteLevel(add_prefix_space=%d use_regex=%d)",
(s.flags & 1) ? 1 : 0, (s.flags & 2) ? 1 : 0);
@@ -806,6 +861,9 @@ std::string step_describe(const VocabStep& s) {
case RAD_PRE_DIGITS:
return fmt("Digits(individual=%d)", (s.flags & 1) ? 1 : 0);
case RAD_PRE_BYTE_FALLBACK: return "ByteFallback";
case RAD_PRE_END_OF_WORD: return fmt("EndOfWordSuffix('%s')", s.arg0.c_str());
case RAD_PRE_ADDED_NORMALIZED:
return fmt("AddedNormalized('%s' = %lld)", s.arg0.c_str(), (long long)s.iarg);
case RAD_DEC_BYTELEVEL: return "decode ByteLevel";
case RAD_DEC_METASPACE:
return fmt("decode Metaspace('%s' prepend=%lld)", s.arg0.c_str(), (long long)s.iarg);
@@ -839,7 +897,13 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) {
std::vector<uint32_t> cpts = unicode_cpts_from_utf8(text);
std::string out;
out.reserve(text.size());
for (uint32_t c : cpts) out += unicode_cpt_to_utf8(unicode_tolower(c));
/* HuggingFace lowercases a character at a time with Rust's char::to_lowercase, whose
* one unconditional mapping to two characters is U+0130 (I with dot above) to
* "i" U+0307; every other character maps to one. */
for (uint32_t c : cpts) {
if (c == 0x130) out += "i\xcc\x87";
else out += unicode_cpt_to_utf8(unicode_tolower(c));
}
text.swap(out);
break;
}
@@ -868,6 +932,7 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) {
}
break;
case RAD_NORM_PREPEND: text = s.arg0 + text; break;
case RAD_NORM_PRECOMPILED: text = st.pmap->normalize(text); break;
}
}
@@ -1055,7 +1120,8 @@ private:
void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out,
EncodeScratch& sc) {
const bool raw = e.defer_bytelevel >= 0;
const TokTable& table = raw ? e.raw : e.text;
const bool eow = !e.eow.empty();
const TokTable& table = raw ? (eow ? e.raw_eow : e.raw) : e.text;
/* A user-defined token is taken whole: added tokens must round-trip, and the merge table was
* never fitted over them, so re-merging can give a different sequence.
@@ -1065,7 +1131,9 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
* different split of a rare word). The raw-byte table finds the same entry by its byte
* spelling. A control entry is never taken whole: reaching here means the caller asked for
* it to be read as text. */
const int32_t whole = table.find(w);
/* With an end-of-word suffix the whole word is its text and the suffix: `raw_eow` is keyed
* without it, the text table with it. */
const int32_t whole = eow && !raw ? table.find(std::string(w) + e.eow) : table.find(w);
if (whole >= 0 && (e.types[whole] == RAD_TT_USER_DEFINED ||
(e.ignore_merges && e.types[whole] != RAD_TT_CONTROL))) {
out.push_back(whole);
@@ -1083,10 +1151,13 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
if (raw) {
for (size_t i = 0; i < n; ++i)
syms.push_back({ (uint32_t)i, 1, e.byte_sym[(unsigned char)w[i]] });
if (eow) syms.back().id = e.byte_sym_eow[(unsigned char)w[n - 1]];
} else {
for (size_t i = 0; i < n; ) {
const size_t len = std::min(unicode_len_utf8(w[i]), n - i);
syms.push_back({ (uint32_t)i, (uint32_t)len, table.find(w.substr(i, len)) });
syms.push_back({ (uint32_t)i, (uint32_t)len,
eow && i + len == n ? table.find(std::string(w.substr(i, len)) + e.eow)
: table.find(w.substr(i, len)) });
i += len;
}
}
@@ -1103,9 +1174,12 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
/* Miss: decompose into byte tokens, spelt per the chain. Under ByteLevel each byte is its
* own mapped codepoint, so the piece splits at codepoint boundaries; under byte fallback
* a byte is "<0xNN>". */
const bool last = s.start + s.len == n;
if (raw) {
for (unsigned char c : str) {
const int32_t b = e.byte_sym[c];
for (size_t k = 0; k < str.size(); ++k) {
const unsigned char c = (unsigned char)str[k];
const int32_t b = eow && last && k + 1 == str.size() ? e.byte_sym_eow[c]
: e.byte_sym[c];
if (b >= 0) out.push_back(b);
else RAD_WARN("tokenizer: no token for byte-level piece '%s'",
alphabet().to_utf8[c].c_str());
@@ -1113,7 +1187,9 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
} else if (e.bytelevel) {
for (size_t k = 0; k < str.size(); ) {
const size_t m = std::min(unicode_len_utf8(str[k]), str.size() - k);
const int32_t b = e.text.find(str.substr(k, m));
const int32_t b = eow && last && k + m == str.size()
? e.text.find(std::string(str.substr(k, m)) + e.eow)
: e.text.find(str.substr(k, m));
if (b >= 0) out.push_back(b);
else RAD_WARN("tokenizer: no token for byte-level piece '%s'",
std::string(str.substr(k, m)).c_str());
@@ -1142,9 +1218,13 @@ void bpe(const TokEncoder& e, const Pieces& p, std::vector<int32_t>& out, Encode
if (w.empty()) continue;
/* A one-byte word of a byte-level vocab is that byte's token; the lookup and the merge
* would both land on byte_sym. A missing one takes the warning path in bpe_word. */
if (raw && w.size() == 1 && e.byte_sym[(unsigned char)w[0]] >= 0) {
out.push_back(e.byte_sym[(unsigned char)w[0]]);
continue;
if (raw && w.size() == 1) {
const int32_t b = e.eow.empty() ? e.byte_sym[(unsigned char)w[0]]
: e.byte_sym_eow[(unsigned char)w[0]];
if (b >= 0) {
out.push_back(b);
continue;
}
}
if (w.size() > WordCache::kMaxKey) { bpe_word(e, w, out, sc); continue; }
const uint64_t h = tok_hash(w);
@@ -1259,13 +1339,10 @@ void wordpiece(const Vocab& v, const TokEncoder& e, const Pieces& p, std::vector
}
}
/* One segment -- the text between two special tokens -- through the whole chain. `at_start`:
* the segment begins the text (see apply_metaspace). */
int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
std::vector<int32_t>& out, EncodeScratch& sc, WordCache& words, bool at_start) {
/* Normalised text in `sc.p.buf` through the pre-tokenisers and the model. */
int encode_normalized(const Vocab& v, const TokEncoder& e, std::vector<int32_t>& out,
EncodeScratch& sc, WordCache& words, bool at_start) {
Pieces& p = sc.p;
p.buf.assign(seg.data(), seg.size());
for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st);
if (p.buf.size() > (size_t)(UINT32_MAX / 8)) {
RAD_ERR("tokenizer: a %zu-byte segment is past what one encode can index", p.buf.size());
return RAD_E_INVAL;
@@ -1302,6 +1379,12 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
case RAD_PRE_BYTE_FALLBACK:
/* Declares how an unknown piece is encoded, not a split; bpe_word handles it. */
break;
case RAD_PRE_END_OF_WORD:
/* Declares how a word's last symbol is spelt, not a split; bpe_word handles it. */
break;
case RAD_PRE_ADDED_NORMALIZED:
/* Cut out by encode_segment before the pre-tokenisers run. */
break;
}
}
@@ -1323,8 +1406,45 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
return RAD_OK;
}
/* One segment -- the text between two special tokens -- through the whole chain. `at_start`:
* the segment begins the text (see apply_metaspace). The added tokens matched in the normalised
* text are cut out of it after the normalisers, under the same `parse_special` rule as the raw
* ones, and each piece between them goes through the rest of the chain on its own. */
int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg,
std::vector<int32_t>& out, EncodeScratch& sc, WordCache& words, bool at_start,
bool parse_special) {
Pieces& p = sc.p;
p.buf.assign(seg.data(), seg.size());
for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st);
if (!e.has_nspecials) return encode_normalized(v, e, out, sc, words, at_start);
const std::string norm = p.buf;
std::vector<SpecialFrag> frags;
e.nspecials.split(norm, parse_special, frags);
for (const SpecialFrag& f : frags) {
if (f.id >= 0) { out.push_back(f.id); continue; }
if (f.len == 0) continue;
p.buf.assign(norm, f.off, f.len);
RAD_TRY(encode_normalized(v, e, out, sc, words, at_start && f.off == 0));
}
return RAD_OK;
}
} /* namespace */
int vocab_normalize(const std::vector<VocabStep>& steps, std::string* text) {
for (const VocabStep& s : steps) {
if (!step_is_norm(s.kind)) continue;
TokEncoder::Step st{ s, nullptr, nullptr };
if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) {
std::string why;
if (TokRegex::compile(s.arg0, &st.re, &why) < 0) return RAD_E_UNSUPPORTED;
}
apply_norm(*text, st);
}
return RAD_OK;
}
/* ================================================================== encode */
int Tokenizer::init(std::shared_ptr<const Vocab> v) {
@@ -1372,14 +1492,17 @@ int Tokenizer::encode(std::string_view text, std::vector<int32_t>& out,
/* The cache is keyed on the segment's bytes, so a segment whose ids also depend on
* starting the text bypasses it. */
const bool at_start = f.off == 0;
if (!use_cache_ || seg.size() < kSegmentCacheMin || (at_start && e.prepend_first)) {
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start));
/* A segment's ids also depend on parse_special when added tokens are matched in its
* normalised text; the cache holds only the parse_special form. */
if (!use_cache_ || seg.size() < kSegmentCacheMin || (at_start && e.prepend_first) ||
(e.has_nspecials && !parse_special)) {
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start, parse_special));
continue;
}
const uint64_t h = tok_hash(seg);
if (e.cache.lookup(seg, h, out)) continue;
const size_t start = out.size();
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start));
RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start, parse_special));
e.cache.insert(seg, h, out.data() + start, out.size() - start);
}
+4
View File
@@ -337,6 +337,10 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t section_
int vocab_deserialize(const void* file_base, uint64_t file_bytes,
const RadVocabHeader* h, VocabBuild& out);
/* `text` through the normaliser steps of `steps` (the others are skipped), as the encoder runs
* them. RAD_E_UNSUPPORTED when a Replace pattern does not compile. */
int vocab_normalize(const std::vector<VocabStep>& steps, std::string* text);
/* Human-readable one-liner for a step, for --debug-graph and for the convert log. */
std::string step_describe(const VocabStep& s);
+210
View File
@@ -0,0 +1,210 @@
/* tokenizer_grapheme.cpp -- extended grapheme clusters and the precompiled normaliser
* (tokenizer_grapheme.h). */
#include "text/tokenizer_grapheme.h"
#include "rad_internal.h"
#include <algorithm>
#include <cstring>
namespace rad {
namespace {
enum Gcb : uint32_t { kOther, kCR, kLF, kControl, kExtend, kZWJ, kRI, kPrepend, kSpacingMark,
kL, kV, kT, kLV, kLVT };
enum InCB : uint32_t { kInNone, kInLinker, kInConsonant, kInExtend };
uint32_t lookup(const ucd::GbRange* r, size_t n, uint32_t c) {
size_t lo = 0, hi = n;
while (lo < hi) {
const size_t mid = (lo + hi) / 2;
if (r[mid].last < c) lo = mid + 1;
else hi = mid;
}
return lo < n && r[lo].first <= c ? r[lo].v : 0;
}
uint32_t gcb(uint32_t c) { return lookup(ucd::k_gcb, ucd::k_gcb_n, c); }
bool pict(uint32_t c) { return lookup(ucd::k_ext_pict, ucd::k_ext_pict_n, c) != 0; }
uint32_t incb(uint32_t c) { return lookup(ucd::k_incb, ucd::k_incb_n, c); }
/* One codepoint off well-formed UTF-8 at `p`, its byte length in *len. A byte that starts no
* well-formed sequence is taken alone. */
uint32_t utf8_at(const unsigned char* p, size_t left, size_t* len) {
const unsigned char b = p[0];
auto cont = [&](size_t k) { return k < left && (p[k] & 0xC0) == 0x80; };
if (b < 0x80) { *len = 1; return b; }
if ((b & 0xE0) == 0xC0 && cont(1)) { *len = 2; return ((b & 0x1Fu) << 6) | (p[1] & 0x3Fu); }
if ((b & 0xF0) == 0xE0 && cont(1) && cont(2)) {
*len = 3;
return ((b & 0x0Fu) << 12) | ((p[1] & 0x3Fu) << 6) | (p[2] & 0x3Fu);
}
if ((b & 0xF8) == 0xF0 && cont(1) && cont(2) && cont(3)) {
*len = 4;
return ((b & 0x07u) << 18) | ((p[1] & 0x3Fu) << 12) | ((p[2] & 0x3Fu) << 6) |
(p[3] & 0x3Fu);
}
*len = 1;
return 0xFFFD;
}
int b64_value(char c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
}
} /* namespace */
/* UAX #29's rules GB3 to GB13 in their order, the lookbehind of GB9c (a conjunct's consonant,
* linker and consonant), GB11 (an emoji ZWJ sequence) and GB12/13 (regional indicator pairs)
* carried as state from the cluster's start, where no such sequence can be cut. */
size_t grapheme_end(const uint32_t* cps, size_t n, size_t i) {
uint32_t prev = gcb(cps[i]);
/* The text so far ends in Extended_Pictographic Extend*; and did before `prev`. */
bool ep = pict(cps[i]), ep_before = false;
/* Regional indicators ending at `prev`. */
int ri = prev == kRI ? 1 : 0;
/* GB9c: 0 nothing, 1 a consonant then Extend/Linker without a linker, 2 with one. */
int conj = 0;
{
const uint32_t in = incb(cps[i]);
conj = in == kInConsonant ? 1 : 0;
}
size_t j = i + 1;
for (; j < n; ++j) {
const uint32_t c = cps[j], cur = gcb(c);
bool join;
if (prev == kCR && cur == kLF) join = true; /* GB3 */
else if (prev == kControl || prev == kCR || prev == kLF) join = false; /* GB4 */
else if (cur == kControl || cur == kCR || cur == kLF) join = false; /* GB5 */
else if (prev == kL && (cur == kL || cur == kV || cur == kLV || cur == kLVT)) join = true;
else if ((prev == kLV || prev == kV) && (cur == kV || cur == kT)) join = true; /* GB7 */
else if ((prev == kLVT || prev == kT) && cur == kT) join = true; /* GB8 */
else if (cur == kExtend || cur == kZWJ) join = true; /* GB9 */
else if (cur == kSpacingMark) join = true; /* GB9a */
else if (prev == kPrepend) join = true; /* GB9b */
else if (conj == 2 && incb(c) == kInConsonant) join = true; /* GB9c */
else if (prev == kZWJ && ep_before && pict(c)) join = true; /* GB11 */
else if (prev == kRI && cur == kRI && (ri & 1)) join = true; /* GB12/13 */
else join = false;
if (!join) break;
ep_before = ep;
ep = pict(c) || (ep && cur == kExtend);
ri = cur == kRI ? ri + 1 : 0;
const uint32_t in = incb(c);
if (in == kInConsonant) conj = 1;
else if (in == kInLinker && conj >= 1) conj = 2;
else if (in == kInExtend && conj >= 1) { /* kept */ }
else conj = 0;
prev = cur;
}
return j;
}
/* ================================================================== the precompiled map */
/* The charsmap is a little-endian u32 byte count of the trie, the trie's u32 units (Darts' double
* array), then the replacement strings, each NUL-terminated. */
int PrecompiledMap::load(std::string_view b64, std::string* why) {
std::string raw;
raw.reserve(b64.size() / 4 * 3);
uint32_t acc = 0;
int bits = 0;
for (char ch : b64) {
if (ch == '=') break;
const int v = b64_value(ch);
if (v < 0) {
if (why) *why = "the precompiled charsmap is not base64";
return RAD_E_FORMAT;
}
acc = (acc << 6) | (uint32_t)v;
bits += 6;
if (bits >= 8) {
bits -= 8;
raw.push_back((char)((acc >> bits) & 0xFF));
}
}
if (raw.size() < 4) {
if (why) *why = "the precompiled charsmap is shorter than its header";
return RAD_E_FORMAT;
}
uint32_t tbytes = 0;
std::memcpy(&tbytes, raw.data(), 4);
if (tbytes % 4 || (size_t)tbytes > raw.size() - 4 || tbytes == 0) {
if (why) *why = "the precompiled charsmap's trie does not fit it";
return RAD_E_FORMAT;
}
trie_.resize(tbytes / 4);
std::memcpy(trie_.data(), raw.data() + 4, tbytes);
blob_.assign(raw.data() + 4 + tbytes, raw.size() - 4 - tbytes);
return RAD_OK;
}
bool PrecompiledMap::transform(std::string_view s, std::string_view* out) const {
auto offset = [](uint32_t u) { return (u >> 10) << ((u & (1u << 9)) >> 6); };
auto label = [](uint32_t u) { return u & ((1u << 31) | 0xFFu); };
auto leaf = [](uint32_t u) { return ((u >> 8) & 1u) != 0; };
auto value = [](uint32_t u) { return u & ((1u << 31) - 1); };
size_t pos = 0;
uint32_t unit = trie_[0];
pos ^= offset(unit);
for (unsigned char c : s) {
if (c == 0) break;
pos ^= c;
if (pos >= trie_.size()) return false;
unit = trie_[pos];
if (label(unit) != c) return false;
pos ^= offset(unit);
if (pos >= trie_.size()) return false;
if (leaf(unit)) {
const size_t at = value(trie_[pos]);
if (at >= blob_.size()) return false;
const size_t end = blob_.find('\0', at);
*out = std::string_view(blob_).substr(at, (end == std::string::npos ? blob_.size()
: end) - at);
return true;
}
}
return false;
}
/* HuggingFace's Precompiled::normalize: a cluster under six bytes goes whole to its shortest
* mapped prefix's replacement when it has one; otherwise each character goes to its own, or
* stays. */
std::string PrecompiledMap::normalize(std::string_view text) const {
std::vector<uint32_t> cps;
std::vector<size_t> at;
cps.reserve(text.size());
at.reserve(text.size() + 1);
const unsigned char* p = (const unsigned char*)text.data();
for (size_t k = 0; k < text.size();) {
size_t len = 1;
cps.push_back(utf8_at(p + k, text.size() - k, &len));
at.push_back(k);
k += len;
}
at.push_back(text.size());
std::string out;
out.reserve(text.size());
std::string_view rep;
for (size_t i = 0; i < cps.size();) {
const size_t e = grapheme_end(cps.data(), cps.size(), i);
const std::string_view g = text.substr(at[i], at[e] - at[i]);
if (g.size() < 6 && transform(g, &rep)) {
out.append(rep);
} else {
for (size_t k = i; k < e; ++k) {
const std::string_view ch = text.substr(at[k], at[k + 1] - at[k]);
if (transform(ch, &rep)) out.append(rep);
else out.append(ch);
}
}
i = e;
}
return out;
}
} /* namespace rad */
+56
View File
@@ -0,0 +1,56 @@
/* tokenizer_grapheme.h -- extended grapheme clusters (UAX #29) and SentencePiece's precompiled
* normaliser, which walks its text by them.
*
* HuggingFace tokenizers' `Precompiled` normaliser (a SentencePiece model's `precompiled_charsmap`,
* T5's among them) takes the text one extended grapheme cluster at a time: a cluster shorter than
* six bytes is replaced whole by the mapping of its shortest mapped prefix, if it has one;
* otherwise each of its characters is replaced by its own mapping or kept. The cluster
* boundaries are therefore part of the result, and they are Unicode 16.0.0's, the version the
* reference's segmentation crate implements (tools/gen_grapheme_ucd.py writes the tables).
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include <string_view>
#include <vector>
namespace rad {
namespace ucd {
/* A run of codepoints [first, last] holding one value of a property. */
struct GbRange { uint32_t first, last; uint32_t v; };
/* Grapheme_Cluster_Break, values in tools/gen_grapheme_ucd.py's GCB order (0 is Other). */
extern const GbRange k_gcb[];
extern const size_t k_gcb_n;
/* Extended_Pictographic (v 1). */
extern const GbRange k_ext_pict[];
extern const size_t k_ext_pict_n;
/* Indic_Conjunct_Break: 1 Linker, 2 Consonant, 3 Extend (absent: None). */
extern const GbRange k_incb[];
extern const size_t k_incb_n;
} /* namespace ucd */
/* The end of the extended grapheme cluster that starts at `cps[i]`: the index one past its last
* codepoint. `i < n`. */
size_t grapheme_end(const uint32_t* cps, size_t n, size_t i);
/* SentencePiece's precompiled character map: a double-array trie over UTF-8 source strings, each
* leaf the offset of its NUL-terminated replacement in a string blob. */
class PrecompiledMap {
public:
/* `charsmap_b64` is tokenizer.json's `precompiled_charsmap` as it stands, base64. RAD_OK, or
* RAD_E_FORMAT with `why` for a map that does not decode or whose trie points outside it. */
int load(std::string_view charsmap_b64, std::string* why);
bool ready() const { return !trie_.empty(); }
/* The normalised text, as HuggingFace's Precompiled normaliser writes it. */
std::string normalize(std::string_view text) const;
private:
/* The replacement of the shortest mapped prefix of `s`, or false when no prefix is mapped. */
bool transform(std::string_view s, std::string_view* out) const;
std::vector<uint32_t> trie_;
std::string blob_;
};
} /* namespace rad */
File diff suppressed because it is too large. Load diff
+83 -15
View File
@@ -9,6 +9,7 @@
* vocab_serialize() into the .rad's vocab section, and back.
*/
#include "text/tokenizer.h"
#include "text/tokenizer_grapheme.h"
#include "text/tokenizer_regex.h"
#include "text/gguf.h"
@@ -164,6 +165,21 @@ int read_normalizer(const json& n, std::vector<VocabStep>& out, const char* orig
out.push_back(s);
return RAD_OK;
}
if (t == "Precompiled") {
/* SentencePiece's precompiled character map (T5's), kept base64 as the file carries it
* and decoded at load (tokenizer_grapheme.h). */
s.kind = RAD_NORM_PRECOMPILED;
s.arg0 = str_or(n, "precompiled_charsmap", "");
PrecompiledMap pm;
std::string why;
if (s.arg0.empty() || pm.load(s.arg0, &why) < 0) {
RAD_ERR("%s: Precompiled normalizer: %s", origin,
s.arg0.empty() ? "no precompiled_charsmap" : why.c_str());
return RAD_E_FORMAT;
}
out.push_back(s);
return RAD_OK;
}
if (t == "Prepend") {
s.kind = RAD_NORM_PREPEND;
s.arg0 = str_or(n, "prepend", "");
@@ -385,12 +401,10 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
if (type == "BPE") {
out.kind = RAD_TOK_BPE;
out.ignore_merges = bool_or(m, "ignore_merges", false);
/* Subword affixes change what every merge produces, and dropout makes encoding random;
* the encoder implements neither. */
for (const char* k : { "continuing_subword_prefix", "end_of_word_suffix" }) {
const std::string v = str_or(m, k, "");
if (!v.empty()) return refuse_value(origin, (std::string("BPE ") + k).c_str(), v);
}
/* A continuation prefix changes what every merge produces, and dropout makes encoding
* random; the encoder implements neither. */
const std::string prefix = str_or(m, "continuing_subword_prefix", "");
if (!prefix.empty()) return refuse_value(origin, "BPE continuing_subword_prefix", prefix);
if (const json* d = get(m, "dropout"); d && d->is_number() && d->get<double>() > 0.0)
return refuse_value(origin, "BPE dropout", d->dump());
RAD_TRY(read_text_to_id("BPE"));
@@ -434,6 +448,18 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
return RAD_E_UNSUPPORTED;
}
/* The end-of-word suffix (CLIP's "</w>") is a model property in tokenizer.json but a step
* here, as byte fallback is below: it changes the symbols a word starts as. */
if (type == "BPE") {
const std::string eow = str_or(m, "end_of_word_suffix", "");
if (!eow.empty()) {
VocabStep s;
s.kind = RAD_PRE_END_OF_WORD;
s.arg0 = eow;
out.steps.push_back(s);
}
}
/* Byte fallback is a model property in tokenizer.json but a step here: it changes what the
* encoder does on a miss. */
if (bool_or(m, "byte_fallback", false)) {
@@ -472,12 +498,17 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
* The encoder matches an added token against the raw text, exactly as written. HuggingFace's
* AddedToken flags each change that: `single_word` matches only between word boundaries,
* `normalized` matches against the normalised text (the same thing when there is no normaliser),
* and `lstrip` / `rstrip` take the whitespace beside a match into it. Most files spell out every
* and `lstrip` / `rstrip` take the whitespace beside a match into it. A normalised token becomes a
* RAD_PRE_ADDED_NORMALIZED step, placed first among the pre-tokenisers (so `<|StartOfText|>` under
* a Lowercase is CLIP's `<|startoftext|>`); one whose spelling the normaliser itself changes would
* be matched by that changed spelling, which is refused. Most files spell out every
* flag, so a flag is refused only at a value that changes the result. lstrip and rstrip would
* also refuse released models (Phi-3's chat markers carry rstrip), and the container has no field
* to carry them, so they are warned about instead. */
int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id_limit,
bool has_normalizer) {
const std::vector<VocabStep>& norm) {
const bool has_normalizer = !norm.empty();
std::vector<VocabStep> matched_normalized;
if (!arr.is_array()) return RAD_OK;
std::string stripped;
for (const json& e : arr) {
@@ -500,14 +531,27 @@ int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id
const bool special = bool_or(e, "special", false);
if (bool_or(e, "single_word", false))
return refuse_value(origin, "added token single_word=true on", content);
if (has_normalizer && bool_or(e, "normalized", false))
return refuse_value(origin, "added token normalized=true (under a normalizer) on",
content);
if (has_normalizer && bool_or(e, "normalized", false)) {
std::string n = content;
if (vocab_normalize(norm, &n) != RAD_OK || n != content)
return refuse_value(origin, "added token normalized=true (under a normalizer that "
"changes its spelling) on", content);
if (!content.empty()) {
VocabStep st;
st.kind = RAD_PRE_ADDED_NORMALIZED;
st.arg0 = content;
st.iarg = (int64_t)id;
matched_normalized.push_back(st);
}
}
if (bool_or(e, "lstrip", false) || bool_or(e, "rstrip", false))
stripped += (stripped.empty() ? "" : " ") + content;
out.tokens[id] = content;
out.types[id] = special ? (uint8_t)RAD_TT_CONTROL : (uint8_t)RAD_TT_USER_DEFINED;
}
/* Ahead of the other pre-tokenisers, after the normalisers. */
out.steps.insert(out.steps.begin() + (std::ptrdiff_t)norm.size(), matched_normalized.begin(),
matched_normalized.end());
if (!stripped.empty())
RAD_WARN("%s: added tokens %s take the whitespace beside them in HuggingFace (lstrip / "
"rstrip); this tokenizer keeps it as text, so prompts with whitespace next to "
@@ -544,8 +588,11 @@ void read_config_json(const std::string& dir, VocabBuild& out) {
auto it = id_of.find(text);
return it == id_of.end() ? -1 : it->second;
};
out.bos = token_id("bos_token");
out.eos = token_id("eos_token");
/* An id the post-processor already gave (interpret_tokenizer_json) stays when the config
* names no such token. */
const int32_t bos = token_id("bos_token"), eos = token_id("eos_token");
if (bos >= 0 || out.bos < 0) out.bos = bos;
if (eos >= 0 || out.eos < 0) out.eos = eos;
out.pad = token_id("pad_token");
out.unk = out.unk >= 0 ? out.unk : token_id("unk_token");
out.sep = token_id("sep_token");
@@ -622,7 +669,7 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
out.steps.insert(out.steps.end(), dec.begin(), dec.end());
if (const json* a = get(j, "added_tokens"))
RAD_TRY(read_added(*a, out, origin, id_limit, !norm.empty()));
RAD_TRY(read_added(*a, out, origin, id_limit, norm));
/* The model's unknown token, by text. The encoder emits it for text no token covers, which
* HuggingFace does too; tokenizer_config.json's unk_token, read later, agrees or is absent. */
@@ -654,7 +701,28 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi
* Only a special token before and/or after the sequence is read. The config's
* add_bos_token / add_eos_token, read later, win where present. */
if (const json* pp = get(j, "post_processor")) {
if (str_or(*pp, "type", "") == "TemplateProcessing") {
const std::string ppt = str_or(*pp, "type", "");
/* RobertaProcessing and BertProcessing frame a sequence as `cls $A sep`; they name the
* two tokens, which stand for BOS and EOS where the config names none (CLIP's). */
if (ppt == "RobertaProcessing" || ppt == "BertProcessing") {
auto framing = [&](const char* k) -> int32_t {
const json* v = get(*pp, k);
int32_t id = -1;
if (!v || !v->is_array() || v->size() != 2 || !read_id((*v)[1], out.tokens.size(), &id))
return -1;
return id;
};
const int32_t cls = framing("cls"), sep = framing("sep");
if (cls < 0 || sep < 0) {
RAD_ERR("%s: %s names no [token, id] cls and sep in the vocabulary", origin,
ppt.c_str());
return RAD_E_FORMAT;
}
out.bos = cls;
out.eos = sep;
out.add_bos = out.add_eos = true;
}
if (ppt == "TemplateProcessing") {
const json* single = get(*pp, "single");
if (single && single->is_array() && !single->empty()) {
auto special = [](const json& e) -> bool { return e.is_object() && e.contains("SpecialToken"); };
+16
View File
@@ -0,0 +1,16 @@
# anima-bf16.recipe -- Anima (Base, Aesthetic or Turbo) at bf16.
#
# rad-convert <Anima>/split_files/diffusion_models/anima-aesthetic-v1.1.safetensors \
# --add <Anima>/split_files/text_encoders/qwen_3_06b_base.safetensors \
# --add <Anima>/split_files/vae/qwen_image_vae.safetensors \
# --config <Qwen/Qwen3-0.6B-Base> --tokenizer2 <ComfyUI>/comfy/text_encoders/t5_tokenizer/tokenizer.json \
# --arch anima --set anima.variant=aesthetic \
# --recipe data/recipes/anima-bf16.recipe -o anima-aesthetic-bf16.rad
#
# Every linear stays as the release holds it (bf16). Two weights are computed at convert, in f32,
# and stored bf16 here: the patch embedding without its padding-mask columns, and the VAE's causal
# 3-D convolutions read at their last temporal tap.
dit.x_embed.weight cast dtype=bf16
decoder.* cast dtype=bf16
conv2.* cast dtype=bf16
+31
View File
@@ -0,0 +1,31 @@
# anima-fp8.recipe -- Anima (Base, Aesthetic or Turbo) with block-scaled fp8 linears.
#
# rad-convert <Anima>/split_files/diffusion_models/anima-aesthetic-v1.1.safetensors \
# --add <Anima>/split_files/text_encoders/qwen_3_06b_base.safetensors \
# --add <Anima>/split_files/vae/qwen_image_vae.safetensors \
# --config <Qwen/Qwen3-0.6B-Base> --tokenizer2 <ComfyUI>/comfy/text_encoders/t5_tokenizer/tokenizer.json \
# --arch anima --set anima.variant=aesthetic \
# --recipe data/recipes/anima-fp8.recipe -o anima-aesthetic-fp8.rad
#
# Every linear of the text encoder and of the DiT's 28 blocks (self- and cross-attention, MLP)
# becomes E4M3 codes with a bf16 scale a 128 x 128 block, read by the fp8a8 GEMMs over activations
# quantised the same way. The LLM adapter, the embeddings, the modulation linears, the final layer
# and the VAE stay bf16. The patch embedding (without its padding-mask columns) and the VAE's causal
# convolutions (at their last temporal tap) are computed at convert and stored bf16.
te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.cross_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.cross_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.cross_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.cross_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.mlp_layer1.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.mlp_layer2.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.x_embed.weight cast dtype=bf16
decoder.* cast dtype=bf16
conv2.* cast dtype=bf16
+45
View File
@@ -0,0 +1,45 @@
# krea-2-fp8-unscaled.recipe -- a Krea 2 finetune shipped as plain fp8 (every tensor E4M3 with no
# scale, as ComfyUI's fp8 checkpoints and most civitai Krea 2 files store it), with block-scaled fp8
# linears.
#
# rad-convert <pipeline directory: Krea-2-Turbo's (or -Raw's) model_index, scheduler, text encoder,
# tokenizer and VAE, with the finetune's DiT as transformer/> \
# --recipe data/recipes/krea-2-fp8-unscaled.recipe -o finetune-fp8.rad
#
# The DiT's and the text fusion's linears keep the checkpoint's codes: every value is already on the
# E4M3 grid, so a block scale of exactly 1 (rule=fixed) holds each one as the code it was shipped
# as, where an absmax scale would round it a second time. The text encoder is the release's bf16 and
# is rounded as krea-2-fp8.recipe rounds it. The norms, tables and embedders the finetune stores as
# E4M3 are widened exactly to the dtypes krea-2-fp8.recipe gives them. A Turbo finetune takes
# Turbo's model_index.json (`is_distilled`: 8 steps, no guidance), a Raw one Raw's.
te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
fuse.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
fuse.*.attn_gate.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
fuse.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
fuse.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
fuse.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
dit.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
dit.blk.*.attn_gate.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
dit.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
dit.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
dit.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1
# The release stores its norms, modulation tables, embedders, projector and output layer f32.
# diffusers keeps every norm f32 and runs the rest bf16. Here the text fusion's norms, the q/k norms
# and txt_in's norm stay f32; the DiT's norm1, norm2 and final norm are bf16, the fused modulation
# kernel's operand, with the rest.
fuse.*.norm1.weight cast dtype=f32
fuse.*.norm2.weight cast dtype=f32
fuse.*.q_norm.weight cast dtype=f32
fuse.*.k_norm.weight cast dtype=f32
dit.blk.*.q_norm.weight cast dtype=f32
dit.blk.*.k_norm.weight cast dtype=f32
txt.norm.weight cast dtype=f32
fuse.* cast dtype=bf16
txt.* cast dtype=bf16
dit.* cast dtype=bf16
vae.* cast dtype=bf16
+41
View File
@@ -0,0 +1,41 @@
# q38-27b-mxfp4-df2.recipe -- a bf16 Qwen3.8-27B (or a finetune of it) at MXFP4 with the DFlash2
# drafter.
#
# rad-convert <bf16 Qwen3.8-27B checkpoint> --draft-model <z-lab/Qwen3.8-27B-DFlash2> \
# --recipe q38-27b-mxfp4-df2.recipe \
# --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \
# -o q38-27b-mxfp4-df2.rad
#
# The --set keys give the container the family's fp8 descriptor, so qwen35_fp8 serves it as it
# serves the Quark, ParoQuant and NVFP4 releases; without them a bf16 checkpoint selects
# qwen35_bf16, which has no 4-bit GEMM.
#
# The trunk's linears are rounded to MXFP4 (`fp4_e2m1`, an e8m0 scale per 32 of K, the OCP exponent
# rule) from the bf16 source, once: the encoding and kernels of q38-27b-quark-mxfp4-df2.recipe,
# without Quark's AWQ fold. The delta net's a/b projections, the norms, the embedding and the
# vision tower stay bf16; the head goes block fp8 as in the other 27B recipes. The checkpoint's MTP
# head is not read: the DFlash2 drafter displaces it.
#
# The drafter as q38-27b-quark-mxfp4-df2.recipe makes it: its linears at MXFP4, and a 2-bit copy
# of the target's head (u2 with a u8 zero, least-squares clip search) whose top 32 the engine
# rescores against the target's fp8 head.
blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.attn_qg.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.ssm_inz.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.ssm_out.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
dflash.fc.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
dflash.blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
dflash.blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
dflash.blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
dflash.blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
dflash.blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
dflash.blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
+9
View File
@@ -0,0 +1,9 @@
# sdxl-bf16.recipe -- Stable Diffusion XL (and its finetunes: Illustrious, NoobAI, Pony, ...) at bf16.
#
# rad-convert <checkpoint>.safetensors --tokenizer <CLIP tokenizer.json> \
# --recipe data/recipes/sdxl-bf16.recipe -o sdxl.rad
#
# A single-file SDXL checkpoint (Stability's layout) ships its weights f16, some finetunes partly
# bf16 or f32; every weight the model reads is served bf16. The VAE's encoder, the text encoders'
# unused tails and the checkpoint's bookkeeping tensors are not carried.
* cast dtype=bf16
+19
View File
@@ -0,0 +1,19 @@
# Anima Aesthetic (circlestone-labs/Anima) as block fp8: text to image on OpenAI's
# /v1/images/generations, on one card, RADIANCE_GPU in .env (default 0). The Base and Turbo
# containers serve the same way (anima-base-fp8.rad, anima-turbo-fp8.rad).
# The CircleStone Labs Non-Commercial License and NVIDIA's Open Model License apply to the model;
# the pictures may be used commercially.
# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under
# $RADIANCE_MODELS/loras/anima and add `--lora-dir /models/loras/anima` to the command;
# a request names them in `loras` or as <lora:name:0.8> in its prompt.
name: radiance-anima
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-anima
environment:
ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
command: >
--model /models/anima-aesthetic-fp8.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 1
+3
View File
@@ -2,6 +2,9 @@
# distilled to eight steps with video sparse attention, the same /v1/videos API and host memory
# as minimax-h3.yaml, about 70 s a 1344x768 clip. It runs only its trained schedule, so a
# request's num_inference_steps may only be 9 (grid points). MiniMax-H3's license applies to it.
# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under
# $RADIANCE_MODELS/loras/h3 and add `--lora-dir /models/loras/h3` to the command;
# a request names them in `loras` or as <lora:name:0.8> in its prompt.
name: radiance-fasth3
services:
radiance:
+3
View File
@@ -2,6 +2,9 @@
# to ten reference pictures on OpenAI's /v1/images/generations and /v1/images/edits, on one card,
# RADIANCE_GPU in .env (default 0). For the base model, point --model at flux-3-klein-base-fp8.rad.
# The FLUX Kommunity License (non-commercial use) applies.
# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under
# $RADIANCE_MODELS/loras/flux3 and add `--lora-dir /models/loras/flux3` to the command;
# a request names them in `loras` or as <lora:name:0.8> in its prompt.
name: radiance-flux-3-klein
services:
radiance:
+3
View File
@@ -1,6 +1,9 @@
# Krea 2 Raw (krea/Krea-2-Raw) as block fp8: text to image on OpenAI's /v1/images/generations, on one
# card, RADIANCE_GPU in .env (default 0). The Krea 2 Community License and Krea's acceptable use
# policy apply.
# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under
# $RADIANCE_MODELS/loras/krea2 and add `--lora-dir /models/loras/krea2` to the command;
# a request names them in `loras` or as <lora:name:0.8> in its prompt.
name: radiance-krea-2-raw
services:
radiance:
+3
View File
@@ -1,6 +1,9 @@
# Krea 2 Turbo (krea/Krea-2-Turbo) as block fp8: text to image on OpenAI's /v1/images/generations,
# on one card, RADIANCE_GPU in .env (default 0).
# The Krea 2 Community License and Krea's acceptable use policy apply.
# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under
# $RADIANCE_MODELS/loras/krea2 and add `--lora-dir /models/loras/krea2` to the command;
# a request names them in `loras` or as <lora:name:0.8> in its prompt.
name: radiance-krea-2-turbo
services:
radiance:
+4
View File
@@ -2,6 +2,10 @@
# from text or from text and a first frame, on OpenAI's /v1/videos, on one card, RADIANCE_GPU in
# .env (default 0). The text encoder is read from pinned host memory (--vision-tower-placement ram).
# For the base model, point --model at ltx-2.5-fp8.rad. The LTX-2.x Community License applies.
# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under
# $RADIANCE_MODELS/loras/ltx2 and add `--lora-dir /models/loras/ltx2` to the command;
# a request names them in `loras` or as <lora:name:0.8> in its prompt.
# At one card the adapter slots fit at `--max-lora-rank 16 --max-loras 1` (433 MiB).
name: radiance-ltx-2.5
services:
radiance:
+3
View File
@@ -3,6 +3,9 @@
# The text encoder and the modulation projections are read from pinned host memory
# (--vision-tower-placement ram), about 39 GiB of it. MiniMax-H3's license excludes use in the EU,
# the UK, the Republic of Korea and the USA.
# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under
# $RADIANCE_MODELS/loras/h3 and add `--lora-dir /models/loras/h3` to the command;
# a request names them in `loras` or as <lora:name:0.8> in its prompt.
name: radiance-minimax-h3
services:
radiance:
+3
View File
@@ -2,6 +2,9 @@
# qwen-image-2.1.yaml's model, the same images API, 2048x2048 by default. It samples on its own
# 8-step schedule, so a request's num_inference_steps may only be 8. --tp-wire wht6 sends the DiT's
# all-reduces as 6-bit; drop it for the exact wire.
# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under
# $RADIANCE_MODELS/loras/qwen-image and add `--lora-dir /models/loras/qwen-image` to the command;
# a request names them in `loras` or as <lora:name:0.8> in its prompt.
name: radiance-qwen-image-turbo
services:
radiance:
+3
View File
@@ -5,6 +5,9 @@
# batch and context for an image generator itself (docs/GUIDE.md §5.6). --tp-wire wht6 sends the
# DiT's all-reduces as 6-bit: about 10% faster per picture at a cost of a few tenths of a dB
# against diffusers; drop it for the exact wire.
# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under
# $RADIANCE_MODELS/loras/qwen-image and add `--lora-dir /models/loras/qwen-image` to the command;
# a request names them in `loras` or as <lora:name:0.8> in its prompt.
name: radiance-qwen-image
services:
radiance:
+15
View File
@@ -0,0 +1,15 @@
# Stable Diffusion XL or one of its finetunes (here Illustrious-XL v2.0, OnomaAIResearch) at bf16: text
# to image on OpenAI's /v1/images/generations, on one card, RADIANCE_GPU in .env (default 0). Any
# single-file SDXL checkpoint converts the same way (README, "Stable Diffusion XL"); point --model
# at its container. The checkpoint's own license applies.
name: radiance-sdxl
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-sdxl
environment:
ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
command: >
--model /models/illustrious-xl-v2.0-bf16.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 1
+149
View File
@@ -22,7 +22,9 @@ plugin claims.
| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 |
| `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 |
| `arch/krea2` | `krea2` | *(empty)* | Krea 2 Raw and Turbo, an image generator: Qwen3-VL-4B's tapped layers through a text-fusion transformer, a 12.9B single-stream DiT and Wan 2.1's VAE, from the diffusers pipeline directory; bf16 or block fp8 |
| `arch/sdxl` | `sdxl` | *(empty)* | Stable Diffusion XL and its finetunes (Illustrious, NoobAI, Pony), an image generator: CLIP ViT-L and OpenCLIP bigG text encoders, the 2.6B UNet sampled by k-diffusion's Euler, Euler ancestral or DPM++ 2M on ComfyUI's schedules, the SDXL VAE; from the single-file checkpoint, bf16, one card |
| `arch/flux3` | `flux3` | *(empty)* | FLUX.3 [klein] and its base, an image generator and editor: Qwen3-VL-4B's tapped layers, a 5.6B three-mode DiT over the text, up to ten reference pictures and the image, FLUX.2's VAE; bf16 or block fp8 |
| `arch/anima` | `anima` | *(empty)* | Anima (Base, Aesthetic, Turbo), an image generator: Qwen3-0.6B-Base through the LLM adapter over the prompt's T5 tokens, Cosmos-Predict2's 2B cross-attention DiT and the Qwen-Image VAE, from the release's single files; bf16 or block fp8, one card |
| `arch/flux3distilled` | `flux3distilled` | *(empty)* | the same plugin under the name FLUX.3 [klein]'s step-distilled release gives itself (`Flux3DistilledModularPipeline`; its base is a `Flux3ModularPipeline`) |
| `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text |
| `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 |
@@ -39,6 +41,25 @@ The traps below are readings that are wrong without any error: the model produce
widths, the KV page size and the attention kernel's band. `core/engine_bringup.cpp` takes it from
the container's meta.
## Adapter key names of the generators
A generator that serves LoRA files ([GUIDE §4.9.2](GUIDE.md)) declares, before its GEMMs, how
those files name its modules (`rad_lora_root`, `rad_lora_alias`; `lora_names` in
`arch/common/rad_arch.h`). Files follow the model's original code or ComfyUI's port of it, while
containers keep the diffusers names, and the two disagree in ways that load without an error and
generate garbage: a fused `qkv` against separate q, k and v, a SwiGLU projection whose gate half
comes first in one and second in the other. The tables, by plugin:
| plugin | adapter files | checkpoint |
|---|---|---|
| `krea2` | `blocks.N.attn.wq/wk/wv/wo/gate`, `mlp.gate/up/down`, `txtfusion.{layerwise,refiner}_blocks.N.*`, `first`, `last_linear`, `tmlp.0/2`, `tproj.1`, `txtmlp.1/3` | `transformer_blocks.N.attn.to_q/...`, `ff.*`, `text_fusion.*`, `img_in`, `final_layer.linear`, `time_embed.linear_1/2`, `time_mod_proj`, `txt_in.linear_1/2` |
| `qwenimage21` | the checkpoint's names, or `img_mlp.gate_up` = [gate; up] | `img_mlp.gate_layer`, `img_mlp.proj` |
| `minimaxh3` | `blocks.N.attn.qkv_proj` (q, k, v), `out_proj`, `mlp.fc1` = [gate; up], `fc2`; `token_refiner.blocks.N.*`; `video_patch_proj`, `audio_patch_proj`, `condition_proj`, `time_embedder.proj_in/out`, `final_layer.video_out/audio_out` | `attn.to_q/k/v`, `to_out.0`, `ff.net.0.proj` = [up; gate], `ff.net.2`; `token_refiner.refiner_blocks.N.*`; `proj_in`, `audio_proj_in`, `context_embedder`, `time_embedder.linear_1/2`, `proj_out`, `audio_proj_out` |
| `flux3` | `single_blocks.N`, `txt_mode_blocks.N`, `content_mode_blocks.{image,image_cond}.N` with `q_proj/k_proj/v_proj` or `qkv`, `attn_out`, `mlp_in`, `mlp_out` | `single_transformer_blocks.N`, `txt_mode_blocks.N`, `mode_blocks.{image,image_cond}.N` with `attn.to_q/k/v`, `attn.to_out.0`, `ff.linear_in/out` |
| `ltx2` | the checkpoint's names | |
| `anima` | the checkpoint's names behind `diffusion_model.` / `lora_unet_`; the text encoder as `lora_te_layers_N_...` | DiT under `net.` or `model.diffusion_model.`, Qwen3 under `model.layers.` |
| `sdxl` | kohya's `lora_unet_` over the single-file UNet paths (convolutions included), `lora_te1_` / `lora_te2_` over the CLIPs' transformers names | UNet under `model.diffusion_model.`, CLIP-L and bigG under `conditioner.embedders.{0,1}.transformer.` |
---
# `llama`: the plain decoder
@@ -922,6 +943,76 @@ quantisation's: the container's codes decoded to bf16 on the host give the same
---
# `sdxl`: Stable Diffusion XL and its finetunes, an image generator
`arch/sdxl` serves SDXL 1.0 and every finetune published as one `.safetensors` in Stability's
(sgm) layout: Illustrious, NoobAI, Pony and the civitai checkpoints built on them. rad-convert's
importer (`core/format/checkpoint.cpp`, `open_sgm`) reads the file as it ships; the plugin is a
JOINT_STEP generator whose conditioning rides in each lane's store and is read by the UNet's cross
attention, and whose sampler is the core's discrete-time one (`RadGeneratorDecl::train_steps`).
```
names the UNet under model.diffusion_model.*, CLIP ViT-L under
conditioner.embedders.0.transformer.text_model.*, both as the file has them; OpenCLIP
bigG renamed to transformers' CLIPTextModelWithProjection under
conditioner.embedders.1.transformer.* (in_proj split into q/k/v_proj, c_fc/c_proj as
fc1/fc2, ln_* as layer_norm*, text_projection transposed into a linear's weight); the VAE
decoder in diffusers' names under vae.*. These are the names kohya's lora_unet_*,
lora_te1_* and lora_te2_* adapters are written against
text the prompt in CLIP windows: BOS, up to 75 tokens, EOS, padding to 77 (the core cuts them,
RadGeneratorDecl::chunk_tokens), each window encoded on its own and causally. ViT-L (12
layers, quick_gelu) and bigG (32 layers, gelu); the context is ViT-L's and bigG's
PENULTIMATE hidden states side by side (2048 wide, no final norm); the pooled vector is
bigG's LAST layer through final_layer_norm at the first window's EOS, through
text_projection
padding ViT-L's padding is EOS (49407), bigG's is token 0 ("!"), as the two tokenizers pad; the
padded rows are part of the context the UNet attends to
UNet 320/640/1280 channels at 1, 1/2, 1/4 of the latent; residual blocks (GroupNorm(32) eps
1e-5, SiLU, 3x3 conv, the time embedding's projection added per channel, a 1x1 skip when
the width changes); spatial transformers (GroupNorm eps 1e-6, linear proj_in/out, blocks
of self attention, cross attention over the context and GEGLU, 64-wide heads) 2 deep at
1/2, 10 deep at 1/4 and in the middle; skip connections concatenated after h
added the time embedding (sinusoid of the timestep, cos first, 320 wide) plus label_emb of
[pooled | sinusoids of (height, width), (0, 0), (height, width)] (2816 wide)
VAE AutoencoderKL, 4 channels at 8x, the latent divided by 0.13025; run bf16
sampler k-diffusion over 1000 scaled-linear timesteps (betas 0.00085..0.012): f32 latent lanes,
the UNet's input x / sqrt(sigma^2 + 1), the timestep the nearest trained one (ComfyUI),
guidance on the denoised estimates; Euler, Euler ancestral, DPM++ 2M on ComfyUI's
normal, karras, exponential, sgm_uniform and simple schedules
```
Each denoising pass runs the UNet once per entry at that entry's size: a convolution's image size
comes from its operands, so two sizes cannot share a launch. The sampler ops run over every entry.
Every 3x3 convolution is `im2col_nhwc` and a `gemm_nt_bias` over the weight read as
`[cout, cin * 9]` (the checkpoint's order), so it carries a runtime LoRA like a linear; this is 9%
faster than `conv2d_nhwc` over the UNet's shapes at 1024x1024, slower only at 1/1 with 320
channels. conv_in and out.2 (4 channels) are direct convolutions.
Traps:
- **The context is the penultimate layer of both encoders.** hidden_states[-2], before any final
norm; only the pooled vector goes through bigG's final norm, from its last layer.
- **bigG's padding is not EOS.** Its tokenizer pads with "!"; reading the padding as EOS changes
the context rows the UNet attends to (it does not change the pooled vector).
- **The size conditioning is (height, width), not (width, height)**, each through its own
256-wide sinusoid, after the pooled vector.
- **open_clip's text_projection multiplies from the right** (x @ P); a linear's weight is P^T.
- **bf16, not f16.** The release is f16 and the SDXL VAE overflows in f16; bf16 has f32's range.
Against a torch reference -- diffusers' text encoders, UNet and VAE in f32 under the same
k-diffusion loop, schedule and Philox noise -- from the same seeds at 1024x1024 on one R9700 (relative
L2; diffusers' own bf16 run against the same f32 one in brackets): ViT-L's context 0.28% (0.28%),
bigG's 1.8% (2.0%), the pooled vector 0.9% (1.0%), the UNet's first evaluation 0.25% (0.31%); the VAE
on the same latent 45.0 dB. Whole pictures (PSNR against f32; diffusers bf16 in brackets): SDXL 1.0
Euler 31.3 dB (27.4), DPM++ 2M Karras 34.6 dB, Euler ancestral 24.8 dB (18.0); Illustrious-XL v2.0
Euler 30.0 dB, Euler ancestral 22.3 dB (25.7), 832x1216 Euler 33.1 dB (28.3 against a reference
given (width, height) for its size); NoobAI-XL V-Pred 1.0 (v prediction, zero terminal
SNR) Euler 22.4 dB (22.6). A 91-token prompt's two windows against the same windows encoded by
transformers in f32 (Illustrious): ViT-L 0.7% in each, bigG 1.6% and 2.2%, the pooled vector 1.3%.
An image is the same bytes whether its pass carries other requests' images of other sizes or not.
---
# `flux3`: FLUX.3 [klein] and its base, an image generator and editor
`arch/flux3` declares a JOINT_STEP generator over three modes: the text, the reference pictures'
@@ -968,6 +1059,64 @@ base guided 2.30, an edit with one reference picture 1.16.
---
# `anima`: Anima (Base, Aesthetic, Turbo), an image generator
`arch/anima` declares a JOINT_STEP generator, though its DiT is a cross-attention model: the
conditioning pass leaves each lane's 512 context rows in its store, and every denoising step reads
them back (the entry's text mode, `mode_src`) for the cross-attention's keys and values; the text
rows the layout carries are never run through the DiT. Served on `/v1/images/generations`; it
takes no reference pictures.
```
text Qwen3-0.6B-Base over the prompt as it is (no template); its last hidden state after the
final norm. An empty prompt is one <|endoftext|> (min_tokens 1), not " "
adapter the LLM adapter: the prompt's T5 tokens (the container's second vocabulary) as query
rows, embedded from a 32128-row table; six blocks of RMS-normed self-attention over them,
cross-attention to the Qwen3 rows and a GELU MLP, 16 heads of 64, q and k RMS-normed and
rotated (NeoX, theta 1e4) at their own row index on either side; out_proj and an RMS
norm; zero-padded to 512 rows
DiT Cosmos-Predict2's MiniTrainDIT at 2B: 28 blocks of 2048 (16 heads of 128); per block a
self-attention (q/k RMS norms, a NeoX rotary of 22 + 21 + 21 frequency pairs over
frame, row and column at 10000 x 4^(42/40); the frame is 0), a cross-attention to the
512 context rows (q/k norms, no rotary) and a GELU MLP, each behind a LayerNorm without
affine times (1 + scale) plus shift and added back times its gate
modulation each of a block's three: Linear(256, 6144)(Linear(2048, 256)(silu(e))) + the shared
AdaLN-LoRA term Linear(2048, 6144)(silu(Linear(2048, 2048)(t))), t the sinusoid of the
step's sigma (a timestep in [0, 1], [cos | sin]) and e its RMS norm
patches a token is 2 x 2 latents, 64 values channel-major; the patch embedding was trained on 68
(a padding-mask channel, always zero), read over its first 64 columns (RAD_MAP_COLS);
the final linear's rows reordered from (row, column, channel) to channel-major
VAE the Qwen-Image VAE under ComfyUI's Wan 2.1 names, 16 channels at 8x; the latent
denormalised with Wan 2.1's statistics in f32
schedule ComfyUI's FLOW sampling (multiplier 1, shift 3) and its `simple` scheduler over 1000
timesteps (sigma_grid), Euler steps; guidance uncond + s (cond - uncond). Base and
Aesthetic: 30 steps, s 4, the card's negative prompt; Turbo: 10 steps, unguided. The
variant is `anima.variant` (rad-convert --set)
```
Traps:
- **T5 tokens, not Qwen3's, are the queries.** The adapter reads the same prompt twice: Qwen3's
ids for the source, T5's for the queries; T5's normaliser is SentencePiece's precompiled map
over extended grapheme clusters (core/text/tokenizer_grapheme.h). Reading the queries off Qwen3's
tokens gives a plausible, wrong picture.
- **The padding rows are attended to.** The context is zero-padded to 512 rows and the DiT's
cross-attention reads all 512: a zero row is a zero key and value, which still takes its share
of the softmax.
- **The DiT keys have two spellings.** Base ships `net.blocks.N...`, Aesthetic 1.1 and Turbo 1.1
`model.diffusion_model.blocks.N...`; the plugin reads the prefix off the checkpoint at convert
and keeps the file's own names as the name map's sources.
- **The empty negative prompt is not " ".** ComfyUI encodes "" as one padding token for Qwen3 and
</s> for T5; the core keeps an empty prompt empty for a model with `min_tokens`.
Against ComfyUI in bf16 on an RTX 4090 from the same noise: the DiT's velocity at sigma 1 rel
0.48% (cos 0.99999) from the bf16 container and 1.5% from the block-fp8 one, the adapter's 512 rows
rel 1.9% (Qwen3's output in bf16 against ComfyUI's f32), the VAE on the same latent 46.9 dB; three
1024 x 1024 pictures after 30 guided steps 32.8, 36.0 and 39.0 dB from bf16, 26.7, 26.0 and 28.6 dB
from fp8 (the same picture to the eye).
---
# `qwen3asr`: speech to text
`model_type: qwen3_asr` (`Qwen3ASRForConditionalGeneration`), served from the checkpoint as it
+2
View File
@@ -145,7 +145,9 @@ the cards the engine runs on.
| `qwen-image-2.1.yaml` | `qwen-image-2.1-fp8.rad` | Qwen-Image 2.1 as block fp8 on two cards: OpenAI's images API, generation and edits |
| `qwen-image-2.1-turbo.yaml` | `qwen-image-2.1-turbo-fp8.rad` | Qwen-Image 2.1 Turbo, the same in 8 steps |
| `krea-2-turbo.yaml`, `krea-2-raw.yaml` | `krea-2-turbo-fp8.rad`, `krea-2-raw-fp8.rad` | Krea 2 Turbo and Raw as block fp8: text to image on one card (`RADIANCE_GPU`) |
| `anima.yaml` | `anima-aesthetic-fp8.rad` | Anima Aesthetic as block fp8: text to image on one card (`RADIANCE_GPU`); the Base and Turbo containers serve the same way |
| `flux-3-klein.yaml` | `flux-3-klein-fp8.rad` | FLUX.3 [klein] as block fp8: generation and edits on one card (`RADIANCE_GPU`); the base container serves the same way |
| `sdxl.yaml` | `illustrious-xl-v2.0-bf16.rad` | Stable Diffusion XL in bf16 (here Illustrious-XL v2.0; any single-file SDXL checkpoint converts the same way): text to image on one card (`RADIANCE_GPU`) |
| `qwen3-asr-1.7b.yaml` | `Qwen3-ASR-1.7B-hf/` (the checkpoint) | Qwen3-ASR 1.7B: `/v1/audio/transcriptions` and live `/v1/realtime`, on one card (`RADIANCE_GPU`) |
| `minimax-h3.yaml` | `minimax-h3-fp8.rad` | MiniMax-H3 as block fp8: video with its stereo soundtrack on `/v1/videos`, two cards and about 39 GiB of pinned host memory |
| `fasth3.yaml` | `fasth3-8-step-v2-fp8.rad` | FastVideo's FastH3 8-Step V2, the same in eight steps |
+134 -11
View File
@@ -277,6 +277,7 @@ and runs.
| `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) |
| `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) |
| `krea2` | Krea 2 Raw and Turbo, an image model from text (§5.6) |
| `anima` | Anima Base, Aesthetic and Turbo, an anime and illustration image model from text (§5.6) |
| `flux3`, `flux3distilled` | FLUX.3 [klein] and its base, an image model that also edits (§5.6); one plugin under the two names the releases give themselves |
| `qwen3asr_bf16` | Qwen3-ASR, speech to text from the checkpoint as it ships (§5.14) |
| `minimaxmusic3` | MiniMax-Music3, songs from a description and lyrics (§5.15) |
@@ -405,6 +406,36 @@ rad-convert /srv/models/krea/Krea-2-Turbo -o krea-2-turbo-fp8.rad \
rad-convert /srv/models/black-forest-labs/flux-3-image-klein -o flux-3-klein-fp8.rad \
--recipe data/recipes/flux-3-klein-fp8.recipe
# A Krea 2 finetune shipped as one DiT file in Krea's key names (civitai, ComfyUI): rewritten as the
# transformer/ of a directory holding the release's other parts (Turbo's model_index.json for a Turbo
# finetune, Raw's for a Raw one); a plain-fp8 file keeps its codes under krea-2-fp8-unscaled.recipe
P=/srv/models/lustify-krea2; mkdir -p $P/transformer
cp -r /srv/models/krea/Krea-2-Turbo/{model_index.json,scheduler,text_encoder,tokenizer,vae} $P/
cp /srv/models/krea/Krea-2-Turbo/transformer/config.json $P/transformer/
scripts/krea2_native.py lustifyNSFWCheckpoint_v10Krea2_fp8.safetensors \
$P/transformer/diffusion_pytorch_model.safetensors
rad-convert $P -o lustify-krea2-turbo-fp8.rad --recipe data/recipes/krea-2-fp8-unscaled.recipe
# Anima, an image model (§5.6): the release's three single files merged (--add), Qwen3-0.6B-Base's
# config.json and tokenizer.json (--config: the repository or a directory with just those two), and
# ComfyUI's T5 tokenizer (comfy/text_encoders/t5_tokenizer/tokenizer.json, with its
# tokenizer_config.json beside it) as the second vocabulary. The variant (base, aesthetic, turbo)
# sets the defaults; anima-bf16.recipe keeps every linear bf16
A=/srv/models/circlestone-labs/Anima/split_files
rad-convert $A/diffusion_models/anima-aesthetic-v1.1.safetensors \
--add $A/text_encoders/qwen_3_06b_base.safetensors --add $A/vae/qwen_image_vae.safetensors \
--config /srv/models/Qwen/Qwen3-0.6B-Base --tokenizer2 /srv/ComfyUI/comfy/text_encoders/t5_tokenizer/tokenizer.json \
--arch anima --set anima.variant=aesthetic -o anima-aesthetic-fp8.rad \
--recipe data/recipes/anima-fp8.recipe
# Stable Diffusion XL or any of its finetunes (Illustrious, NoobAI, Pony, ...), an image model
# (§5.6): the single .safetensors as civitai and Hugging Face publish it (Stability's layout, read as
# it ships), bf16 throughout (6.4 GiB, one card). The file carries no tokenizer: CLIP's tokenizer.json
# (openai/clip-vit-large-patch14) is passed beside it
rad-convert /srv/models/OnomaAIResearch/Illustrious-XL-v2.0/Illustrious-XL-v2.0.safetensors \
-o illustrious-xl-v2.0-bf16.rad --recipe data/recipes/sdxl-bf16.recipe \
--tokenizer /srv/models/openai/clip-vit-large-patch14/tokenizer.json
# LTX-2.5, video with sound (§5.16): the diffusers pipeline directory, latent_upsampler/ included
# for the distilled release's two-stage recipe; fp8 blocks for the text encoder, the connectors and
# the DiT, or bf16 (both recipes keep the vocoders f32, which they run in)
@@ -515,6 +546,13 @@ rad-convert /srv/models/amd/GLM-5.3-Flash-Quark-MXFP4 \
rad-convert /srv/models/unsloth/Qwen3.8-27B-NVFP4 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \
--recipe data/recipes/q38-27b-nvfp4-df2.recipe -o q38-27b-nvfp4-df2.rad
# A bf16 Qwen3.8-27B or finetune (here orcarouter's Uncensored) with the DFlash2 drafter: the trunk
# rounded to MXFP4 once, the head block fp8; the --set keys select the quantised plugin
rad-convert /srv/models/orcarouter/Qwen3.8-27B-Uncensored --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \
--recipe data/recipes/q38-27b-mxfp4-df2.recipe \
--set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \
-o qwen3.8-27b-uncensored-mxfp4.rad
# An int4 W4A16 Qwen3.8-27B (compressed-tensors AWQ or GPTQ, AutoRound's auto_gptq; here ukisai's
# Swift 1.5 W4A16-AWQ, and its INT4 and W4A16-AutoRound the same way): the shipped grids on the
# 4-bit GEMMs, the head block fp8
@@ -1345,11 +1383,57 @@ below.
Refused at startup or load, by name: DoRA, embedding or `lm_head` LoRA, `modules_to_save`, trained
biases, PEFT's `layer_replication`, QA-LoRA and activated LoRA, a module the base does not have, and
a module some op cannot carry -- a routed MoE expert, a rotated (ParoQuant) or otherwise transformed
weight, a GEMM fed int8 codes in the WMMA's step order (`w4a8`, `w8a8`, `w2a8`). Adapters serve models that generate text: an
image, audio or video generator and an embedding model refuse `--lora` and `--max-loras`. A fused
GEMM over a targeted weight (the fp8 gated gate_up fold) is not used while LoRA is on, for base
requests too; the unfused pair runs instead. A drafter keeps the base's weights: proposals are
still verified by the adapter, so output is exact and only the acceptance rate can drop.
weight, a GEMM fed int8 codes in the WMMA's step order (`w4a8`, `w8a8`, `w2a8`). An audio
generator and an embedding model refuse `--lora` and `--max-loras`; image and video generators take
adapter files instead (§4.9.2). A fused GEMM over a targeted weight (the fp8 gated gate_up fold) is
not used while LoRA is on, for base requests too; the unfused pair runs instead. A drafter keeps the
base's weights: proposals are still verified by the adapter, so output is exact and only the
acceptance rate can drop.
### 4.9.2 LoRA files for image and video models
The LoRAs shared for image and video models (Civitai, Hugging Face) are single `.safetensors` files,
named after the model's original code and written by whichever trainer or UI made them. Radiance
reads them as they come, on Krea 2, Anima, Stable Diffusion XL and its finetunes (Illustrious,
NoobAI, Pony), Qwen-Image 2.1, MiniMax H3, FLUX.3 [klein] and LTX-2.5:
```sh
radiance --model krea-2-turbo-fp8.rad --lora-dir /loras --lora film=/loras/film-grain.safetensors
```
- **Spellings:** kohya (`lora_unet_blocks_0_attn_wq.lora_down/up` + `alpha`), ComfyUI
(`diffusion_model.*.lora_A/B` or `lora_down/up`), PEFT/diffusers (`transformer.*.lora_A/B`,
`.default`), bare keys, and the checkpoint's own names. Each model declares how its original
module names map onto the container's (a fused `qkv` onto separate q, k and v, a SwiGLU whose
halves are ordered the other way), so a file trained against either layout lands on the same
weights.
- **Kinds:** LoRA and LoCon (`alpha / rank * up @ down`; on SDXL a LoCon's convolutions too, its
3 x 3 `down` read flattened as the UNet's im2col GEMMs read theirs), LoHa (`hada_w*`, applied exactly as a
product of rank1 x rank2), LoKr (`lokr_w*`, by its Kronecker structure) and full deltas (`.diff`).
DoRA, OFT and Tucker cores are refused by name; bias and norm deltas are reported and left out.
- **Choosing per request:** `/v1/images/generations`, `/v1/images/edits` and `/v1/videos` take
`"loras": ["film", "ink:0.6", {"name": "style/watercolor", "weight": 0.8}]` (or an object
`{"film": 1, "ink": 0.6}`), and Stable Diffusion web UI tags in the prompt, `<lora:film:0.8>`,
which are taken out of the prompt. A strength not given is 1; several adapters stack.
`GET /v1/loras` lists what a request may name: the `--lora` files and every `NAME.safetensors`
under `--lora-dir` (subdirectories one level deep, as `sub/NAME`).
- **Slots:** a slot holds one combination of adapters at their strengths. The first request that
asks for a combination composes it into a free slot, or into the least recently used one no running
request holds (milliseconds to a second, logged with what it left out); later requests find it
there. Requests with different combinations run in separate passes. `--max-loras` sets the slot
count (default: the number of `--lora`, 2 with `--lora-dir` alone).
- **Rank:** `--max-lora-rank` (default 64 for a generator) is the rank every checkpoint module's
slot holds. The slots are VRAM the weights and the arena would otherwise have (startup prints
their size); LTX-2.5, which fills one card on its own, fits one slot at rank 16. Stacked adapters whose ranks fit it, and LoHa and LoKr within it, are held exactly;
past it the sum is truncated to its best rank-R approximation, and the log says how much of the
delta was kept.
- **What carries an adapter:** every plain GEMM of the denoiser (attention, feed-forward, the text
fusion or refiner, embedders and modulation where they are plain), and of the text encoder where
adapter files train it (Anima's Qwen3, SDXL's two CLIPs as kohya's `lora_te1_` / `lora_te2_`;
CLIP-L's last layer, whose output SDXL never reads, has nothing to adapt). An adapter module the model has no
such GEMM for is reported and skipped, as UIs do.
- `POST /v1/load_lora_adapter {"lora_name": "x", "lora_path": "/file.safetensors"}` adds a file
under a name; unload removes it and frees the slots of every combination using it.
### 4.10 Every flag
@@ -1368,7 +1452,7 @@ still verified by the adapter, so output is exact and only the acceptance rate c
| flag | default | |
|---|---|---|
| `--max-num-batched-tokens N` | 8192 | largest token count one step may carry |
| `--max-num-batched-tokens N` | 2048 | largest token count one step may carry |
| `--prefill-interleave N` | 0 (off) | decode-only steps after each prefill chunk while other sequences decode (§4.5), at most 64 |
| `--busy-prefill-chunk MODE` | auto | a prefill chunk's share of a step that has other work: `auto` leaves decode rows and waiting requests their room (§4.5), `off` takes the whole step, `N` holds it to N tokens |
| `--max-num-seqs N` | 256 | largest number of sequences one step may carry |
@@ -1392,9 +1476,10 @@ still verified by the adapter, so output is exact and only the acceptance rate c
| flag | default | |
|---|---|---|
| `--lora NAME=PATH` | none | serve a PEFT LoRA adapter as model NAME; repeatable |
| `--max-loras N` | the number of `--lora` | adapter slots resident at once; 0 with no `--lora` is off |
| `--max-lora-rank R` | 16 | the rank each slot is sized for |
| `--lora NAME=PATH` | none | serve a LoRA adapter: a PEFT directory as model NAME (text), a `.safetensors` file requests name in `loras` (image and video, §4.9.2); repeatable |
| `--lora-dir DIR` | none | image and video models: requests may name any `NAME.safetensors` under DIR |
| `--max-loras N` | the number of `--lora` (2 with `--lora-dir` alone) | adapter slots resident at once; 0 with no adapter is off |
| `--max-lora-rank R` | 16 text, 64 image and video | the rank each slot is sized for |
| `--lora-target-modules LIST` | the adapters' own | HF module names adapters may target |
**Host tier for finished conversations**
@@ -1756,7 +1841,7 @@ becomes up to 280 tokens by default (`--image-tokens`, or a request's `image_tok
`document`, `Retrieval-query`, `STS`, ...) and applies to text and content-part inputs; a model that
states a default prompt applies it when the request names none.
**An image model** (Qwen-Image 2.1 or 2.1-Turbo, Krea 2, FLUX.3 [klein]) serves OpenAI's images API only; completions, chat
**An image model** (Qwen-Image 2.1 or 2.1-Turbo, Krea 2, FLUX.3 [klein], Anima) serves OpenAI's images API only; completions, chat
and embeddings answer 501. OpenAI images clients (Open WebUI, the OpenAI SDKs) work unchanged; the
picture always comes back in the response. The engine sizes the step, batch and context for an image
model itself (`--max-num-batched-tokens` and `--max-model-len` from the model's largest pass,
@@ -1829,6 +1914,44 @@ pictures, each shrunk to 1024x1024 of area when larger. The guidance scale is `g
`true_cfg_scale` (one of them), in the model card's terms. FLUX.3's pipeline can rewrite a prompt
with a separate language model first; radiance reads the prompt as given.
**Anima** makes RGB pictures, 1024x1024 by default, sides rounded down to multiples of 16, up to
1536x1536 (9216 latent tokens; the card's range is 512x512 to 1536x1536). Base and Aesthetic run 30
steps at guidance 4 (`uncond + s (cond - uncond)`, so 1 is off) against the card's negative prompt
(`worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts,
chromatic aberration`); Turbo runs 10 unguided. The sampler is ComfyUI's Euler over its `simple`
schedule at shift 3, so a seed's noise aside, a picture is what ComfyUI's `euler` / `simple`
workflow makes. The prompt is read as written, Danbooru tags and natural language as the card
describes: ComfyUI's `(word:1.2)` weighting and its `\(` escapes are not interpreted, so write
`fern (sousou no frieren)` rather than `fern \(sousou no frieren\)`. A prompt is at most 512
tokens to either of its two tokenizers. Anima reads only text, so `/v1/images/edits` answers 501.
It is under the CircleStone Labs non-commercial license (the pictures may be used commercially).
On one R9700 a 1024x1024 picture takes 8.5 s from the Aesthetic or Base fp8 container (30 guided
steps) and 12.0 s from bf16; Turbo takes 1.6 s (fp8) and 2.2 s (bf16); 1536x1536 takes 24.8 s (fp8).
The fp8 pictures look the same as bf16's; against ComfyUI from the same noise bf16 is 33 to 39 dB,
fp8 26 to 29 dB (docs/ARCHITECTURES.md).
**Stable Diffusion XL** and its finetunes (Illustrious, NoobAI, Pony: any single-file SDXL
checkpoint, §3.2) take the same fields and two more, `sampler` and `scheduler`, by ComfyUI's names:
| field | |
|---|---|
| `sampler` | `euler`, `euler_ancestral` (the default) or `dpmpp_2m` |
| `scheduler` | `normal` (the default), `karras`, `exponential`, `sgm_uniform` or `simple` |
A model sampled by flow matching refuses both fields. SDXL makes RGB pictures, 1024x1024 by default,
sides rounded down to multiples of 32, up to 36864 latent tokens (1536x1536, or that area at another
aspect: 2048x1152). It runs 28 steps at guidance 6 (`guidance_scale`, uncond + s (cond - uncond))
against an empty negative prompt unless the request names one; guidance 1 turns it off. A prompt
longer than CLIP's 75 tokens is read in windows of 75, each encoded on its own and laid end to end
(A1111's and ComfyUI's long-prompt behaviour), up to 8 windows. Emphasis syntax such as
`(masterpiece:1.2)` is not interpreted: the parentheses and the number are read as text. The noise
is radiance's own (the same seed gives the same picture here, not the picture ComfyUI gives).
`/v1/images/edits` answers 501: there is no image-to-image or inpainting yet. A v-prediction
checkpoint (NoobAI-XL V-Pred, marked by its `v_pred` tensor) is sampled as one, with the zero
terminal SNR schedule when the checkpoint says so (`ztsnr`). On one R9700 a 1024x1024 picture at 28
guided steps takes about 5.1 s and 1536x1536 at 25 about 10.8 s; images in flight together share
passes but not launches (the UNet runs once per image and branch), so two take twice as long.
### 5.7 Request fields
| field | notes |
@@ -2748,7 +2871,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.9.0
I STARTUP REPORT -- radiance 1.10.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]
+60 -2
View File
@@ -219,6 +219,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
| `gelu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gelu·up, tanh approx) |
| `seg_sinusoid` | `M`(range) `n` `period` `max_timescale`:f64/opt `cu_div`/opt `dtype` | `cu_seqlens` → `y` |
| `gelu` / `silu` | `M`(range) `n` `dtype` | `x` → `y` |
| `gelu_quick` | `M`(range) `n` `dtype` | `x` → `y` |
| `cast` | `M`(range) `n` `from` `to` | `x` → `y` |
| `softmax` | `M`(range) `n` `dtype` | `x` → `y` |
| `sigmoid` | `M`(range) `n` `dtype` | `x` → `y` |
@@ -230,6 +231,10 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
`gelu` (exact erf) and `silu` share one schema; `silu` has a row of its own because a row names one
op.
**`gelu_quick`** is CLIP's `quick_gelu`, `x * sigmoid(1.702 x)`, rounded where torch stores each
tensor in a reduced dtype: `a = rd(1.702 x)`, `s = rd(1 / (1 + exp(-a)))`, `y = rd(x s)`, `rd` the
rounding to `y`'s dtype and the arithmetic f32 (CLIP-L's feed-forward in SDXL's text encoder).
**`rmsnorm`** is `y = x * rsqrt(mean(x^2) + eps) * (w + wadd)`; `wadd` is GemmaRMSNorm's `1 +`,
added in f32. `mult` scales the normed row before its one rounding, for a residual branch weighted
by a constant (Gemma 4's audio feed-forward adds half its output). For a power of two this equals
@@ -732,6 +737,7 @@ butterfly), so every tile is byte-identical (`tests/r4d_emu/test_f32.cpp`).
|---|---|---|
| `lora_shrink` | `M`(range) `K` `R` `S` `group`/opt `dtype` | `a`, `a_scale`?, `slot`, `lora_a` → `t` |
| `lora_expand` | `M`(range) `N` `R` `S` `dtype` | `t`, `slot`, `lora_b`, `scale`, `y`:inout |
| `lora_expand_mm` | `M`(range) `N` `R` `S` `dtype` | `t`, `slot`, `lora_b`, `scale`, `y`:inout |
The two halves of `y += scale ⊙ (B · (A · x))` at a trunk GEMM, issued by the core right after the
GEMM in the GEMM's own row slice, with several adapters and no adapter mixed in one step; a step
@@ -740,7 +746,9 @@ an i32 per row naming its adapter's pool slot -- the step batch's `RadBatch::lor
GEMM's first row on; **a row with `slot < 0 || slot >= S` is a base row and neither op touches
it**: `lora_shrink` writes nothing into its `t` row, and `lora_expand` does not read or write its
`y` row at all — so a base row stays bit for bit what the GEMM wrote, where `y + 0` would already
have turned a -0 into +0.
have turned a -0 into +0. On an image or video generator's pass every row runs the same adapter,
and `slot` is a run of the core's slot-row table holding that slot's index in every element, so the
GEMM's rows need not be the pass's token rows.
- `lora_shrink`: `t[m, j] = Σ_k x(m, k) · lora_a[s, j, k]`, `s = slot[m]`, f32 accumulate.
`a`/`a_scale` are the GEMM's own first two operands, and `x(m, k)` is the value `gemm_nt_q` uses
@@ -756,6 +764,13 @@ have turned a -0 into +0.
`[S, N, R]` bf16 and `scale` `[S, N]` f32 — per output column, so a fused projection whose parts
carry different `alpha / r` is one launch.
- `lora_expand_mm`: `lora_expand` with `t` rounded to bf16 and the sum over `j` in any order,
`y[m, n] = y[m, n] + scale[s, n] · Σ_j bf16(t[m, j]) · lora_b[s, n, j]`, f32 accumulate, one
rounding to `y`; base rows as `lora_expand`. A row's bytes may depend on `M`. The core declares
it in place of `lora_expand` for an image or video generator, whose passes are thousands of rows
of one adapter and where the exact row's scalar sum is most of the adapter's cost; libr4d runs
it on the WMMA over 64 x 64 tiles.
`a`, `a_scale` and `y` may be row and column slices of wider buffers; every row stride is the
tensor's. The pools are ordinary inputs and not weights: the engine owns them as program buffers
and copies an adapter into a slot between steps, so a recorded pass replays the same pointers and
@@ -1006,8 +1021,11 @@ says which (`libref/ref_gen.cpp`).
| `lane_store` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `dst`:inout |
| `randn_lanes` | `M`(range) `n` `stride` `dtype` | `flags`, `seed`, `lane`, `cu_seqlens`, `dst`:inout |
| `flow_euler` | `M`(range) `n` `stride` `dtype` | `v`, `sigma`, `sigma_next`, `cfg`, `pair`, `lane`, `flags`, `seed`, `cu_seqlens`, `inp_lat`?, `inp_mask`?, `state`:inout, `preview`:inout? |
| `kd_input` | `M`(range) `n` `stride` `dtype` | `sigma`, `pair`, `lane`, `flags`, `seed`, `cu_seqlens`, `state`:inout → `y` |
| `kd_step` | `M`(range) `n` `stride` `pred` `dtype` | `out`, `sigma`, `sigma_next`, `sigma_prev`, `cfg`, `pair`, `lane`, `flags`, `seed`, `sampler`, `step`, `cu_seqlens`, `state`:inout, `hist`:inout, `preview`:inout? |
| `chan_affine` | `M`(range) `n` `mul` `add` `mode` `dtype` `round`/opt | `x` → `y` |
| `conv2d_nhwc` | `M`(range) `cin` `cout` `k` `stride` `pad` `up` `dtype` | `x`, `w`w, `b`w → `y` |
| `im2col_nhwc` | `M`(range) `cin` `k` `stride` `pad` `up` `dtype` | `x` → `y` |
| `l2norm_chan` | `M`(range) `n` `act` `dtype` | `x`, `gamma`w → `y` |
| `d2s_add` | `M`(range) `cin` `cout` `ft` `dtype` | `x`, `y`:inout |
| `s2d_avg_add` | `M`(range) `cin` `cout` `ft` `dtype` | `x`, `y`:inout |
@@ -1057,6 +1075,34 @@ source into every listed lane (a repainted picture's latent into each of its ima
`x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise))` with `m` the lane's f32
`inp_mask` row, `src` its `inp_lat` row and `noise` the seed's stream.
**The k-diffusion sampler.** A denoiser trained on discrete timesteps of a variance-preserving
schedule (SDXL; eps- or v-prediction) is sampled as k-diffusion samples it, in the
variance-exploding form `x = x0 + sigma eps`: the lane holds `x` in f32 (`state` and `hist` are f32
`[lanes * stride, n]`), the model reads `c_in x` with `c_in = 1 / sqrt(sigma^2 + 1)`, and its output
`out` (`dtype`, in the pass's compact image order bounded by `cu_seqlens`) becomes the clean
estimate. Entries, pairs, lanes, flags and seeds are `flow_euler`'s; `sigma`, `sigma_next`,
`sigma_prev` and `cfg` are f32 `[n_seq]`, `sampler` and `step` i32 `[n_seq]`. Every product and sum
is one f32 rounding; `log`, `expm1` and `sqrt` are the library's. A repaint (flag 2) is refused.
- `kd_input`: for every entry with `pair != -2`, a first step (flag 1) sets the lane to the seed's
normal stream times `sqrt(1 + sigma^2)` (`rad_philox_normal(seed, k n + c)`, the start of a
schedule at the model's largest sigma); then `y = rd(x / sqrt(sigma^2 + 1))` at the entry's rows
and, when `pair >= 0`, at the pair's rows too, so the negative entry reads the same latent without
a second writer.
- `kd_step`: for every entry with `pair != -2`, with `x` the lane's value,
`D(o) = x - sigma o` (`pred` `eps`) or `x / (sigma^2 + 1) - o sigma / sqrt(sigma^2 + 1)` (`v`),
guided as `D = D(o_u) + cfg (D(o_c) - D(o_u))` against the pair's rows (`D(o_c)` without one);
flag 4 writes `D` to the lane's `preview`. Then by `sampler`:
0, Euler: `x' = x + (sigma_next - sigma)(x - D) / sigma`;
1, Euler ancestral (eta 1): `sigma_up = min(sigma_next, sqrt(sigma_next^2 (sigma^2 -
sigma_next^2) / sigma^2))`, `sigma_down = sqrt(sigma_next^2 - sigma_up^2)`,
`x' = x + (x - D) / sigma (sigma_down - sigma)`, plus `sigma_up` times the seed's stream
`1 + step` (`rad_philox_normal_s`, element `k n + c`) while `sigma_next > 0`;
2, DPM++ 2M: `x' = D` at `sigma_next` 0; otherwise with `t = -ln sigma`, `h = -ln sigma_next - t`,
`x' = (sigma_next / sigma) x - expm1(-h) D'`, where `D' = D` on a first step and otherwise
`(1 + 1/(2r)) D - (1/(2r)) hist` with `r = (t + ln sigma_prev) / h`.
Every step stores `D` to `hist` for the next. Any other sampler is refused.
**Images** are `[height, width * channels]`, dense, and the ops read both sizes off the operand
shapes: an image's size belongs to a request, and a parameter is fixed at declare.
@@ -1065,6 +1111,16 @@ shapes: an image's size belongs to a request, and a parameter is fixed at declar
is `k/2` zeros a side, `down` is none above and left and one below and right
(`ZeroPad2d((0,1,0,1))` before a stride-2 conv), `causal` is `k - 1` rows above, none below and
`k/2` columns a side (causal along the rows: LTX-2's audio VAE). f32 accumulation, the bias added, one rounding.
- `im2col_nhwc`: `conv2d_nhwc`'s receptive fields as rows, so a convolution is a GEMM against the
checkpoint's own weight. `x` is the image `[Hin, Win * cin]` (rows at their own pitch), read
through `up`, `pad` and `stride` as `conv2d_nhwc` reads it; `y` is `[Ho * Wo, cin * k * k]`, its
rows exactly the output pixels, and row `oy * Wo + ox`, column `(ci * k + i) * k + j` holds the
value `conv2d_nhwc` multiplies `w[o, ci, i, j]` by, 0 in the padding. That column order is the
weight's own `[cout, cin, k, k]` flattened, so `y @ w.reshape(cout, cin k k)^T + b` (a
`gemm_nt_bias`) is the convolution with the weight as stored, and a runtime LoRA over that GEMM
reads a conv adapter's down projection `[rank, cin, k, k]` flattened the same way. A copy: no
arithmetic, the bits moved. libr4d stages a block's k input rows in LDS so its reads and its
stores are both coalesced; it serves `k` up to 7 and `stride` and `up` 1 or 2.
- `l2norm_chan`: each pixel's channels to unit L2 (eps 1e-12), times `sqrt(n)`, times `gamma`
(three roundings), then `act` `none` or `silu`.
- `chan_affine`: `mul` and `add` are space-separated lists of `n` values, each rounded to bf16;
@@ -1464,7 +1520,9 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
and `rstd_g`, and the rest is the implementation's scratch (partial sums of up to 1024 parts a
group; libref leaves it untouched). A kernel may take several launches but must be deterministic,
a fixed reduction order with no float atomics. `y` may be the same memory as `x`. `w` and `b`
`[n]`, bf16 or f32. MiniMax-H3: `n` 512, `groups` 32, `eps` 1e-5.
`[n]`, bf16 or f32. MiniMax-H3: `n` 512, `groups` 32, `eps` 1e-5; SDXL's UNet 320 to 2560
channels in 32 groups (10 to 80 a group), its VAE 128 to 512. libr4d serves `n` a multiple of 8
up to 8192 with an even group width.
- `tconv_dw`: a depthwise convolution along the frames (a Conv3d of kernel `(k, 1, 1)`, one group a
channel): `geom = (T, H, W)`, `P = H W` rows a frame, `w` PyTorch's `[n, 1, k, 1, 1]` (tap `j` of
channel `c` at `c k + j`), `b [n]`, `k` odd:
+12
View File
@@ -107,6 +107,12 @@ rad-convert [options] <input> -o <model.rad>
else every library found
--tokenizer F tokenizer.json; its declared chain is baked instead of being
reconstructed from a pre-tokenizer name
--tokenizer2 F a second tokenizer.json, baked as the container's second vocab: a
generator that reads its prompt through two tokenizers
--add FILE one more .safetensors file merged in, its tensor names kept (a release
shipped as separate single files). Repeatable
--config DIR config.json, generation_config.json and tokenizer.json from DIR, for a
single-file checkpoint that ships none
--imatrix F llama.cpp imatrix: expert profile, column importances, error weighting
--set K=V a metadata key, seen by declare and written into the container. Repeatable
--max-tok N the max_tok declare is run at (default 8192)
@@ -268,6 +274,12 @@ rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
refuses a `--max-tok` and context pair whose score plane would pass 2 GiB.
- `--max-spec`: a container carries what the model can serve, so a draft head is written even when
this run would not draft. `0` leaves it out.
- `--add`, `--config` and `--tokenizer2` read a release that ships as ComfyUI's single files
(Anima: a diffusion model, a text encoder and a VAE in `split_files/`): the files merge into one
namespace with their own tensor names (a name in two files is refused), the text encoder's
repository supplies the config and tokenizer the plugin is sized by, and a second tokenizer.json
(with its `tokenizer_config.json` beside it) becomes the container's second vocab section, which
a generator declaring `aux_tokens` reads its prompt through. GUIDE §3.2 has the Anima command.
- `--draft-model` merges a drafter here; the engine refuses the flag. The drafter's tensors go in
under a `draft.` prefix and its config under `draft.` keys. It has no embedding and no `lm_head`
of its own; it uses the target's.
+19 -2
View File
@@ -314,8 +314,9 @@ std::vector<Case> build_cases() {
add("lora_shrink", { HI("M", M), HI("K", K), HI("R", 48), HI("S", 4),
HI("group", 128), HS("dtype", dt) }, 0, 2.0 * M * 48 * K);
for (const char* dt : { "f32", "bf16", "f16" })
add("lora_expand", { HI("M", M), HI("N", 645), HI("R", 48), HI("S", 4),
HS("dtype", dt) }, 0, 2.0 * M * 645 * 48);
for (const char* op : { "lora_expand", "lora_expand_mm" })
add(op, { HI("M", M), HI("N", 645), HI("R", 48), HI("S", 4), HS("dtype", dt) }, 0,
2.0 * M * 645 * 48);
}
for (const char* dt : { "f32", "bf16" }) {
add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
@@ -728,6 +729,10 @@ std::vector<Case> build_cases() {
add("randn_lanes", { HI("M", 24), HI("n", 64), HI("stride", 16), HI("n_seq", 2),
HS("dtype", dt) });
add("flow_euler", { HI("M", 24), HI("n", 64), HI("stride", 16), HS("dtype", dt) });
add("kd_input", { HI("M", 24), HI("n", 4), HI("stride", 16), HS("dtype", dt) });
for (const char* pred : { "eps", "v" })
add("kd_step", { HI("M", 24), HI("n", 4), HI("stride", 16), HS("pred", pred),
HS("dtype", dt) });
for (const char* mode : { "fma", "inv" })
for (int round : { 1, 0 })
add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()),
@@ -737,6 +742,7 @@ std::vector<Case> build_cases() {
add("l2norm_chan", { HI("M", 9), HI("n", 645), HS("act", act), HS("dtype", dt) });
add("to_rgba8", { HI("M", 9), HI("n", 4), HS("dtype", dt) });
add("gelu_tanh", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
add("gelu_quick", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
add("scatter_add_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
struct Conv { int M, cin, cout, k, stride, up; const char* pad; };
static const Conv kConv[] = {
@@ -751,6 +757,17 @@ std::vector<Case> build_cases() {
HI("stride", v.stride), HS("pad", v.pad), HI("up", v.up),
HS("dtype", dt) },
0, 2.0 * v.M * v.cout * v.cin * v.k * v.k);
/* The convolutions' geometries once each: cout is not a parameter of the unfold. */
for (const Conv& v : kConv) {
bool seen = false;
for (const Conv* u = kConv; u != &v; ++u)
seen = seen || (u->M == v.M && u->cin == v.cin && u->k == v.k &&
u->stride == v.stride && u->up == v.up && u->pad == v.pad);
if (seen) continue;
add("im2col_nhwc", { HI("M", v.M), HI("cin", v.cin), HI("k", v.k),
HI("stride", v.stride), HS("pad", v.pad), HI("up", v.up),
HS("dtype", dt) });
}
for (int ft : { 1, 2 }) {
add("d2s_add", { HI("M", 64), HI("cin", 24), HI("cout", 24), HI("ft", ft),
HS("dtype", dt) });
+45
View File
@@ -1913,6 +1913,51 @@ void gen_cases(std::vector<Hand>& hs) {
.pi("M", 17).pi("n", n).pi("stride", 6).ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* The k-diffusion input: entry 0 a first step guided against entry 1 (pair -2, which
* only its positive entry writes), entry 2 a later step, unguided, in lane 3. */
static const uint32_t kSeeds[6] = { 11u, 0u, 0u, 0u, 0xfeedbeefu, 3u };
Hand h(("first, parked, later, n 4" + sfx).c_str(), "kd_input", 0.0);
h.dense(RAD_F32, { 3 }, [](int64_t i) { return 14.6f - 6.0f * (float)i; })
.idx({ 1, -2, -1 })
.idx({ 0, 1, 3 })
.idx({ 1, 0, 0 })
.raw(RAD_U32, { 6 }, kSeeds)
.idx({ 0, 5, 10, 13 })
.dense(RAD_F32, { 24, 4 }, hfill(227), true)
.dense(dt, { 13, 4 }, zero, true)
.pi("M", 13).pi("n", 4).pi("stride", 6).ps("dtype", dn);
hs.push_back(std::move(h));
}
for (const char* pred : { "eps", "v" }) {
/* Every sampler: entry 0 Euler guided against entry 1 with a preview, entry 2 Euler
* ancestral at step 7, entry 3 DPM++ 2M past its first step, entry 4 DPM++ 2M's first
* step, entry 5 Euler ancestral to sigma 0, entry 6 DPM++ 2M to sigma 0. */
static const uint32_t kSeeds[14] = { 3u, 0u, 4u, 0u, 5u, 9u, 6u, 1u, 7u, 0u, 8u, 0u,
9u, 2u };
Hand h(("seven entries, every sampler, " + std::string(pred) + sfx).c_str(), "kd_step",
0.0);
static const float kS[7] = { 6.0f, 6.0f, 3.5f, 1.25f, 9.0f, 0.4f, 0.3f };
static const float kSn[7] = { 4.5f, 4.5f, 2.0f, 0.7f, 6.5f, 0.0f, 0.0f };
static const float kSp[7] = { 0.0f, 0.0f, 5.0f, 2.0f, 0.0f, 0.9f, 0.6f };
h.dense(dt, { 21, 5 }, hfill(228))
.dense(RAD_F32, { 7 }, [](int64_t i) { return kS[i]; })
.dense(RAD_F32, { 7 }, [](int64_t i) { return kSn[i]; })
.dense(RAD_F32, { 7 }, [](int64_t i) { return kSp[i]; })
.dense(RAD_F32, { 7 }, [](int64_t) { return 6.5f; })
.idx({ 1, -2, -1, -1, -1, -1, -1 })
.idx({ 0, 1, 2, 3, 4, 5, 6 })
.idx({ 4, 0, 0, 0, 1, 0, 0 })
.raw(RAD_U32, { 14 }, kSeeds)
.idx({ 0, 0, 1, 2, 2, 1, 2 })
.idx({ 0, 0, 7, 4, 0, 20, 21 })
.idx({ 0, 3, 6, 9, 12, 15, 18, 21 })
.dense(RAD_F32, { 28, 5 }, hfill(229, 3.0f), true)
.dense(RAD_F32, { 28, 5 }, hfill(230), true)
.dense(RAD_F32, { 28, 5 }, zero, true)
.pi("M", 21).pi("n", 5).pi("stride", 4).ps("pred", pred).ps("dtype", dn);
hs.push_back(std::move(h));
}
{
Hand h(("a mask column into three lanes" + sfx).c_str(), "lane_store", 0.0);
h.dense(dt, { 9, 1 }, hfill(225))
+273
View File
@@ -677,6 +677,203 @@ AVX_KERNEL(flow_euler) {
return RAD_OK;
}
/* ------------------------------------------------------------------ kd_input, kd_step */
/* The k-diffusion sampler over a discrete-time denoiser (libref/ref_gen.cpp): libref's f32 steps
* bit for bit, element by element, `kd_keep` holding every product to its own rounding before the
* sum that follows it. The lanes are a few thousand rows of four channels, so a scalar loop costs
* nothing next to the denoiser. */
namespace {
enum { kSamplerEuler = 0, kSamplerEulerAncestral = 1, kSamplerDpmpp2m = 2 };
/* A product the compiler may not fuse into the next add (any ISA level: a scalar in an xmm). */
inline float kd_keep(float x) { __asm__("" : "+x"(x)); return x; }
struct KdEntry {
float s = 0, sn = 0, w = 0;
float cskip = 0, cout = 0;
float sup = 0, sdown = 0;
float ratio = 0, em = 0;
float c1 = 0, c2 = 0;
bool second = false;
};
KdEntry kd_entry(float s, float sn, float sp, float w, int64_t sampler, bool first) {
KdEntry k;
k.s = s;
k.sn = sn;
k.w = w;
const float s2p = kd_keep(s * s) + 1.0f;
k.cskip = 1.0f / s2p;
k.cout = s / std::sqrt(s2p);
if (sampler == kSamplerEulerAncestral) {
const float s2 = kd_keep(s * s), sn2 = kd_keep(sn * sn);
const float up2 = kd_keep(sn2 * (s2 - sn2)) / s2;
float sup = std::sqrt(up2);
if (!(sup < sn)) sup = sn;
const float dn2 = sn2 - kd_keep(sup * sup);
k.sup = sup;
k.sdown = std::sqrt(dn2 > 0.0f ? dn2 : 0.0f);
} else if (sampler == kSamplerDpmpp2m && sn > 0.0f) {
const float t = -std::log(s), tn = -std::log(sn);
const float h = tn - t;
k.ratio = sn / s;
k.em = std::expm1(-h);
if (!first) {
const float hl = t - (-std::log(sp));
const float r = hl / h;
k.c2 = 1.0f / kd_keep(2.0f * r);
k.c1 = 1.0f + k.c2;
k.second = true;
}
}
return k;
}
inline float kd_denoised(const KdEntry& k, bool v_pred, float x, float o) {
return v_pred ? kd_keep(x * k.cskip) - kd_keep(o * k.cout) : x - kd_keep(k.s * o);
}
inline float kd_next(const KdEntry& k, int64_t sampler, float x, float D, float hist, float nz) {
if (sampler == kSamplerEuler) {
const float d = (x - D) / k.s;
return x + kd_keep((k.sn - k.s) * d);
}
if (sampler == kSamplerEulerAncestral) {
const float d = (x - D) / k.s;
float xn = x + kd_keep(d * (k.sdown - k.s));
if (k.sn > 0.0f) xn = xn + kd_keep(nz * k.sup);
return xn;
}
if (k.sn == 0.0f) return D;
const float Dd = k.second ? kd_keep(k.c1 * D) - kd_keep(k.c2 * hist) : D;
return kd_keep(k.ratio * x) - kd_keep(k.em * Dd);
}
} /* namespace */
/* The model's input per entry that moves a lane: a first step's noise times sqrt(1 + sigma^2)
* into the lane, then rd(x / sqrt(sigma^2 + 1)) at the entry's rows and its pair's. Every entry is
* checked before any is written. */
AVX_KERNEL(kd_input) {
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
const RadTensor *sg = &a->t[0], *pair = &a->t[1], *lane = &a->t[2], *fl = &a->t[3];
const RadTensor *seed = &a->t[4], *cu = &a->t[5], *st = &a->t[6], *Y = &a->t[7];
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), y_rows = rows_of(Y, n);
if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
if (numel(sg) < n_seq || numel(pair) < n_seq || numel(lane) < n_seq || numel(fl) < n_seq ||
numel(seed) < 2 * n_seq)
return RAD_E_SHAPE;
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t pr = ldi(pair, offlin(pair, e));
if (pr == -2) continue;
const int64_t L = ldi(lane, offlin(lane, e));
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > y_rows)
return RAD_E_SHAPE;
if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len ||
cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > y_rows)))
return RAD_E_SHAPE;
if (ldi(fl, offlin(fl, e)) & kInpaint) return RAD_E_UNSUPPORTED;
}
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t pr = ldi(pair, offlin(pair, e));
if (pr == -2) continue;
const int64_t L = ldi(lane, offlin(lane, e));
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0;
const float s = ldt(sg, offlin(sg, e));
const float init = std::sqrt(1.0f + kd_keep(s * s));
const float cin = 1.0f / std::sqrt(kd_keep(s * s) + 1.0f);
const bool first = (ldi(fl, offlin(fl, e)) & kFirst) != 0;
const uint64_t sd = seed_of(seed, e);
AVX_PARALLEL_FOR_IF(len * n * 8 >= AVX_PAR_MIN)
for (int64_t k = 0; k < len; ++k) {
const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st);
const int64_t yb = rowoff(Y, b0 + k, n), ys = laststride(Y);
const int64_t pb = pr >= 0 ? rowoff(Y, p0 + k, n) : 0;
for (int64_t c = 0; c < n; ++c) {
if (first) stt(st, sb + c * ss, rad_philox_normal(sd, (uint64_t)(k * n + c)) * init);
const float v = ldt(st, sb + c * ss) * cin;
stt(Y, yb + c * ys, v);
if (pr >= 0) stt(Y, pb + c * ys, v);
}
}
}
return RAD_OK;
}
/* One sampler step per entry that moves a lane, libref's arithmetic (docs/OPS.md, kd_step). */
AVX_KERNEL(kd_step) {
if (!rad_args_have(a, 14)) return RAD_E_INVAL;
const RadTensor *O = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *sgp = &a->t[3];
const RadTensor *cfg = &a->t[4], *pair = &a->t[5], *lane = &a->t[6], *fl = &a->t[7];
const RadTensor *seed = &a->t[8], *smp = &a->t[9], *stp = &a->t[10], *cu = &a->t[11];
const RadTensor *st = &a->t[12], *hs = &a->t[13], *pv = rad_arg_in(a, 14);
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
const char* pred = p_str(a, "pred", "eps");
const bool v_pred = pred && !std::strcmp(pred, "v");
if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return RAD_E_INVAL;
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), o_rows = rows_of(O, n);
if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
for (const RadTensor* t : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp })
if (numel(t) < n_seq) return RAD_E_SHAPE;
if (numel(seed) < 2 * n_seq || rows_of(hs, n) < st_rows || (pv && rows_of(pv, n) < st_rows))
return RAD_E_SHAPE;
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t pr = ldi(pair, offlin(pair, e));
if (pr == -2) continue;
const int64_t L = ldi(lane, offlin(lane, e));
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > o_rows)
return RAD_E_SHAPE;
if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len ||
cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > o_rows)))
return RAD_E_SHAPE;
const int64_t f = ldi(fl, offlin(fl, e)), sm = ldi(smp, offlin(smp, e));
if ((f & kInpaint) || sm < kSamplerEuler || sm > kSamplerDpmpp2m) return RAD_E_UNSUPPORTED;
if ((f & kPreview) && !pv) return RAD_E_INVAL;
}
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t pr = ldi(pair, offlin(pair, e));
if (pr == -2) continue;
const int64_t L = ldi(lane, offlin(lane, e));
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0;
const int64_t f = ldi(fl, offlin(fl, e)), sm = ldi(smp, offlin(smp, e));
const uint64_t stream = (uint64_t)(uint32_t)(1 + ldi(stp, offlin(stp, e)));
const KdEntry K = kd_entry(ldt(sg, offlin(sg, e)), ldt(sgn, offlin(sgn, e)),
ldt(sgp, offlin(sgp, e)), ldt(cfg, offlin(cfg, e)), sm,
(f & kFirst) != 0);
const uint64_t sd = seed_of(seed, e);
AVX_PARALLEL_FOR_IF(len * n * 8 >= AVX_PAR_MIN)
for (int64_t k = 0; k < len; ++k) {
const int64_t ob = rowoff(O, b0 + k, n), os = laststride(O);
const int64_t ub = pr >= 0 ? rowoff(O, p0 + k, n) : 0;
const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st);
const int64_t hb = rowoff(hs, L * stride + k, n), hss = laststride(hs);
for (int64_t c = 0; c < n; ++c) {
const float x = ldt(st, sb + c * ss);
float D = kd_denoised(K, v_pred, x, ldt(O, ob + c * os));
if (pr >= 0) {
const float Du = kd_denoised(K, v_pred, x, ldt(O, ub + c * os));
D = Du + kd_keep(K.w * (D - Du));
}
if (f & kPreview)
stt(pv, rowoff(pv, L * stride + k, n) + c * laststride(pv), D);
const float nz = sm == kSamplerEulerAncestral && K.sn > 0.0f
? rad_philox_normal_s(sd, stream, (uint64_t)(k * n + c)) : 0.0f;
stt(st, sb + c * ss, kd_next(K, sm, x, D, ldt(hs, hb + c * hss), nz));
stt(hs, hb + c * hss, D);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ flow_x0_step */
/* x' = f32(f32(r x) + f32(f32(1 - r) d)) with d = f32(x + f32((1 - t) v)) and
* r = sigma_next / sigma: libref's f32 steps bit for bit, `keep` holding each product to its own
@@ -768,6 +965,56 @@ AVX_KERNEL(chan_affine) {
return RAD_OK;
}
/* ------------------------------------------------------------------ im2col_nhwc */
/* conv2d_nhwc's receptive fields as rows (libref's definition): y [Ho * Wo, cin * k * k], column
* (ci k + i) k + j of row oy * Wo + ox the input at that tap, 0 in the padding. Each output row is
* filled tap by tap from the input pixel's channel run; bf16 into bf16 copies the bits. Parallel
* over output image rows. */
AVX_KERNEL(im2col_nhwc) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t cin = p_int(a, "cin", 0), k = p_int(a, "k", 0);
const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1);
const char* pad = p_str(a, "pad", "same");
const bool down = pad && !std::strcmp(pad, "down");
const bool causal = pad && !std::strcmp(pad, "causal");
if (cin <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE;
if (X->rank != 2 || X->shape[1] % cin) return RAD_E_SHAPE;
const int64_t Hin = X->shape[0], Win = X->shape[1] / cin, kk = cin * k * k;
if (Hin <= 0 || Win <= 0) return RAD_E_SHAPE;
const int64_t Hv = Hin * up, Wv = Win * up;
const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
const int64_t Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1;
if (Ho <= 0 || Wo <= 0 || rows_of(Y, kk) != Ho * Wo) return RAD_E_SHAPE;
const int64_t xr = X->stride[0], xs = laststride(X), ys = laststride(Y);
const bool bits = X->dtype == RAD_BF16 && Y->dtype == RAD_BF16;
AVX_PARALLEL_FOR_IF(Ho * Wo * kk >= AVX_PAR_MIN)
for (int64_t oy = 0; oy < Ho; ++oy)
for (int64_t ox = 0; ox < Wo; ++ox) {
const int64_t yb = rowoff(Y, oy * Wo + ox, kk);
for (int64_t i = 0; i < k; ++i) {
const int64_t iy = oy * stride + i - pt;
for (int64_t j = 0; j < k; ++j) {
const int64_t ix = ox * stride + j - pl;
const bool in = iy >= 0 && iy < Hv && ix >= 0 && ix < Wv;
const int64_t xb = in ? (iy / up) * xr + (ix / up) * cin * xs : 0;
const int64_t yt = yb + (i * k + j) * ys;
for (int64_t ci = 0; ci < cin; ++ci) {
const int64_t yo = yt + ci * k * k * ys;
if (bits) {
((uint16_t*)Y->data)[yo] =
in ? ((const uint16_t*)X->data)[xb + ci * xs] : (uint16_t)0;
} else {
stt(Y, yo, in ? ldt(X, xb + ci * xs) : 0.0f);
}
}
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ conv2d_nhwc */
/* An image convolution as GEMMs over patch rows. x [Hin, Win * cin] and y [Ho, Wo * cout] are
* images whose sizes come from the operands, rows at their own pitch and channels contiguous, as
@@ -1169,6 +1416,32 @@ AVX_KERNEL(gelu_tanh) {
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu_quick */
/* CLIP's quick_gelu in libref's three roundings: a = rd(1.702 x), s = rd(sigmoid(a)),
* y = rd(x s), libm's exp, element by element: a text encoder's feed-forward, small beside its
* GEMMs. */
AVX_KERNEL(gelu_quick) {
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);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
const uint32_t dt = Y->dtype;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), xs = laststride(X);
const int64_t yb = rowoff(Y, r, n), ys = laststride(Y);
for (int64_t c = 0; c < n; ++c) {
const float v = ldt(X, xb + c * xs);
const float t = narrow1(dt, 1.702f * v);
const float s = narrow1(dt, 1.0f / (1.0f + std::exp(-t)));
stt(Y, yb + c * ys, v * s);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scatter_add_rows */
/* x[idx[i]] = x[idx[i]] + v[i], rounded to x's dtype; a negative index adds nothing. Every index
* is checked before the first write. Rows run in parallel only when no destination repeats: a
+3 -2
View File
@@ -98,7 +98,7 @@ int avx_par_force(int threads);
/* ---- gemm and the vocabulary edges */ \
X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
X(lora_shrink) X(lora_expand) \
X(lora_shrink) X(lora_expand) X(lora_expand_mm) \
/* ---- attention */ \
X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(rope) \
X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \
@@ -117,7 +117,8 @@ int avx_par_force(int threads);
X(gather_rows2) X(lane_gather) X(lane_store) X(randn_lanes) \
X(flow_euler) X(chan_affine) X(conv2d_nhwc) X(l2norm_chan) \
X(d2s_add) X(s2d_avg_add) X(to_rgba8) X(gelu_tanh) \
X(scatter_add_rows) X(attn_prefix_self) \
X(scatter_add_rows) X(attn_prefix_self) X(kd_input) X(kd_step) \
X(gelu_quick) X(im2col_nhwc) \
/* ---- video generation */ \
X(rms_mod) X(rms_mod_quant_fp8) X(flow_x0_step) X(patch_unfold) \
X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \
+13 -2
View File
@@ -150,8 +150,8 @@ AVX_KERNEL(lora_shrink) {
return RAD_OK;
}
/* operands: t, slot, lora_b, scale, y (inout) */
AVX_KERNEL(lora_expand) {
/* operands: t, slot, lora_b, scale, y (inout). `bf16_t`: lora_expand_mm, t rounded to bf16. */
static int expand_impl(const RadArgs* a, bool bf16_t) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *T = &a->t[0], *SL = &a->t[1], *LB = &a->t[2], *SC = &a->t[3], *Y = &a->t[4];
const int64_t N = p_int(a, "N", 0), R = p_int(a, "R", 0), S = p_int(a, "S", 0);
@@ -176,6 +176,12 @@ AVX_KERNEL(lora_expand) {
const int64_t s = row_slot(SL, m, S);
if (s < 0) continue; /* a base row: not read, not written */
const float* tv = in_row(T, m * mt.rs, R, scratch_f32((size_t)R));
if (bf16_t) {
float* tr = scratch_f32((size_t)R);
if (tr != tv) for (int64_t j = 0; j < R; ++j) tr[j] = tv[j];
for (int64_t j = 0; j < R; ++j) tr[j] = rad_bf16_to_f32(rad_f32_to_bf16(tr[j]));
tv = tr;
}
const float* bv = in_row(LB, s * pb.s0 + n * pb.s1, R, scratch_f32_b((size_t)R));
const float d = scd[s * sc_r + n * sc_c] * dotf(tv, bv, R);
const int64_t o = m * ys_r + n * ys_c;
@@ -183,3 +189,8 @@ AVX_KERNEL(lora_expand) {
}
return RAD_OK;
}
AVX_KERNEL(lora_expand) { return expand_impl(a, false); }
/* lora_expand with t rounded to bf16 (docs/OPS.md). */
AVX_KERNEL(lora_expand_mm) { return expand_impl(a, true); }
+38
View File
@@ -550,11 +550,24 @@ static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma
OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"),
OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"),
INOUT("state"), INOUT_O("preview") };
/* The k-diffusion sampler's input and step: `pred` "eps" or "v", the lanes f32. */
static const RadParamSpec pKdStep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("pred"),
P_STR("dtype") };
static const RadOperandSpec oKdInput[] = { OPD("sigma"), OPD("pair"), OPD("lane"), OPD("flags"),
OPD("seed"), OPD("cu_seqlens"), INOUT("state"),
OUT("y") };
static const RadOperandSpec oKdStep[] = { OPD("out"), OPD("sigma"), OPD("sigma_next"),
OPD("sigma_prev"), OPD("cfg"), OPD("pair"), OPD("lane"),
OPD("flags"), OPD("seed"), OPD("sampler"), OPD("step"),
OPD("cu_seqlens"), INOUT("state"), INOUT("hist"),
INOUT_O("preview") };
static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"),
P_STR("mode"), P_STR("dtype"), P_INTO("round") };
static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") };
static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") };
static const RadParamSpec pIm2col[] = { P_INT("M"), P_INT("cin"), P_INT("k"), P_INT("stride"),
P_STR("pad"), P_INT("up"), P_STR("dtype") };
static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
static const RadOperandSpec oL2Norm[] = { OPD("x"), WGT("gamma"), OUT("y") };
static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"),
@@ -937,6 +950,9 @@ static const RadOpSchema kSchemas[] = {
{ "lora_expand", ARR(pLoraExpand), ARR(oLoraExpand),
"y[m, n] += scale[slot[m], n] * sum_j t[m, j] * lora_b[slot[m], n, j]; a base row is neither "
"read nor written." },
{ "lora_expand_mm", ARR(pLoraExpand), ARR(oLoraExpand),
"lora_expand with t rounded to bf16, the sum over j in any order; a base row is neither read nor "
"written." },
{ "gemm_nt_q_gated", ARR(pGemmQGated), ARR(oGemmQGated),
"gemm_nt_q over a [N, K] gate_up plane with gated_quant_fp8's pass in the epilogue, byte for "
"byte the pair. `N` is the weight's rows, twice the fused width; the output is [M, N/2]." },
@@ -1044,12 +1060,22 @@ static const RadOpSchema kSchemas[] = {
{ "flow_euler", ARR(pLane), ARR(oFlowEuler),
"one flow-matching Euler step per entry that moves a lane, with guidance, the preview and the "
"repaint's kept region; libref's roundings bit for bit." },
{ "kd_input", ARR(pLane), ARR(oKdInput),
"a k-diffusion sampler's model input per entry that moves a lane: a first step's noise times "
"sqrt(1 + sigma^2) into the lane, then rd(x / sqrt(sigma^2 + 1)) at the entry's and its pair's "
"rows; libref's arithmetic bit for bit." },
{ "kd_step", ARR(pKdStep), ARR(oKdStep),
"one k-diffusion sampler step per entry that moves a lane: the guided clean estimate from an "
"eps or v output, then Euler, Euler ancestral or DPM++ 2M; libref's arithmetic bit for bit." },
{ "chan_affine", ARR(pChanAffine), ARR(oUnary),
"a per-channel affine from two lists of n bf16 values, `fma` or `inv`; `round` 0 keeps the "
"lists and the arithmetic in f32, rounded once." },
{ "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc),
"an image convolution, channels innermost, as GEMMs over bands of patch rows; `up` 2 reads the "
"input upsampled nearest-neighbour, `pad` same or down." },
{ "im2col_nhwc", ARR(pIm2col), ARR(oUnary),
"conv2d_nhwc's receptive fields as rows, y [Hout * Wout, cin * k * k], column (ci * k + i) * k "
"+ j the value conv2d_nhwc multiplies weight[o, ci, i, j] by; libref's copies bit for bit." },
{ "l2norm_chan", ARR(pL2Norm), ARR(oL2Norm),
"each pixel's channels to unit L2, times sqrt(n), times gamma (three roundings), then `act`." },
{ "d2s_add", ARR(pSpaceDepth), ARR(oSpaceDepth),
@@ -1060,6 +1086,8 @@ static const RadOpSchema kSchemas[] = {
{ "to_rgba8", ARR(pMnD), ARR(oUnary),
"decoded pixels in [-1, 1] to bytes as diffusers' postprocess makes them, u8 out." },
{ "gelu_tanh", ARR(pMnD), ARR(oUnary), "the tanh approximation of gelu." },
{ "gelu_quick", ARR(pMnD), ARR(oUnary),
"CLIP's quick_gelu, three roundings: a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s)." },
{ "scatter_add_rows", ARR(pMnD), ARR(oScatterRows),
"x[idx[i]] += v[i], rounded to x's dtype; a negative index adds nothing." },
{ "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS),
@@ -1473,6 +1501,9 @@ SIMPLE("avx_lora_shrink", "lora_shrink", "gemm", "t = x A[slot]^T per row, base
SIMPLE("avx_lora_expand", "lora_expand", "gemm",
"y += scale * (t B[slot]^T) per row, base rows untouched",
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", L(lora_expand)),
SIMPLE("avx_lora_expand_mm", "lora_expand_mm", "gemm",
"y += scale * (bf16(t) B[slot]^T) per row, base rows untouched",
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", L(lora_expand_mm)),
SIMPLE("avx_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm",
"gemm_nt_q over a gate_up plane with the gated E4M3 quantiser in the epilogue",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; fp8_e4m3 out, f32 scale",
@@ -1586,11 +1617,17 @@ SIMPLE("avx_randn_lanes", "randn_lanes", "elem", "a lane's rows from its seed's
DT_FLOAT, L(randn_lanes)),
SIMPLE("avx_flow_euler", "flow_euler", "elem", "a flow-matching Euler step with guidance",
DT_FLOAT, L(flow_euler)),
SIMPLE("avx_kd_input", "kd_input", "elem", "a k-diffusion sampler's model input", DT_FLOAT,
L(kd_input)),
SIMPLE("avx_kd_step", "kd_step", "elem", "a k-diffusion sampler step with guidance", DT_FLOAT,
L(kd_step)),
SIMPLE("avx_chan_affine", "chan_affine", "elem", "a per-channel affine from parameter lists",
DT_FLOAT, L(chan_affine)),
SIMPLE("avx_conv2d_nhwc", "conv2d_nhwc", "conv",
"an image convolution, channels innermost, as GEMMs over patch rows", DT_FLOAT,
L(conv2d_nhwc)),
SIMPLE("avx_im2col_nhwc", "im2col_nhwc", "elem", "a convolution's receptive fields as rows",
DT_FLOAT, L(im2col_nhwc)),
SIMPLE("avx_l2norm_chan", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu",
DT_FLOAT, L(l2norm_chan)),
SIMPLE("avx_d2s_add", "d2s_add", "elem", "an upsampling shortcut added in", DT_FLOAT, L(d2s_add)),
@@ -1598,6 +1635,7 @@ SIMPLE("avx_s2d_avg_add", "s2d_avg_add", "elem", "a downsampling shortcut added
L(s2d_avg_add)),
SIMPLE("avx_to_rgba8", "to_rgba8", "elem", "decoded pixels to bytes", DT_FLOAT, L(to_rgba8)),
SIMPLE("avx_gelu_tanh", "gelu_tanh", "elem", "tanh gelu", DT_FLOAT, L(gelu_tanh)),
SIMPLE("avx_gelu_quick", "gelu_quick", "elem", "quick gelu", DT_FLOAT, L(gelu_quick)),
SIMPLE("avx_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", DT_FLOAT,
L(scatter_add_rows)),
SIMPLE("avx_attn_prefix_self", "attn_prefix_self", "attn",
+354
View File
@@ -17,6 +17,7 @@
#include "r4d_q8.h"
#include "rad_philox.h"
#include <algorithm>
#include <cmath>
#include <initializer_list>
#include <cstdlib>
@@ -380,6 +381,118 @@ __global__ __launch_bounds__(kT) void flow_euler_kernel(
st[so] = f32_to_bf16(xn);
}
// ---------------------------------------------------------------------------- kd_input, kd_step
// The k-diffusion sampler over a discrete-time denoiser (libref's ref_kd_input / ref_kd_step): the
// lanes hold x = x0 + sigma eps in f32, a thread one element of one entry, every entry's constants
// computed by each of its threads (a handful of f32 operations beside the element's own).
constexpr int kKdEuler = 0, kKdAncestral = 1, kKdDpm2m = 2;
struct KdConst {
float s, sn, w, cskip, cout, sup, sdown, ratio, em, c1, c2;
bool second;
};
__device__ __forceinline__ KdConst kd_const(float s, float sn, float sp, float w, int sampler,
bool first) {
KdConst k{};
k.s = s;
k.sn = sn;
k.w = w;
const float s2p = s * s + 1.0f;
k.cskip = 1.0f / s2p;
k.cout = s / sqrtf(s2p);
if (sampler == kKdAncestral) {
const float s2 = s * s, sn2 = sn * sn;
const float up2 = sn2 * (s2 - sn2) / s2;
float sup = sqrtf(up2);
if (!(sup < sn)) sup = sn;
const float dn2 = sn2 - sup * sup;
k.sup = sup;
k.sdown = sqrtf(dn2 > 0.0f ? dn2 : 0.0f);
} else if (sampler == kKdDpm2m && sn > 0.0f) {
const float t = -logf(s), tn = -logf(sn);
const float h = tn - t;
k.ratio = sn / s;
k.em = expm1f(-h);
if (!first) {
const float r = (t - (-logf(sp))) / h;
k.c2 = 1.0f / (2.0f * r);
k.c1 = 1.0f + k.c2;
k.second = true;
}
}
return k;
}
__device__ __forceinline__ float kd_den(const KdConst& k, bool v_pred, float x, float o) {
return v_pred ? x * k.cskip - o * k.cout : x - k.s * o;
}
__global__ __launch_bounds__(kT) void kd_input_kernel(
const float* __restrict__ sg, const int* __restrict__ pair, const int* __restrict__ lane,
const int* __restrict__ flags, const uint32_t* __restrict__ seed, const int* __restrict__ cu,
float* __restrict__ st, uint16_t* __restrict__ y, int n, int stride, int st_ld, int y_ld) {
const int e = blockIdx.y;
const int pr = pair[e];
if (pr == -2) return;
const int b0 = cu[e];
const int64_t len = cu[e + 1] - b0;
const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x;
if (i >= len * n) return;
const int64_t k = i / n, c = i % n;
const float s = sg[e];
float* xp = st + ((size_t)lane[e] * stride + k) * st_ld + c;
if (flags[e] & 1) *xp = rad_philox_normal(seed_of(seed, e), (uint64_t)i) * sqrtf(1.0f + s * s);
const uint16_t v = f32_to_bf16(*xp * (1.0f / sqrtf(s * s + 1.0f)));
y[(size_t)(b0 + k) * y_ld + c] = v;
if (pr >= 0) y[(size_t)(cu[pr] + k) * y_ld + c] = v;
}
__global__ __launch_bounds__(kT) void kd_step_kernel(
const uint16_t* __restrict__ out, const float* __restrict__ sg, const float* __restrict__ sgn,
const float* __restrict__ sgp, const float* __restrict__ cfg, const int* __restrict__ pair,
const int* __restrict__ lane, const int* __restrict__ flags, const uint32_t* __restrict__ seed,
const int* __restrict__ sampler, const int* __restrict__ step, const int* __restrict__ cu,
float* __restrict__ st, float* __restrict__ hist, float* __restrict__ pv, int n, int stride,
int o_ld, int st_ld, int h_ld, int pv_ld, int v_pred) {
const int e = blockIdx.y;
const int pr = pair[e];
if (pr == -2) return;
const int b0 = cu[e];
const int64_t len = cu[e + 1] - b0;
const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x;
if (i >= len * n) return;
const int64_t k = i / n, c = i % n;
const int f = flags[e], sm = sampler[e];
const KdConst K = kd_const(sg[e], sgn[e], sgp[e], cfg[e], sm, (f & 1) != 0);
const size_t row = (size_t)lane[e] * stride + k;
const float x = st[row * st_ld + c];
float D = kd_den(K, v_pred != 0, x, bf2f(out[(size_t)(b0 + k) * o_ld + c]));
if (pr >= 0) {
const float Du = kd_den(K, v_pred != 0, x, bf2f(out[(size_t)(cu[pr] + k) * o_ld + c]));
D = Du + K.w * (D - Du);
}
if ((f & 4) && pv) pv[row * pv_ld + c] = D;
float xn;
if (sm == kKdEuler) {
xn = x + (K.sn - K.s) * ((x - D) / K.s);
} else if (sm == kKdAncestral) {
xn = x + ((x - D) / K.s) * (K.sdown - K.s);
if (K.sn > 0.0f)
xn += rad_philox_normal_s(seed_of(seed, e), (uint64_t)(uint32_t)(1 + step[e]),
(uint64_t)i) * K.sup;
} else if (sm != kKdDpm2m) {
return;
} else if (K.sn == 0.0f) {
xn = D;
} else {
const float Dd = K.second ? K.c1 * D - K.c2 * hist[row * h_ld + c] : D;
xn = K.ratio * x - K.em * Dd;
}
st[row * st_ld + c] = xn;
hist[row * h_ld + c] = D;
}
// ---------------------------------------------------------------------------- per-channel ops
// The two lists ride in the kernel arguments, whose segment the backend caps at 768 bytes; two
// lists of 64 channels (a latent's) take 512.
@@ -504,6 +617,20 @@ __global__ __launch_bounds__(kT) void to_rgba8_kernel(const uint16_t* __restrict
y[i] = (uint8_t)rintf(u * 255.0f);
}
// ---------------------------------------------------------------------------- gelu_quick
// CLIP's quick_gelu, libref's three roundings: a workgroup a row, a thread an element.
template <typename T>
__global__ __launch_bounds__(kT) void gelu_quick_kernel(const T* __restrict__ x, T* __restrict__ y,
int n, int x_ld, int y_ld) {
const int r = blockIdx.x;
for (int c = threadIdx.x; c < n; c += kT) {
const float v = ca_ld(x, (size_t)r * x_ld + c);
const float a = ca_rd(y, 1.702f * v);
const float s = ca_rd(y, 1.0f / (1.0f + expf(-a)));
ca_st(y, (int64_t)r * y_ld + c, v * s);
}
}
__global__ __launch_bounds__(kT) void gelu_tanh_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int n, int x_ld, int y_ld) {
const int r = blockIdx.x;
@@ -698,6 +825,91 @@ __global__ __launch_bounds__(kT) void conv_direct_kernel(
y[(size_t)oy * y_ld + (size_t)ox * cout + co] = f32_to_bf16(acc + bf2f(bias[co]));
}
// ---------------------------------------------------------------------------- im2col_nhwc
// conv2d_nhwc's receptive fields as rows: y[oy Wo + ox][(ci k + i) k + j] = the input at tap
// (i, j) of output pixel (oy, ox), channel ci. A block is a run of IC_TW output pixels of one
// output row and IC_CC input channels: it stages the k input rows those pixels read (through the
// upsample and the zero padding) in LDS channel-major, [cl][i][xw], 16 bytes of NHWC channels a
// load, then writes each pixel's cc k k columns -- one contiguous run of its y row -- VW elements a
// thread, so both the reads and the writes are coalesced. KS is k at compile time (3 and 1), 0 for
// any other. Values are copied bit for bit.
constexpr int IC_TW = 32;
constexpr int IC_CC = 64;
template <int KS, int VW>
__global__ __launch_bounds__(kT) void im2col_nhwc_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo,
int k_rt, int stride, int up, int pt, int pl, int64_t x_ld, int64_t y_ld, int vec) {
extern __shared__ uint16_t ic_lds[];
const int k = KS ? KS : k_rt, kk = k * k;
const int ox0 = blockIdx.x * IC_TW, oy = blockIdx.y, c0 = blockIdx.z * IC_CC;
const int cc = min(IC_CC, cin - c0), nq = min(IC_TW, Wo - ox0);
const int W = (IC_TW - 1) * stride + k;
const int iy0 = oy * stride - pt, ix0 = ox0 * stride - pl;
const int sites = k * W;
const int tid = threadIdx.x;
if (vec) {
const int groups = cc >> 3;
for (int u = tid; u < sites * groups; u += kT) {
const int g = u % groups, site = u / groups;
const int i = site / W, xw = site - i * W;
const int iy = iy0 + i, ix = ix0 + xw;
uint4 v = make_uint4(0, 0, 0, 0);
if (iy >= 0 && iy < Hv && ix >= 0 && ix < Wv)
v = *(const uint4*)(x + (size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin + c0 +
g * 8);
const uint32_t w4[4] = { v.x, v.y, v.z, v.w };
#pragma unroll
for (int e = 0; e < 8; ++e)
ic_lds[((g * 8 + e) * k + i) * W + xw] =
(uint16_t)(e & 1 ? w4[e >> 1] >> 16 : w4[e >> 1] & 0xffffu);
}
} else {
for (int u = tid; u < sites * cc; u += kT) {
const int cl = u % cc, site = u / cc;
const int i = site / W, xw = site - i * W;
const int iy = iy0 + i, ix = ix0 + xw;
uint16_t v = 0;
if (iy >= 0 && iy < Hv && ix >= 0 && ix < Wv)
v = x[(size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin + c0 + cl];
ic_lds[(cl * k + i) * W + xw] = v;
}
}
__syncthreads();
/* The block's pixels' runs as one list of VW-element pieces, so every thread stores whatever
* the run length; a thread's (pixel, piece) advances by the block each pass, without a
* division. */
const int span = cc * kk, pieces = span / VW;
uint16_t* yb = y + (size_t)((int64_t)oy * Wo + ox0) * y_ld + (size_t)c0 * kk;
int q = tid / pieces, pc = tid - q * pieces;
for (; q < nq;) {
const int t = pc * VW;
uint16_t* yr = yb + (size_t)q * y_ld;
const int xq = q * stride;
uint16_t v[VW];
#pragma unroll
for (int e = 0; e < VW; ++e) {
const int te = t + e;
const int cl = te / kk, r = te - cl * kk, i = r / k, j = r - i * k;
v[e] = ic_lds[(cl * k + i) * W + xq + j];
}
if constexpr (VW == 8)
*(uint4*)(yr + t) = make_uint4((uint32_t)v[0] | ((uint32_t)v[1] << 16),
(uint32_t)v[2] | ((uint32_t)v[3] << 16),
(uint32_t)v[4] | ((uint32_t)v[5] << 16),
(uint32_t)v[6] | ((uint32_t)v[7] << 16));
else if constexpr (VW == 4)
*(uint2*)(yr + t) = make_uint2((uint32_t)v[0] | ((uint32_t)v[1] << 16),
(uint32_t)v[2] | ((uint32_t)v[3] << 16));
else if constexpr (VW == 2)
*(uint32_t*)(yr + t) = (uint32_t)v[0] | ((uint32_t)v[1] << 16);
else
yr[t] = v[0];
pc += kT;
while (pc >= pieces) { pc -= pieces; ++q; }
}
}
inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); }
inline unsigned blocks_for(int64_t n) { return (unsigned)((n + kT - 1) / kT); }
@@ -1073,6 +1285,72 @@ extern "C" int r4d_rad_flow_euler(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_kd_input(const RadArgs* a, RadStream s) {
const RadTensor *sg = r4d_opt(a, 0), *pair = r4d_opt(a, 1), *lane = r4d_opt(a, 2);
const RadTensor *fl = r4d_opt(a, 3), *seed = r4d_opt(a, 4), *cu = r4d_opt(a, 5);
const RadTensor *st = r4d_opt(a, 6), *y = r4d_opt(a, 7);
if (!sg || !pair || !lane || !fl || !seed || !cu || !st || !y) return R4D_NO(RAD_E_INVAL);
if (st->dtype != RAD_F32 || !is_bf16(y) || sg->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0);
long long rs = 0, ry = 0;
const long long sl = r4d_rows_pitch(st, n, &rs), yl = r4d_rows_pitch(y, n, &ry);
if (sl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
if (n <= 0 || stride <= 0 || n_seq <= 0 || rs < stride) return R4D_NO(RAD_E_SHAPE);
/* One scalar of each kind an entry, two seed words. A lane's rows, a pair's entry and a
* repaint flag (device data) are not checked. */
for (const RadTensor* e : { sg, pair, lane, fl })
if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(seed) < 2 * n_seq) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(kd_input_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0,
(hipStream_t)s, (const float*)sg->data, (const int*)pair->data,
(const int*)lane->data, (const int*)fl->data, (const uint32_t*)seed->data,
(const int*)cu->data, (float*)st->data, (uint16_t*)y->data, (int)n,
(int)stride, (int)sl, (int)yl);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_kd_step(const RadArgs* a, RadStream s) {
const RadTensor *o = r4d_opt(a, 0), *sg = r4d_opt(a, 1), *sgn = r4d_opt(a, 2);
const RadTensor *sgp = r4d_opt(a, 3), *cfg = r4d_opt(a, 4), *pair = r4d_opt(a, 5);
const RadTensor *lane = r4d_opt(a, 6), *fl = r4d_opt(a, 7), *seed = r4d_opt(a, 8);
const RadTensor *smp = r4d_opt(a, 9), *stp = r4d_opt(a, 10), *cu = r4d_opt(a, 11);
const RadTensor *st = r4d_opt(a, 12), *hs = r4d_opt(a, 13), *pv = r4d_opt(a, 14);
if (!o || !sg || !sgn || !sgp || !cfg || !pair || !lane || !fl || !seed || !smp || !stp || !cu ||
!st || !hs)
return R4D_NO(RAD_E_INVAL);
if (!is_bf16(o) || st->dtype != RAD_F32 || hs->dtype != RAD_F32 ||
(pv && pv->dtype != RAD_F32))
return R4D_NO(RAD_E_DTYPE);
const char* pred = r4d_gets(a, "pred");
const int v_pred = pred && !std::strcmp(pred, "v");
if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return R4D_NO(RAD_E_INVAL);
const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0);
long long ro = 0, rs = 0, rh = 0, rp = 0;
const long long ol = r4d_rows_pitch(o, n, &ro), sl = r4d_rows_pitch(st, n, &rs);
const long long hl = r4d_rows_pitch(hs, n, &rh), pl = pv ? r4d_rows_pitch(pv, n, &rp) : 0;
if (ol < 0 || sl < 0 || hl < 0 || pl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
if (n <= 0 || stride <= 0 || n_seq <= 0 || rs < stride || rh < rs || (pv && rp < rs))
return R4D_NO(RAD_E_SHAPE);
/* One scalar of each kind an entry, two seed words. A lane's rows, a pair's entry, the
* sampler ids and the flags (device data) are not checked here: the kernel leaves the lane of
* an entry whose sampler it does not know, and writes no preview without the operand, where
* libref refuses both. */
for (const RadTensor* e : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp })
if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(seed) < 2 * n_seq) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(kd_step_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0,
(hipStream_t)s, (const uint16_t*)o->data, (const float*)sg->data,
(const float*)sgn->data, (const float*)sgp->data, (const float*)cfg->data,
(const int*)pair->data, (const int*)lane->data, (const int*)fl->data,
(const uint32_t*)seed->data, (const int*)smp->data, (const int*)stp->data,
(const int*)cu->data, (float*)st->data, (float*)hs->data,
pv ? (float*)pv->data : nullptr, (int)n, (int)stride, (int)ol, (int)sl,
(int)hl, (int)pl, v_pred);
return st_of(hipGetLastError());
}
/* Both rows: x and y bf16 (chan_affine_bf16) or both f32 (chan_affine_f32). `round` 0 keeps the
* lists and the arithmetic in f32. */
extern "C" int r4d_rad_chan_affine(const RadArgs* a, RadStream s) {
@@ -1175,6 +1453,61 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_im2col_nhwc(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
const long long cin = r4d_geti_or(a, "cin", 0), k = r4d_geti_or(a, "k", 0);
const long long stride = r4d_geti_or(a, "stride", 1), up = r4d_geti_or(a, "up", 1);
const char* pad = r4d_gets(a, "pad");
const bool down = pad && !std::strcmp(pad, "down");
const bool causal = pad && !std::strcmp(pad, "causal");
if (pad && !down && !causal && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL);
if (cin <= 0 || k <= 0 || k > 7 || stride <= 0 || stride > 2 || up <= 0 || up > 2)
return R4D_NO(RAD_E_SHAPE);
long long Hin = 0, Win = 0;
if (!image_of(x, cin, &Hin, &Win, true)) return R4D_NO(RAD_E_SHAPE);
const long long Hv = Hin * up, Wv = Win * up;
const long long pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
const long long pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
const long long Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1;
const long long KK = cin * k * k;
long long rows = 0;
const long long y_ld = r4d_rows_pitch(y, KK, &rows);
if (y_ld < 0 || y->stride[y->rank - 1] != 1) return R4D_NO(RAD_E_STRIDE);
if (Ho <= 0 || Wo <= 0 || rows != Ho * Wo || Ho > 65535 || Ho * Wo * y_ld >= (1ll << 40))
return R4D_NO(RAD_E_SHAPE);
/* 16-byte channel loads where every chunk's channels start on one; the widest store every
* chunk's run, the row pitch and the base allow. */
const long long tail = cin % IC_CC ? cin % IC_CC : IC_CC;
const int vec = cin % 8 == 0 && x->stride[0] % 8 == 0 && !((uintptr_t)x->data & 15);
auto fits = [&](long long vw) {
return (std::min((long long)IC_CC, cin) * k * k) % vw == 0 && (tail * k * k) % vw == 0 &&
y_ld % vw == 0 && !((uintptr_t)y->data & (2 * vw - 1));
};
const int VW = fits(8) ? 8 : fits(4) ? 4 : fits(2) ? 2 : 1;
const long long W = (IC_TW - 1) * stride + k;
const size_t lds = (size_t)(std::min((long long)IC_CC, cin) * k * W) * sizeof(uint16_t);
const dim3 grid((unsigned)((Wo + IC_TW - 1) / IC_TW), (unsigned)Ho,
(unsigned)((cin + IC_CC - 1) / IC_CC));
#define R4D_IC(KS, V) \
hipLaunchKernelGGL((im2col_nhwc_kernel<KS, V>), grid, dim3(kT), lds, (hipStream_t)s, \
(const uint16_t*)x->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, \
(int)Wo, (int)k, (int)stride, (int)up, (int)pt, (int)pl, \
(int64_t)x->stride[0], (int64_t)y_ld, vec)
#define R4D_IC_K(V) \
if (k == 3) R4D_IC(3, V); \
else if (k == 1) R4D_IC(1, V); \
else R4D_IC(0, V)
if (VW == 8) { R4D_IC_K(8); }
else if (VW == 4) { R4D_IC_K(4); }
else if (VW == 2) { R4D_IC_K(2); }
else { R4D_IC_K(1); }
#undef R4D_IC_K
#undef R4D_IC
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_l2norm_chan(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *y = r4d_opt(a, 2);
if (!x || !g || !y) return R4D_NO(RAD_E_INVAL);
@@ -1246,6 +1579,27 @@ extern "C" int r4d_rad_to_rgba8(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_gelu_quick(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
const bool f32 = x->dtype == RAD_F32;
if ((!is_bf16(x) && !f32) || y->dtype != x->dtype) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
long long rx = 0, ry = 0;
const long long xl = r4d_rows_pitch(x, n, &rx), yl = r4d_rows_pitch(y, n, &ry);
if (n <= 0 || xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE);
if (ry <= 0 || rx < ry) return R4D_NO(RAD_E_SHAPE);
if (f32)
hipLaunchKernelGGL(gelu_quick_kernel<float>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const float*)x->data, (float*)y->data, (int)n, (int)xl,
(int)yl);
else
hipLaunchKernelGGL(gelu_quick_kernel<uint16_t>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const uint16_t*)x->data, (uint16_t*)y->data, (int)n,
(int)xl, (int)yl);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_gelu_tanh(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
+153
View File
@@ -252,6 +252,11 @@ enum {
kExThreads = 256,
kZMax = 16, /* the passes of one tile spread over at most this many blocks */
kZGrid = 256, /* ... and only while the grid is smaller than this */
kMmMT = 128, /* expand_mm: rows a tile, 32 a wave */
kMmNT = 256, /* expand_mm: columns a tile, 128 a wave */
kMmJC = 32, /* expand_mm: j a staged step */
kMmWaves = 8, /* 4 (rows) x 2 (columns) over the tile */
kMmThreads = kMmWaves * 32,
};
struct ShrinkTArgs {
@@ -590,6 +595,119 @@ __global__ __launch_bounds__(kExThreads) void lora_expand_tiled_kernel(ExpandTAr
}
}
/* lora_expand_mm: the same delta on the WMMA, t rounded to bf16, for the passes whose rows are
* many and mostly of one slot (an image or video generator's). One block a (256 columns, 128 rows),
* eight waves, wave w the 32 rows at 32 (w >> 1) and the 128 columns at 128 (w & 1): 2 x 8 WMMA
* tiles. Each 32-wide j step stages t's [128 rows][32 j] (rounded to bf16) and B[s]'s [256 columns]
* [32 j] in LDS, read by every wave; B's fragment is the WMMA's A operand (16 n x 16 j) and t's its
* B (16 j x 16 m), so lane l's eight outputs are row l % 16 of its m tile at columns 8 (l / 16) ..
* +7 -- eight neighbours in y. Rows of a slot not in the pass are staged as zeros and not stored. */
template <int YDT, bool V>
__global__ __launch_bounds__(kMmThreads) void lora_expand_mm_kernel(ExpandTArgs T) {
__shared__ uint16_t ts[kMmMT][kMmJC + 8]; /* +8: rows land on different banks */
__shared__ uint16_t bs[kMmNT][kMmJC + 8];
__shared__ int mm_slot[kMmMT], mm_list[kMmMT];
__shared__ int mm_n;
const ExpandArgs& A = T.b;
const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, half = lane >> 4;
const long long nb = (long long)blockIdx.x * kMmNT;
const int mb = (int)blockIdx.y * kMmMT;
const int wm = 32 * (wave >> 1), wn = 128 * (wave & 1);
for (int i = tid; i < kMmMT; i += kMmThreads) {
int s = -1;
if (mb + i < T.M) {
s = A.slot[(long long)(mb + i) * A.slot_st];
if (s < 0 || s >= A.S) s = -1;
}
mm_slot[i] = s;
}
__syncthreads();
if (tid == 0) mm_n = distinct_slots(mm_slot, mm_list, kMmMT);
__syncthreads();
const int npass = mm_n;
for (int p = 0; p < npass; ++p) {
const int s = mm_list[p];
const uint16_t* bp = A.lb + (long long)s * A.lb_s0;
lr_v8f acc[2][8];
for (int b = 0; b < 2; ++b)
for (int a = 0; a < 8; ++a) acc[b][a] = (lr_v8f)(0.0f);
for (int j0 = 0; j0 < A.R; j0 += kMmJC) {
__syncthreads(); /* the last step's readers are done */
/* t: 128 rows x 32 j, one row's 32 a pair of lanes */
for (int i = tid; i < kMmMT * 2; i += kMmThreads) {
const int r = i >> 1, h = (i & 1) * 16;
const bool on = mm_slot[r] == s;
const long long row = (long long)(mb + r) * A.t_rs;
for (int e = 0; e < 16; ++e) {
const int j = j0 + h + e;
ts[r][h + e] = on && j < A.R ? f2bf(A.t[row + (long long)j * A.t_cs]) : (uint16_t)0;
}
}
/* B[s]: 256 columns x 32 j, one column's 32 a pair of lanes */
for (int i = tid; i < kMmNT * 2; i += kMmThreads) {
const int c = i >> 1, h = (i & 1) * 16;
const long long n = nb + c;
lr_v8s f[2];
ld_pool16<V>(bp + (n < A.N ? n : 0) * A.lb_s1, j0 + h, A.R, A.lb_s2, n < A.N, f);
for (int e = 0; e < 16; ++e) bs[c][h + e] = (uint16_t)f[e >> 3][e & 7];
}
__syncthreads();
lr_v8s tf[2][2];
for (int b = 0; b < 2; ++b)
for (int q = 0; q < 2; ++q)
for (int e = 0; e < 8; ++e)
tf[b][q][e] = (short)ts[wm + 16 * b + col][16 * half + 8 * q + e];
for (int a = 0; a < 8; ++a) {
lr_v8s bf[2];
for (int q = 0; q < 2; ++q)
for (int e = 0; e < 8; ++e)
bf[q][e] = (short)bs[wn + 16 * a + col][16 * half + 8 * q + e];
for (int b = 0; b < 2; ++b) {
acc[b][a] = wmma_bf16(bf[0], tf[b][0], acc[b][a]);
acc[b][a] = wmma_bf16(bf[1], tf[b][1], acc[b][a]);
}
}
}
for (int b = 0; b < 2; ++b) {
const int ml = wm + 16 * b + col;
if (mm_slot[ml] != s) continue;
const long long m = mb + ml;
for (int a = 0; a < 8; ++a) {
const long long n0 = nb + wn + 16 * a + 8 * half;
const long long o = m * A.y_rs + n0 * A.y_cs;
const float* scp = A.sc + (long long)s * A.sc_rs;
if (YDT == kBF16 && A.y_cs == 1 && n0 + 8 <= A.N && (((uintptr_t)A.y + 2 * o) & 15) == 0) {
lr_v8s* yp = (lr_v8s*)((uint16_t*)A.y + o);
lr_v8s yv = *yp;
for (int e = 0; e < 8; ++e)
yv[e] = (short)f2bf(bf2f((uint16_t)yv[e]) + scp[(n0 + e) * A.sc_cs] * acc[b][a][e]);
*yp = yv;
continue;
}
for (int e = 0; e < 8; ++e) {
const long long n = n0 + e;
if (n >= A.N) continue;
const float d = scp[n * A.sc_cs] * acc[b][a][e];
const long long oe = m * A.y_rs + n * A.y_cs;
if (YDT == kBF16) {
uint16_t* y = (uint16_t*)A.y + oe;
*y = f2bf(bf2f(*y) + d);
} else if (YDT == kF16) {
uint16_t* y = (uint16_t*)A.y + oe;
*y = f32_to_f16(f16_to_f32(*y) + d);
} else {
float* y = (float*)A.y + oe;
*y = *y + d;
}
}
}
}
}
}
/* ---------------------------------------------------------------- operand reading (host) */
/* `t` read as [rows, cols]: the trailing axes that span `cols` must be one dense run, the leading
@@ -885,6 +1003,13 @@ static void launch_expand_tiled(const ExpandTArgs& P, dim3 grid, RadStream strea
(hipStream_t)stream, P);
}
template <int YDT, bool V>
static void launch_expand_mm(const ExpandTArgs& P, dim3 grid, RadStream stream) {
(void)stream;
R4D_KLAUNCH(R4D_KNAME(lora_expand_mm_kernel<YDT, V>), grid, dim3(kMmThreads),
(hipStream_t)stream, P);
}
} /* namespace r4d_lora */
extern "C" {
@@ -1003,4 +1128,32 @@ int r4d_rad_lora_expand_tiled(const RadArgs* a, RadStream stream) {
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
/* lora_expand_mm: one block a (256 columns, 128 rows); expand_operands reads the same operands. */
int r4d_rad_lora_expand_mm(const RadArgs* a, RadStream stream) {
using namespace r4d_lora;
ExpandArgs P{};
int ydt = 0;
int64_t M = 0;
const int rc = expand_operands(a, &P, &ydt, &M);
if (rc != RAD_OK || M <= 0) return rc;
const int64_t rt = (M + kMmMT - 1) / kMmMT, nt = (P.N + kMmNT - 1) / kMmNT;
if (rt > 65535 || nt > 0x7fffffff) return RAD_E_SHAPE;
ExpandTArgs T{};
T.b = P;
T.M = (int)M;
T.Z = 1;
const bool v = P.lb_s2 == 1 && (uintptr_t)P.lb % 16 == 0 && P.lb_s1 % 8 == 0 &&
P.lb_s0 % 8 == 0;
const dim3 grid((unsigned)nt, (unsigned)rt, 1u);
switch (ydt) {
case kBF16: v ? launch_expand_mm<kBF16, true>(T, grid, stream)
: launch_expand_mm<kBF16, false>(T, grid, stream); break;
case kF16: v ? launch_expand_mm<kF16, true>(T, grid, stream)
: launch_expand_mm<kF16, false>(T, grid, stream); break;
default: v ? launch_expand_mm<kF32, true>(T, grid, stream)
: launch_expand_mm<kF32, false>(T, grid, stream); break;
}
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
} /* extern "C" */
+5
View File
@@ -156,6 +156,7 @@ int r4d_rad_lora_expand (const RadArgs*, RadStream);
int r4d_rad_lora_shrink_wmma (const RadArgs*, RadStream);
int64_t r4d_rad_lora_shrink_wmma_scratch(const RadArgs*);
int r4d_rad_lora_expand_tiled (const RadArgs*, RadStream);
int r4d_rad_lora_expand_mm (const RadArgs*, RadStream);
int r4d_rad_attn_vit (const RadArgs*, RadStream);
int r4d_rad_attn_dense (const RadArgs*, RadStream);
int r4d_rad_seg_sinusoid (const RadArgs*, RadStream);
@@ -179,13 +180,17 @@ int r4d_rad_lane_gather (const RadArgs*, RadStream);
int r4d_rad_lane_store (const RadArgs*, RadStream);
int r4d_rad_randn_lanes (const RadArgs*, RadStream);
int r4d_rad_flow_euler (const RadArgs*, RadStream);
int r4d_rad_kd_input (const RadArgs*, RadStream);
int r4d_rad_kd_step (const RadArgs*, RadStream);
int r4d_rad_chan_affine (const RadArgs*, RadStream);
int r4d_rad_conv2d_nhwc (const RadArgs*, RadStream);
int r4d_rad_im2col_nhwc (const RadArgs*, RadStream);
int r4d_rad_l2norm_chan (const RadArgs*, RadStream);
int r4d_rad_d2s_add (const RadArgs*, RadStream);
int r4d_rad_s2d_avg_add (const RadArgs*, RadStream);
int r4d_rad_to_rgba8 (const RadArgs*, RadStream);
int r4d_rad_gelu_tanh (const RadArgs*, RadStream);
int r4d_rad_gelu_quick (const RadArgs*, RadStream);
int r4d_rad_scatter_add_rows (const RadArgs*, RadStream);
/* r4d_audio.hip */
int r4d_rad_conv1d (const RadArgs*, RadStream);
+88 -7
View File
@@ -2318,6 +2318,21 @@ static const RadOperandSpec oFlowEuler[] = {
{ "inp_lat", RAD_OPD_IN, 1 }, { "inp_mask", RAD_OPD_IN, 1 }, { "state", RAD_OPD_INOUT, 0 },
{ "preview", RAD_OPD_INOUT, 1 },
};
/* The k-diffusion sampler's input and step: `pred` "eps" or "v", the lanes f32. */
static const RadParamSpec pKdStep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("pred"),
P_STR("dtype") };
static const RadOperandSpec oKdInput[] = {
{ "sigma", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 },
{ "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "state", RAD_OPD_INOUT, 0 }, { "y", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oKdStep[] = {
{ "out", RAD_OPD_IN, 0 }, { "sigma", RAD_OPD_IN, 0 }, { "sigma_next", RAD_OPD_IN, 0 },
{ "sigma_prev", RAD_OPD_IN, 0 }, { "cfg", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 },
{ "lane", RAD_OPD_IN, 0 }, { "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 },
{ "sampler", RAD_OPD_IN, 0 }, { "step", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "state", RAD_OPD_INOUT, 0 }, { "hist", RAD_OPD_INOUT, 0 }, { "preview", RAD_OPD_INOUT, 1 },
};
/* `round` 0 keeps the lists and the arithmetic in f32 (default 1, bf16 lists and roundings). */
static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"),
P_STR("mode"), P_STR("dtype"), P_INTO("round") };
@@ -2329,6 +2344,8 @@ static const RadOperandSpec oConvNhwc[] = {
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pIm2col[] = { P_INT("M"), P_INT("cin"), P_INT("k"), P_INT("stride"),
P_STR("pad"), P_INT("up"), P_STR("dtype") };
static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
static const RadOperandSpec oL2Norm[] = {
{ "x", RAD_OPD_IN, 0 }, { "gamma", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 },
@@ -3231,6 +3248,11 @@ static const RadOpSchema kSchemas[] = {
"y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * lora_b[s, n, j] for each row m "
"whose s = slot[m] is in [0, S), f32 accumulate, one rounding to y's dtype. A base "
"row's `y` is neither read nor written."),
SCHEMA("lora_expand_mm", pLoraExpand, oLoraExpand,
"lora_expand with t rounded to bf16 and the sum over j in any order: y[m, n] = y[m, n] "
"+ scale[s, n] * sum_j bf16(t[m, j]) * lora_b[s, n, j], f32 accumulate, one rounding "
"to y's dtype; a base row's `y` is neither read nor written. A row's bytes may depend "
"on M."),
SCHEMA("ln_mod", pLnMod, oLnMod,
"y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the "
"row's sequence's modulation row of `s`."),
@@ -3258,17 +3280,30 @@ static const RadOpSchema kSchemas[] = {
"an image's first step: its lane's rows become its seed's normal stream."),
SCHEMA("flow_euler", pLane, oFlowEuler,
"one Euler step of a flow-matching sampler per entry that moves a lane."),
SCHEMA("kd_input", pLane, oKdInput,
"a k-diffusion sampler's model input per entry that moves a lane: a first step's noise "
"times sqrt(1 + sigma^2) into the lane, then rd(x / sqrt(sigma^2 + 1)) at its rows and "
"its pair's."),
SCHEMA("kd_step", pKdStep, oKdStep,
"one k-diffusion sampler step per entry that moves a lane: the guided clean estimate "
"from an eps or v output, then Euler, Euler ancestral or DPM++ 2M; the lanes f32."),
SCHEMA("chan_affine", pChanAffine, oGenUnary,
"a per-channel affine from two parameter lists of n values; `round` 0 keeps the lists "
"and the arithmetic in f32, rounded once into y."),
SCHEMA("conv2d_nhwc", pConvNhwc, oConvNhwc,
"an image convolution, channels innermost, the sizes read off the operands."),
SCHEMA("im2col_nhwc", pIm2col, oGenUnary,
"conv2d_nhwc's receptive fields as rows: y [Ho * Wo, cin * k * k], column "
"(ci * k + i) * k + j of row oy * Wo + ox the input conv2d_nhwc multiplies weight[o, ci, "
"i, j] by, 0 in the padding."),
SCHEMA("l2norm_chan", pL2Norm, oL2Norm,
"unit-L2 per row, times sqrt(n), times gamma, then `act`: an image decoder's norm."),
SCHEMA("d2s_add", pSpaceDepth, oSpaceDepth, "an upsampling shortcut added in."),
SCHEMA("s2d_avg_add", pSpaceDepth, oSpaceDepth, "a downsampling shortcut added in."),
SCHEMA("to_rgba8", pGenMn, oGenUnary, "decoded pixels in [-1, 1] to bytes."),
SCHEMA("gelu_tanh", pGenMn, oGenUnary, "the tanh approximation of gelu."),
SCHEMA("gelu_quick", pGenMn, oGenUnary,
"CLIP's quick_gelu: a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s)."),
SCHEMA("scatter_add_rows", pGenMn, oScatterAdd, "x[idx[i]] += v[i]; a negative index adds nothing."),
SCHEMA("attn_prefix_self", pAttnPS, oAttnPS,
"attention over a paged prefix and the step's own rows, causal over the own rows or not. "
@@ -4784,14 +4819,14 @@ static const RadConstraint cPatchUnfold[] = { C_IN("dtype", "f32"), C_LE("C", 64
static const RadConstraint cGenAnyFloat[] = { C_IN("dtype", "bf16 f32") };
static const RadConstraint cSnakeAa[] = { C_IN("dtype", "f32"), C_LE("k", 32) };
/* ---- a video latent upscaler (r4d_upscaler.hip). The convolution decodes 3 x 3 x 3 taps as
* constants and reads 16-byte chunks of a voxel row; the group norm puts a thread on an 8-channel
* chunk inside one group, a row's chunks a power of two dividing the 256-thread block (the shim
* checks that and n / groups % 8), and merges at most 256 groups; the temporal convolution keeps
* constants and reads 16-byte chunks of a voxel row; the group norm puts a thread on chunks of 8, 4
* or 2 channels inside one group, a row's chunks spread over at most the 256-thread block (the
* shim checks an even group width), and merges at most 256 groups; the temporal convolution keeps
* its 5-frame window in registers; the fold's lists are kernel arguments, 64 floats at most. */
static const RadConstraint cConv3d[] = { C_IN("dtype", "bf16"), C_EQ("k", 3), C_EQ("kt", 3),
C_DIV("cin", 8) };
static const RadConstraint cGroupNorm[] = { C_IN("dtype", "bf16 f32"), C_DIV("n", 8),
C_LE("n", 2048), C_LE("groups", 256) };
C_LE("n", 8192), C_LE("groups", 256) };
static const RadConstraint cTconvDw[] = { C_IN("dtype", "bf16"), C_EQ("k", 5), C_DIV("n", 8) };
static const RadConstraint cResizeBil[] = { C_IN("dtype", "bf16 f32"), C_DIV("n", 8) };
static const RadConstraint cPatchFold[] = { C_IN("dtype", "bf16 f32"), C_LE("C", 64) };
@@ -4799,6 +4834,8 @@ static const RadConstraint cLnModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128),
C_EQ("group", 128) };
/* The lane copies move 32-bit words, so any row of whole words: bf16 latents and an f32 mask. */
static const RadConstraint cGenLanes[] = { C_IN("dtype", "bf16 f32") };
/* gelu_quick: x and y of one dtype, any width and pitch. */
static const RadConstraint cGeluQuick[] = { C_IN("dtype", "bf16 f32") };
/* The two lists are kernel arguments, 64 floats each at most (r4d_gen.hip). */
static const RadConstraint cGenAffine[] = { C_IN("dtype", "bf16"), C_LE("n", 64) };
static const RadConstraint cGenAffineF32[] = { C_IN("dtype", "f32"), C_LE("n", 64) };
@@ -7868,6 +7905,17 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
RAD_DOMAIN_DEVICE, R4D_PRIO_LORA_TILED,
ROW(cLoraExpand), NOTUNE,
nullptr, nullptr, r4d_rad_lora_expand_tiled },
/* The generators' expand (lora_expand_mm): the same delta on the WMMA, for passes of many rows of
* one adapter, where the exact row's scalar sum is most of the adapter's cost. */
{ "lora_expand_mm_wmma", "lora_expand_mm", "gemm",
"y += scale * (bf16(t) B[slot]^T) per row, base rows neither read nor written: WMMA bf16 over "
"64-row x 64-column tiles, four waves of 2 x 2 16 x 16 tiles, one pass a distinct slot of a tile",
"any M and N, 1 <= R <= 65536, 1 <= S <= 2^20; row and column strides of t and y honoured, "
"16-byte pool loads where B's rows are aligned",
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y",
RAD_DOMAIN_DEVICE, R4D_PRIO_LORA_TILED,
ROW(cLoraExpand), NOTUNE,
nullptr, nullptr, r4d_rad_lora_expand_mm },
{ "attn_prefix_self_h128_bf16", "attn_prefix_self", "attn",
"attention over a paged prefix and the pass's own rows, causal over the own rows or not",
"head_dim 128, 1/2/4/8 query heads a KV head, a flat grid over the sequences' query blocks; "
@@ -8062,6 +8110,22 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_flow_euler },
{ "kd_input_bf16", "kd_input", "elem",
"a k-diffusion sampler's model input: a first step's noise into the f32 lane, c_in x out",
"any M, row pitches honoured; a thread an element of an entry",
"f32 lanes, bf16 y",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_kd_input },
{ "kd_step_bf16", "kd_step", "elem",
"a k-diffusion sampler step with guidance and preview: Euler, Euler ancestral or DPM++ 2M",
"any M, row pitches honoured; a thread an element of an entry",
"bf16 model output, f32 lanes, history and preview, f32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_kd_step },
{ "chan_affine_bf16", "chan_affine", "elem",
"a per-channel affine from parameter lists; `round` 0 keeps the lists and arithmetic f32",
"any M, row pitches honoured",
@@ -8118,6 +8182,14 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cGenRows8), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_tanh },
{ "gelu_quick_bf16", "gelu_quick", "elem",
"CLIP's quick_gelu, libref's three roundings",
"any M and n, row pitches honoured",
"bf16 or f32 in and out (one dtype), f32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGeluQuick), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_quick },
{ "scatter_add_rows_bf16", "scatter_add_rows", "elem",
"x[idx[i]] += v[i]",
"any M, row pitches honoured",
@@ -8135,6 +8207,15 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_conv2d_nhwc, nullptr, r4d_rad_layout_conv_tap, r4d_rad_relayout_conv_tap,
nullptr, r4d_rad_unrelayout_conv_tap },
{ "im2col_nhwc_bf16", "im2col_nhwc", "elem",
"a convolution's receptive fields as GEMM rows in the weight's (cin, kh, kw) order: 32 output "
"pixels by 64 channels a block, the input rows staged in LDS, coalesced loads and stores",
"k <= 7, stride and up 1 or 2; x rows at their own pitch; y exactly Ho * Wo rows at its pitch",
"bf16 in and out, copied bit for bit",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_im2col_nhwc },
/* -------------------------------------------------------------------------- audio generation */
{ "conv1d_bf16", "conv1d", "conv",
"a 1-D convolution over sequences as an implicit GEMM over (tap, cin), the weight tap-major",
@@ -8392,9 +8473,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
{ "group_norm", "group_norm", "norm",
"GroupNorm over all rows in three launches: per-part (count, mean, M2), their merge to mean and "
"rstd, then the affine, modulation and SiLU a thread an 8-channel chunk",
"n % 8 == 0 with n / 8 a power of two up to 256, n / groups % 8 == 0, groups <= 256, M n / "
"groups < 2^24; row pitches honoured, y may alias x",
"rstd, then the affine, modulation and SiLU a thread an 8-, 4- or 2-channel chunk",
"n % 8 == 0 up to 8192, an even n / groups, groups <= 256, M n / groups < 2^31; row pitches "
"honoured, y may alias x",
"bf16 or f32 rows, bf16 or f32 gain, bias and modulation, f32 statistics",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGroupNorm), NOTUNE,
+339 -5
View File
@@ -8004,6 +8004,60 @@ void conv2d_cases(const Plugin& pl) {
}
}
/* im2col_nhwc against a host unfold, bit for bit: SDXL's widths (a tail of channels past the
* 64-channel chunks, the upsample, both stride-2 paddings), an input whose channels are not a
* multiple of eight (the element loads), a 1x1 and a 5x5 (k at run time), x at a row pitch, and an
* odd output width (the narrowest stores). The y rows past the unfold must stay as they were. */
void im2col_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "im2col_nhwc_bf16");
if (!r) { ok("im2col_nhwc_bf16", false, "row absent"); return; }
struct Case { const char* pad; int64_t cin, k, stride, up, H, W, xpad; };
for (const Case c : { Case{ "same", 320, 3, 1, 1, 40, 37, 0 }, Case{ "same", 200, 3, 1, 2, 9, 13, 0 },
Case{ "same", 640, 3, 2, 1, 22, 17, 0 }, Case{ "down", 64, 3, 2, 1, 10, 14, 0 },
Case{ "same", 4, 3, 1, 1, 33, 35, 0 }, Case{ "same", 6, 3, 1, 1, 7, 9, 2 },
Case{ "same", 96, 1, 1, 1, 11, 7, 8 }, Case{ "same", 72, 5, 1, 1, 12, 15, 0 },
Case{ "causal", 24, 3, 1, 1, 8, 5, 0 } }) {
const bool down = !std::strcmp(c.pad, "down"), causal = !std::strcmp(c.pad, "causal");
const int64_t Hv = c.H * c.up, Wv = c.W * c.up;
const int64_t pt = down ? 0 : causal ? c.k - 1 : c.k / 2, pb = down ? 1 : causal ? 0 : c.k / 2;
const int64_t pl0 = down ? 0 : c.k / 2, pr = down ? 1 : c.k / 2;
const int64_t Ho = (Hv + pt + pb - c.k) / c.stride + 1, Wo = (Wv + pl0 + pr - c.k) / c.stride + 1;
const int64_t KK = c.cin * c.k * c.k, ld = c.W * c.cin + c.xpad;
const std::string nm = fmt("im2col_nhwc_bf16 %s, %lld channels, k %lld, stride %lld, up %lld, "
"%lldx%lld", c.pad, (long long)c.cin, (long long)c.k,
(long long)c.stride, (long long)c.up, (long long)c.H,
(long long)c.W);
std::vector<float> x = randv((size_t)(c.H * ld), 1.0f);
void* dx = up_bf16(x);
std::vector<float> pre((size_t)((Ho * Wo + 1) * KK), -7.5f);
void* dy = up_bf16(pre);
RadTensor tx = T(dx, RAD_BF16, { c.H, c.W * c.cin });
tx.stride[0] = ld;
const int rc = launch(r, { tx, T(dy, RAD_BF16, { Ho * Wo, KK }) },
{ PI("M", Ho * Wo), PI("cin", c.cin), PI("k", c.k),
PI("stride", c.stride), PS("pad", c.pad), PI("up", c.up),
PS("dtype", "bf16") });
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
const std::vector<float> got = down_bf16(dy, pre.size());
int64_t bad = 0;
for (int64_t oy = 0; oy < Ho; ++oy)
for (int64_t ox = 0; ox < Wo; ++ox)
for (int64_t ci = 0; ci < c.cin; ++ci)
for (int64_t i = 0; i < c.k; ++i)
for (int64_t j = 0; j < c.k; ++j) {
const int64_t iy = oy * c.stride + i - pt, ix = ox * c.stride + j - pl0;
const float v = iy < 0 || iy >= Hv || ix < 0 || ix >= Wv
? 0.0f
: x[(size_t)((iy / c.up) * ld + (ix / c.up) * c.cin + ci)];
const int64_t at = (oy * Wo + ox) * KK + (ci * c.k + i) * c.k + j;
bad += got[(size_t)at] != v;
}
for (int64_t e = Ho * Wo * KK; e < (Ho * Wo + 1) * KK; ++e)
bad += got[(size_t)e] != -7.5f;
ok(nm.c_str(), bad == 0, fmt("%lld elements differ", (long long)bad));
}
}
} /* namespace ltx */
/* ---- a video latent upscaler's ops, at MiniMax-H3's shapes ---------------------------------------
@@ -8287,6 +8341,7 @@ void group_norm_cases(const Plugin& pl) {
bool silu, inplace;
float offset; /* added to every value: a mean far from zero */
int64_t pad;
float eps = 1e-5f;
};
for (const G& g : {
/* The target size modulated with SiLU (a block's second norm), then plain with SiLU
@@ -8306,6 +8361,17 @@ void group_norm_cases(const Plugin& pl) {
G{ "2 channels a group", 48 * 8 * 8, 64, 32, false, false, false, 0, true, false, 0.0f, 0 },
G{ "2 channels a group, f32 rows", 777, 64, 32, true, true, true, 2, false, false, 5.0f, 8 },
G{ "4 channels a group, f32", 777, 128, 32, true, true, true, 2, false, false, 20.0f, 8 },
/* SDXL's UNet: 10 to 80 channels a group, a row's chunks not a power of two (160),
* or more than the block (480 and 320 chunks, three and two to a thread); a
* resnet's norm with SiLU at eps 1e-5, a transformer's without at 1e-6. */
G{ "SDXL 320", 128 * 128, 320, 32, false, false, false, 0, true, false, 0.0f, 0 },
G{ "SDXL 640, eps 1e-6", 64 * 64, 640, 32, false, false, false, 0, false, false, 3.0f, 8, 1e-6f },
G{ "SDXL 960 in place", 128 * 128, 960, 32, false, false, false, 0, true, true, 0.0f, 0 },
G{ "SDXL 1280, eps 1e-6", 32 * 32, 1280, 32, false, false, false, 0, false, false, 0.0f, 0, 1e-6f },
G{ "SDXL 1920", 64 * 64, 1920, 32, false, false, false, 0, true, false, -2.0f, 16 },
G{ "SDXL 2560", 32 * 32 + 7, 2560, 32, false, false, true, 2, true, false, 0.0f, 8 },
/* A group of more than 2^24 values: the counts past f32's integers. */
G{ "2^24 values a group", 600 * 1024, 64, 2, false, false, false, 0, true, false, 1.0f, 0 },
}) {
const int64_t M = g.M, n = g.n, ld = n + g.pad, rows = M + 2;
const std::string nm = fmt("group_norm %s: %lld x %lld in %lld groups", g.what,
@@ -8343,12 +8409,12 @@ void group_norm_cases(const Plugin& pl) {
T(db, g.wf ? RAD_F32 : RAD_BF16, { n }), tm,
T(ds, RAD_F32, { g.groups * (2 + 3 * 1024) }), pitched(dy, ydt, M, n, ld) };
const std::vector<RadParam> ps = { PI("M", M), PI("n", n), PI("groups", g.groups),
PF("eps", 1e-5), PS("act", g.silu ? "silu" : "none"),
PF("eps", g.eps), PS("act", g.silu ? "silu" : "none"),
PS("dtype", g.xf ? "f32" : "bf16") };
const int rc = launch(r, ts, ps);
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
std::vector<float> want, mean, rstd;
gn_ref(x, M, n, g.groups, w, b, g.mod ? &mod : nullptr, g.silu, 1e-5f, !g.yf, &want,
gn_ref(x, M, n, g.groups, w, b, g.mod ? &mod : nullptr, g.silu, g.eps, !g.yf, &want,
&mean, &rstd);
const size_t yel = (size_t)(rows * ld);
const std::vector<float> yall = g.yf ? down_f32(dy, yel) : down_bf16(dy, yel);
@@ -8395,10 +8461,10 @@ void group_norm_cases(const Plugin& pl) {
}
RadTensor nomod = T(nullptr, RAD_BF16, { 1 });
absent(nomod);
ok("group_norm refuses 12 channels a group",
ok("group_norm refuses 3 channels a group",
launch(r, { TA(RAD_BF16, { 4, 96 }), TA(RAD_BF16, { 96 }), TA(RAD_BF16, { 96 }), nomod,
TA(RAD_F32, { 8 * 3074 }), TA(RAD_BF16, { 4, 96 }) },
{ PI("M", 4), PI("n", 96), PI("groups", 8), PF("eps", 1e-5), PS("act", "none"),
TA(RAD_F32, { 32 * 3074 }), TA(RAD_BF16, { 4, 96 }) },
{ PI("M", 4), PI("n", 96), PI("groups", 32), PF("eps", 1e-5), PS("act", "none"),
PS("dtype", "bf16") }) == RAD_E_SHAPE);
}
@@ -9474,6 +9540,165 @@ void attn_long_case(const Plugin& pl, const char* name, int64_t hd, int64_t nh,
check(nm + " numerics", got, want, 2e-2);
}
/* ---- SDXL's: CLIP-L's activation and the k-diffusion sampler, against a host port of libref's
* arithmetic (libref/ref_gen.cpp). */
void gelu_quick_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "gelu_quick_bf16");
if (!r) { ok("gelu_quick_bf16", false, "row absent"); return; }
const int64_t M = 77, n = 3072, ld = 3080;
std::vector<float> x = randv((size_t)(M * ld), 4.0f);
void* dx = up_bf16(x);
void* dy = dalloc((size_t)(M * n) * 2);
RadTensor tx = T(dx, RAD_BF16, { M, n });
tx.stride[0] = ld;
const int rc = launch(r, { tx, T(dy, RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PS("dtype", "bf16") });
if (rc != RAD_OK) { ok("gelu_quick_bf16", false, "rc " + std::to_string(rc)); return; }
std::vector<float> want((size_t)(M * n));
for (int64_t m = 0; m < M; ++m)
for (int64_t c = 0; c < n; ++c) {
const float v = x[(size_t)(m * ld + c)];
const float a = bfr(1.702f * v), s = bfr(1.0f / (1.0f + std::exp(-a)));
want[(size_t)(m * n + c)] = bfr(v * s);
}
check("gelu_quick_bf16 over pitched rows", down_bf16(dy, want.size()), want, 4e-3);
}
/* The host port of kd_step's per-element arithmetic for one entry. */
struct KdHost {
float s, sn, w, cskip, cout, sup = 0, sdown = 0, ratio = 0, em = 0, c1 = 0, c2 = 0;
bool second = false;
KdHost(float s_, float sn_, float sp, float w_, int sampler, bool first)
: s(s_), sn(sn_), w(w_) {
const float s2p = s * s + 1.0f;
cskip = 1.0f / s2p;
cout = s / std::sqrt(s2p);
if (sampler == 1) {
const float s2 = s * s, sn2 = sn * sn;
float u = std::sqrt(sn2 * (s2 - sn2) / s2);
if (!(u < sn)) u = sn;
sup = u;
const float d2 = sn2 - u * u;
sdown = std::sqrt(d2 > 0.0f ? d2 : 0.0f);
} else if (sampler == 2 && sn > 0.0f) {
const float t = -std::log(s), h = -std::log(sn) - t;
ratio = sn / s;
em = std::expm1(-h);
if (!first) {
const float rr = (t + std::log(sp)) / h;
c2 = 1.0f / (2.0f * rr);
c1 = 1.0f + c2;
second = true;
}
}
}
float den(bool v, float x, float o) const { return v ? x * cskip - o * cout : x - s * o; }
float next(int sampler, float x, float D, float hist, float nz) const {
if (sampler == 0) return x + (sn - s) * ((x - D) / s);
if (sampler == 1) return x + ((x - D) / s) * (sdown - s) + (sn > 0.0f ? nz * sup : 0.0f);
if (sn == 0.0f) return D;
return ratio * x - em * (second ? c1 * D - c2 * hist : D);
}
};
/* Five entries over lanes of 300 rows by 4 channels, an image of 280 latent rows each: entry 0 a
* first step guided against entry 1 (parked), entries 2-4 unguided at later steps. kd_input fills
* entry 0's lane and writes both entries' rows; kd_step takes every sampler at each prediction. */
void kd_cases(const Plugin& pl) {
const RadKernelInfo* ri = find(pl, "kd_input_bf16");
const RadKernelInfo* rs = find(pl, "kd_step_bf16");
if (!ri || !rs) { ok("kd_input_bf16 / kd_step_bf16", false, "row absent"); return; }
const int64_t n = 4, stride = 300, len = 280, S = 5, R = S * len, LR = S * stride;
const std::vector<int32_t> pair = { 1, -2, -1, -1, -1 }, lane = { 3, 0, 1, 4, 2 };
std::vector<int32_t> cu(S + 1);
for (int64_t e = 0; e <= S; ++e) cu[(size_t)e] = (int32_t)(e * len);
const std::vector<uint32_t> seeds = { 0x9e3779b9u, 7u, 0, 0, 5u, 1u, 77u, 0, 0xdeadbeefu, 3u };
std::vector<int32_t> sdw(seeds.begin(), seeds.end());
const std::vector<float> sg = { 14.6f, 14.6f, 3.5f, 1.25f, 0.4f };
const std::vector<float> sgn = { 11.0f, 11.0f, 2.0f, 0.7f, 0.0f };
const std::vector<float> sgp = { 0.0f, 0.0f, 5.0f, 2.0f, 0.9f };
const std::vector<float> cfg = { 6.0f, 1.0f, 1.0f, 1.0f, 1.0f };
const std::vector<int32_t> step = { 0, 0, 7, 4, 20 };
std::vector<float> st0 = randv((size_t)(LR * n), 2.0f);
/* ---- kd_input */
void* dst = up_f32(st0);
void* dy = dalloc((size_t)(R * n) * 2);
const std::vector<int32_t> fl_in = { 1, 0, 0, 0, 0 };
int rc = launch(ri, { T(up_f32(sg), RAD_F32, { S }), TI32({ S }, pair), TI32({ S }, lane),
TI32({ S }, fl_in), T(up_i32(sdw), RAD_U32, { 2 * S }),
TI32({ S + 1 }, cu), T(dst, RAD_F32, { LR, n }),
T(dy, RAD_BF16, { R, n }) },
{ PI("M", R), PI("n", n), PI("stride", stride), PS("dtype", "bf16") });
if (rc != RAD_OK) { ok("kd_input_bf16", false, "rc " + std::to_string(rc)); return; }
std::vector<float> st1 = st0, ywant((size_t)(R * n), 0.0f);
for (int64_t e = 0; e < S; ++e) {
if (pair[(size_t)e] == -2) continue;
const float s = sg[(size_t)e];
const uint64_t sd = (uint64_t)seeds[(size_t)(2 * e)] | ((uint64_t)seeds[(size_t)(2 * e + 1)] << 32);
for (int64_t k = 0; k < len; ++k)
for (int64_t c = 0; c < n; ++c) {
float& x = st1[(size_t)(((int64_t)lane[(size_t)e] * stride + k) * n + c)];
if (fl_in[(size_t)e] & 1)
x = rad_philox_normal(sd, (uint64_t)(k * n + c)) * std::sqrt(1.0f + s * s);
const float v = x * (1.0f / std::sqrt(s * s + 1.0f));
ywant[(size_t)((cu[(size_t)e] + k) * n + c)] = v;
if (pair[(size_t)e] >= 0) ywant[(size_t)((cu[(size_t)pair[(size_t)e]] + k) * n + c)] = v;
}
}
check_f32("kd_input_bf16 lanes", down_f32(dst, st1.size()), st1, 1e-6);
check("kd_input_bf16 model input", down_bf16(dy, ywant.size()), ywant, 4e-3);
/* ---- kd_step, each sampler for every entry, both predictions */
for (const bool v_pred : { false, true })
for (int smp = 0; smp < 3; ++smp) {
std::vector<float> out = randv((size_t)(R * n), 1.5f), hs = randv((size_t)(LR * n), 1.0f);
void* ds = up_f32(st1);
void* dh = up_f32(hs);
void* dp = dalloc((size_t)(LR * n) * 4);
const std::vector<int32_t> fl = { 5, 0, 0, 1, 0 };
const std::vector<int32_t> sm(S, smp);
const int rc2 = launch(rs, { T(up_bf16(out), RAD_BF16, { R, n }),
T(up_f32(sg), RAD_F32, { S }), T(up_f32(sgn), RAD_F32, { S }),
T(up_f32(sgp), RAD_F32, { S }), T(up_f32(cfg), RAD_F32, { S }),
TI32({ S }, pair), TI32({ S }, lane), TI32({ S }, fl),
T(up_i32(sdw), RAD_U32, { 2 * S }), TI32({ S }, sm),
TI32({ S }, step), TI32({ S + 1 }, cu),
T(ds, RAD_F32, { LR, n }), T(dh, RAD_F32, { LR, n }),
T(dp, RAD_F32, { LR, n }) },
{ PI("M", R), PI("n", n), PI("stride", stride),
PS("pred", v_pred ? "v" : "eps"), PS("dtype", "bf16") });
const std::string nm = fmt("kd_step_bf16 sampler %d %s", smp, v_pred ? "v" : "eps");
if (rc2 != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc2)); return; }
std::vector<float> sw = st1, hw = hs, pw((size_t)(LR * n), 0.0f);
for (int64_t e = 0; e < S; ++e) {
const int32_t pr = pair[(size_t)e];
if (pr == -2) continue;
const KdHost K(sg[(size_t)e], sgn[(size_t)e], sgp[(size_t)e], cfg[(size_t)e], smp,
(fl[(size_t)e] & 1) != 0);
const uint64_t sd = (uint64_t)seeds[(size_t)(2 * e)] | ((uint64_t)seeds[(size_t)(2 * e + 1)] << 32);
for (int64_t k = 0; k < len; ++k)
for (int64_t c = 0; c < n; ++c) {
const size_t li = (size_t)(((int64_t)lane[(size_t)e] * stride + k) * n + c);
const float x = sw[li];
float D = K.den(v_pred, x, out[(size_t)((cu[(size_t)e] + k) * n + c)]);
if (pr >= 0) {
const float Du = K.den(v_pred, x, out[(size_t)((cu[(size_t)pr] + k) * n + c)]);
D = Du + K.w * (D - Du);
}
if (fl[(size_t)e] & 4) pw[li] = D;
const float nz = rad_philox_normal_s(sd, (uint64_t)(uint32_t)(1 + step[(size_t)e]),
(uint64_t)(k * n + c));
sw[li] = K.next(smp, x, D, hw[li], nz);
hw[li] = D;
}
}
check_f32(nm + " lanes", down_f32(ds, sw.size()), sw, 1e-5);
check_f32(nm + " history", down_f32(dh, hw.size()), hw, 1e-5);
if (smp == 0) check_f32(nm + " preview", down_f32(dp, pw.size()), pw, 1e-5);
}
}
} /* namespace vg */
/* ---- video sparse attention: vsa_select and attn_vsa against a host port of their contract
@@ -16227,6 +16452,96 @@ static void attn_perf(const Plugin& pl, int64_t M, int64_t H, int iters) {
dfree_all();
}
/* SDXL's UNet convolutions at 1024 x 1024 (a 128 x 128 latent): the implicit GEMM against the
* unfold and a GEMM over the checkpoint's own weight, which runtime LoRA can attach to. */
static void conv_perf(const Plugin& pl, int iters) {
if (iters <= 0) iters = 20;
const RadKernelInfo* rc = find(pl, "conv2d_nhwc_bf16");
const RadKernelInfo* ri = find(pl, "im2col_nhwc_bf16");
const RadKernelInfo* rg = find(pl, "gemm_bf16_nt_bias_tiled");
if (!rc || !ri || !rg) { std::printf("conv timing: a row is absent\n"); return; }
auto rand_fill = [](void* d, size_t bytes) {
const size_t chunk = std::min<size_t>(bytes, (size_t)16 << 20);
std::vector<uint16_t> h(chunk / 2);
for (size_t i = 0; i < h.size(); ++i) h[i] = st_rand_bf16((uint32_t)i);
for (size_t off = 0; off < bytes; off += chunk)
st_memcpy((uint8_t*)d + off, h.data(), std::min(chunk, bytes - off), hipMemcpyHostToDevice);
};
auto time_row = [&](const RadKernelInfo* r, std::vector<RadTensor> ts, std::vector<RadParam> ps)
-> double {
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
const int code = r->launch(&a, nullptr);
if (code != RAD_OK) return (double)code;
if (st_stream_sync(nullptr) != hipSuccess) return -1000.0;
return st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr);
};
struct C { int64_t side, cin, cout, stride, up; };
static const C kC[] = {
{ 128, 320, 320, 1, 1 }, { 128, 960, 320, 1, 1 }, { 128, 640, 320, 1, 1 },
{ 64, 640, 640, 1, 2 }, { 128, 320, 320, 2, 1 },
{ 64, 320, 640, 1, 1 }, { 64, 640, 640, 1, 1 }, { 64, 1920, 640, 1, 1 },
{ 64, 1280, 640, 1, 1 }, { 64, 960, 640, 1, 1 }, { 32, 1280, 1280, 1, 2 },
{ 64, 640, 640, 2, 1 },
{ 32, 640, 1280, 1, 1 }, { 32, 1280, 1280, 1, 1 }, { 32, 2560, 1280, 1, 1 },
{ 32, 1920, 1280, 1, 1 },
};
std::printf("SDXL's 3x3 convolutions at 1024 x 1024, %d launches each: conv2d_nhwc_bf16 "
"against im2col_nhwc_bf16 + gemm_bf16_nt_bias_tiled\n", iters);
std::printf(" %-28s %10s %10s %10s %10s %7s\n", "input -> output, channels", "conv us",
"im2col us", "gemm us", "sum us", "ratio");
double tc = 0, ti = 0, tg = 0;
for (const C& c : kC) {
const int64_t Hin = c.side, Hv = Hin * c.up, Ho = (Hv + 2 - 3) / c.stride + 1, k = 3;
const int64_t P = Ho * Ho, K = c.cin * k * k;
void* dx = dalloc((size_t)(Hin * Hin * c.cin) * 2);
void* dw = dalloc((size_t)(c.cout * K) * 2);
void* db = dalloc((size_t)c.cout * 2);
void* dc = dalloc((size_t)(P * K) * 2);
void* dy = dalloc((size_t)(P * c.cout) * 2);
if (!dx || !dw || !db || !dc || !dy) { std::printf(" hipMalloc failed\n"); dfree_all(); continue; }
rand_fill(dx, (size_t)(Hin * Hin * c.cin) * 2);
rand_fill(dw, (size_t)(c.cout * K) * 2);
rand_fill(db, (size_t)c.cout * 2);
const std::vector<RadParam> pc = { PI("M", P), PI("cin", c.cin), PI("cout", c.cout),
PI("k", k), PI("stride", c.stride), PS("pad", "same"),
PI("up", c.up), PS("dtype", "bf16") };
const double uc = time_row(rc, { T(dx, RAD_BF16, { Hin, Hin * c.cin }),
T(dw, RAD_BF16, { c.cout, c.cin, k, k }),
T(db, RAD_BF16, { c.cout }), T(dy, RAD_BF16, { Ho, Ho * c.cout }) },
pc);
const std::vector<RadParam> pi = { PI("M", P), PI("cin", c.cin), PI("k", k),
PI("stride", c.stride), PS("pad", "same"), PI("up", c.up),
PS("dtype", "bf16") };
const double ui = time_row(ri, { T(dx, RAD_BF16, { Hin, Hin * c.cin }),
T(dc, RAD_BF16, { P, K }) }, pi);
RadTensor tres = T(nullptr, RAD_BF16, { 1 });
absent(tres);
const double ug = time_row(rg, { T(dc, RAD_BF16, { P, K }), T(dw, RAD_BF16, { c.cout, K }),
T(db, RAD_BF16, { c.cout }), tres,
T(dy, RAD_BF16, { P, c.cout }) },
{ PI("M", P), PI("N", c.cout), PI("K", K), PS("dtype", "bf16") });
const std::string nm = fmt("%lldx%lld%s -> %lldx%lld, %lld -> %lld", (long long)Hin,
(long long)Hin, c.up == 2 ? " up2" : "", (long long)Ho,
(long long)Ho, (long long)c.cin, (long long)c.cout);
if (uc < 0 || ui < 0 || ug < 0) {
std::printf(" %-28s rc %d / %d / %d\n", nm.c_str(), (int)uc, (int)ui, (int)ug);
} else {
std::printf(" %-28s %10.1f %10.1f %10.1f %10.1f %7.2f\n", nm.c_str(), uc, ui, ug,
ui + ug, (ui + ug) / uc);
tc += uc;
ti += ui;
tg += ug;
}
dfree_all();
}
std::printf(" %-28s %10.1f %10.1f %10.1f %10.1f %7.2f\n", "total", tc, ti, tg, ti + tg,
(ti + tg) / tc);
}
static void video_perf(const Plugin& pl, int iters, const char* only) {
if (iters <= 0) iters = 10;
/* One section by name, or every one. */
@@ -24719,6 +25034,7 @@ static void device_phase(const Plugin& pl) {
if (sel("stft_logmel")) ltx::stft_cases(pl);
if (sel("bwe_up")) ltx::bwe_cases(pl);
if (sel("conv2d_nhwc_bf16")) ltx::conv2d_cases(pl);
if (sel("im2col_nhwc_bf16")) ltx::im2col_cases(pl);
if (sel("int_affine")) ltx::int_affine_cases(pl);
if (sel("vsa_select_h128_bf16")) vsa::select_cases(pl);
if (sel("attn_vsa_h128_bf16")) vsa::attn_cases(pl);
@@ -24738,6 +25054,8 @@ static void device_phase(const Plugin& pl) {
if (sel("layernorm_bf16")) vg::norm_f32_rows_cases(pl, true);
if (sel("timestep_embed_f32")) vg::timestep_f32_case(pl);
if (sel("randn_lanes_f32")) vg::randn_f32_case(pl);
if (sel("gelu_quick_bf16")) vg::gelu_quick_cases(pl);
if (sel("kd_input_bf16") || sel("kd_step_bf16")) vg::kd_cases(pl);
if (sel("interleave2_bf16")) vg::interleave2_f32_case(pl);
if (sel("chan_affine_f32")) vg::chan_affine_cases(pl, "chan_affine_f32");
if (sel("chan_affine_bf16")) vg::chan_affine_cases(pl, "chan_affine_bf16");
@@ -25518,6 +25836,8 @@ static void usage(void) {
" decoder's tiles), upscaler (a latent upscaler's 3D convolutions\n"
" beside the bf16 GEMM at the same M, N and K, then its norm and\n"
" elementwise ops); every section without one.\n"
" --perfconv [iters]: SDXL's 3x3 convolutions at 1024 x 1024, conv2d_nhwc against\n"
" im2col_nhwc and the biased GEMM over the unfolded rows.\n"
" --perfvsa [iters] [local]: vsa_select and attn_vsa at 1344 x 768 (38010\n"
" rows, 28 heads), sparsity 0.8 and 0, beside attn_dense over the same\n"
" rows. `local` gives q and k features of the row's grid position, so a\n"
@@ -25591,6 +25911,7 @@ int main(int argc, char** argv) {
long long m16_m = 0, m16_e = 256, m16_k = 10, m16_d = 0;
int m16_it = 20;
int video_it = 0;
int conv_it = 0;
long long attn_m = 0, attn_h = 0;
int attn_it = 5;
int vsa_it = 0;
@@ -25778,6 +26099,9 @@ int main(int argc, char** argv) {
video_it = 10;
if (i + 1 < argc && argv[i + 1][0] != '-') video_it = (int)std::strtol(argv[++i], nullptr, 0);
if (i + 1 < argc && argv[i + 1][0] != '-') video_sec = argv[++i];
} else if (!std::strcmp(argv[i], "--perfconv")) {
conv_it = 20;
if (i + 1 < argc && argv[i + 1][0] != '-') conv_it = (int)std::strtol(argv[++i], nullptr, 0);
} else if (!std::strcmp(argv[i], "--perfvsa")) {
vsa_it = 5;
if (i + 1 < argc && argv[i + 1][0] != '-' && std::strcmp(argv[i + 1], "local"))
@@ -25813,6 +26137,16 @@ int main(int argc, char** argv) {
attn_perf(pl, attn_m, attn_h, attn_it);
#else
skip("attention timing", "built without HIP");
#endif
return 0;
}
if (conv_it) {
if (!load(&pl, path)) return 1;
#ifdef RAD_HAVE_HIP
conv_perf(pl, conv_it);
dfree_all();
#else
skip("convolution timing", "built without HIP");
#endif
return 0;
}
+55 -52
View File
@@ -412,12 +412,15 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
// give the same bytes:
//
// 1. parts: block p takes rows [p rpp, (p + 1) rpp) and writes each group's (count, mean, M2)
// of them to the scratch. A thread keeps one 8-channel chunk of one group over every
// `slots`-th row, summing deviations from its first value (the shift keeps the f32 sums of
// squares from cancelling against a large mean); the block merges its threads' triples per
// group in thread order (Chan's parallel update).
// of them to the scratch. A row is `tpr` threads, each owning `cpt` consecutive CW-channel
// chunks of one group, and the block holds `slots` = 256 / tpr rows at a time (the threads
// past slots * tpr idle). A thread keeps its chunks over every `slots`-th row, summing
// deviations from its first value (the shift keeps the f32 sums of squares from cancelling
// against a large mean); the block merges its threads' triples per group in thread order
// (Chan's parallel update).
// 2. final: block g merges group g's parts, 256 strided runs then a fixed tree, and writes
// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps).
// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps), the count the
// group's exact M n / groups.
// 3. apply: a thread an 8-channel chunk, v = (x - mean) rstd w + b, the modulation and SiLU in
// f32, one rounding.
//
@@ -436,31 +439,33 @@ __device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, flo
n = nab;
}
/* `cpr_log`: log2 of the chunks a row (n / CW, a power of two dividing the block); `gs8` the
* chunks a group. A chunk is CW channels: 8, or 4 for groups of 4 channels. */
/* A chunk is CW channels (8, 4 or 2: the widest dividing a group). `tpr` threads a row, each over
* `cpt` chunks; `tpg` threads a group (its chunks / cpt). */
template <typename TX, int CW>
__global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
float* __restrict__ stats, int M, int groups,
int cpr_log, int gs8, int ldx, int rpp) {
int tpr, int cpt, int tpg, int ldx, int rpp) {
__shared__ float sh[3][kT];
const int tid = threadIdx.x;
const int cpr = 1 << cpr_log, slots = kT >> cpr_log;
const int c = tid & (cpr - 1), slot = tid >> cpr_log;
const int slots = kT / tpr;
const int c = tid % tpr, slot = tid / tpr;
const int p = blockIdx.x;
const int r0 = p * rpp, r1 = min(M, r0 + rpp);
float cnt = 0.0f, s1 = 0.0f, s2 = 0.0f, shift = 0.0f;
for (int r = r0 + slot; r < r1; r += slots) {
float v[CW];
ldc<CW>(x + (size_t)r * ldx + c * CW, v);
if (cnt == 0.0f) shift = v[0];
if (slot < slots)
for (int r = r0 + slot; r < r1; r += slots)
for (int q = 0; q < cpt; ++q) {
float v[CW];
ldc<CW>(x + (size_t)r * ldx + (c * cpt + q) * CW, v);
if (cnt == 0.0f) shift = v[0];
#pragma unroll
for (int j = 0; j < CW; ++j) {
const float d = v[j] - shift;
s1 += d;
s2 += d * d;
}
cnt += (float)CW;
}
for (int j = 0; j < CW; ++j) {
const float d = v[j] - shift;
s1 += d;
s2 += d * d;
}
cnt += (float)CW;
}
float mean = 0.0f, m2 = 0.0f;
if (cnt > 0.0f) {
const float q = s1 / cnt;
@@ -474,8 +479,8 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
for (int g = tid; g < groups; g += kT) {
float N = 0.0f, Mn = 0.0f, Q = 0.0f;
for (int s = 0; s < slots; ++s)
for (int k = 0; k < gs8; ++k) {
const int t = (s << cpr_log) + g * gs8 + k;
for (int k = 0; k < tpg; ++k) {
const int t = s * tpr + g * tpg + k;
chan_merge(N, Mn, Q, sh[0][t], sh[1][t], sh[2][t]);
}
float* o = stats + 2 * groups + ((size_t)g * kGnParts + p) * 3;
@@ -486,7 +491,7 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
}
__global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats, int groups,
int parts, float eps) {
int parts, float count, float eps) {
__shared__ float sh[3][kT];
const int g = blockIdx.x, tid = threadIdx.x;
const float* P = stats + 2 * groups + (size_t)g * kGnParts * 3;
@@ -507,24 +512,24 @@ __global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats,
__syncthreads();
}
if (tid == 0) {
const float var = sh[2][0] / sh[0][0];
const float var = sh[2][0] / count;
stats[2 * g] = sh[1][0];
stats[2 * g + 1] = 1.0f / sqrtf(var + eps);
}
}
/* `wf`, `bf`: the gain's and bias's dtype is f32; `modk` 0 no modulation, 1 a bf16 row, 2 an f32
* one. x and y may be the same memory: a thread reads its chunk before it writes it. */
* one. A thread is chunk `i % cpr` of row `i / cpr`, `gs8` chunks a group. x and y may be the same
* memory: a thread reads its chunk before it writes it. */
template <typename TX, typename TY, int CW>
__global__ __launch_bounds__(kT) void gn_apply_kernel(
const TX* x, TY* y, const void* __restrict__ w, const void* __restrict__ b,
const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr_log,
const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr,
int gs8, int ldx, int ldy, int wf, int bf, int modk, int silu) {
const int slots = kT >> cpr_log;
const int tid = threadIdx.x;
const int r = blockIdx.x * slots + (tid >> cpr_log);
const long long i = (long long)blockIdx.x * kT + threadIdx.x;
const int r = (int)(i / cpr);
if (r >= M) return;
const int ck = tid & ((1 << cpr_log) - 1), c = ck * CW;
const int ck = (int)(i - (long long)r * cpr), c = ck * CW;
const int g = ck / gs8;
const float mean = stats[2 * g], rstd = stats[2 * g + 1];
float v[CW], wv[CW], bv[CW];
@@ -741,12 +746,6 @@ int parse_f32_list(const char* s, float* out, int max) {
return n;
}
inline int log2_exact(long long v) {
int l = 0;
while ((1ll << l) < v) ++l;
return (1ll << l) == v ? l : -1;
}
} // namespace
// ============================================================== the plugin ABI entry points
@@ -833,14 +832,18 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
if (!std::strcmp(act, "silu")) silu = 1;
else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL);
}
/* A thread a chunk of CW channels inside one group (8; 4 for groups of 4 channels, the
* FLUX.2 VAE's 128 channels in 32 groups; 2 for groups of 2), a row's chunks a power of two
* dividing the 256-thread block. */
/* A chunk is CW channels inside one group: 8, 4 or 2, the widest dividing the group (the
* FLUX.2 VAE's 128 channels in 32 groups take 4, SDXL's 320 in 32 take 2). A row's chunks are
* split over at most 256 threads, each taking `cpt` consecutive chunks of one group, `cpt`
* the smallest divisor of the group's chunks that fits the row in the block. */
if (groups <= 0 || groups > kT || n <= 0 || n % groups || (n / groups) % 2)
return R4D_NO(RAD_E_SHAPE);
const int CW = (n / groups) % 8 == 0 ? 8 : (n / groups) % 4 == 0 ? 4 : 2;
const int cpr_log = log2_exact(n / CW);
if (cpr_log < 0 || n / CW > kT) return R4D_NO(RAD_E_SHAPE);
const long long cg = n / groups;
const int CW = cg % 8 == 0 ? 8 : cg % 4 == 0 ? 4 : 2;
const int cpr = (int)(n / CW), gs8 = (int)(cg / CW);
int cpt = 1;
while (cpr / cpt > kT || gs8 % cpt) ++cpt;
const int tpr = cpr / cpt, tpg = gs8 / cpt;
if (r4d_numel(w) < n || r4d_numel(b) < n || (mod && r4d_numel(mod) < 2 * n) ||
r4d_numel(st) < groups * (2 + 3 * kGnParts))
return R4D_NO(RAD_E_SHAPE);
@@ -849,22 +852,22 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
return R4D_NO(RAD_E_STRIDE);
long long rx = 0, ldx = 0, ry = 0, ldy = 0;
if (!rows8(x, n, &rx, &ldx) || !rows8(y, n, &ry, &ldy)) return R4D_NO(RAD_E_STRIDE);
/* Over y's rows, as libref's (x may hold more); M is not read. Counts are f32 sums: exact
* while a group's M n / groups values stay under 2^24. */
/* Over y's rows, as libref's (x may hold more); M is not read. A part's count is exact in f32
* (rpp cg <= 2^24); the merged counts only weigh the merges, and the variance divides by the
* group's exact count. */
const long long M = ry;
if (M <= 0 || M > rx || M > ry || M * (n / groups) >= (1ll << 24)) return R4D_NO(RAD_E_SHAPE);
const int slots = kT >> cpr_log;
if (M <= 0 || M > rx || M > ry || M * cg >= (1ll << 31)) return R4D_NO(RAD_E_SHAPE);
const int slots = kT / tpr;
/* Whole passes of the block a part, as few parts as fill the scratch. */
long long rpp = (M + kGnParts - 1) / kGnParts;
rpp = (rpp + slots - 1) / slots * slots;
const int parts = (int)((M + rpp - 1) / rpp);
const int gs8 = (int)(n / groups / CW);
float* S = (float*)r4d_wp(st);
const float eps = (float)r4d_getf(a, "eps", 1e-5);
int rc;
#define GN_P(TX, C4) \
rc = R4D_EMIT(stream, (gn_part_kernel<TX, C4>), dim3((unsigned)parts), dim3(kT), 0, \
(const TX*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, (int)rpp)
(const TX*)r4d_p(x), S, (int)M, (int)groups, tpr, cpt, tpg, (int)ldx, (int)rpp)
if (is_f32(x)) {
if (CW == 8) GN_P(float, 8);
else if (CW == 4) GN_P(float, 4);
@@ -877,14 +880,14 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
#undef GN_P
if (rc != RAD_OK) return R4D_NO(rc);
rc = R4D_EMIT(stream, gn_final_kernel, dim3((unsigned)groups), dim3(kT), 0, S, (int)groups,
parts, eps);
parts, (float)(M * cg), eps);
if (rc != RAD_OK) return R4D_NO(rc);
const int modk = !mod ? 0 : is_f32(mod) ? 2 : 1;
const dim3 grid((unsigned)((M + slots - 1) / slots));
const dim3 grid((unsigned)((M * cpr + kT - 1) / kT));
#define GN_A2(TX, TY, C4) \
return R4D_EMIT(stream, (gn_apply_kernel<TX, TY, C4>), grid, dim3(kT), 0, (const TX*)r4d_p(x),\
(TY*)r4d_wp(y), r4d_p(w), r4d_p(b), r4d_p(mod), (const float*)S, (int)M, \
(int)n, cpr_log, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \
(int)n, cpr, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \
modk, silu)
#define GN_A(TX, TY) \
do { if (CW == 8) GN_A2(TX, TY, 8); if (CW == 4) GN_A2(TX, TY, 4); GN_A2(TX, TY, 2); } while (0)
+284
View File
@@ -532,6 +532,221 @@ int ref_flow_x0_step(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ kd_input, kd_step */
/* A k-diffusion sampler over a discrete-time (VP-trained) denoiser, run in the variance-exploding
* form x = x0 + sigma eps: the lane holds x in f32, the model reads c_in x with
* c_in = 1 / sqrt(sigma^2 + 1), and a step turns the model's output into the clean estimate D and
* moves x along the schedule (docs/OPS.md, "Image generation"). Every product and sum is one f32
* rounding in the order written; libm's log, expm1 and sqrt. */
namespace {
enum { kSamplerEuler = 0, kSamplerEulerAncestral = 1, kSamplerDpmpp2m = 2 };
/* One entry's per-step constants, from its sigmas and guidance. */
struct KdEntry {
float s = 0, sn = 0, w = 0;
float cskip = 0, cout = 0; /* v-prediction's c_skip and c_out */
float sup = 0, sdown = 0; /* the ancestral step's split of sigma_next */
float ratio = 0, em = 0; /* DPM++ 2M: sigma_next / sigma, expm1(-h) */
float c1 = 0, c2 = 0; /* DPM++ 2M's second-order blend of D and the last D */
bool second = false;
};
KdEntry kd_entry(float s, float sn, float sp, float w, int64_t sampler, bool first) {
KdEntry k;
k.s = s;
k.sn = sn;
k.w = w;
const float s2p = s * s + 1.0f;
k.cskip = 1.0f / s2p;
k.cout = s / std::sqrt(s2p);
if (sampler == kSamplerEulerAncestral) {
const float s2 = s * s, sn2 = sn * sn;
const float up2 = sn2 * (s2 - sn2) / s2;
float sup = std::sqrt(up2);
if (!(sup < sn)) sup = sn;
const float dn2 = sn2 - sup * sup;
k.sup = sup;
k.sdown = std::sqrt(dn2 > 0.0f ? dn2 : 0.0f);
} else if (sampler == kSamplerDpmpp2m && sn > 0.0f) {
const float t = -std::log(s), tn = -std::log(sn);
const float h = tn - t;
k.ratio = sn / s;
k.em = std::expm1(-h);
if (!first) {
const float hl = t - (-std::log(sp));
const float r = hl / h;
k.c2 = 1.0f / (2.0f * r);
k.c1 = 1.0f + k.c2;
k.second = true;
}
}
return k;
}
/* The clean estimate from the model's output `o` at x. */
inline float kd_denoised(const KdEntry& k, bool v_pred, float x, float o) {
return v_pred ? x * k.cskip - o * k.cout : x - k.s * o;
}
/* x after the step, from x, the guided estimate D, the lane's last estimate and the noise. */
inline float kd_next(const KdEntry& k, int64_t sampler, float x, float D, float hist, float nz) {
if (sampler == kSamplerEuler) {
const float d = (x - D) / k.s;
return x + (k.sn - k.s) * d;
}
if (sampler == kSamplerEulerAncestral) {
const float d = (x - D) / k.s;
float xn = x + d * (k.sdown - k.s);
if (k.sn > 0.0f) xn = xn + nz * k.sup;
return xn;
}
if (k.sn == 0.0f) return D;
const float Dd = k.second ? k.c1 * D - k.c2 * hist : D;
return k.ratio * x - k.em * Dd;
}
inline uint64_t kd_seed(const RadTensor* seed, int64_t e) {
return (uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e)) |
((uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e + 1)) << 32);
}
} /* namespace */
/* The model's input for every entry that moves a lane (pair != -2): on a first step the lane
* becomes the seed's normal stream times sqrt(1 + sigma^2) (k-diffusion's start at the schedule's
* largest sigma), then y = rd(x / sqrt(sigma^2 + 1)) at the entry's rows and, when it is guided, at
* its pair's rows too (the negative entry reads the same latent). */
int ref_kd_input(const RadArgs* a, RadStream) {
if (!have(a, 8)) return RAD_E_INVAL;
const RadTensor *sg = &a->t[0], *pair = &a->t[1], *lane = &a->t[2], *fl = &a->t[3];
const RadTensor *seed = &a->t[4], *cu = &a->t[5], *st = &a->t[6], *y = &a->t[7];
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), y_rows = rows_of(y, n);
if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
if (numel(sg) < n_seq || numel(pair) < n_seq || numel(lane) < n_seq || numel(fl) < n_seq ||
numel(seed) < 2 * n_seq)
return RAD_E_SHAPE;
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e));
if (pr == -2) continue;
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > y_rows)
return RAD_E_SHAPE;
if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len ||
cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > y_rows)))
return RAD_E_SHAPE;
if (ld_int(fl->dtype, fl->data, offlin(fl, e)) & kInpaint) return RAD_E_UNSUPPORTED;
}
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e));
if (pr == -2) continue;
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0;
const float s = ldt(sg, offlin(sg, e));
const float init = std::sqrt(1.0f + s * s), cin = 1.0f / std::sqrt(s * s + 1.0f);
const bool first = (ld_int(fl->dtype, fl->data, offlin(fl, e)) & kFirst) != 0;
const uint64_t sd = kd_seed(seed, e);
REF_PAR_FOR(len * n * 8)
for (int64_t k = 0; k < len; ++k) {
const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st);
const int64_t yb = rowoff(y, b0 + k, n), ys = laststride(y);
const int64_t pb = pr >= 0 ? rowoff(y, p0 + k, n) : 0;
for (int64_t c = 0; c < n; ++c) {
if (first) stt(st, sb + c * ss, rad_philox_normal(sd, (uint64_t)(k * n + c)) * init);
const float v = ldt(st, sb + c * ss) * cin;
stt(y, yb + c * ys, v);
if (pr >= 0) stt(y, pb + c * ys, v);
}
}
}
return RAD_OK;
}
/* One sampler step for every entry that moves a lane (pair != -2), x the lane's f32 state:
*
* D = eps: x - sigma o v: x / (sigma^2 + 1) - o sigma / sqrt(sigma^2 + 1)
* D = pair >= 0 ? D(o_u) + cfg (D(o_c) - D(o_u)) : D(o_c)
*
* then by the entry's sampler: 0 Euler, x + (sigma_next - sigma)(x - D) / sigma; 1 Euler ancestral
* (eta 1): the step to sigma_down plus sigma_up times the seed's stream 1 + step; 2 DPM++ 2M:
* (sigma_next / sigma) x - expm1(-h) D', D' blending D with the lane's last estimate after the first
* step, and D itself at sigma_next 0. Flag 4 writes D to the preview; every step leaves D in
* `hist` for the next. */
int ref_kd_step(const RadArgs* a, RadStream) {
if (!have(a, 14)) return RAD_E_INVAL;
const RadTensor *O = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *sgp = &a->t[3];
const RadTensor *cfg = &a->t[4], *pair = &a->t[5], *lane = &a->t[6], *fl = &a->t[7];
const RadTensor *seed = &a->t[8], *smp = &a->t[9], *stp = &a->t[10], *cu = &a->t[11];
const RadTensor *st = &a->t[12], *hs = &a->t[13], *pv = t_in(a, 14);
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
const char* pred = p_str(a, "pred", "eps");
const bool v_pred = pred && !std::strcmp(pred, "v");
if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return RAD_E_INVAL;
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), o_rows = rows_of(O, n);
if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
for (const RadTensor* t : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp })
if (numel(t) < n_seq) return RAD_E_SHAPE;
if (numel(seed) < 2 * n_seq || rows_of(hs, n) < st_rows || (pv && rows_of(pv, n) < st_rows))
return RAD_E_SHAPE;
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e));
if (pr == -2) continue;
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > o_rows)
return RAD_E_SHAPE;
if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len ||
cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > o_rows)))
return RAD_E_SHAPE;
const int64_t f = ld_int(fl->dtype, fl->data, offlin(fl, e));
const int64_t sm = ld_int(smp->dtype, smp->data, offlin(smp, e));
if ((f & kInpaint) || sm < kSamplerEuler || sm > kSamplerDpmpp2m) return RAD_E_UNSUPPORTED;
if ((f & kPreview) && !pv) return RAD_E_INVAL;
}
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e));
if (pr == -2) continue;
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0;
const int64_t f = ld_int(fl->dtype, fl->data, offlin(fl, e));
const int64_t sm = ld_int(smp->dtype, smp->data, offlin(smp, e));
const uint64_t stream = (uint64_t)(uint32_t)(1 + ld_int(stp->dtype, stp->data, offlin(stp, e)));
const KdEntry K = kd_entry(ldt(sg, offlin(sg, e)), ldt(sgn, offlin(sgn, e)),
ldt(sgp, offlin(sgp, e)), ldt(cfg, offlin(cfg, e)), sm,
(f & kFirst) != 0);
const uint64_t sd = kd_seed(seed, e);
REF_PAR_FOR(len * n * 8)
for (int64_t k = 0; k < len; ++k) {
const int64_t ob = rowoff(O, b0 + k, n), os = laststride(O);
const int64_t ub = pr >= 0 ? rowoff(O, p0 + k, n) : 0;
const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st);
const int64_t hb = rowoff(hs, L * stride + k, n), hss = laststride(hs);
for (int64_t c = 0; c < n; ++c) {
const float x = ldt(st, sb + c * ss);
float D = kd_denoised(K, v_pred, x, ldt(O, ob + c * os));
if (pr >= 0) {
const float Du = kd_denoised(K, v_pred, x, ldt(O, ub + c * os));
D = Du + K.w * (D - Du);
}
if (f & kPreview)
stt(pv, rowoff(pv, L * stride + k, n) + c * laststride(pv), D);
const float nz = sm == kSamplerEulerAncestral && K.sn > 0.0f
? rad_philox_normal_s(sd, stream, (uint64_t)(k * n + c)) : 0.0f;
stt(st, sb + c * ss, kd_next(K, sm, x, D, ldt(hs, hb + c * hss), nz));
stt(hs, hb + c * hss, D);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ chan_affine */
/* A per-channel affine from two parameter lists (a latent's mean and deviation are configuration,
* not weights), each value rounded to bf16 as upstream holds it: mode `fma` is
@@ -621,6 +836,50 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ im2col_nhwc */
/* conv2d_nhwc's receptive fields as rows, so a convolution is a GEMM against its own weight read as
* [cout, cin k k]: x is [Hin, Win * cin] (rows at their own pitch), y [Ho * Wo, cin * k * k], and
* row oy * Wo + ox, column (ci k + i) k + j holds the value conv2d_nhwc multiplies weight
* [o, ci, i, j] by -- x at the tap's position read through `up` and `pad` as conv2d_nhwc reads it,
* 0 in the padding. The output size follows from x's; y must have exactly Ho * Wo rows. A copy:
* the values are stored as they are (rounded only when y is narrower than x). */
int ref_im2col_nhwc(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t cin = p_int(a, "cin", 0), k = p_int(a, "k", 0);
const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1);
const char* pad = p_str(a, "pad", "same");
const bool down = pad && !std::strcmp(pad, "down");
const bool causal = pad && !std::strcmp(pad, "causal");
if (cin <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE;
if (x->rank != 2 || x->shape[1] % cin) return RAD_E_SHAPE;
const int64_t Hin = x->shape[0], Win = x->shape[1] / cin, kk = cin * k * k;
if (Hin <= 0 || Win <= 0) return RAD_E_SHAPE;
const int64_t Hv = Hin * up, Wv = Win * up;
const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
const int64_t Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1;
if (Ho <= 0 || Wo <= 0 || rows_of(y, kk) != Ho * Wo) return RAD_E_SHAPE;
const int64_t xr = x->stride[0], xs = laststride(x), ys = laststride(y);
REF_PAR_FOR(Ho * Wo * kk)
for (int64_t oy = 0; oy < Ho; ++oy)
for (int64_t ox = 0; ox < Wo; ++ox) {
const int64_t yb = rowoff(y, oy * Wo + ox, kk);
for (int64_t ci = 0; ci < cin; ++ci)
for (int64_t i = 0; i < k; ++i) {
const int64_t iy = oy * stride + i - pt;
for (int64_t j = 0; j < k; ++j) {
const int64_t ix = ox * stride + j - pl;
const bool in = iy >= 0 && iy < Hv && ix >= 0 && ix < Wv;
const float v = in ? ldt(x, (iy / up) * xr + ((ix / up) * cin + ci) * xs)
: 0.0f;
stt(y, yb + ((ci * k + i) * k + j) * ys, v);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ l2norm_chan */
/* An image norm over each pixel's channels, as upstream's three bf16 tensors:
* n1 = bf16(x / max(||x||, 1e-12)), n2 = bf16(n1 * sqrt(n)), y = bf16(n2 * gamma), then `act`
@@ -761,6 +1020,31 @@ int ref_gelu_tanh(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu_quick */
/* CLIP's quick_gelu as torch evaluates it in a reduced dtype, three stored tensors:
* a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s). */
int ref_gelu_quick(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE;
const uint32_t dt = y->dtype;
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
for (int64_t c = 0; c < n; ++c) {
const float v = ldt(x, xb + c * xs);
const float t = round_dt(dt, 1.702f * v);
const float s = round_dt(dt, 1.0f / (1.0f + std::exp(-t)));
stt(y, yb + c * ys, v * s);
}
}
return RAD_OK;
}
/* x[idx[i]] = x[idx[i]] + v[i], rounded to x's dtype; a negative index is a skip. */
int ref_scatter_add_rows(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
+13 -5
View File
@@ -101,8 +101,8 @@ int ref_lora_shrink(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* operands: t, slot, lora_b, scale, y (inout) */
int ref_lora_expand(const RadArgs* a, RadStream) {
/* operands: t, slot, lora_b, scale, y (inout). `bf16_t`: lora_expand_mm, t rounded to bf16. */
static int lora_expand_impl(const RadArgs* a, bool bf16_t) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *T = &a->t[0], *SL = &a->t[1], *LB = &a->t[2], *SC = &a->t[3], *Y = &a->t[4];
const int64_t N = p_int(a, "N", 0), R = p_int(a, "R", 0), S = p_int(a, "S", 0);
@@ -127,9 +127,11 @@ int ref_lora_expand(const RadArgs* a, RadStream) {
if (s < 0) continue; /* a base row: not read, not written */
const int64_t t0 = m * mt.rs, b0 = s * pb.s0 + n * pb.s1;
float acc = 0.0f;
for (int64_t j = 0; j < R; ++j)
acc += ((const float*)T->data)[t0 + j * mt.cs] *
ld_dt(LB->dtype, LB->data, b0 + j * pb.s2);
for (int64_t j = 0; j < R; ++j) {
float tv = ((const float*)T->data)[t0 + j * mt.cs];
if (bf16_t) tv = rad_bf16_to_f32(rad_f32_to_bf16(tv));
acc += tv * ld_dt(LB->dtype, LB->data, b0 + j * pb.s2);
}
const float sc = ((const float*)SC->data)[s * sc_r + n * sc_c];
const int64_t o = m * ys_r + n * ys_c;
/* `sc * acc` and then the add, each rounded: the order is the definition. */
@@ -138,3 +140,9 @@ int ref_lora_expand(const RadArgs* a, RadStream) {
}
return RAD_OK;
}
int ref_lora_expand(const RadArgs* a, RadStream) { return lora_expand_impl(a, false); }
/* lora_expand with t rounded to bf16; the order of the sum is free, so j ascending is one of the
* answers it allows. */
int ref_lora_expand_mm(const RadArgs* a, RadStream) { return lora_expand_impl(a, true); }
+10
View File
@@ -137,6 +137,7 @@ int ref_gemm_nt_q_bias (const RadArgs*, RadStream);
/* Runtime LoRA's two halves, per-row adapter slot (ref_lora.cpp). */
int ref_lora_shrink (const RadArgs*, RadStream);
int ref_lora_expand (const RadArgs*, RadStream);
int ref_lora_expand_mm (const RadArgs*, RadStream);
int ref_embed_lookup (const RadArgs*, RadStream);
int ref_embed_lookup_q (const RadArgs*, RadStream);
int ref_logits_gemm (const RadArgs*, RadStream);
@@ -162,6 +163,8 @@ int ref_lane_gather(const RadArgs*, RadStream);
int ref_lane_store(const RadArgs*, RadStream);
int ref_randn_lanes(const RadArgs*, RadStream);
int ref_flow_euler(const RadArgs*, RadStream);
int ref_kd_input(const RadArgs*, RadStream);
int ref_kd_step(const RadArgs*, RadStream);
int ref_rms_mod(const RadArgs*, RadStream);
int ref_rms_mod_quant_fp8(const RadArgs*, RadStream);
int ref_flow_x0_step(const RadArgs*, RadStream);
@@ -219,11 +222,13 @@ int ref_cu_repeat(const RadArgs*, RadStream);
int ref_int_affine(const RadArgs*, RadStream);
int ref_chan_affine(const RadArgs*, RadStream);
int ref_conv2d_nhwc(const RadArgs*, RadStream);
int ref_im2col_nhwc(const RadArgs*, RadStream);
int ref_l2norm_chan(const RadArgs*, RadStream);
int ref_d2s_add(const RadArgs*, RadStream);
int ref_s2d_avg_add(const RadArgs*, RadStream);
int ref_to_rgba8(const RadArgs*, RadStream);
int ref_gelu_tanh(const RadArgs*, RadStream);
int ref_gelu_quick(const RadArgs*, RadStream);
int ref_scatter_add_rows(const RadArgs*, RadStream);
int ref_attn_prefix_self(const RadArgs*, RadStream);
int ref_qsa_block_key (const RadArgs*, RadStream);
@@ -379,6 +384,7 @@ REF_SHAPE_FN(ref_gemm_nt_q);
REF_SHAPE_FN(ref_gemm_nt_q_bias);
REF_SHAPE_FN(ref_lora_shrink);
REF_SHAPE_FN(ref_lora_expand);
REF_SHAPE_FN(ref_lora_expand_mm);
REF_SHAPE_FN(ref_embed_lookup);
REF_SHAPE_FN(ref_embed_lookup_q);
REF_SHAPE_FN(ref_logits_gemm);
@@ -402,6 +408,8 @@ REF_SHAPE_FN(ref_lane_gather);
REF_SHAPE_FN(ref_lane_store);
REF_SHAPE_FN(ref_randn_lanes);
REF_SHAPE_FN(ref_flow_euler);
REF_SHAPE_FN(ref_kd_input);
REF_SHAPE_FN(ref_kd_step);
REF_SHAPE_FN(ref_rms_mod);
REF_SHAPE_FN(ref_rms_mod_quant_fp8);
REF_SHAPE_FN(ref_flow_x0_step);
@@ -453,11 +461,13 @@ REF_SHAPE_FN(ref_cu_repeat);
REF_SHAPE_FN(ref_int_affine);
REF_SHAPE_FN(ref_chan_affine);
REF_SHAPE_FN(ref_conv2d_nhwc);
REF_SHAPE_FN(ref_im2col_nhwc);
REF_SHAPE_FN(ref_l2norm_chan);
REF_SHAPE_FN(ref_d2s_add);
REF_SHAPE_FN(ref_s2d_avg_add);
REF_SHAPE_FN(ref_to_rgba8);
REF_SHAPE_FN(ref_gelu_tanh);
REF_SHAPE_FN(ref_gelu_quick);
REF_SHAPE_FN(ref_scatter_add_rows);
REF_SHAPE_FN(ref_attn_prefix_self);
REF_SHAPE_FN(ref_qsa_block_key);
+44
View File
@@ -741,12 +741,25 @@ static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma
OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"),
OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"),
INOUT("state"), INOUT_O("preview") };
/* The k-diffusion sampler's input and step: `pred` "eps" or "v", the lanes f32. */
static const RadParamSpec pKdStep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("pred"),
P_STR("dtype") };
static const RadOperandSpec oKdInput[] = { OPD("sigma"), OPD("pair"), OPD("lane"), OPD("flags"),
OPD("seed"), OPD("cu_seqlens"), INOUT("state"),
OUT("y") };
static const RadOperandSpec oKdStep[] = { OPD("out"), OPD("sigma"), OPD("sigma_next"),
OPD("sigma_prev"), OPD("cfg"), OPD("pair"), OPD("lane"),
OPD("flags"), OPD("seed"), OPD("sampler"), OPD("step"),
OPD("cu_seqlens"), INOUT("state"), INOUT("hist"),
INOUT_O("preview") };
/* `round` 0 keeps the lists and the arithmetic in f32 (default 1, bf16 lists and roundings). */
static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"),
P_STR("mode"), P_STR("dtype"), P_INTO("round") };
static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") };
static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") };
static const RadParamSpec pIm2col[] = { P_INT("M"), P_INT("cin"), P_INT("k"), P_INT("stride"),
P_STR("pad"), P_INT("up"), P_STR("dtype") };
static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
static const RadOperandSpec oL2Norm[] = { OPD("x"), WGT("gamma"), OUT("y") };
static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"),
@@ -1265,6 +1278,11 @@ static const RadOpSchema kSchemas[] = {
"slot[m] is in [0, S), f32 accumulate, j ascending, one rounding to y's dtype. A base row's `y` "
"is neither read nor written, so it stays bit for bit what the GEMM wrote (not y + 0: that "
"turns -0 into +0)." },
{ "lora_expand_mm", ARR(pLoraExpand), ARR(oLoraExpand),
"lora_expand with t rounded to bf16 and the sum over j in any order: y[m, n] = y[m, n] + "
"scale[s, n] * sum_j bf16(t[m, j]) * lora_b[s, n, j], f32 accumulate, one rounding to y's dtype. "
"A base row's `y` is neither read nor written. A row's bytes may depend on M: the generators' "
"expand, whose passes are many rows of one adapter." },
{ "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged),
"Paged attention over kv_cache[num_blocks, kv_heads, block_size, 2*head_dim] (K then V per "
@@ -1550,6 +1568,15 @@ static const RadOpSchema kSchemas[] = {
"one Euler step of a flow-matching sampler per entry that moves a lane: guidance against the "
"paired entry, x' = bf16(x + bf16(bf16(sigma_next - sigma) * v)), a preview of the clean "
"latent with flag 4, the kept region of a repaint restored with flag 2 (docs/OPS.md)." },
{ "kd_input", ARR(pLane), ARR(oKdInput),
"a k-diffusion sampler's model input per entry that moves a lane: on a first step the lane "
"becomes its seed's normal stream times sqrt(1 + sigma^2); y = rd(x / sqrt(sigma^2 + 1)) at the "
"entry's rows and at its pair's (docs/OPS.md)." },
{ "kd_step", ARR(pKdStep), ARR(oKdStep),
"one k-diffusion sampler step over a discrete-time denoiser per entry that moves a lane: the "
"clean estimate D from an eps or v output, guided against the pair, then Euler, Euler ancestral "
"or DPM++ 2M by the entry's sampler, the lane f32; flag 4 previews D, `hist` keeps it "
"(docs/OPS.md)." },
{ "chan_affine", ARR(pChanAffine), ARR(oUnary),
"a per-channel affine from two parameter lists of n values (rounded to bf16): `fma` is "
"bf16(bf16(x * mul) + add), `inv` bf16(bf16(x - add) / mul). `round` 0 keeps the lists and "
@@ -1559,6 +1586,11 @@ static const RadOpSchema kSchemas[] = {
"the sizes read off them; PyTorch's [cout, cin, k, k] weight and a bias; `up` 2 reads the input "
"upsampled nearest-neighbour; `pad` same (k/2 a side) or down (0 above and left, 1 below and "
"right)." },
{ "im2col_nhwc", ARR(pIm2col), ARR(oUnary),
"conv2d_nhwc's receptive fields as rows: x [Hin, Win * cin], y [Hout * Wout, cin * k * k], row "
"oy * Wout + ox and column (ci * k + i) * k + j the value conv2d_nhwc multiplies weight[o, ci, "
"i, j] by (0 in the padding), so y @ w.reshape(cout, cin * k * k)^T + b is the convolution; "
"`up`, `pad` and `stride` as conv2d_nhwc reads them." },
{ "l2norm_chan", ARR(pL2Norm), ARR(oL2Norm),
"each row normalised to unit L2 (eps 1e-12), times sqrt(n), times gamma -- three bf16 roundings "
"-- then `act` none or silu: an image decoder's channel norm." },
@@ -1572,6 +1604,8 @@ static const RadOpSchema kSchemas[] = {
"decoded pixels in [-1, 1] to bytes as diffusers' postprocess makes them: "
"round(clamp(bf16(bf16(clamp(x) / 2) + 0.5), 0, 1) * 255), u8 out." },
{ "gelu_tanh", ARR(pMnD), ARR(oUnary), "the tanh approximation of gelu." },
{ "gelu_quick", ARR(pMnD), ARR(oUnary),
"CLIP's quick_gelu, three roundings: a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s)." },
{ "scatter_add_rows", ARR(pMnD), ARR(oScatterRows),
"x[idx[i]] += v[i], rounded to x's dtype; a negative index adds nothing." },
{ "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS),
@@ -2072,6 +2106,9 @@ SIMPLE("ref_lora_shrink", "lora_shrink", "gemm", "t = x A[slot]^T per row, base
SIMPLE("ref_lora_expand", "lora_expand", "gemm",
"y += scale * (t B[slot]^T) per row, base rows untouched",
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", ref_lora_expand),
SIMPLE("ref_lora_expand_mm", "lora_expand_mm", "gemm",
"y += scale * (bf16(t) B[slot]^T) per row, base rows untouched",
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", ref_lora_expand_mm),
ROW("ref_attn_paged", "attn_paged", "attn",
"paged causal / sliding-window attention, any query length",
@@ -2209,10 +2246,16 @@ SIMPLE("ref_randn_lanes", "randn_lanes", "elem", "a lane's rows from its seed's
DT_FLOAT, ref_randn_lanes),
SIMPLE("ref_flow_euler", "flow_euler", "elem", "a flow-matching Euler step with guidance",
DT_FLOAT, ref_flow_euler),
SIMPLE("ref_kd_input", "kd_input", "elem", "a k-diffusion sampler's model input", DT_FLOAT,
ref_kd_input),
SIMPLE("ref_kd_step", "kd_step", "elem", "a k-diffusion sampler step with guidance", DT_FLOAT,
ref_kd_step),
SIMPLE("ref_chan_affine", "chan_affine", "elem", "a per-channel affine from parameter lists",
DT_FLOAT, ref_chan_affine),
SIMPLE("ref_conv2d_nhwc", "conv2d_nhwc", "elem", "an image convolution, channels innermost",
DT_FLOAT, ref_conv2d_nhwc),
SIMPLE("ref_im2col_nhwc", "im2col_nhwc", "elem", "a convolution's receptive fields as rows",
DT_FLOAT, ref_im2col_nhwc),
SIMPLE("ref_l2norm_chan", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu",
DT_FLOAT, ref_l2norm_chan),
SIMPLE("ref_d2s_add", "d2s_add", "elem", "an upsampling shortcut added in", DT_FLOAT,
@@ -2221,6 +2264,7 @@ SIMPLE("ref_s2d_avg_add", "s2d_avg_add", "elem", "a downsampling shortcut added
ref_s2d_avg_add),
SIMPLE("ref_to_rgba8", "to_rgba8", "elem", "decoded pixels to bytes", DT_FLOAT, ref_to_rgba8),
SIMPLE("ref_gelu_tanh", "gelu_tanh", "elem", "tanh gelu", DT_FLOAT, ref_gelu_tanh),
SIMPLE("ref_gelu_quick", "gelu_quick", "elem", "quick gelu", DT_FLOAT, ref_gelu_quick),
SIMPLE("ref_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", DT_FLOAT,
ref_scatter_add_rows),
SIMPLE("ref_attn_prefix_self", "attn_prefix_self", "attn",
+80
View File
@@ -1254,6 +1254,10 @@ int ref_lora_expand_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o
return o.finish("lora_expand", operand, out);
}
int ref_lora_expand_mm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return ref_lora_expand_shape(p, n_p, operand, out);
}
/* ================================================================== attention
*
* The paged layout (ref_ops.h):
@@ -2602,6 +2606,53 @@ int ref_flow_euler_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("flow_euler", operand, out);
}
/* The k-diffusion sampler's two ops over flow_euler's entries: two equal-length entries where M
* allows, the lanes f32, sigmas drawn in (0, 1) so every logarithm and root is of a positive
* value. Flags draw only the first step (bit 1): the preview needs its optional operand and
* neither op repaints; the hand-written cases take the rest. */
int ref_kd_input_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), st = gi(p, n_p, "stride", 0);
if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED;
const int64_t S = (M % 2 == 0 && M / 2 <= st) ? 2 : 1;
if (M > S * st) return RAD_E_UNSUPPORTED;
const uint32_t F = (uint32_t)RAD_F32;
Opd o;
o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */
o.t_idx({ S }, S, -1, 0); /* pair */
o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
o.t_idx({ S }, 2, -1, 0); /* flags */
o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(F, { REF_LANES * st, n }); /* state, INOUT */
o.t(act_dt(p, n_p), { M, n }); /* y */
return o.finish("kd_input", operand, out);
}
int ref_kd_step_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), st = gi(p, n_p, "stride", 0);
if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED;
const int64_t S = (M % 2 == 0 && M / 2 <= st) ? 2 : 1;
if (M > S * st) return RAD_E_UNSUPPORTED;
const uint32_t F = (uint32_t)RAD_F32;
Opd o;
o.t(act_dt(p, n_p), { M, n }); /* out */
o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */
o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma_next */
o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma_prev */
o.t(F, { S }); /* cfg */
o.t_idx({ S }, S, -1, 0); /* pair */
o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
o.t_idx({ S }, 2, -1, 0); /* flags */
o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed */
o.t_idx({ S }, 3, -1, 0); /* sampler */
o.t_idx({ S }, 64, -1, 0); /* step */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(F, { REF_LANES * st, n }); /* state, INOUT */
o.t(F, { REF_LANES * st, n }); /* hist, INOUT */
o.t(F, { REF_LANES * st, n }); /* preview, INOUT */
return o.finish("kd_step", operand, out);
}
/* ---- an image decoder's convolutions and shortcuts. Sizes are read off the operands and M counts
* output pixels, so this picks eight columns where M allows (a row with both edges and an interior)
* and the input that produces that output; otherwise it declines. */
@@ -2636,6 +2687,27 @@ int ref_conv2d_nhwc_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o
return o.finish("conv2d_nhwc", operand, out);
}
/* conv2d_nhwc's geometry with the receptive fields as y's rows: M output pixels of cin k k values. */
int ref_im2col_nhwc_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), k = gi(p, n_p, "k", 0);
const int64_t stride = gi(p, n_p, "stride", 1), up = gi(p, n_p, "up", 1);
const char* pad = gs(p, n_p, "pad");
if (M <= 0 || cin <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_UNSUPPORTED;
const bool down = pad && !std::strcmp(pad, "down");
const int64_t pads = down ? 1 : 2 * (k / 2);
const int64_t Wo = cols_for(M, 1), Ho = Wo ? M / Wo : 0;
if (!Wo) return RAD_E_UNSUPPORTED;
const int64_t Hv = (Ho - 1) * stride + k - pads, Wv = (Wo - 1) * stride + k - pads;
if (Hv <= 0 || Wv <= 0 || Hv % up || Wv % up) return RAD_E_UNSUPPORTED;
if ((Hv + pads - k) / stride + 1 != Ho || (Wv + pads - k) / stride + 1 != Wo)
return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { Hv / up, (Wv / up) * cin }); /* x */
o.t(D, { Ho * Wo, cin * k * k }); /* y */
return o.finish("im2col_nhwc", operand, out);
}
int ref_d2s_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0);
if (M <= 0 || cin <= 0 || cout <= 0) return RAD_E_UNSUPPORTED;
@@ -2745,6 +2817,14 @@ int ref_gelu_tanh_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
o.t(D, { M, n });
return o.finish("gelu_tanh", operand, out);
}
int ref_gelu_quick_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M, n });
o.t(D, { M, n });
return o.finish("gelu_quick", operand, out);
}
int ref_scatter_add_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
+1
View File
@@ -23,6 +23,7 @@ and `agentreplay.py` need `python3`. Scripts find each other through `$(dirname
| `convdspark.sh` | Rebuilds the container `mcserve.sh` serves, with the drafter merged, as `minicpm5-2b-dspark.new.rad` beside it. The checkpoint and drafter paths are fixed; `RECIPE=` overrides the recipe. |
| `convfn.sh` | Rebuilds the container `fnserve.sh` serves, as `w4nl64-i8lm.new.rad` beside it, from `data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`. Needs `CALIB=<dir>`: the recipe's expert rule runs GPTQ against the calibration Grams there (`docs/MOE-W4.md`). |
| `hfget.sh` | Fetches a Hugging Face repo with `curl` and `jq`. Resumable, and skips the duplicate weight formats a repo often carries beside its safetensors. `radiance --model <repo id>` runs it. |
| `krea2_native.py` | Rewrites a Krea 2 DiT single file in Krea's own key names (`turbo.safetensors`, civitai and ComfyUI finetunes) as diffusers' transformer file, bytes unchanged, so it converts as the `transformer/` of a Krea 2 pipeline directory (`docs/GUIDE.md`). |
## Measuring
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
# krea2_native.py -- a Krea 2 DiT single file in the reference code's key names, as diffusers'
# Krea2Transformer2DModel file, so rad-convert reads it as the transformer/ of a pipeline directory.
#
# krea2_native.py <single file> <pipeline>/transformer/diffusion_pytorch_model.safetensors
#
# Krea's own turbo.safetensors / raw.safetensors, and the finetunes civitai and ComfyUI ship, name
# the DiT by krea-ai/krea-2 mmdit.py (`blocks.N.attn.wq`, `txtfusion.refiner_blocks.N.mlp.up`,
# `tproj.1`) and carry no text encoder or VAE. Each tensor maps to one diffusers tensor, the same
# bytes under a new name; the blocks' modulation tables are flat ([6 * D]) where diffusers stores
# them [6, D], so only their shape is restated. Checked against krea/Krea-2-Turbo, whose turbo.safetensors
# and diffusers shards hold byte-identical tensors under this map (norms, tables, embedders, linears).
#
# The rest of the pipeline directory (model_index.json, scheduler/, text_encoder/, tokenizer/, vae/,
# transformer/config.json) is the release's: Raw and Turbo ship identical parts but for
# model_index.json, whose `is_distilled` selects Turbo's sampling (8 steps, no guidance). A finetune
# stored as plain fp8 converts with data/recipes/krea-2-fp8-unscaled.recipe.
#
# Needs only python3; the data is copied, never decoded.
import json
import os
import re
import shutil
import struct
import sys
RULES = [
(r"^blocks\.(\d+)\.", r"transformer_blocks.\1."),
(r"^txtfusion\.", r"text_fusion."),
(r"\.attn\.wq\.", ".attn.to_q."), (r"\.attn\.wk\.", ".attn.to_k."), (r"\.attn\.wv\.", ".attn.to_v."),
(r"\.attn\.wo\.", ".attn.to_out.0."), (r"\.attn\.gate\.", ".attn.to_gate."),
(r"\.attn\.qknorm\.qnorm\.scale$", ".attn.norm_q.weight"),
(r"\.attn\.qknorm\.knorm\.scale$", ".attn.norm_k.weight"),
(r"\.mlp\.(gate|up|down)\.", r".ff.\1."),
(r"\.prenorm\.scale$", ".norm1.weight"), (r"\.postnorm\.scale$", ".norm2.weight"),
(r"\.mod\.lin$", ".scale_shift_table"),
(r"^first\.", "img_in."),
(r"^last\.linear\.", "final_layer.linear."), (r"^last\.norm\.scale$", "final_layer.norm.weight"),
(r"^last\.modulation\.lin$", "final_layer.scale_shift_table"),
(r"^tmlp\.0\.", "time_embed.linear_1."), (r"^tmlp\.2\.", "time_embed.linear_2."),
(r"^tproj\.1\.", "time_mod_proj."),
(r"^txtmlp\.0\.scale$", "txt_in.norm.weight"),
(r"^txtmlp\.1\.", "txt_in.linear_1."), (r"^txtmlp\.3\.", "txt_in.linear_2."),
]
def to_diffusers(k):
for a, b in RULES:
k = re.sub(a, b, k)
return k
def main():
if len(sys.argv) != 3:
sys.exit("usage: krea2_native.py <single file> <out .safetensors>")
src, dst = sys.argv[1], sys.argv[2]
with open(src, "rb") as f:
n = struct.unpack("<Q", f.read(8))[0]
h = json.loads(f.read(n))
meta = h.pop("__metadata__", None)
out = {}
for k, v in h.items():
dk = to_diffusers(k)
if dk == k or dk in out:
sys.exit(f"krea2_native.py: '{k}' is not a Krea 2 DiT tensor this map knows")
v = dict(v)
if dk.endswith(".scale_shift_table") and len(v["shape"]) == 1:
if v["shape"][0] % 6:
sys.exit(f"krea2_native.py: '{k}' is {v['shape']}, not six rows of the width")
v["shape"] = [6, v["shape"][0] // 6]
out[dk] = v
if meta:
out["__metadata__"] = meta
hb = json.dumps(out, separators=(",", ":")).encode()
hb += b" " * (-len(hb) % 8)
with open(src, "rb") as f, open(dst + ".tmp", "wb") as g:
g.write(struct.pack("<Q", len(hb)))
g.write(hb)
f.seek(8 + n)
shutil.copyfileobj(f, g, 64 << 20)
os.replace(dst + ".tmp", dst)
print(f"{len(h)} tensors -> {dst}")
if __name__ == "__main__":
main()
+25
View File
@@ -362,6 +362,16 @@ ABI_FIELD(RadGenBatch, mode_src)
ABI_FIELD(RadGenBatch, mode_ccu)
ABI_FIELD(RadGenBatch, n_mode_h)
ABI_FIELD(RadGenBatch, mode_rope_f)
ABI_FIELD(RadGenBatch, n_aux)
ABI_FIELD(RadGenBatch, aux_ids)
ABI_FIELD(RadGenBatch, aux_cu)
ABI_FIELD(RadGenBatch, sigma_prev)
ABI_FIELD(RadGenBatch, timestep)
ABI_FIELD(RadGenBatch, sampler)
ABI_FIELD(RadGenBatch, step)
ABI_FIELD(RadGenBatch, size_px)
ABI_FIELD(RadGenBatch, entry_h)
ABI_FIELD(RadGenBatch, tokens_h)
ABI_STRUCT(RadGeneratorDecl)
ABI_FIELD(RadGeneratorDecl, name)
ABI_FIELD(RadGeneratorDecl, layout)
@@ -403,6 +413,21 @@ ABI_FIELD(RadGeneratorDecl, pad_token)
ABI_FIELD(RadGeneratorDecl, cfg_original)
ABI_FIELD(RadGeneratorDecl, default_negative)
ABI_FIELD(RadGeneratorDecl, ref_shrink_only)
ABI_FIELD(RadGeneratorDecl, aux_max_tokens)
ABI_FIELD(RadGeneratorDecl, sigma_grid)
ABI_FIELD(RadGeneratorDecl, min_tokens)
ABI_FIELD(RadGeneratorDecl, aux_tokens)
ABI_FIELD(RadGeneratorDecl, beta_start)
ABI_FIELD(RadGeneratorDecl, beta_end)
ABI_FIELD(RadGeneratorDecl, train_steps)
ABI_FIELD(RadGeneratorDecl, beta_schedule)
ABI_FIELD(RadGeneratorDecl, zero_snr)
ABI_FIELD(RadGeneratorDecl, samplers)
ABI_FIELD(RadGeneratorDecl, default_sampler)
ABI_FIELD(RadGeneratorDecl, default_scheduler)
ABI_FIELD(RadGeneratorDecl, chunk_tokens)
ABI_FIELD(RadGeneratorDecl, chunk_bos)
ABI_FIELD(RadGeneratorDecl, chunk_eos)
ABI_STRUCT(RadKVGroupBatch)
ABI_FIELD(RadKVGroupBatch, group)
ABI_FIELD(RadKVGroupBatch, slot_mapping)
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more