diff --git a/CMakeLists.txt b/CMakeLists.txt index a6fbedcf..01b4b9fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is the server release that /version reports. The plugin ABI version is separate and is # read from abi/rad_abi.h below. -project(radiance VERSION 1.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) diff --git a/README.md b/README.md index d1546995..3b980f2a 100644 --- a/README.md +++ b/README.md @@ -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 ...`. diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 292e14b4..7353a917 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -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: diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 5b1713c5..3e33597d 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -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 diff --git a/abi/rad_format.h b/abi/rad_format.h index 73a40f99..625241d8 100644 --- a/abi/rad_format.h +++ b/abi/rad_format.h @@ -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 ""): 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 }; diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 912a25b4..6fde1f91 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -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. */ diff --git a/arch/anima/CMakeLists.txt b/arch/anima/CMakeLists.txt new file mode 100644 index 00000000..b9bebe27 --- /dev/null +++ b/arch/anima/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/anima -B build -DCMAKE_PREFIX_PATH=`); 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) diff --git a/arch/anima/anima.cpp b/arch/anima/anima.cpp new file mode 100644 index 00000000..9a746204 --- /dev/null +++ b/arch/anima/anima.cpp @@ -0,0 +1,1367 @@ +/* anima -- Anima (CircleStone Labs and Comfy Org): text to an RGB image. + * + * ============================== THE MODEL ============================== + * + * Three networks behind one prompt, as ComfyUI runs them (comfy/ldm/anima, comfy/ldm/cosmos/ + * predict2.py, comfy/text_encoders/anima.py): + * + * Conditioning: Qwen3-0.6B-Base reads the prompt as it is (no template), and its last hidden + * state after the final norm is the source. The LLM adapter (six blocks of 1024 wide, 16 heads of + * 64) then reads the same prompt again through T5's tokenizer: each T5 token's learned embedding + * is a query row that attends to the other T5 rows (self-attention) and to the Qwen3 rows (cross + * attention), both rotated with a 64-wide NeoX rotary at the rows' own indices, then a GELU MLP; + * an output linear and an RMS norm close it. Its rows, zero-padded to 512, are the DiT's context. + * An empty prompt is one padding token to Qwen3 and T5's alone. + * + * Denoiser: Cosmos-Predict2's MiniTrainDIT at 2B (28 blocks of 2048, 16 heads of 128). A token + * is 2 x 2 positions of the 16-channel latent (64 values, channel-major; 16 pixels a side) and + * the patch embedding reads them beside an all-zero padding-mask channel, so only its first 64 + * columns are kept (RAD_MAP_COLS). Each block: a self-attention with q/k RMS norms and a three-axis rotary over + * (frame, row, column) at 10000 x 4^(42/40) (the frame axis is 0 for an image), a cross-attention + * to the 512 context rows (q/k norms, no rotary), and a GELU MLP, each behind a LayerNorm + * without affine modulated by (shift, scale) and added back gated, `x += gate f(norm(x)(1 + scale) + * + shift)`. The modulation of each of the three is Linear(256, 6144)(Linear(2048, 256)(silu(e))) + * plus a shared AdaLN-LoRA term, `e` the RMS-normed sinusoid of the step's sigma (a timestep in + * [0, 1]) and the shared term Linear(2048, 6144)(silu(Linear(2048, 2048)(sinusoid))). + * + * Decoder: the Qwen-Image VAE (Wan 2.1's, its causal 3-D convolutions on one frame), 16 latent + * channels at 8x, read under ComfyUI's original Wan names (decoder.upsamples.N.residual.K). + * + * The model is a rectified flow (ComfyUI's FLOW at multiplier 1): the DiT predicts the velocity, + * sampled by Euler steps over ComfyUI's `simple` schedule at shift 3, guided as uncond + s (cond - + * uncond). The variant (`anima.variant` in the container, set at convert) picks the card's + * settings: Base and Aesthetic 30 steps at guidance 4 with the card's negative prompt, Turbo 10 + * steps unguided. + * + * ============================== THE CHECKPOINT ============================== + * + * ComfyUI's single files, merged by rad-convert (--add): the DiT under `net.` (Base) or + * `model.diffusion_model.` (Aesthetic 1.1, Turbo 1.1), the text encoder under `model.` and the VAE + * under its Wan names. The source names are the files' own, so a LoRA's module path (`blocks.N. + * self_attn.q_proj`) is the DiT key after its prefix. The prefix is read off the checkpoint at + * convert, and a container records it in the name of the one weight declared under it. + * + * ============================== WHAT IS QUANTISED ============================== + * + * One plugin serves bf16 and block-fp8 containers: the text encoder's linears and the DiT blocks' + * attention and MLP linears are LinearFP8s (rad_fp8.h), bf16 throughout when the first DiT + * projection is plain. The adapter, the modulation and embedding linears, the final layer and the + * VAE stay bf16. Every linear a LoRA for Anima names is a plain capable GEMM (gemm_nt or gemm_nt_q + * without rotation), its activation applied by a separate op. + * + * One card: tensor parallelism is refused. + */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace anima { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* The largest image: 1536 x 1536 pixels, 9216 latent tokens (the card's largest resolution). + * 1024 x 1024 is the default. */ +enum { kMaxImageTokens = 9216 }; +/* The context the DiT reads: the adapter's rows zero-padded to 512, as ComfyUI pads them. A prompt + * longer than that to T5 or Qwen3 is refused. */ +enum { kCondRows = 512 }; +/* Images in flight, and so the lanes of latent state. */ +enum { kMaxLanes = 8 }; +/* The adapter: six blocks over a 32128-row T5 embedding. */ +enum { kAdLayers = 6, kT5Vocab = 32128 }; +/* Qwen3's padding token: an empty prompt is this one token. */ +enum { kQwenPad = 151643 }; + +static const char* kNegative = + "worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts, " + "chromatic aberration"; + +/* Wan 2.1's latent statistics (ComfyUI's latent_formats.Wan21): x std + mean in f32. */ +static const double kLatMean[16] = { -0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, + 1.5508, 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, + 0.2503, -0.2921 }; +static const double kLatStd[16] = { 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743, + 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160 }; + +/* ================================================================== the model */ +struct TeLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_add1 = 0, op_n2 = 0, op_add2 = 0; +}; + +/* An adapter block: RMS-normed self-attention over the T5 rows, cross-attention to the Qwen3 rows + * and a GELU MLP, each added back. bf16 throughout. */ +struct AdLayer { + rad_weight w_nsa = 0, w_nca = 0, w_nmlp = 0; + rad_weight w_sqn = 0, w_skn = 0, w_cqn = 0, w_ckn = 0; + rad_weight w_sqkv = 0, w_so = 0, w_cq = 0, w_ckv = 0, w_co = 0; + rad_weight w_m1 = 0, b_m1 = 0, w_m2 = 0, b_m2 = 0; + rad_op op_nsa = 0, op_sqkv = 0, op_sqkr = 0, op_sattn = 0, op_so = 0, op_sadd = 0; + rad_op op_nca = 0, op_cq = 0, op_ckv = 0, op_cpq = 0, op_cpkv = 0, op_cqkr = 0, op_cattn = 0; + rad_op op_co = 0, op_cadd = 0; + rad_op op_nmlp = 0, op_m1 = 0, op_gelu = 0, op_m2 = 0, op_madd = 0; +}; + +/* A DiT block's three modulations and its linears. */ +struct DitLayer { + rad_weight w_qn = 0, w_kn = 0, w_cqn = 0, w_ckn = 0; + rad_weight w_mod1[3] = { 0, 0, 0 }, w_mod2[3] = { 0, 0, 0 }; + rad_op op_mod1[3] = { 0, 0, 0 }, op_mod2[3] = { 0, 0, 0 }, op_modadd[3] = { 0, 0, 0 }; + LinearFP8 qkv{}, o{}, cq{}, ck{}, cv{}, co{}, l1{}, l2{}; + QuantFP8 q_attn{}, q_cattn{}, q_ffn{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0; + rad_op op_n2 = 0, op_cqn = 0, op_ckn = 0, op_cattn = 0; + rad_op op_n3 = 0, op_gelu = 0; +}; + +/* Weight groups (movement units) by network. */ +enum : int { + kGrpAd = 1000, /* the adapter's blocks, kGrpAd + i; its model-level weights kGrpAd + 10 */ + kGrpVaeDec = 1200, + kGrpDit = 2000, /* the DiT's model-level weights; its blocks kGrpDit + 1.. */ +}; + +struct Model { + Names nm{""}; + Geom gt{}, ga{}, gd{}; /* the text encoder's, the adapter's and the DiT's geometry */ + int variant = 0; /* 0 base, 1 aesthetic, 2 turbo */ + std::string pre; /* the DiT's checkpoint prefix */ + + /* ---- the text encoder */ + rad_weight w_tok = 0, w_tnorm = 0; + rad_op op_embed = 0, op_tnorm = 0; + rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0, b_src = 0; + ActFP8 a_th{}, a_tattn{}, a_tffn{}; + std::vector te; + + /* ---- the adapter */ + rad_weight w_t5 = 0, w_aout = 0, b_aout = 0, w_anorm = 0; + rad_op op_t5 = 0, op_pos = 0, op_fill = 0, op_aout = 0, op_anorm = 0, op_ctxz = 0; + rad_op op_store = 0; + rad_buf b_ax = 0, b_ah = 0, b_aqkv = 0, b_aq = 0, b_akv = 0, b_aattn = 0, b_ab = 0, b_am = 0; + rad_buf b_apos = 0, b_ctx = 0; + std::vector ad; + + /* ---- the timestep and the modulations */ + rad_weight w_t1 = 0, w_t2 = 0, w_temb_norm = 0, w_f1 = 0, w_f2 = 0; + rad_op op_temb = 0, op_t1 = 0, op_tsilu = 0, op_t2 = 0, op_tnormed = 0, op_esilu = 0; + rad_op op_f1 = 0, op_f2 = 0, op_fadd = 0; + rad_buf b_tproj = 0, b_t1 = 0, b_t1s = 0, b_lora = 0, b_emb = 0, b_esilu = 0, b_mh = 0; + rad_buf b_mods = 0, b_mod1 = 0, b_fh = 0, b_fmod = 0; + + /* ---- the DiT */ + int64_t C = 64; /* latent values a token */ + rad_weight w_xemb = 0, w_final = 0; + rad_op op_randn = 0, op_lgather = 0, op_xemb = 0, op_cgather = 0; + rad_op op_g3 = 0, op_fn = 0, op_final = 0, op_euler = 0; + rad_buf b_lat = 0, b_h = 0, b_qkv = 0, b_cq = 0, b_ck = 0, b_cv = 0, b_ao = 0, b_l1 = 0; + rad_buf b_fz = 0, b_v = 0; + ActFP8 a_hm{}, a_attn{}, a_ffn{}, a_ctx{}; + std::vector dit; + LinearFP8 qkv0{}; + QuantFP8 q_ctx{}; + + /* ---- the per-image state and the conditioning store (PERSIST) */ + rad_buf b_state = 0, b_prev = 0, b_store = 0; + + /* ---- the VAE */ + Vae dec{}; + VImg dec_out{}; + rad_buf b_dl = 0, b_decin = 0, b_cu4 = 0, b_img = 0; + rad_op op_dnorm = 0, op_dzero = 0, op_unpack = 0, op_cu4 = 0, op_rgb = 0; + std::string mul, add; +}; + +static Model g_model[MAX_RANKS]; + +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A plain bf16 linear without a bias: gemm_nt, the activation a separate op. `src` is one + * checkpoint name, or several stacked along dim 0. */ +static rad_op dense(RadBuilder* b, const char* dn, std::initializer_list src, + int64_t N, int64_t K, int64_t rows, rad_buf in, rad_buf out, rad_weight* w, + int access, int group, std::initializer_list parts = {}) { + if (map_linear(b, dn, src) < 0) return 0; + *w = decl_w(b, dn, RAD_BF16, { N, K }, access, RAD_SHARD_NONE, grp_layer(group), 0, parts); + if (!*w) return 0; + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w)), + { in }, { out }); +} + +/* A bf16 linear with a bias. */ +static rad_op dense_bias(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t N, + int64_t K, int64_t rows, rad_buf in, rad_buf out, rad_weight* w, + rad_weight* bias, int access, int group) { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.weight", src), RAD_BF16, { N, K }, access, + group); + *bias = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { N }, access, group); + if (!*w || !*bias) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w, *bias)), + { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in, + rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +/* An RMS norm with a gain, `rows` rows of `n`. */ +static rad_op rms(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x, + rad_buf y) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (rad_meta_geti(meta, "num_hidden_layers", 0) != 28 || + rad_meta_geti(meta, "hidden_size", 0) != 1024) { + fprintf(stderr, "radiance: anima: the text encoder must be Qwen3-0.6B (28 layers of " + "1024); convert with --config naming the directory of Qwen3-0.6B-Base's " + "config.json\n"); + return RAD_E_UNSUPPORTED; + } + if (ctx->world_size > 1) { + fprintf(stderr, "radiance: anima: a 2B model served on one card; --tp %d is not " + "supported\n", ctx->world_size); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== declare */ +/* Qwen3-0.6B over the prompt: every layer, then the final norm, into `b_src`. */ +static int declare_te(RadBuilder* b, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = kCondRows; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), nm.ckpt("model.embed_tokens.weight"))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd }); + m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd }); + RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd, T)); + m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim }); + m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim }); + RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T)); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T)); + m.b_src = decl_b(b, nm.f("te.out"), RAD_BF16, { T, g.n_embd }); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + m.te.resize((size_t)g.n_layer); + for (int l = 0; l < (int)g.n_layer; ++l) { + TeLayer& L = m.te[(size_t)l]; + const char* lp = nm.ckpt("model.layers.%d", l); + L.w_n1 = wcopy(b, nm.f("te.blk.%d.attn_norm.weight", l), + nm.ckpt("%s.input_layernorm.weight", lp), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, l); + L.w_n2 = wcopy(b, nm.f("te.blk.%d.ffn_norm.weight", l), + nm.ckpt("%s.post_attention_layernorm.weight", lp), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, l); + L.w_qn = wcopy(b, nm.f("te.blk.%d.q_norm.weight", l), + nm.ckpt("%s.self_attn.q_norm.weight", lp), RAD_BF16, { g.head_dim }, + RAD_ACCESS_PER_TOKEN, l); + L.w_kn = wcopy(b, nm.f("te.blk.%d.k_norm.weight", l), + nm.ckpt("%s.self_attn.k_norm.weight", lp), RAD_BF16, { g.head_dim }, + RAD_ACCESS_PER_TOKEN, l); + if (!L.w_n1 || !L.w_n2 || !L.w_qn || !L.w_kn) return RAD_E_INVAL; + L.op_n1 = rms(b, T, g.n_embd, g.eps, L.w_n1, m.b_tx, m.a_th.x); + RAD_ARCH_TRY(L.q_h.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.qkv.declare(b, nm, g, nm.f("te.blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, + g.n_embd, RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.self_attn.q_proj.weight", lp), + nm.ckpt("%s.self_attn.k_proj.weight", lp), + nm.ckpt("%s.self_attn.v_proj.weight", lp) }, + m.a_th, m.b_tkv, T, { q_dim, kv_dim, kv_dim })); + L.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_INT("rotary_dim", g.head_dim)), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_tkv }, { m.b_tkv }); + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim)), + RAD_INT("max_seqlen", T)), + RAD_NOWEIGHTS), + { m.b_tkv }, { m.a_tattn.x }); + RAD_ARCH_TRY(L.q_attn.declare(b, g, m.a_tattn, q_dim)); + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("te.blk.%d.attn_output", l), g.n_embd, q_dim, + RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.self_attn.o_proj.weight", lp) }, m.a_tattn, m.b_th2, + T)); + L.op_add1 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); + L.op_n2 = rms(b, T, g.n_embd, g.eps, L.w_n2, m.b_tx, m.a_th.x); + RAD_ARCH_TRY(L.q_h2.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("te.blk.%d.ffn_gate_up", l), 2 * g.n_ff, + g.n_embd, RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.mlp.gate_proj.weight", lp), + nm.ckpt("%s.mlp.up_proj.weight", lp) }, + m.a_th, m.b_tgu, T, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, m.b_tgu, m.a_tffn, g.n_ff, "silu", T, true)); + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("te.blk.%d.ffn_down", l), g.n_embd, g.n_ff, + RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.mlp.down_proj.weight", lp) }, m.a_tffn, m.b_th2, + T)); + L.op_add2 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); + if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2) + return RAD_E_INVAL; + } + m.w_tnorm = wcopy(b, nm.f("te.output_norm.weight"), nm.ckpt("model.norm.weight"), RAD_F32, + { g.n_embd }, RAD_ACCESS_PER_TOKEN, (int)g.n_layer - 1); + m.op_tnorm = rms(b, T, g.n_embd, g.eps, m.w_tnorm, m.b_tx, m.b_src); + return m.op_embed && m.w_tnorm && m.op_tnorm ? RAD_OK : RAD_E_INVAL; +} + +/* The LLM adapter: the T5 rows' embeddings through six blocks, the output linear and norm, into + * the 512 context rows (zero past the prompt's) and from there into every lane's store at this + * branch. Its cross-attention lays q (the T5 rows), k and v (the Qwen3 rows) side by side in one + * [q | k | v] row so one qk_norm_rope rotates each at its own row index. */ +static int declare_adapter(RadBuilder* b, Model& m) { + Geom& g = m.ga; + Names& nm = m.nm; + const char* P = m.pre.c_str(); + const int64_t R = kCondRows, D = g.n_embd, hd = g.head_dim, F = g.n_ff_all; + const int acc = RAD_ACCESS_PER_REQUEST; + const double eps = 1e-6; + const int gm = kGrpAd + 10; + + RAD_ARCH_TRY(map_copy(b, nm.f("ad.embed.weight"), nm.ckpt("%sllm_adapter.embed.weight", P))); + m.w_t5 = decl_w(b, nm.f("ad.embed.weight"), RAD_BF16, { kT5Vocab, D }, acc, RAD_SHARD_NONE, + grp_layer(gm)); + m.b_ax = decl_b(b, nm.f("ad.x"), RAD_BF16, { R, D }); + m.b_ah = decl_b(b, nm.f("ad.h"), RAD_BF16, { R, D }); + m.b_aqkv = decl_b(b, nm.f("ad.qkv"), RAD_BF16, { R, 3 * D }); + m.b_aq = decl_b(b, nm.f("ad.q"), RAD_BF16, { R, D }); + m.b_akv = decl_b(b, nm.f("ad.kv"), RAD_BF16, { R, 2 * D }); + m.b_aattn = decl_b(b, nm.f("ad.attn"), RAD_BF16, { R, D }); + m.b_ab = decl_b(b, nm.f("ad.branch"), RAD_BF16, { R, D }); + m.b_am = decl_b(b, nm.f("ad.mlp"), RAD_BF16, { R, F }); + m.b_apos = decl_b(b, nm.f("ad.pos"), RAD_I32, { R }); + m.b_ctx = decl_b(b, nm.f("ad.ctx"), RAD_BF16, { R, D }); + + m.op_t5 = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n_embd", D), + RAD_INT("n_vocab", kT5Vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_t5)), + {}, { m.b_ax }); + m.op_pos = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("start", 0), + RAD_INT("step", 1)), + RAD_NOWEIGHTS), + {}, { m.b_apos }); + /* The [q | k | v] rows past either side's count are read by the norm and rotary and never by + * the attention; zeroed once so they are finite. */ + m.op_fill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 3 * D), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_aqkv }); + if (!m.w_t5 || !m.op_t5 || !m.op_pos || !m.op_fill) return RAD_E_INVAL; + + auto qk_rope = [&](rad_weight qn, rad_weight kn) { + return rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", 10000.0), RAD_F64("eps", eps), + RAD_INT("rotary_dim", hd)), + RAD_WEIGHTS(qn, kn)), + { m.b_aqkv, m.b_apos }, { m.b_aqkv }); + }; + auto gather = [&](rad_buf src, rad_buf dst) { + return rw(b, RAD_OP(b, "gather_rows2", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { src, m.b_apos, dst }, { dst }); + }; + + m.ad.resize(kAdLayers); + for (int i = 0; i < kAdLayers; ++i) { + AdLayer& L = m.ad[(size_t)i]; + const int grp = kGrpAd + i; + const char* pre = nm.ckpt("%sllm_adapter.blocks.%d", P, i); + const char* dn = nm.f("ad.blk.%d", i); + L.w_nsa = wcopy(b, nm.f("%s.norm_sa.weight", dn), nm.ckpt("%s.norm_self_attn.weight", pre), + RAD_BF16, { D }, acc, grp); + L.w_nca = wcopy(b, nm.f("%s.norm_ca.weight", dn), nm.ckpt("%s.norm_cross_attn.weight", pre), + RAD_BF16, { D }, acc, grp); + L.w_nmlp = wcopy(b, nm.f("%s.norm_mlp.weight", dn), nm.ckpt("%s.norm_mlp.weight", pre), + RAD_BF16, { D }, acc, grp); + L.w_sqn = wcopy(b, nm.f("%s.sa_q_norm.weight", dn), + nm.ckpt("%s.self_attn.q_norm.weight", pre), RAD_BF16, { hd }, acc, grp); + L.w_skn = wcopy(b, nm.f("%s.sa_k_norm.weight", dn), + nm.ckpt("%s.self_attn.k_norm.weight", pre), RAD_BF16, { hd }, acc, grp); + L.w_cqn = wcopy(b, nm.f("%s.ca_q_norm.weight", dn), + nm.ckpt("%s.cross_attn.q_norm.weight", pre), RAD_BF16, { hd }, acc, grp); + L.w_ckn = wcopy(b, nm.f("%s.ca_k_norm.weight", dn), + nm.ckpt("%s.cross_attn.k_norm.weight", pre), RAD_BF16, { hd }, acc, grp); + if (!L.w_nsa || !L.w_nca || !L.w_nmlp || !L.w_sqn || !L.w_skn || !L.w_cqn || !L.w_ckn) + return RAD_E_INVAL; + /* ---- self-attention over the T5 rows */ + L.op_nsa = rms(b, R, D, eps, L.w_nsa, m.b_ax, m.b_ah); + L.op_sqkv = dense(b, nm.f("%s.sa_qkv.weight", dn), + { nm.ckpt("%s.self_attn.q_proj.weight", pre), + nm.ckpt("%s.self_attn.k_proj.weight", pre), + nm.ckpt("%s.self_attn.v_proj.weight", pre) }, + 3 * D, D, R, m.b_ah, m.b_aqkv, &L.w_sqkv, acc, grp, { D, D, D }); + L.op_sqkr = qk_rope(L.w_sqn, L.w_skn); + L.op_sattn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_aqkv }, { m.b_aattn }); + L.op_so = dense(b, nm.f("%s.sa_o.weight", dn), { nm.ckpt("%s.self_attn.o_proj.weight", pre) }, + D, D, R, m.b_aattn, m.b_ab, &L.w_so, acc, grp); + L.op_sadd = add_op(b, R, D, m.b_ax, m.b_ab, m.b_ax); + /* ---- cross-attention to the Qwen3 rows */ + L.op_nca = rms(b, R, D, eps, L.w_nca, m.b_ax, m.b_ah); + L.op_cq = dense(b, nm.f("%s.ca_q.weight", dn), { nm.ckpt("%s.cross_attn.q_proj.weight", pre) }, + D, D, R, m.b_ah, m.b_aq, &L.w_cq, acc, grp); + L.op_ckv = dense(b, nm.f("%s.ca_kv.weight", dn), + { nm.ckpt("%s.cross_attn.k_proj.weight", pre), + nm.ckpt("%s.cross_attn.v_proj.weight", pre) }, + 2 * D, m.gt.n_embd, R, m.b_src, m.b_akv, &L.w_ckv, acc, grp, { D, D }); + L.op_cpq = gather(m.b_aq, m.b_aqkv); + L.op_cpkv = rw(b, RAD_OP(b, "gather_rows2", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 2 * D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_akv, m.b_apos, m.b_aqkv }, { m.b_aqkv }); + L.op_cqkr = qk_rope(L.w_cqn, L.w_ckn); + L.op_cattn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_aqkv }, { m.b_aattn }); + L.op_co = dense(b, nm.f("%s.ca_o.weight", dn), { nm.ckpt("%s.cross_attn.o_proj.weight", pre) }, + D, D, R, m.b_aattn, m.b_ab, &L.w_co, acc, grp); + L.op_cadd = add_op(b, R, D, m.b_ax, m.b_ab, m.b_ax); + /* ---- the MLP */ + L.op_nmlp = rms(b, R, D, eps, L.w_nmlp, m.b_ax, m.b_ah); + L.op_m1 = dense_bias(b, nm, nm.f("%s.mlp1", dn), nm.ckpt("%s.mlp.0", pre), F, D, R, m.b_ah, + m.b_am, &L.w_m1, &L.b_m1, acc, grp); + L.op_gelu = unary(b, "gelu", R, F, m.b_am, m.b_am); + L.op_m2 = dense_bias(b, nm, nm.f("%s.mlp2", dn), nm.ckpt("%s.mlp.2", pre), D, F, R, m.b_am, + m.b_ab, &L.w_m2, &L.b_m2, acc, grp); + L.op_madd = add_op(b, R, D, m.b_ax, m.b_ab, m.b_ax); + if (!L.op_nsa || !L.op_sqkv || !L.op_sqkr || !L.op_sattn || !L.op_so || !L.op_sadd || + !L.op_nca || !L.op_cq || !L.op_ckv || !L.op_cpq || !L.op_cpkv || !L.op_cqkr || + !L.op_cattn || !L.op_co || !L.op_cadd || !L.op_nmlp || !L.op_m1 || !L.op_gelu || + !L.op_m2 || !L.op_madd) + return RAD_E_INVAL; + } + m.op_aout = dense_bias(b, nm, nm.f("ad.out"), nm.ckpt("%sllm_adapter.out_proj", P), D, D, R, + m.b_ax, m.b_ah, &m.w_aout, &m.b_aout, acc, gm); + m.w_anorm = wcopy(b, nm.f("ad.norm.weight"), nm.ckpt("%sllm_adapter.norm.weight", P), RAD_BF16, + { D }, acc, gm); + m.op_ctxz = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_ctx }); + m.op_anorm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", D), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_anorm)), + { m.b_ah, m.b_ctx }, { m.b_ctx }); + /* Lane l's branch b at rows (2 l + b) kCondRows: the store's `stride` is two branches. */ + m.op_store = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", D), + RAD_INT("stride", 2 * (int64_t)kCondRows), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ctx, m.b_store }, { m.b_store }); + return m.op_aout && m.w_anorm && m.op_ctxz && m.op_anorm && m.op_store ? RAD_OK : RAD_E_INVAL; +} + +/* The final linear's rows reordered from the DiT's (row, column, channel) unpatchify order to the + * lane state's channel-major one: state value c 4 + k is output row k 16 + c. Eight ROWS maps of + * eight one-row pieces, joined in call order. */ +static int map_final(RadBuilder* b, const char* declared, const char* src, int64_t C) { + const int64_t ch = C / 4; + for (int64_t t0 = 0; t0 < C; t0 += 8) { + RadNameMap mp = map_base(declared, RAD_MAP_ROWS); + for (int64_t t = t0; t < t0 + 8 && t < C; ++t) { + const int64_t c = t / 4, k = t % 4; + mp.src[mp.n_src] = src; + mp.src_index[mp.n_src] = (int)(k * ch + c); + mp.src_rows[mp.n_src] = 1; + ++mp.n_src; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mp)); + } + return RAD_OK; +} + +/* The step's timestep embedding and every modulation: the shared AdaLN-LoRA term, the normed + * embedding, each block's three (shift | scale | gate) rows into its columns of `mods`, and the + * final layer's (shift | scale). All `S` rows, one an entry. */ +static int declare_mod(RadBuilder* b, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const char* P = m.pre.c_str(); + const int64_t S = g.max_seqs, D = g.n_embd, L = g.n_layer, M3 = 3 * D; + const int64_t R = 256; /* AdaLN-LoRA's rank */ + const int acc = RAD_ACCESS_PER_TOKEN; + const int gx = kGrpDit; + m.b_tproj = decl_b(b, nm.f("dit.tproj"), RAD_BF16, { S, D }); + m.b_t1 = decl_b(b, nm.f("dit.t1"), RAD_BF16, { S, D }); + m.b_t1s = decl_b(b, nm.f("dit.t1s"), RAD_BF16, { S, D }); + m.b_lora = decl_b(b, nm.f("dit.adaln_lora"), RAD_BF16, { S, M3 }); + m.b_emb = decl_b(b, nm.f("dit.temb"), RAD_BF16, { S, D }); + m.b_esilu = decl_b(b, nm.f("dit.temb_silu"), RAD_BF16, { S, D }); + m.b_mh = decl_b(b, nm.f("dit.mod_h"), RAD_BF16, { S, R }); + m.b_mods = decl_b(b, nm.f("dit.mods"), RAD_BF16, { S, L * 3 * M3 }); + m.b_fh = decl_b(b, nm.f("dit.fmod_raw"), RAD_BF16, { S, 2 * D }); + m.b_fmod = decl_b(b, nm.f("dit.fmod"), RAD_BF16, { S, 2 * D }); + m.b_mod1 = decl_b(b, nm.f("dit.mod_one"), RAD_BF16, { S, M3 }); + const rad_buf mod1 = m.b_mod1; + + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_t1 = dense(b, nm.f("dit.t_embed1.weight"), { nm.ckpt("%st_embedder.1.linear_1.weight", P) }, + D, D, S, m.b_tproj, m.b_t1, &m.w_t1, acc, gx); + m.op_tsilu = unary(b, "silu", S, D, m.b_t1, m.b_t1s); + m.op_t2 = dense(b, nm.f("dit.t_embed2.weight"), { nm.ckpt("%st_embedder.1.linear_2.weight", P) }, + M3, D, S, m.b_t1s, m.b_lora, &m.w_t2, acc, gx); + m.op_tnormed = rms(b, S, D, 1e-6, m.w_temb_norm, m.b_tproj, m.b_emb); + m.op_esilu = unary(b, "silu", S, D, m.b_emb, m.b_esilu); + if (!m.op_temb || !m.op_t1 || !m.op_tsilu || !m.op_t2 || !m.op_tnormed || !m.op_esilu) + return RAD_E_INVAL; + + static const char* kMods[3] = { "self_attn", "cross_attn", "mlp" }; + for (int64_t l = 0; l < L; ++l) { + DitLayer& B = m.dit[(size_t)l]; + const int grp = kGrpDit + 1 + (int)l; + for (int k = 0; k < 3; ++k) { + const char* src = nm.ckpt("%sblocks.%d.adaln_modulation_%s", P, (int)l, kMods[k]); + B.op_mod1[k] = dense(b, nm.f("dit.blk.%d.mod_%s.1.weight", (int)l, kMods[k]), + { nm.ckpt("%s.1.weight", src) }, R, D, S, m.b_esilu, m.b_mh, + &B.w_mod1[k], acc, grp); + B.op_mod2[k] = dense(b, nm.f("dit.blk.%d.mod_%s.2.weight", (int)l, kMods[k]), + { nm.ckpt("%s.2.weight", src) }, M3, R, S, m.b_mh, mod1, + &B.w_mod2[k], acc, grp); + B.op_modadd[k] = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", M3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { mod1, m.b_lora }, { m.b_mods }); + if (!B.op_mod1[k] || !B.op_mod2[k] || !B.op_modadd[k]) return RAD_E_INVAL; + } + } + m.op_f1 = dense(b, nm.f("dit.final.mod.1.weight"), + { nm.ckpt("%sfinal_layer.adaln_modulation.1.weight", P) }, R, D, S, m.b_esilu, + m.b_mh, &m.w_f1, acc, gx); + m.op_f2 = dense(b, nm.f("dit.final.mod.2.weight"), + { nm.ckpt("%sfinal_layer.adaln_modulation.2.weight", P) }, 2 * D, R, S, m.b_mh, + m.b_fh, &m.w_f2, acc, gx); + m.op_fadd = add_op(b, S, 2 * D, m.b_fh, m.b_lora, m.b_fmod); + return m.op_f1 && m.op_f2 && m.op_fadd ? RAD_OK : RAD_E_INVAL; +} + +static int declare_dit(RadBuilder* b, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const char* P = m.pre.c_str(); + const int64_t T = g.max_tok; + const int64_t D = g.n_embd, hd = g.head_dim, qd = g.q_dim(), C = m.C, L = g.n_layer; + const int64_t Dc = m.ga.n_embd; /* the context's width */ + const double eps = 1e-6; + const int gx = kGrpDit; + const int64_t NI = std::min(T, 2 * (int64_t)kMaxImageTokens); + + /* ---- the input rows: the images' latents a lane at a time through the patch embedding, and + * every entry's context rows out of the store */ + m.b_lat = decl_b(b, nm.f("dit.lat"), RAD_BF16, { NI, C }); + m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D }); + m.op_randn = rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_state }); + m.op_lgather = rw(b, RAD_OP(b, "lane_gather", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_lat }); + { + const char* dn = nm.f("dit.x_embed.weight"); + RadNameMap mp = map_base(dn, RAD_MAP_COLS); + mp.n_src = 1; + mp.src[0] = nm.ckpt("%sx_embedder.proj.1.weight", P); + mp.src_index[0] = 0; + mp.src_rows[0] = C; + RAD_ARCH_TRY(rad_decl_name_map(b, &mp)); + m.w_xemb = decl_w(b, dn, RAD_BF16, { D, C }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(gx)); + if (!m.w_xemb) return RAD_E_INVAL; + m.op_xemb = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("N", D), RAD_INT("K", C), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_xemb)), + { m.b_lat }, { m.b_h }); + } + m.a_ctx.x = decl_b(b, nm.f("dit.ctx"), RAD_BF16, { T, Dc }); + RAD_ARCH_TRY(m.a_ctx.declare_qs(b, nm, g, "dit.ctx", Dc)); + m.op_cgather = rw(b, RAD_OP(b, "gather_rows2", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", Dc), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_store }, { m.a_ctx.x }); + RAD_ARCH_TRY(m.q_ctx.declare(b, g, m.a_ctx, Dc)); + if (!m.op_randn || !m.op_lgather || !m.op_xemb || !m.op_cgather) return RAD_E_INVAL; + + /* ---- the blocks */ + m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D }); + RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D)); + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd }); + m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd }); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd)); + m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D }); + m.b_cq = decl_b(b, nm.f("dit.cq"), RAD_BF16, { T, qd }); + m.b_ck = decl_b(b, nm.f("dit.ck"), RAD_BF16, { T, qd }); + m.b_cv = decl_b(b, nm.f("dit.cv"), RAD_BF16, { T, qd }); + m.b_l1 = decl_b(b, nm.f("dit.l1"), RAD_BF16, { T, g.n_ff }); + m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff)); + + /* Cosmos's rotary: of the 64 frequency pairs 22 turn with the frame, 21 with the row and 21 + * with the column, NeoX pairs over the head; the row and column ladders at 10000 scaled by + * the extrapolation ratio 4 to the power 42 / 40. The frame is 0 for an image, so its + * section's base does not matter. */ + const int64_t dim_h = hd / 6 * 2, dim_t = hd - 2 * dim_h; + const char* sections = nm.f("%lld %lld %lld", (long long)dim_t / 2, (long long)dim_h / 2, + (long long)dim_h / 2); + const double theta = 10000.0 * std::pow(4.0, (double)dim_h / (double)(dim_h - 2)); + + /* The modulated LayerNorm (no affine), gated by the branch before it when `gated`, into the + * next linear's input: codes for fp8, the bf16 plane for bf16. */ + auto mod_norm = [&](bool gated) { + const bool q = !g.w_bf16; + rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS) + : RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS); + if (!op) return op; + rad_buf rd[3] = { m.b_mods, m.b_h, m.b_ao }; + rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h }; + rad_buf wb[2] = { m.a_hm.x, m.b_h }; + rad_op_reads(b, op, rd, gated ? 3 : 2); + if (q) rad_op_writes(b, op, wq, 3); + else rad_op_writes(b, op, wb, 2); + return op; + }; + /* A per-head RMS norm in place: [rows, heads * hd] read as [rows heads, hd]. */ + auto head_norm = [&](rad_weight w, rad_buf x) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T * g.n_head), RAD_INT("n", hd), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { x }); + }; + + for (int64_t l = 0; l < L; ++l) { + DitLayer& B = m.dit[(size_t)l]; + const int li = (int)l; + const int grp = kGrpDit + 1 + li; + const char* pre = nm.ckpt("%sblocks.%d", P, li); + const char* dn = nm.f("dit.blk.%d", li); + B.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.self_attn.q_norm.weight", pre), + RAD_BF16, { hd }, RAD_ACCESS_PER_TOKEN, grp); + B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.self_attn.k_norm.weight", pre), + RAD_BF16, { hd }, RAD_ACCESS_PER_TOKEN, grp); + B.w_cqn = wcopy(b, nm.f("%s.cq_norm.weight", dn), + nm.ckpt("%s.cross_attn.q_norm.weight", pre), RAD_BF16, { hd }, + RAD_ACCESS_PER_TOKEN, grp); + B.w_ckn = wcopy(b, nm.f("%s.ck_norm.weight", dn), + nm.ckpt("%s.cross_attn.k_norm.weight", pre), RAD_BF16, { hd }, + RAD_ACCESS_PER_TOKEN, grp); + if (!B.w_qn || !B.w_kn || !B.w_cqn || !B.w_ckn) return RAD_E_INVAL; + + /* ---- self-attention */ + B.op_n1 = mod_norm(l > 0); + if (l == 0) B.qkv = m.qkv0; + RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_NONE, + grp_layer(grp), + { nm.ckpt("%s.self_attn.q_proj.weight", pre), + nm.ckpt("%s.self_attn.k_proj.weight", pre), + nm.ckpt("%s.self_attn.v_proj.weight", pre) }, + m.a_hm, m.b_qkv, 0, { qd, qd, qd })); + B.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", theta), RAD_F64("eps", eps), + RAD_STR("mode", "axial"), RAD_INT("rotary_dim", hd), + RAD_STR("sections", sections)), + RAD_WEIGHTS(B.w_qn, B.w_kn)), + { m.b_qkv }, { m.b_qkv }); + B.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.a_attn.x }); + RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.self_attn.output_proj.weight", pre) }, + m.a_attn, m.b_ao)); + + /* ---- cross-attention to the context */ + B.op_n2 = mod_norm(true); + RAD_ARCH_TRY(B.cq.declare(b, nm, g, nm.f("%s.cross_q", dn), qd, D, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.cross_attn.q_proj.weight", pre) }, + m.a_hm, m.b_cq)); + RAD_ARCH_TRY(B.ck.declare(b, nm, g, nm.f("%s.cross_k", dn), qd, Dc, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.cross_attn.k_proj.weight", pre) }, + m.a_ctx, m.b_ck)); + RAD_ARCH_TRY(B.cv.declare(b, nm, g, nm.f("%s.cross_v", dn), qd, Dc, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.cross_attn.v_proj.weight", pre) }, + m.a_ctx, m.b_cv)); + B.op_cqn = head_norm(B.w_cqn, m.b_cq); + B.op_ckn = head_norm(B.w_ckn, m.b_ck); + B.op_cattn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_cq, m.b_ck, m.b_cv }, { m.a_attn.x }); + RAD_ARCH_TRY(B.q_cattn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(B.co.declare(b, nm, g, nm.f("%s.cross_output", dn), D, qd, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.cross_attn.output_proj.weight", pre) }, + m.a_attn, m.b_ao)); + + /* ---- the MLP: layer1, an exact GELU, layer2 */ + B.op_n3 = mod_norm(true); + RAD_ARCH_TRY(B.l1.declare(b, nm, g, nm.f("%s.mlp_layer1", dn), g.n_ff, D, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.mlp.layer1.weight", pre) }, m.a_hm, + m.b_l1)); + B.op_gelu = unary(b, "gelu", T, g.n_ff, m.b_l1, m.a_ffn.x); + RAD_ARCH_TRY(B.q_ffn.declare(b, g, m.a_ffn, g.n_ff)); + RAD_ARCH_TRY(B.l2.declare(b, nm, g, nm.f("%s.mlp_layer2", dn), D, g.n_ff, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.mlp.layer2.weight", pre) }, m.a_ffn, + m.b_ao)); + if (!B.op_n1 || !B.op_qkr || !B.op_attn || !B.op_n2 || !B.op_cqn || !B.op_ckn || + !B.op_cattn || !B.op_n3 || !B.op_gelu) + return RAD_E_INVAL; + } + + /* ---- the output: the last MLP gated in, the final modulated norm and linear, the sampler's + * step */ + m.b_fz = decl_b(b, nm.f("dit.fz"), RAD_BF16, { NI, D }); + m.b_v = decl_b(b, nm.f("dit.v"), RAD_BF16, { NI, C }); + m.op_g3 = rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { m.b_ao, m.b_mods, m.b_h }, { m.b_h }); + m.op_fn = rw(b, RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("gated", 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS), + { m.b_fmod, m.b_h }, { m.b_h, m.b_fz }); + { + const char* dn = nm.f("dit.final.weight"); + RAD_ARCH_TRY(map_final(b, dn, nm.ckpt("%sfinal_layer.linear.weight", P), C)); + m.w_final = decl_w(b, dn, RAD_BF16, { C, D }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(gx)); + if (!m.w_final) return RAD_E_INVAL; + m.op_final = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("N", C), RAD_INT("K", D), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_final)), + { m.b_fz }, { m.b_v }); + } + m.op_euler = rw(b, RAD_OP(b, "flow_euler", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_v, m.b_state, m.b_prev }, { m.b_state, m.b_prev }); + return m.op_g3 && m.op_fn && m.op_final && m.op_euler ? RAD_OK : RAD_E_INVAL; +} + +/* Wan 2.1's residual block under its own names: residual.0 (norm), .2 (conv), .3 (norm), .6 + * (conv), plus the input or its 1x1x1 `shortcut`. */ +static VImg wan_resblock(Vae& v, const VImg& x, int64_t out, const char* ckpt) { + Names& nm = *v.nm; + VImg h = x; + if (x.ch != out) h = v.conv(x, out, 1, 1, 1, "same", nm.f("%s.shortcut", ckpt)); + VImg t = v.norm(x, true, nm.f("%s.residual.0", ckpt), 4); + t = v.conv(t, out, 3, 1, 1, "same", nm.f("%s.residual.2", ckpt)); + t = v.norm(t, true, nm.f("%s.residual.3", ckpt), 4); + t = v.conv(t, out, 3, 1, 1, "same", nm.f("%s.residual.6", ckpt)); + return v.add(t, h); +} + +/* The decoder: the latent denormalised and unpacked to the VAE's 16 channels, then Wan 2.1's + * decoder on one frame. Its residual, head, conv1 and the top-level conv2 (post_quant_conv) + * convolutions are causal 3-D ones read at their last tap; the attention's and the upsamplers' + * are 2-D. */ +static int declare_decoder(RadBuilder* b, Model& m) { + Vae& v = m.dec; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "vdec"; + v.down = false; + v.first_group = kGrpVaeDec; + v.base_px = (int64_t)kMaxImageTokens * 4; + v.form = VAE_CONV_CAUSAL; + const int64_t zd = 16, base = 96; + const double mult[4] = { 1, 2, 4, 4 }; + /* The packed channel c 4 + k reads latent channel c: the statistics repeated four times. */ + for (int64_t k = 0; k < 4 * zd; ++k) { + char t[64]; + std::snprintf(t, sizeof t, "%s%.9g", k ? " " : "", kLatStd[k / 4]); + m.mul += t; + std::snprintf(t, sizeof t, "%s%.9g", k ? " " : "", kLatMean[k / 4]); + m.add += t; + } + const int64_t NT = kMaxImageTokens; + m.b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, 4 * zd }); + m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zd }); + m.b_cu4 = decl_b(b, nm.f("vdec.cu"), RAD_I32, { 2 }); + /* ComfyUI's Wan21.process_out on the f32 latent: x std + mean in f32, then bf16. */ + m.op_dnorm = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", 4 * zd), + RAD_STR("mul", m.mul.c_str()), RAD_STR("add", m.add.c_str()), + RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"), + RAD_INT("round", 0)), + RAD_NOWEIGHTS), + { m.b_state, m.b_prev }, { m.b_dl }); + m.op_dzero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("n", zd), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_decin }); + m.op_unpack = rw(b, RAD_OP(b, "d2s_add", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("cin", 4 * zd), + RAD_INT("cout", zd), RAD_INT("ft", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dl, m.b_decin }, { m.b_decin }); + m.op_cu4 = rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)), + RAD_NOWEIGHTS), + {}, { m.b_cu4 }); + if (!m.op_dnorm || !m.op_dzero || !m.op_unpack || !m.op_cu4) return RAD_E_INVAL; + + std::vector dims{ base * (int64_t)mult[3] }; + for (int i = 3; i >= 0; --i) dims.push_back(base * (int64_t)mult[i]); + VImg x{ m.b_decin, zd, 0 }; + x = v.conv(x, zd, 1, 1, 1, "same", "conv2"); + x = v.conv(x, dims[0], 3, 1, 1, "same", "decoder.conv1"); + x = wan_resblock(v, x, dims[0], "decoder.middle.0"); + v.form = VAE_CONV_2D; + x = v.attention(x, "decoder.middle.1"); + v.form = VAE_CONV_CAUSAL; + x = wan_resblock(v, x, dims[0], "decoder.middle.2"); + int idx = 0; + for (int i = 0; i < 4; ++i) { + for (int r = 0; r < 3; ++r) + x = wan_resblock(v, x, dims[(size_t)i + 1], nm.f("decoder.upsamples.%d", idx++)); + if (i != 3) { + v.form = VAE_CONV_2D; + x = v.conv(x, dims[(size_t)i + 1] / 2, 3, 1, 2, "same", + nm.f("decoder.upsamples.%d.resample.1", idx++)); + v.form = VAE_CONV_CAUSAL; + } + } + x = v.norm(x, true, "decoder.head.0", 4); + m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "decoder.head.2"); + if (!m.dec_out.buf) return RAD_E_INVAL; + RAD_ARCH_TRY(v.attn_reads(m.b_cu4)); + const int64_t px = (int64_t)kMaxImageTokens * 256; + m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST); + m.op_rgb = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_img }); + return m.op_rgb ? RAD_OK : RAD_E_INVAL; +} + +/* Which of the release's key spellings the DiT is under: `net.` (Base) or `model.diffusion_model.` + * (Aesthetic and Turbo 1.1). The checkpoint answers at convert; a container, by which marker name + * it holds the timestep norm's gain under (declared under the prefix it was read with). */ +static int find_prefix(RadBuilder* b, Model& m, const char** marker) { + static const char* kPre[2] = { "net.", "model.diffusion_model." }; + static const char* kTag[2] = { "dit.t_norm.net.weight", "dit.t_norm.mdm.weight" }; + int found = -1; + for (int i = 0; i < 2; ++i) { + RAD_ARCH_TRY(map_copy(b, m.nm.f("%s", kTag[i]), + m.nm.ckpt("%st_embedding_norm.weight", kPre[i]))); + RadEncoding e{}; + if (weight_enc(b, m.nm.f("%s", kTag[i]), &e)) found = found < 0 ? i : 2; + } + if (found < 0 || found > 1) { + fprintf(stderr, "radiance: anima: the DiT's keys are under neither `net.` nor " + "`model.diffusion_model.`, or under both\n"); + return RAD_E_UNSUPPORTED; + } + m.pre = kPre[found]; + *marker = kTag[found]; + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta, ctx)); + RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16)); + Names& nm = m.nm; + const char* variant = rad_meta_gets(meta, "anima.variant", "base"); + m.variant = std::strcmp(variant, "turbo") == 0 ? 2 : std::strcmp(variant, "aesthetic") == 0 ? 1 + : 0; + if (m.variant == 0 && std::strcmp(variant, "base") != 0) { + fprintf(stderr, "radiance: anima: anima.variant is '%s'; base, aesthetic or turbo\n", + variant); + return RAD_E_INVAL; + } + const char* marker = nullptr; + RAD_ARCH_TRY(find_prefix(b, m, &marker)); + + /* ---- the adapter's and the DiT's geometry */ + Geom& ga = m.ga; + ga = m.gt; + ga.n_embd = 1024; + ga.n_head = ga.n_head_all = ga.n_head_kv = ga.n_head_kv_all = 16; + ga.head_dim = 64; + ga.n_ff = ga.n_ff_all = 4096; + ga.w_bf16 = true; + Geom& gd = m.gd; + gd = m.gt; + gd.n_layer = 28; + gd.n_embd = 2048; + gd.n_head = gd.n_head_all = gd.n_head_kv = gd.n_head_kv_all = 16; + gd.head_dim = 128; + gd.n_ff = gd.n_ff_all = 8192; + gd.eps = 1e-6f; + + /* ---- bf16 or block fp8: what the container holds for the first DiT projection decides it + * for every LinearFP8 of the text encoder and the DiT (rad_fp8.h, Geom::w_bf16). */ + { + LinearFP8& probe = m.qkv0; + RAD_ARCH_TRY(probe.probe(b, nm, gd, nm.f("dit.blk.0.attn_qkv"), + { nm.ckpt("%sblocks.0.self_attn.q_proj.weight", m.pre.c_str()), + nm.ckpt("%sblocks.0.self_attn.k_proj.weight", m.pre.c_str()), + nm.ckpt("%sblocks.0.self_attn.v_proj.weight", m.pre.c_str()) })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) && + rad_enc_is(&e, "plain"); + gd.w_bf16 = m.gt.w_bf16 = plain; + } + + /* ---- the per-image state, the conditioning store, and in issue order the text encoder, + * the adapter, the modulations, the DiT and the decoder */ + const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens; + m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + 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, m.ga.n_embd }, RAD_BUF_PERSIST); + m.w_temb_norm = decl_w(b, nm.f("%s", marker), RAD_BF16, { gd.n_embd }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(kGrpDit)); + if (!m.w_temb_norm) return RAD_E_INVAL; + m.dit.resize((size_t)gd.n_layer); + /* ---- adapter key names: LoRA files name the DiT by the checkpoint's own modules behind + * ComfyUI's or kohya's prefix, and the text encoder as kohya's `lora_te_layers_N_...`. */ + RAD_ARCH_TRY(lora_names(b, m.pre.c_str(), kLoraDiffusionSpellings, {})); + RAD_ARCH_TRY(lora_names(b, "model.layers.", "lora_te_layers_", {})); + RAD_ARCH_TRY(declare_te(b, m)); + RAD_ARCH_TRY(declare_adapter(b, m)); + RAD_ARCH_TRY(declare_mod(b, m)); + RAD_ARCH_TRY(declare_dit(b, m)); + RAD_ARCH_TRY(declare_decoder(b, m)); + + /* ---- what the core drives */ + if (!ctx->shape_probe) { + static thread_local std::string name; + name = std::string("anima-") + variant; + RadGeneratorDecl d{}; + d.name = name.c_str(); + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.tmpl_text = "{prompt}"; + d.tmpl_edit = "{prompt}"; + d.drop_prefix = ""; + d.latent_channels = m.C; + d.latent_scale = 16; + d.size_multiple = 16; + d.pixel_channels = 3; + d.slot_rows = 1; + d.max_tokens = kMaxImageTokens; + d.max_refs = 0; + d.ref_area = 1; + d.default_width = 1024; + d.default_height = 1024; + /* ComfyUI's FLOW sampling at shift 3 over its `simple` schedule of 1000 timesteps, Euler + * steps; Base and Aesthetic at the card's 30 steps and guidance 4 with its negative + * prompt, Turbo at 10 steps without guidance (the card's CFG 1). */ + d.default_steps = m.variant == 2 ? 10 : 30; + d.n_sigmas = 0; + d.sigmas = nullptr; + d.shift = 3.0; + d.dyn_shift = 0; + d.shift_exp = 0; + d.base_shift = d.max_shift = 0.0; + d.base_seq = 256; + d.max_seq = 4096; + d.shift_terminal = 0.0; + d.sigma_grid = 1000; + d.cfg_original = 0; + d.default_cfg = m.variant == 2 ? 1.0 : 4.0; + d.default_negative = kNegative; + d.max_lanes = kMaxLanes; + d.image_out = m.b_img; + /* The conditioning's rows: the prompt padded to the 512 rows the DiT reads, which the + * COND pass leaves in each lane's store and every DENOISE entry names (mode 0). */ + d.cond_rows = kCondRows; + d.rope_hw_scale = 1.0; + d.rope_text_l = 0; + d.pad_multiple = kCondRows; + d.pad_token = kQwenPad; + d.min_tokens = 1; + d.aux_tokens = 1; + d.aux_max_tokens = kCondRows; + RAD_ARCH_TRY(rad_declare_generator(b, &d)); + } + rad_note(b, "rank %d/%d: Anima (%s) -- Qwen3-0.6B, the LLM adapter, a 2B DiT of %lld blocks " + "(DiT keys under `%s`), %s linears", m.gt.rank, m.gt.world, variant, + (long long)gd.n_layer, m.pre.c_str(), gd.w_bf16 ? "bf16" : "block-fp8"); + return RAD_OK; +} + +/* ================================================================== step */ +/* Qwen3 over the prompt's own tokens (not the padding the layout adds), into `b_src`. */ +static void step_te(RadCtx* c, const RadBatch* batch, const Model& m, int64_t T) { + const Geom& g = m.gt; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const RadGenBatch* G = batch->gen_b; + RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), + brows(m.b_tx, T)); + const RadOperand pos = praw(batch->positions, RAD_I32, T); + const RadOperand cu = praw(G->valid_cu, RAD_I32, 2); + for (const TeLayer& L : m.te) { + RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_tx, T), RAD_W(L.w_n1), brows(m.a_th.x, T)); + L.q_h.step(c, T); + L.qkv.step(c, m.a_th, m.b_tkv, T); + RAD_ISSUE_N(c, L.op_qkr, T, brows(m.b_tkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_tkv, 0, q_dim, T), bcol(m.b_tkv, q_dim, kv_dim, T), + bcol(m.b_tkv, q_dim + kv_dim, kv_dim, T), cu, brows(m.a_tattn.x, T)); + L.q_attn.step(c, T); + L.o.step(c, m.a_tattn, m.b_th2, T); + RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_tx, T), RAD_W(L.w_n2), brows(m.a_th.x, T)); + L.q_h2.step(c, T); + L.gate_up.step(c, m.a_th, m.b_tgu, T); + L.gq.step(c, m.b_tgu, T); + L.down.step(c, m.a_tffn, m.b_th2, T); + RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + } + RAD_ISSUE_N(c, m.op_tnorm, T, brows(m.b_tx, T), RAD_W(m.w_tnorm), brows(m.b_src, T)); +} + +/* The conditioning: Qwen3, the adapter over the T5 rows, the 512 context rows into every lane's + * store at this branch. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t Lq = batch->n_tok - G->n_pad, Lt = G->n_aux, R = kCondRows; + const int64_t D = m.ga.n_embd; + if (Lq <= 0 || Lt <= 0 || Lq > R || Lt > R || !G->aux_ids || !G->aux_cu) { + rad_step_fail(c, "anima: a conditioning pass with no prompt, or no T5 tokens of it"); + return; + } + step_te(c, batch, m, Lq); + const int64_t Rm = std::max(Lq, Lt); + const RadOperand tcu = praw(G->aux_cu, RAD_I32, 2), qcu = praw(G->valid_cu, RAD_I32, 2); + RAD_ISSUE_N(c, m.op_t5, Lt, praw(G->aux_ids, RAD_I32, Lt), RAD_W(m.w_t5), brows(m.b_ax, Lt)); + RAD_ISSUE_N(c, m.op_pos, R, brows(m.b_apos, R)); + RAD_ISSUE_N(c, m.op_fill, R, brows(m.b_aqkv, R)); + for (const AdLayer& L : m.ad) { + RAD_ISSUE_N(c, L.op_nsa, Lt, brows(m.b_ax, Lt), RAD_W(L.w_nsa), brows(m.b_ah, Lt)); + RAD_ISSUE_N(c, L.op_sqkv, Lt, brows(m.b_ah, Lt), RAD_W(L.w_sqkv), brows(m.b_aqkv, Lt)); + RAD_ISSUE_N(c, L.op_sqkr, Lt, brows(m.b_aqkv, Lt), brows(m.b_apos, Lt), RAD_W(L.w_sqn), + RAD_W(L.w_skn)); + RAD_ISSUE_N(c, L.op_sattn, Lt, bcol(m.b_aqkv, 0, D, Lt), bcol(m.b_aqkv, D, D, Lt), + bcol(m.b_aqkv, 2 * D, D, Lt), tcu, brows(m.b_aattn, Lt)); + RAD_ISSUE_N(c, L.op_so, Lt, brows(m.b_aattn, Lt), RAD_W(L.w_so), brows(m.b_ab, Lt)); + RAD_ISSUE_N(c, L.op_sadd, Lt, brows(m.b_ax, Lt), brows(m.b_ab, Lt), brows(m.b_ax, Lt)); + + RAD_ISSUE_N(c, L.op_nca, Lt, brows(m.b_ax, Lt), RAD_W(L.w_nca), brows(m.b_ah, Lt)); + RAD_ISSUE_N(c, L.op_cq, Lt, brows(m.b_ah, Lt), RAD_W(L.w_cq), brows(m.b_aq, Lt)); + RAD_ISSUE_N(c, L.op_ckv, Lq, brows(m.b_src, Lq), RAD_W(L.w_ckv), brows(m.b_akv, Lq)); + RAD_ISSUE_N(c, L.op_cpq, Lt, brows(m.b_aq, Lt), brows(m.b_aq, Lt), brows(m.b_apos, Lt), + bcol(m.b_aqkv, 0, D, Lt)); + RAD_ISSUE_N(c, L.op_cpkv, Lq, brows(m.b_akv, Lq), brows(m.b_akv, Lq), brows(m.b_apos, Lq), + bcol(m.b_aqkv, D, 2 * D, Lq)); + RAD_ISSUE_N(c, L.op_cqkr, Rm, brows(m.b_aqkv, Rm), brows(m.b_apos, Rm), RAD_W(L.w_cqn), + RAD_W(L.w_ckn)); + RAD_ISSUE_N(c, L.op_cattn, Lt, bcol(m.b_aqkv, 0, D, Lt), bcol(m.b_aqkv, D, D, Lq), + bcol(m.b_aqkv, 2 * D, D, Lq), tcu, qcu, brows(m.b_aattn, Lt)); + RAD_ISSUE_N(c, L.op_co, Lt, brows(m.b_aattn, Lt), RAD_W(L.w_co), brows(m.b_ab, Lt)); + RAD_ISSUE_N(c, L.op_cadd, Lt, brows(m.b_ax, Lt), brows(m.b_ab, Lt), brows(m.b_ax, Lt)); + + RAD_ISSUE_N(c, L.op_nmlp, Lt, brows(m.b_ax, Lt), RAD_W(L.w_nmlp), brows(m.b_ah, Lt)); + RAD_ISSUE_N(c, L.op_m1, Lt, brows(m.b_ah, Lt), RAD_W(L.w_m1), RAD_W(L.b_m1), RAD_NONE, + brows(m.b_am, Lt)); + RAD_ISSUE_N(c, L.op_gelu, Lt, brows(m.b_am, Lt), brows(m.b_am, Lt)); + RAD_ISSUE_N(c, L.op_m2, Lt, brows(m.b_am, Lt), RAD_W(L.w_m2), RAD_W(L.b_m2), RAD_NONE, + brows(m.b_ab, Lt)); + RAD_ISSUE_N(c, L.op_madd, Lt, brows(m.b_ax, Lt), brows(m.b_ab, Lt), brows(m.b_ax, Lt)); + } + RAD_ISSUE_N(c, m.op_aout, Lt, brows(m.b_ax, Lt), RAD_W(m.w_aout), RAD_W(m.b_aout), RAD_NONE, + brows(m.b_ah, Lt)); + RAD_ISSUE_N(c, m.op_ctxz, R, brows(m.b_ctx, R)); + RAD_ISSUE_N(c, m.op_anorm, Lt, brows(m.b_ah, Lt), RAD_W(m.w_anorm), brows(m.b_ctx, Lt)); + RAD_ISSUE_N(c, m.op_store, R, brows(m.b_ctx, R), praw(G->lane, RAD_I32, G->n_lane), + brow_slice(m.b_store, (int64_t)G->branch * kCondRows, + 2 * (int64_t)kMaxLanes * kCondRows - G->branch * kCondRows, D)); +} + +/* One denoising step: the entries' modulations, the image rows through the patch embedding, every + * entry's context out of the store, the blocks, and the image rows' velocity through the + * sampler. */ +static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const Geom& g = m.gd; + const int64_t S = batch->n_seq, NI = G->n_img, N0 = G->n_mode_h[0]; + const int64_t D = g.n_embd, qd = g.q_dim(), hd = g.head_dim, M3 = 3 * D, L = g.n_layer; + const int64_t W = L * 3 * M3, nh = g.n_head; + const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1); + const RadOperand ccu = praw(G->mode_ccu, RAD_I32, S + 1); + const RadOperand lanes = praw(G->lane, RAD_I32, S); + const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens; + if (NI <= 0 || N0 <= 0) { + rad_step_fail(c, "anima: a denoising pass with no image or no context rows"); + return; + } + + /* ---- the modulations: block l's module k is columns [(3 l + k) 3D, +3D) of `mods`, as + * (shift | scale | gate) */ + RAD_ISSUE_N(c, m.op_temb, S, praw(G->sigma, RAD_F32, S), brows(m.b_tproj, S)); + RAD_ISSUE_N(c, m.op_t1, S, brows(m.b_tproj, S), RAD_W(m.w_t1), brows(m.b_t1, S)); + RAD_ISSUE_N(c, m.op_tsilu, S, brows(m.b_t1, S), brows(m.b_t1s, S)); + RAD_ISSUE_N(c, m.op_t2, S, brows(m.b_t1s, S), RAD_W(m.w_t2), brows(m.b_lora, S)); + RAD_ISSUE_N(c, m.op_tnormed, S, brows(m.b_tproj, S), RAD_W(m.w_temb_norm), brows(m.b_emb, S)); + RAD_ISSUE_N(c, m.op_esilu, S, brows(m.b_emb, S), brows(m.b_esilu, S)); + auto mod = [&](int64_t l, int k, int part, int64_t width) { + return bcol_at(m.b_mods, 0, W, (3 * l + k) * M3 + part * D, width, S); + }; + for (int64_t l = 0; l < L; ++l) { + const DitLayer& B = m.dit[(size_t)l]; + for (int k = 0; k < 3; ++k) { + RAD_ISSUE_N(c, B.op_mod1[k], S, brows(m.b_esilu, S), RAD_W(B.w_mod1[k]), + brows(m.b_mh, S)); + RAD_ISSUE_N(c, B.op_mod2[k], S, brows(m.b_mh, S), RAD_W(B.w_mod2[k]), + brows(m.b_mod1, S)); + RAD_ISSUE_N(c, B.op_modadd[k], S, brows(m.b_mod1, S), brows(m.b_lora, S), + mod(l, k, 0, M3)); + } + } + RAD_ISSUE_N(c, m.op_f1, S, brows(m.b_esilu, S), RAD_W(m.w_f1), brows(m.b_mh, S)); + RAD_ISSUE_N(c, m.op_f2, S, brows(m.b_mh, S), RAD_W(m.w_f2), brows(m.b_fh, S)); + RAD_ISSUE_N(c, m.op_fadd, S, brows(m.b_fh, S), bcol(m.b_lora, 0, 2 * D, S), + brows(m.b_fmod, S)); + + /* ---- the rows: the images' latents (noise on a first step) through the patch embedding, + * and every entry's context rows out of the store (mode 0, in entry order) */ + RAD_ISSUE_N(c, m.op_randn, NI, praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S), + lanes, icu, brows(m.b_state, LR)); + RAD_ISSUE_N(c, m.op_lgather, NI, brows(m.b_state, LR), lanes, icu, brows(m.b_lat, NI)); + RAD_ISSUE_N(c, m.op_xemb, NI, brows(m.b_lat, NI), RAD_W(m.w_xemb), brows(m.b_h, NI)); + const int64_t SR = 2 * (int64_t)kMaxLanes * kCondRows; + RAD_ISSUE_N(c, m.op_cgather, N0, brows(m.b_store, SR), brows(m.b_store, SR), + praw(G->mode_src, RAD_I32, N0), brows(m.a_ctx.x, N0)); + m.q_ctx.step(c, N0); + + /* ---- the blocks; the image rows' positions are mode 2's block of the mode-major planes */ + const int64_t img0 = G->n_mode_h[0] + G->n_mode_h[1]; + const RadOperand pos = praw2(G->mode_rope_f + 4 * img0, RAD_F32, 4, NI); + const bool q8 = !g.w_bf16; + auto head_rows = [&](rad_buf x, int64_t rows) { + return RAD_P_T2(rad_buf_ptr(c, x), RAD_BF16, rows * nh, hd); + }; + for (int64_t l = 0; l < L; ++l) { + const DitLayer& B = m.dit[(size_t)l]; + const RadOperand gy = l > 0 ? brows(m.b_ao, NI) : RAD_NONE; + const RadOperand gg = l > 0 ? mod(l - 1, 2, 2, D) : RAD_NONE; + if (q8) + RAD_ISSUE_N(c, B.op_n1, NI, gy, gg, mod(l, 0, 0, 2 * D), RAD_NONE, icu, + brows(m.b_h, NI), brows(m.a_hm.q, NI), brows(m.a_hm.s, NI), RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n1, NI, gy, gg, mod(l, 0, 0, 2 * D), RAD_NONE, icu, + brows(m.b_h, NI), brows(m.a_hm.x, NI)); + B.qkv.step(c, m.a_hm, m.b_qkv, NI); + RAD_ISSUE_N(c, B.op_qkr, NI, brows(m.b_qkv, NI), pos, RAD_W(B.w_qn), RAD_W(B.w_kn)); + RAD_ISSUE_N(c, B.op_attn, NI, bcol(m.b_qkv, 0, qd, NI), bcol(m.b_qkv, qd, qd, NI), + bcol(m.b_qkv, 2 * qd, qd, NI), icu, brows(m.a_attn.x, NI)); + B.q_attn.step(c, NI); + B.o.step(c, m.a_attn, m.b_ao, NI); + + if (q8) + RAD_ISSUE_N(c, B.op_n2, NI, brows(m.b_ao, NI), mod(l, 0, 2, D), mod(l, 1, 0, 2 * D), + RAD_NONE, icu, brows(m.b_h, NI), brows(m.a_hm.q, NI), brows(m.a_hm.s, NI), + RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n2, NI, brows(m.b_ao, NI), mod(l, 0, 2, D), mod(l, 1, 0, 2 * D), + RAD_NONE, icu, brows(m.b_h, NI), brows(m.a_hm.x, NI)); + B.cq.step(c, m.a_hm, m.b_cq, NI); + B.ck.step(c, m.a_ctx, m.b_ck, N0); + B.cv.step(c, m.a_ctx, m.b_cv, N0); + RAD_ISSUE_N(c, B.op_cqn, NI * nh, head_rows(m.b_cq, NI), RAD_W(B.w_cqn), + head_rows(m.b_cq, NI)); + RAD_ISSUE_N(c, B.op_ckn, N0 * nh, head_rows(m.b_ck, N0), RAD_W(B.w_ckn), + head_rows(m.b_ck, N0)); + RAD_ISSUE_N(c, B.op_cattn, NI, brows(m.b_cq, NI), brows(m.b_ck, N0), brows(m.b_cv, N0), + icu, ccu, brows(m.a_attn.x, NI)); + B.q_cattn.step(c, NI); + B.co.step(c, m.a_attn, m.b_ao, NI); + + if (q8) + RAD_ISSUE_N(c, B.op_n3, NI, brows(m.b_ao, NI), mod(l, 1, 2, D), mod(l, 2, 0, 2 * D), + RAD_NONE, icu, brows(m.b_h, NI), brows(m.a_hm.q, NI), brows(m.a_hm.s, NI), + RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n3, NI, brows(m.b_ao, NI), mod(l, 1, 2, D), mod(l, 2, 0, 2 * D), + RAD_NONE, icu, brows(m.b_h, NI), brows(m.a_hm.x, NI)); + B.l1.step(c, m.a_hm, m.b_l1, NI); + RAD_ISSUE_N(c, B.op_gelu, NI, brows(m.b_l1, NI), brows(m.a_ffn.x, NI)); + B.q_ffn.step(c, NI); + B.l2.step(c, m.a_ffn, m.b_ao, NI); + } + + /* ---- the last MLP gated in, the final layer, the sampler */ + RAD_ISSUE_N(c, m.op_g3, NI, brows(m.b_ao, NI), mod(L - 1, 2, 2, D), icu, brows(m.b_h, NI)); + RAD_ISSUE_N(c, m.op_fn, NI, RAD_NONE, RAD_NONE, brows(m.b_fmod, S), RAD_NONE, icu, + brows(m.b_h, NI), brows(m.b_fz, NI)); + RAD_ISSUE_N(c, m.op_final, NI, brows(m.b_fz, NI), RAD_W(m.w_final), brows(m.b_v, NI)); + RAD_ISSUE_N(c, m.op_euler, NI, brows(m.b_v, NI), praw(G->sigma, RAD_F32, S), + praw(G->sigma_next, RAD_F32, S), praw(G->cfg, RAD_F32, S), + praw(G->pair, RAD_I32, S), lanes, praw(G->flags, RAD_I32, S), + praw(G->seed, RAD_U32, 2 * S), icu, RAD_NONE, RAD_NONE, brows(m.b_state, LR), + brows(m.b_prev, LR)); +} + +/* One image's latent to RGB: denormalised, unpacked to the VAE's grid, decoded. */ +static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W, C = m.C; + const rad_buf src = G->dec_preview ? m.b_prev : m.b_state; + RAD_ISSUE_N(c, m.op_dnorm, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C), + brows(m.b_dl, n)); + const int64_t zd = C / 4, H0 = 2 * H, W0 = 2 * W; + RAD_ISSUE_N(c, m.op_dzero, H0 * W0, brows(m.b_decin, H0 * W0)); + RAD_ISSUE_N(c, m.op_unpack, H0 * W0, RAD_P_T2(rad_buf_ptr(c, m.b_dl), RAD_BF16, H, W * C), + RAD_P_T2(rad_buf_ptr(c, m.b_decin), RAD_BF16, H0, W0 * zd)); + RAD_ISSUE_N(c, m.op_cu4, 2, praw(batch->cu_seqlens + 1, RAD_I32, 1), brows(m.b_cu4, 2)); + m.dec.issue(c, H0, W0, brows(m.b_cu4, 2), nullptr); + const int64_t npx = (int64_t)G->dec_height * G->dec_width; + RAD_ISSUE_N(c, m.op_rgb, npx, RAD_P_T2(rad_buf_ptr(c, m.dec_out.buf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->gen_b) { + rad_step_fail(c, "anima is an image generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_COND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_DENOISE: step_denoise(c, batch, m); return; + case RAD_GEN_PASS_DECODE: step_decode(c, batch, m); return; + default: rad_step_fail(c, "anima: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries: one image at the largest size with guidance, its context both ways. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kCondRows); + out->gen_patches = 0; + return RAD_OK; +} + +} /* namespace anima */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(anima) +RAD_ARCH_PLUGIN(anima, "anima", "", "0.1.0", + "Anima (Base, Aesthetic, Turbo): Qwen3-0.6B through the LLM adapter, Cosmos-Predict2's " + "2B diffusion transformer and the Qwen-Image VAE; bf16 or block-fp8 linears") +#endif diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index c138838a..01918a7f 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -432,6 +432,28 @@ inline int map_rows(RadBuilder* b, const char* declared, std::initializer_list& 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); diff --git a/arch/flux3/flux3.cpp b/arch/flux3/flux3.cpp index 3eb721ac..4c2e6fa8 100644 --- a/arch/flux3/flux3.cpp +++ b/arch/flux3/flux3.cpp @@ -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 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)); diff --git a/arch/krea2/krea2.cpp b/arch/krea2/krea2.cpp index 9e994f53..99300df0 100644 --- a/arch/krea2/krea2.cpp +++ b/arch/krea2/krea2.cpp @@ -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 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)); diff --git a/arch/ltx2/ltx2.cpp b/arch/ltx2/ltx2.cpp index e0e9f6b5..2249cb05 100644 --- a/arch/ltx2/ltx2.cpp +++ b/arch/ltx2/ltx2.cpp @@ -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(rad_meta_geti(meta, "connectors.video_hidden_dim", 0), diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index 75c310e8..8d1a47b3 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -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 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)); diff --git a/arch/qwenimage21/qwenimage21.cpp b/arch/qwenimage21/qwenimage21.cpp index 70b558b5..e6eb4021 100644 --- a/arch/qwenimage21/qwenimage21.cpp +++ b/arch/qwenimage21/qwenimage21.cpp @@ -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)); diff --git a/arch/sdxl/CMakeLists.txt b/arch/sdxl/CMakeLists.txt new file mode 100644 index 00000000..4e4ce326 --- /dev/null +++ b/arch/sdxl/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/sdxl -B build -DCMAKE_PREFIX_PATH=`); 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) diff --git a/arch/sdxl/sdxl.cpp b/arch/sdxl/sdxl.cpp new file mode 100644 index 00000000..8ace9a10 --- /dev/null +++ b/arch/sdxl/sdxl.cpp @@ -0,0 +1,1236 @@ +/* sdxl -- Stable Diffusion XL and its finetunes (Illustrious, NoobAI, Pony, ...): text to an RGB + * image. + * + * ============================== THE MODEL ============================== + * + * Three networks behind one prompt, as Stability's single-file checkpoint holds them (read by + * rad-convert's SDXL importer, core/format/checkpoint.cpp open_sgm): + * + * Conditioning: two CLIP text encoders over the prompt in 77-token windows (the core cuts it, + * RadGeneratorDecl::chunk_tokens): CLIP ViT-L (12 layers, 768 wide, quick_gelu) and OpenCLIP + * ViT-bigG (32 layers, 1280 wide, gelu). Each window is encoded on its own, causally. The + * cross-attention context is ViT-L's and bigG's penultimate hidden states side by side, 2048 + * wide, the windows end to end; the pooled vector is bigG's last layer through its final norm at + * the first window's end-of-text token, through text_projection. ViT-L reads padding as + * end-of-text tokens, bigG as token 0 ("!"), as each tokenizer pads. + * + * Denoiser: a 2.6B UNet over 4-channel latents at 1/8 of the pixels, three levels (320, 640 and + * 1280 channels), residual blocks (GroupNorm, SiLU, 3x3 convolutions, the time embedding added + * per channel) and spatial transformers at the two lower levels (2 and 10 blocks of self + * attention, cross attention over the context and a GEGLU feed-forward, 64-wide heads). The time + * embedding is the timestep's plus the pooled vector's and the image size's (original size, + * crop at (0, 0), target size), each through its own sinusoid. It predicts the noise (eps), or + * with a `v_pred` checkpoint the velocity. + * + * Decoder: the SDXL VAE (AutoencoderKL, 4 latent channels at 8x, scaling 0.13025), run bf16 + * (bf16 has f32's range, so the fp16 overflow the original VAE is known for does not occur). + * + * Sampling is k-diffusion's over the discrete schedule (1000 steps, scaled-linear betas + * 0.00085..0.012): the core places the sigmas (ComfyUI's schedulers) and conditions each step at + * the nearest trained timestep; kd_input scales the f32 latent by c_in, the UNet runs at bf16, and + * kd_step applies guidance to the denoised estimates and takes the sampler's step (Euler, Euler + * ancestral, DPM++ 2M) in f32. + * + * ============================== ONE IMAGE AT A TIME ============================== + * + * A convolution reads its image's size from its operands, so a denoising pass runs the UNet once + * per entry (an image and its guidance branch are two entries) at that entry's size, over the + * same declared ops; the sampler ops run over every entry at once. The buffers the entries pass + * between them (the model input and output, the lanes, the stores) are kept for the program's + * life. + * + * ============================== RUNTIME LORA ============================== + * + * Every linear and every 3x3 convolution of the UNet and every linear of both text encoders is a + * plain GEMM over a weight declared under its checkpoint name: a 3x3 convolution is `im2col_nhwc` + * then `gemm_nt_bias` over the weight read as [cout, cin * 9] in the checkpoint's own order, a 1x1 + * skip convolution a GEMM over [cout, cin]. Only the UNet's conv_in and out.2 (4 channels) and the + * VAE are direct convolutions. + * + * One card: the model is small enough that tensor parallelism would only add all-reduces. + */ +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace sdxl { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* The largest image in latent pixels: 1536 x 1536 (or the same area at another aspect). */ +enum { kMaxImageTokens = 36864 }; +/* CLIP's window, and the windows a prompt may take. */ +enum { kWin = 77, kMaxWin = 8, kCondRows = kWin * kMaxWin }; +enum { kMaxLanes = 8 }; +enum { kLatC = 4, kCtx = 2048, kPooled = 1280, kAdd = 2816, kTemb = 1280, kGroups = 32 }; +enum { kBos = 49406, kEos = 49407 }; +static const double kVaeScale = 0.13025; +/* group_norm's scratch: 32 groups of (2 + 3 * 1024) floats (docs/OPS.md). */ +enum { kGnStats = kGroups * (2 + 3 * 1024) }; + +static const char* kUnet = "model.diffusion_model"; +static const char* kTe1 = "conditioner.embedders.0.transformer"; +static const char* kTe2 = "conditioner.embedders.1.transformer"; + +/* Movement groups: each text encoder one, the UNet's embeddings and blocks 21 (kGrpUnet + 0..20), + * the VAE one. All lie below the conditioning network's layer count, the container's n_layers, + * since the engine reads a group past it as a drafter's. */ +enum : int { kGrpTe1 = 0, kGrpTe2 = 1, kGrpUnet = 2, kGrpVae = 23 }; + +/* ================================================================== the text encoders */ +struct TextLayer { + rad_weight ln1w = 0, ln1b = 0, ln2w = 0, ln2b = 0; + rad_weight qw = 0, qb = 0, kw = 0, kb = 0, vw = 0, vb = 0, ow = 0, ob = 0; + rad_weight f1w = 0, f1b = 0, f2w = 0, f2b = 0; + rad_op op_ln1 = 0, op_q = 0, op_k = 0, op_v = 0, op_attn = 0, op_o = 0; + rad_op op_ln2 = 0, op_f1 = 0, op_act = 0, op_f2 = 0; +}; + +struct TextEnc { + int64_t D = 0, F = 0, L = 0; /* width, feed-forward width, layers run */ + int64_t tap = 0; /* the layer after which the context is taken */ + int64_t ctx_col = 0; /* where its columns of the context start */ + bool quick = false; /* quick_gelu (ViT-L) or gelu (bigG) */ + rad_weight tok = 0, pos = 0; + rad_buf x = 0, pe = 0, h = 0, q = 0, k = 0, v = 0, a = 0, f1 = 0, f2 = 0; + rad_op op_tok = 0, op_pad = 0, op_pos = 0, op_pe = 0, op_tap = 0; + std::vector layers; + /* bigG's pooled vector */ + rad_weight fnw = 0, fnb = 0, proj = 0; + rad_buf e1 = 0, e2 = 0; + rad_op op_eos = 0, op_fn = 0, op_proj = 0; +}; + +/* ================================================================== the UNet, recorded + * + * The UNet's ops are declared once and issued per entry at the entry's size, so each op is + * recorded with what rebuilds its operands: a value's rows are its level's pixels (level l is + * the latent at 1 / 2^l per side), one row, or the conditioning's rows. */ +enum { kRowsOne = -1, kRowsCond = -2, kRowsTwo = -3 }; + +struct V { + rad_buf buf = 0; + int lvl = 0; /* >= 0 a level; kRows* otherwise */ + int64_t pitch = 0; /* the buffer's width */ + int64_t col = 0, width = 0; /* a column slice; width 0 is the whole row */ + int64_t w() const { return width ? width : pitch; } +}; + +struct Opd { + /* ROWS a value's rows (the entry's conditioning when the value is the store), IMG a level's + * image [h, w * channels], XIN / EPS the entry's rows of the model input and output, IOTA the + * table's entry for a level's pixel count, STATS group_norm's scratch. */ + enum Kind : uint8_t { NONE, ROWS, IMG, WEIGHT, XIN, EPS, IOTA, STATS }; + Kind kind = NONE; + V v{}; + rad_weight w = 0; +}; + +struct UOp { + rad_op op = 0; + std::vector o; + int n = 0; /* the ranged value: a level's pixels, or kRows* */ +}; + +/* One entry's geometry and where its per-entry operands are. */ +struct Geo { + int64_t h = 0, w = 0; /* latent rows and columns */ + int64_t cond = 0; /* conditioning rows */ + int64_t store_row = 0, pool_row = 0; + int64_t row0 = 0; /* its first row in the pass's compact image order */ + int64_t px(int l) const { return (h >> l) * (w >> l); } + int64_t rows(int l) const { + return l >= 0 ? px(l) : l == kRowsOne ? 1 : l == kRowsTwo ? 2 : cond; + } +}; + +struct Net { + std::vector ops; + RadBuilder* b = nullptr; + Names* nm = nullptr; + int64_t P0 = kMaxImageTokens; + int n_buf = 0; + int grp = kGrpUnet; + rad_buf stats = 0, iota = 0, store = 0, xin = 0, eps = 0; + + int64_t cap(int lvl) const { + return lvl >= 0 ? P0 >> (2 * lvl) + : lvl == kRowsCond ? (int64_t)kCondRows : lvl == kRowsTwo ? 2 : 1; + } + V buf(int lvl, int64_t ch, uint32_t dt = RAD_BF16) { + V v; + v.lvl = lvl; + v.pitch = ch; + v.buf = decl_b(b, nm->f("unet.t%d", n_buf++), dt, { cap(lvl), ch }); + return v; + } + static Opd R(const V& v) { Opd o; o.kind = Opd::ROWS; o.v = v; return o; } + static Opd I(const V& v) { Opd o; o.kind = Opd::IMG; o.v = v; return o; } + static Opd W(rad_weight w) { Opd o; o.kind = Opd::WEIGHT; o.w = w; return o; } + static Opd Kd(Opd::Kind k) { Opd o; o.kind = k; return o; } + void add(rad_op op, std::vector o, int n, std::initializer_list rd, + std::initializer_list wr) { + rw(b, op, rd, wr); + UOp u; + u.op = op; + u.o = std::move(o); + u.n = n; + ops.push_back(std::move(u)); + } + /* A weight under its checkpoint name, declared at `shape` (a conv kernel read flat). */ + rad_weight wt(const char* src, std::initializer_list shape) { + if (map_copy(b, src, src) < 0) return 0; + return decl_w(b, src, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(grp)); + } + + /* y = x W^T (+ bias) (+ res): gemm_nt without a bias, gemm_nt_bias with one. */ + V lin(const V& x, int64_t N, const char* src, bool bias, const V* res = nullptr) { + V y = buf(x.lvl, N); + const int64_t K = x.w(); + rad_weight w = wt(nm->ckpt("%s.weight", src), { N, K }); + if (!bias) { + rad_op op = RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("N", N), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + add(op, { R(x), W(w), R(y) }, x.lvl, { x.buf }, { y.buf }); + return y; + } + rad_weight bw = wt(nm->ckpt("%s.bias", src), { N }); + rad_op op = RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("N", N), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + if (res) + add(op, { R(x), W(w), W(bw), R(*res), R(y) }, x.lvl, { x.buf, res->buf }, { y.buf }); + else + add(op, { R(x), W(w), W(bw), Kd(Opd::NONE), R(y) }, x.lvl, { x.buf }, { y.buf }); + return y; + } + /* A 3x3 convolution with a bias (+ res): im2col_nhwc, then a GEMM over the weight read as + * [cout, cin * 9], the checkpoint's order. `stride` 2 halves the side, `up` 2 doubles it. */ + V conv3(const V& x, int64_t cout, const char* src, int stride, int up, const V* res = nullptr) { + const int lo = x.lvl + (stride == 2 ? 1 : 0) - (up == 2 ? 1 : 0); + const int64_t cin = x.pitch; + V col = buf(lo, cin * 9); + rad_op op = RAD_OP(b, "im2col_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, cap(lo)), RAD_INT("cin", cin), + RAD_INT("k", 3), RAD_INT("stride", stride), + RAD_STR("pad", "same"), RAD_INT("up", up), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + add(op, { I(x), R(col) }, lo, { x.buf }, { col.buf }); + V y = buf(lo, cout); + rad_weight w = wt(nm->ckpt("%s.weight", src), { cout, cin * 9 }); + rad_weight bw = wt(nm->ckpt("%s.bias", src), { cout }); + rad_op g = RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, cap(lo)), RAD_INT("N", cout), + RAD_INT("K", cin * 9), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + if (res) + add(g, { R(col), W(w), W(bw), R(*res), R(y) }, lo, { col.buf, res->buf }, { y.buf }); + else + add(g, { R(col), W(w), W(bw), Kd(Opd::NONE), R(y) }, lo, { col.buf }, { y.buf }); + return y; + } + /* A direct convolution (conv_in and the output's, 4 channels on one side). */ + V conv_direct(const Opd& in, int lvl, int64_t cin, int64_t cout, const char* src, + const Opd* out = nullptr) { + V y{}; + y.lvl = lvl; + y.pitch = cout; + if (!out) y = buf(lvl, cout); + rad_weight w = wt(nm->ckpt("%s.weight", src), { cout, cin, 3, 3 }); + rad_weight bw = wt(nm->ckpt("%s.bias", src), { cout }); + rad_op op = RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, cap(lvl)), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", 3), RAD_INT("stride", 1), + RAD_STR("pad", "same"), RAD_INT("up", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + rw(b, op, { in.v.buf }, { out ? out->v.buf : y.buf }); + UOp u; + u.op = op; + u.o = { in, W(w), W(bw), out ? *out : I(y) }; + u.n = lvl; + ops.push_back(std::move(u)); + return y; + } + /* GroupNorm(32) with its affine, then SiLU or not. */ + V gn(const V& x, const char* src, double eps, bool silu) { + V y = buf(x.lvl, x.pitch); + rad_weight w = wt(nm->ckpt("%s.weight", src), { x.pitch }); + rad_weight bw = wt(nm->ckpt("%s.bias", src), { x.pitch }); + rad_op op = RAD_OP(b, "group_norm", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("n", x.pitch), + RAD_INT("groups", kGroups), RAD_F64("eps", eps), + RAD_STR("act", silu ? "silu" : "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + add(op, { R(x), W(w), W(bw), Kd(Opd::NONE), Kd(Opd::STATS), R(y) }, x.lvl, + { x.buf, stats }, { y.buf, stats }); + return y; + } + V ln(const V& x, const char* src) { + V y = buf(x.lvl, x.pitch); + rad_weight w = wt(nm->ckpt("%s.weight", src), { x.pitch }); + rad_weight bw = wt(nm->ckpt("%s.bias", src), { x.pitch }); + rad_op op = RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("n", x.pitch), + RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + add(op, { R(x), W(w), W(bw), R(y) }, x.lvl, { x.buf }, { y.buf }); + return y; + } + /* y = x + e, e one row broadcast along x's rows. */ + V add_row(const V& x, const V& e) { + V y = buf(x.lvl, x.pitch); + rad_op op = RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("n", x.pitch), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + add(op, { R(x), R(e), R(y) }, x.lvl, { x.buf, e.buf }, { y.buf }); + return y; + } + /* dst's columns [col, col + x.w()) = x: a skip connection's half of a concatenation. */ + void copy(const V& x, const V& dst, int64_t col) { + V d = dst; + d.col = col; + d.width = x.w(); + rad_op op = RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("n", x.w()), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS); + add(op, { R(x), R(d) }, x.lvl, { x.buf }, { dst.buf }); + } + /* {0, n}: the bounds of one sequence of the entry's rows at `lvl`, off the iota table. */ + V cu(int lvl) { + V y; + y.lvl = kRowsTwo; + y.pitch = 1; + y.buf = decl_b(b, nm->f("unet.cu%d", n_buf++), RAD_I32, { 2 }); + rad_op op = RAD_OP(b, "cu_repeat", RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 1)), + RAD_NOWEIGHTS); + Opd it = Kd(Opd::IOTA); + it.v.lvl = lvl; + add(op, { it, R(y) }, kRowsTwo, { iota }, { y.buf }); + return y; + } + /* Self attention over the entry's rows, 64-wide heads. */ + V attn(const V& q, const V& k, const V& v, const V& cu_q) { + V y = buf(q.lvl, q.w()); + rad_op op = RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, cap(q.lvl)), RAD_INT("head_dim", 64), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 0.125)), + RAD_NOWEIGHTS); + add(op, { R(q), R(k), R(v), R(cu_q), R(y) }, q.lvl, { q.buf, k.buf, v.buf, cu_q.buf }, + { y.buf }); + return y; + } + /* Cross attention of the entry's rows over its conditioning's. */ + V xattn(const V& q, const V& k, const V& v, const V& cu_q, const V& cu_k) { + V y = buf(q.lvl, q.w()); + rad_op op = RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, cap(q.lvl)), RAD_INT("head_dim", 64), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 0.125)), + RAD_NOWEIGHTS); + add(op, { R(q), R(k), R(v), R(cu_q), R(cu_k), R(y) }, q.lvl, + { q.buf, k.buf, v.buf, cu_q.buf, cu_k.buf }, { y.buf }); + return y; + } + /* GEGLU: the projection's first half times gelu (erf) of its second. */ + V geglu(const V& p) { + const int64_t n = p.pitch / 2; + V y = buf(p.lvl, n); + V a = p, g = p; + a.col = 0; a.width = n; + g.col = n; g.width = n; + rad_op op = RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, cap(p.lvl)), RAD_INT("n", n), + RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + add(op, { R(g), R(a), R(y) }, p.lvl, { p.buf }, { y.buf }); + return y; + } + + /* ---- blocks */ + /* in_layers (GroupNorm, SiLU, conv), the time embedding's projection added per channel, + * out_layers (GroupNorm, SiLU, conv) plus the input or its 1x1 skip convolution. */ + V resblock(const V& x, int64_t cout, const char* pre, const V& emb_s) { + V t = gn(x, nm->ckpt("%s.in_layers.0", pre), 1e-5, true); + V h = conv3(t, cout, nm->ckpt("%s.in_layers.2", pre), 1, 1); + V e = lin(emb_s, cout, nm->ckpt("%s.emb_layers.1", pre), true); + h = add_row(h, e); + V t2 = gn(h, nm->ckpt("%s.out_layers.0", pre), 1e-5, true); + V skip = x; + if (x.pitch != cout) skip = lin(x, cout, nm->ckpt("%s.skip_connection", pre), true); + return conv3(t2, cout, nm->ckpt("%s.out_layers.3", pre), 1, 1, &skip); + } + /* SpatialTransformer with linear projections: GroupNorm, proj_in, `depth` blocks of self + * attention, cross attention and GEGLU each added back, proj_out plus the input. */ + V transformer(const V& x, const char* pre, int depth, const V& ctx, const V& cu_q, + const V& cu_k) { + const int64_t C = x.pitch; + V t = gn(x, nm->ckpt("%s.norm", pre), 1e-6, false); + V h = lin(t, C, nm->ckpt("%s.proj_in", pre), true); + for (int d = 0; d < depth; ++d) { + const char* bp = nm->ckpt("%s.transformer_blocks.%d", pre, d); + V a = ln(h, nm->ckpt("%s.norm1", bp)); + V q = lin(a, C, nm->ckpt("%s.attn1.to_q", bp), false); + V k = lin(a, C, nm->ckpt("%s.attn1.to_k", bp), false); + V v = lin(a, C, nm->ckpt("%s.attn1.to_v", bp), false); + V o = attn(q, k, v, cu_q); + h = lin(o, C, nm->ckpt("%s.attn1.to_out.0", bp), true, &h); + a = ln(h, nm->ckpt("%s.norm2", bp)); + q = lin(a, C, nm->ckpt("%s.attn2.to_q", bp), false); + k = lin(ctx, C, nm->ckpt("%s.attn2.to_k", bp), false); + v = lin(ctx, C, nm->ckpt("%s.attn2.to_v", bp), false); + o = xattn(q, k, v, cu_q, cu_k); + h = lin(o, C, nm->ckpt("%s.attn2.to_out.0", bp), true, &h); + a = ln(h, nm->ckpt("%s.norm3", bp)); + V p = lin(a, 8 * C, nm->ckpt("%s.ff.net.0.proj", bp), true); + V f = geglu(p); + h = lin(f, C, nm->ckpt("%s.ff.net.2", bp), true, &h); + } + return lin(h, C, nm->ckpt("%s.proj_out", pre), true, &x); + } + /* [a | b] along the channels. */ + V concat(const V& a, const V& s) { + V y = buf(a.lvl, a.pitch + s.pitch); + copy(a, y, 0); + copy(s, y, a.pitch); + return y; + } + + RadOperand opd(RadCtx* c, const Opd& o, const Geo& g) const; + void issue(RadCtx* c, const Geo& g) const; +}; + +/* ================================================================== the model */ +struct Model { + Names nm{""}; + std::string pred = "eps"; + bool zero_snr = false; + + /* ---- the conditioning */ + TextEnc te1{}, te2{}; + rad_buf b_pos = 0, b_wcu = 0, b_zero = 0, b_ctx = 0, b_pooled = 0; + rad_op op_pos = 0, op_wcu = 0, op_zero = 0, op_store = 0, op_pstore = 0; + + /* ---- the per-image state and the stores (PERSIST) */ + rad_buf b_state = 0, b_hist = 0, b_prev = 0, b_store = 0, b_pstore = 0; + rad_buf b_xin = 0, b_eps = 0, b_iota = 0, b_zf = 0; + rad_op op_iota = 0, op_zf = 0, op_kdin = 0, op_kdstep = 0; + + /* ---- the time and size embeddings, per entry */ + rad_weight w_t1 = 0, b_t1 = 0, w_t2 = 0, b_t2 = 0, w_l1 = 0, b_l1 = 0, w_l2 = 0, b_l2 = 0; + rad_buf b_tproj = 0, b_te1 = 0, b_te1s = 0, b_temb = 0, b_add = 0, b_le1 = 0, b_le1s = 0; + rad_buf b_emb = 0, b_embs = 0; + rad_op op_tproj = 0, op_t1 = 0, op_ts = 0, op_t2 = 0, op_pool = 0, op_szo = 0, op_szc = 0, + op_szt = 0, op_l1 = 0, op_ls = 0, op_l2 = 0, op_es = 0; + + /* ---- the UNet */ + Net net{}; + + /* ---- the decoder */ + Vae dec{}; + VImg dec_out{}; + rad_buf b_dlf = 0, b_decin = 0, b_img = 0; + rad_op op_dscale = 0, op_dcast = 0, op_rgb = 0; +}; + +static Model g_model[MAX_RANKS]; + +/* ================================================================== the recorded UNet's issue */ +RadOperand Net::opd(RadCtx* c, const Opd& o, const Geo& g) const { + switch (o.kind) { + case Opd::NONE: return RAD_NONE; + case Opd::WEIGHT: return RAD_W(o.w); + case Opd::ROWS: { + /* The context is the entry's conditioning where the store keeps it. */ + if (o.v.buf == store) return brow_slice(store, g.store_row, g.cond, kCtx); + const int64_t r = g.rows(o.v.lvl); + if (o.v.width && o.v.width != o.v.pitch) return bcol(o.v.buf, o.v.col, o.v.width, r); + return brows(o.v.buf, r); + } + case Opd::IMG: { + const int l = o.v.lvl; + return RAD_P_T2(rad_buf_ptr(c, o.v.buf), RAD_BF16, g.h >> l, (g.w >> l) * o.v.pitch); + } + case Opd::XIN: + return RAD_P_T2((const char*)rad_buf_ptr(c, xin) + g.row0 * kLatC * 2, RAD_BF16, g.h, + g.w * kLatC); + case Opd::EPS: + return RAD_P_T2((char*)rad_buf_ptr(c, eps) + g.row0 * kLatC * 2, RAD_BF16, g.h, + g.w * kLatC); + case Opd::IOTA: return brow_slice(iota, g.rows(o.v.lvl), 1, 1); + case Opd::STATS: return RAD_P_T2(rad_buf_ptr(c, stats), RAD_F32, 1, kGnStats); + } + return RAD_NONE; +} + +void Net::issue(RadCtx* c, const Geo& g) const { + RadOperand a[8]; + for (const UOp& u : ops) { + const int n = (int)u.o.size(); + for (int i = 0; i < n; ++i) a[i] = opd(c, u.o[(size_t)i], g); + rad_issue(c, u.op, a, n, g.rows(u.n)); + } +} + +/* ================================================================== declare */ +static rad_weight wcopy(RadBuilder* b, const char* src, std::initializer_list shape, + int access, int group, bool mapped = false) { + if (!mapped && map_copy(b, src, src) < 0) return 0; + return decl_w(b, src, RAD_BF16, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A linear over `rows` rows: gemm_nt_bias with a bias (and a residual `res` added in), gemm_nt + * without. */ +static rad_op dense(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, + rad_weight bias, rad_buf in, rad_buf out, rad_buf res = 0) { + rad_op h = bias ? RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)) + : RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + if (res) return rw(b, h, { in, res }, { out }); + return rw(b, h, { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in, + rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op tstep_embed(RadBuilder* b, int64_t rows, int64_t n, rad_buf out) { + return rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("scale", 1.0), + RAD_F64("max_period", 10000.0), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { out }); +} + +/* One CLIP text encoder over T rows: token and position embeddings, `L` pre-norm layers, the + * context's columns copied out after layer `tap`. */ +static int declare_text(RadBuilder* b, Model& m, TextEnc& E, const char* root, int grp, + int64_t D, int64_t F, int64_t L, int64_t tap, bool pooled) { + Names& nm = m.nm; + const int64_t T = kCondRows; + const char* tm = nm.ckpt("%s.text_model", root); + E.D = D; + E.F = F; + E.L = L; + E.tap = tap; + E.tok = wcopy(b, nm.ckpt("%s.embeddings.token_embedding.weight", tm), { 49408, D }, + RAD_ACCESS_VOCAB, grp); + E.pos = wcopy(b, nm.ckpt("%s.embeddings.position_embedding.weight", tm), { kWin, D }, + RAD_ACCESS_PER_TOKEN, grp); + if (!E.tok || !E.pos) return RAD_E_INVAL; + const char* sc = nm.f("te%d", grp == kGrpTe1 ? 1 : 2); + E.x = decl_b(b, nm.f("%s.x", sc), RAD_BF16, { T, D }); + E.pe = decl_b(b, nm.f("%s.pe", sc), RAD_BF16, { T, D }); + E.h = decl_b(b, nm.f("%s.h", sc), RAD_BF16, { T, D }); + E.q = decl_b(b, nm.f("%s.q", sc), RAD_BF16, { T, D }); + E.k = decl_b(b, nm.f("%s.k", sc), RAD_BF16, { T, D }); + E.v = decl_b(b, nm.f("%s.v", sc), RAD_BF16, { T, D }); + E.a = decl_b(b, nm.f("%s.attn", sc), RAD_BF16, { T, D }); + E.f1 = decl_b(b, nm.f("%s.fc1", sc), RAD_BF16, { T, F }); + E.f2 = decl_b(b, nm.f("%s.act", sc), RAD_BF16, { T, F }); + auto embed = [&](rad_weight w, int64_t vocab, rad_buf ids, rad_buf out) { + rad_op op = RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", D), + RAD_INT("n_vocab", vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(w)); + if (ids) return rw(b, op, { ids }, { out }); + return rw(b, op, {}, { out }); + }; + E.op_tok = embed(E.tok, 49408, 0, E.x); + /* Padding rows that read token 0 (bigG's tokenizer pads with "!"). */ + if (pooled) E.op_pad = embed(E.tok, 49408, m.b_zero, E.x); + E.op_pos = embed(E.pos, kWin, m.b_pos, E.pe); + E.op_pe = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { E.x, E.pe }, { E.x }); + if (!E.op_tok || !E.op_pos || !E.op_pe || (pooled && !E.op_pad)) return RAD_E_INVAL; + E.layers.resize((size_t)L); + for (int64_t l = 0; l < L; ++l) { + TextLayer& Y = E.layers[(size_t)l]; + const char* lp = nm.ckpt("%s.encoder.layers.%lld", tm, (long long)l); + const int g = grp; + auto w = [&](const char* fmt, std::initializer_list shape) { + return wcopy(b, nm.ckpt(fmt, lp), shape, RAD_ACCESS_PER_TOKEN, g); + }; + Y.ln1w = w("%s.layer_norm1.weight", { D }); + Y.ln1b = w("%s.layer_norm1.bias", { D }); + Y.qw = w("%s.self_attn.q_proj.weight", { D, D }); + Y.qb = w("%s.self_attn.q_proj.bias", { D }); + Y.kw = w("%s.self_attn.k_proj.weight", { D, D }); + Y.kb = w("%s.self_attn.k_proj.bias", { D }); + Y.vw = w("%s.self_attn.v_proj.weight", { D, D }); + Y.vb = w("%s.self_attn.v_proj.bias", { D }); + Y.ow = w("%s.self_attn.out_proj.weight", { D, D }); + Y.ob = w("%s.self_attn.out_proj.bias", { D }); + Y.ln2w = w("%s.layer_norm2.weight", { D }); + Y.ln2b = w("%s.layer_norm2.bias", { D }); + Y.f1w = w("%s.mlp.fc1.weight", { F, D }); + Y.f1b = w("%s.mlp.fc1.bias", { F }); + Y.f2w = w("%s.mlp.fc2.weight", { D, F }); + Y.f2b = w("%s.mlp.fc2.bias", { D }); + if (!Y.ln1w || !Y.ln1b || !Y.qw || !Y.qb || !Y.kw || !Y.kb || !Y.vw || !Y.vb || !Y.ow || + !Y.ob || !Y.ln2w || !Y.ln2b || !Y.f1w || !Y.f1b || !Y.f2w || !Y.f2b) + return RAD_E_INVAL; + auto lnorm = [&](rad_weight lw, rad_weight lb) { + return rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(lw, lb)), + { E.x }, { E.h }); + }; + Y.op_ln1 = lnorm(Y.ln1w, Y.ln1b); + Y.op_q = dense(b, T, D, D, Y.qw, Y.qb, E.h, E.q); + Y.op_k = dense(b, T, D, D, Y.kw, Y.kb, E.h, E.k); + Y.op_v = dense(b, T, D, D, Y.vw, Y.vb, E.h, E.v); + Y.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", 64), + RAD_INT("gqa", 1), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 0.125), + RAD_INT("max_seqlen", kWin)), + RAD_NOWEIGHTS), + { E.q, E.k, E.v, m.b_wcu }, { E.a }); + Y.op_o = dense(b, T, D, D, Y.ow, Y.ob, E.a, E.x, E.x); + Y.op_ln2 = lnorm(Y.ln2w, Y.ln2b); + Y.op_f1 = dense(b, T, F, D, Y.f1w, Y.f1b, E.h, E.f1); + Y.op_act = unary(b, E.quick ? "gelu_quick" : "gelu", T, F, E.f1, E.f2); + Y.op_f2 = dense(b, T, D, F, Y.f2w, Y.f2b, E.f2, E.x, E.x); + if (!Y.op_ln1 || !Y.op_q || !Y.op_k || !Y.op_v || !Y.op_attn || !Y.op_o || !Y.op_ln2 || + !Y.op_f1 || !Y.op_act || !Y.op_f2) + return RAD_E_INVAL; + if (l == tap) + E.op_tap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { E.x }, { m.b_ctx }); + } + if (!E.op_tap) return RAD_E_INVAL; + if (!pooled) return RAD_OK; + /* The pooled vector: the first window's end-of-text row through the final norm and the + * projection. */ + E.fnw = wcopy(b, nm.ckpt("%s.final_layer_norm.weight", tm), { D }, RAD_ACCESS_PER_TOKEN, + grp); + E.fnb = wcopy(b, nm.ckpt("%s.final_layer_norm.bias", tm), { D }, RAD_ACCESS_PER_TOKEN, + grp); + E.proj = wcopy(b, nm.ckpt("%s.text_projection.weight", root), { kPooled, D }, + RAD_ACCESS_PER_TOKEN, grp); + if (!E.fnw || !E.fnb || !E.proj) return RAD_E_INVAL; + E.e1 = decl_b(b, nm.f("%s.eos", sc), RAD_BF16, { 1, D }); + E.e2 = decl_b(b, nm.f("%s.eos_norm", sc), RAD_BF16, { 1, D }); + E.op_eos = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { E.x, m.b_pos }, { E.e1 }); + E.op_fn = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", D), RAD_F64("eps", 1e-5), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.fnw, E.fnb)), + { E.e1 }, { E.e2 }); + E.op_proj = dense(b, 1, kPooled, D, E.proj, 0, E.e2, m.b_pooled); + return E.op_eos && E.op_fn && E.op_proj ? RAD_OK : RAD_E_INVAL; +} + +static int declare_cond(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t T = kCondRows; + /* Positions restart in every window; the windows' bounds; a row of token-0 ids. */ + m.b_pos = decl_b(b, nm.f("cond.pos"), RAD_I32, { T }); + m.b_wcu = decl_b(b, nm.f("cond.cu"), RAD_I32, { kMaxWin + 1 }); + m.b_zero = decl_b(b, nm.f("cond.zero_ids"), RAD_I32, { kWin }); + m.b_ctx = decl_b(b, nm.f("cond.ctx"), RAD_BF16, { T, kCtx }); + m.b_pooled = decl_b(b, nm.f("cond.pooled"), RAD_BF16, { 1, kPooled }); + m.op_pos = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("start", 0), + RAD_INT("step", 1), RAD_INT("period", kWin)), + RAD_NOWEIGHTS), + {}, { m.b_pos }); + m.op_wcu = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kMaxWin + 1), RAD_INT("start", 0), + RAD_INT("step", kWin)), + RAD_NOWEIGHTS), + {}, { m.b_wcu }); + m.op_zero = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kWin), RAD_INT("start", 0), + RAD_INT("step", 0)), + RAD_NOWEIGHTS), + {}, { m.b_zero }); + if (!m.op_pos || !m.op_wcu || !m.op_zero) return RAD_E_INVAL; + m.te1.quick = true; + m.te1.ctx_col = 0; + RAD_ARCH_TRY(declare_text(b, m, m.te1, kTe1, kGrpTe1, 768, 3072, 11, 10, false)); + m.te2.quick = false; + m.te2.ctx_col = 768; + RAD_ARCH_TRY(declare_text(b, m, m.te2, kTe2, kGrpTe2, 1280, 5120, 32, 30, true)); + /* Into every lane of the request at this branch: lane l's branch r at row (2 l + r) of the + * stores. */ + m.op_store = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kCtx), + RAD_INT("stride", 2 * (int64_t)kCondRows), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ctx, m.b_store }, { m.b_store }); + m.op_pstore = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", kPooled), + RAD_INT("stride", 2), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_pooled, m.b_pstore }, { m.b_pstore }); + return m.op_store && m.op_pstore ? RAD_OK : RAD_E_INVAL; +} + +/* The time embedding (the timestep's sinusoid through time_embed) plus the added embedding (the + * pooled vector beside the image size's three sinusoid pairs, through label_emb), and its SiLU, + * which every residual block projects. One row an entry. */ +static int declare_emb(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int g = kGrpUnet; + auto w = [&](const char* fmt, std::initializer_list shape) { + return wcopy(b, nm.ckpt(fmt, kUnet), shape, RAD_ACCESS_PER_TOKEN, g); + }; + m.w_t1 = wcopy(b, nm.ckpt("%s.time_embed.0.weight", kUnet), { kTemb, 320 }, + RAD_ACCESS_PER_TOKEN, g, true); + m.b_t1 = w("%s.time_embed.0.bias", { kTemb }); + m.w_t2 = w("%s.time_embed.2.weight", { kTemb, kTemb }); + m.b_t2 = w("%s.time_embed.2.bias", { kTemb }); + m.w_l1 = w("%s.label_emb.0.0.weight", { kTemb, kAdd }); + m.b_l1 = w("%s.label_emb.0.0.bias", { kTemb }); + m.w_l2 = w("%s.label_emb.0.2.weight", { kTemb, kTemb }); + m.b_l2 = w("%s.label_emb.0.2.bias", { kTemb }); + if (!m.w_t1 || !m.b_t1 || !m.w_t2 || !m.b_t2 || !m.w_l1 || !m.b_l1 || !m.w_l2 || !m.b_l2) + return RAD_E_INVAL; + m.b_tproj = decl_b(b, nm.f("emb.tproj"), RAD_BF16, { 1, 320 }); + m.b_te1 = decl_b(b, nm.f("emb.t1"), RAD_BF16, { 1, kTemb }); + m.b_te1s = decl_b(b, nm.f("emb.t1s"), RAD_BF16, { 1, kTemb }); + m.b_temb = decl_b(b, nm.f("emb.temb"), RAD_BF16, { 1, kTemb }); + m.b_add = decl_b(b, nm.f("emb.add"), RAD_BF16, { 1, kAdd }); + m.b_le1 = decl_b(b, nm.f("emb.l1"), RAD_BF16, { 1, kTemb }); + m.b_le1s = decl_b(b, nm.f("emb.l1s"), RAD_BF16, { 1, kTemb }); + m.b_emb = decl_b(b, nm.f("emb.emb"), RAD_BF16, { 1, kTemb }); + m.b_embs = decl_b(b, nm.f("emb.emb_silu"), RAD_BF16, { 1, kTemb }); + m.op_tproj = tstep_embed(b, 1, 320, m.b_tproj); + m.op_t1 = dense(b, 1, kTemb, 320, m.w_t1, m.b_t1, m.b_tproj, m.b_te1); + m.op_ts = unary(b, "silu", 1, kTemb, m.b_te1, m.b_te1s); + m.op_t2 = dense(b, 1, kTemb, kTemb, m.w_t2, m.b_t2, m.b_te1s, m.b_temb); + m.op_pool = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", kPooled), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_pstore }, { m.b_add }); + /* (height, width), (0, 0), (height, width): each value's 256-wide sinusoid, laid end to end + * after the pooled vector. */ + m.op_szo = tstep_embed(b, 2, 256, m.b_add); + m.op_szc = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("n", 256), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_zf }, { m.b_add }); + m.op_szt = tstep_embed(b, 2, 256, m.b_add); + m.op_l1 = dense(b, 1, kTemb, kAdd, m.w_l1, m.b_l1, m.b_add, m.b_le1); + m.op_ls = unary(b, "silu", 1, kTemb, m.b_le1, m.b_le1s); + m.op_l2 = dense(b, 1, kTemb, kTemb, m.w_l2, m.b_l2, m.b_le1s, m.b_emb, m.b_temb); + m.op_es = unary(b, "silu", 1, kTemb, m.b_emb, m.b_embs); + return m.op_tproj && m.op_t1 && m.op_ts && m.op_t2 && m.op_pool && m.op_szo && m.op_szc && + m.op_szt && m.op_l1 && m.op_ls && m.op_l2 && m.op_es + ? RAD_OK : RAD_E_INVAL; +} + +/* The UNet, in the order a step runs it. */ +static int declare_unet(RadBuilder* b, Model& m) { + Net& n = m.net; + Names& nm = m.nm; + n.b = b; + n.nm = &nm; + n.stats = decl_b(b, nm.f("unet.gn_stats"), RAD_F32, { kGnStats }); + n.iota = m.b_iota; + n.store = m.b_store; + n.xin = m.b_xin; + n.eps = m.b_eps; + V emb_s{}; + emb_s.buf = m.b_embs; + emb_s.lvl = kRowsOne; + emb_s.pitch = kTemb; + V ctx{}; + ctx.buf = m.b_store; + ctx.lvl = kRowsCond; + ctx.pitch = kCtx; + const char* U = kUnet; + /* Every op's sequence bounds, off the iota table. */ + const V cu1 = n.cu(1), cu2 = n.cu(2), cuc = n.cu(kRowsCond); + /* ---- the input blocks; each output is kept for its skip connection */ + n.grp = kGrpUnet + 1; + Opd xin = Net::Kd(Opd::XIN); + xin.v.buf = m.b_xin; + V h = n.conv_direct(xin, 0, kLatC, 320, nm.ckpt("%s.input_blocks.0.0", U)); + std::vector skips{ h }; + struct In { int64_t c; int depth; bool down; }; + const In ins[] = { { 320, 0, false }, { 320, 0, false }, { 320, 0, true }, + { 640, 2, false }, { 640, 2, false }, { 640, 0, true }, + { 1280, 10, false }, { 1280, 10, false } }; + auto st = [&](const V& x, const char* pre, int depth) { + const V& cq = x.lvl == 1 ? cu1 : cu2; + return n.transformer(x, pre, depth, ctx, cq, cuc); + }; + for (int i = 1; i <= 8; ++i) { + const In& s = ins[i - 1]; + n.grp = kGrpUnet + 1 + i; + if (s.down) { + h = n.conv3(h, h.pitch, nm.ckpt("%s.input_blocks.%d.0.op", U, i), 2, 1); + } else { + h = n.resblock(h, s.c, nm.ckpt("%s.input_blocks.%d.0", U, i), emb_s); + if (s.depth) h = st(h, nm.ckpt("%s.input_blocks.%d.1", U, i), s.depth); + } + skips.push_back(h); + } + /* ---- the middle block */ + n.grp = kGrpUnet + 10; + h = n.resblock(h, 1280, nm.ckpt("%s.middle_block.0", U), emb_s); + h = st(h, nm.ckpt("%s.middle_block.1", U), 10); + h = n.resblock(h, 1280, nm.ckpt("%s.middle_block.2", U), emb_s); + /* ---- the output blocks: the matching input block's output concatenated after h */ + struct Out { int64_t c; int depth; bool up; }; + const Out outs[] = { { 1280, 10, false }, { 1280, 10, false }, { 1280, 10, true }, + { 640, 2, false }, { 640, 2, false }, { 640, 2, true }, + { 320, 0, false }, { 320, 0, false }, { 320, 0, false } }; + for (int i = 0; i < 9; ++i) { + const Out& s = outs[i]; + n.grp = kGrpUnet + 11 + i; + const V skip = skips.back(); + skips.pop_back(); + V cat = n.concat(h, skip); + h = n.resblock(cat, s.c, nm.ckpt("%s.output_blocks.%d.0", U, i), emb_s); + int sub = 1; + if (s.depth) h = st(h, nm.ckpt("%s.output_blocks.%d.%d", U, i, sub++), s.depth); + if (s.up) h = n.conv3(h, h.pitch, nm.ckpt("%s.output_blocks.%d.%d.conv", U, i, sub), 1, 2); + } + /* ---- the output: GroupNorm, SiLU, conv to the latent's channels */ + n.grp = kGrpUnet + 20; + V o = n.gn(h, nm.ckpt("%s.out.0", U), 1e-5, true); + Opd eps = Net::Kd(Opd::EPS); + eps.v.buf = m.b_eps; + eps.v.lvl = 0; + eps.v.pitch = kLatC; + Opd oi = Net::I(o); + n.conv_direct(oi, 0, 320, kLatC, nm.ckpt("%s.out.2", U), &eps); + for (const UOp& u : n.ops) if (!u.op) return RAD_E_INVAL; + return RAD_OK; +} + +/* The decoder: the f32 latent divided by the scaling factor, to bf16, then the VAE's decoder in + * diffusers' AutoencoderKL names (GroupNorm residual blocks, a mid-block attention, three 2x + * nearest upsamplings). */ +static int declare_decoder(RadBuilder* b, Model& m) { + Vae& v = m.dec; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "vdec"; + v.down = false; + v.first_group = kGrpVae; + v.base_px = kMaxImageTokens; + const int64_t NT = kMaxImageTokens; + m.b_dlf = decl_b(b, nm.f("vdec.lat_f32"), RAD_F32, { NT, kLatC }); + m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { NT, kLatC }); + char mul[64], zero[16]; + const double s = 1.0 / kVaeScale; + std::snprintf(mul, sizeof mul, "%.9g %.9g %.9g %.9g", s, s, s, s); + std::snprintf(zero, sizeof zero, "0 0 0 0"); + static thread_local std::string smul, szero; + smul = mul; + szero = zero; + m.op_dscale = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", kLatC), + RAD_STR("mul", smul.c_str()), + RAD_STR("add", szero.c_str()), + RAD_STR("mode", "fma"), RAD_STR("dtype", "f32"), + RAD_INT("round", 0)), + RAD_NOWEIGHTS), + { m.b_state, m.b_prev }, { m.b_dlf }); + m.op_dcast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", kLatC), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_dlf }, { m.b_decin }); + if (!m.op_dscale || !m.op_dcast) return RAD_E_INVAL; + const int64_t ch[4] = { 512, 512, 256, 128 }; + const double eps = 1e-6; + VImg x{ m.b_decin, kLatC, 0 }; + x = v.conv(x, kLatC, 1, 1, 1, "same", "vae.post_quant_conv"); + x = v.conv(x, ch[0], 3, 1, 1, "same", "vae.decoder.conv_in"); + x = v.resblock_gn(x, x.ch, "vae.decoder.mid_block.resnets.0", kGroups, eps); + x = v.attention_gn(x, "vae.decoder.mid_block.attentions.0", kGroups, eps); + x = v.resblock_gn(x, x.ch, "vae.decoder.mid_block.resnets.1", kGroups, eps); + for (int i = 0; i < 4; ++i) { + for (int r = 0; r < 3; ++r) + x = v.resblock_gn(x, ch[i], nm.f("vae.decoder.up_blocks.%d.resnets.%d", i, r), kGroups, + eps); + if (i < 3) + x = v.conv(x, x.ch, 3, 1, 2, "same", + nm.f("vae.decoder.up_blocks.%d.upsamplers.0.conv", i)); + } + x = v.gnorm(x, true, "vae.decoder.conv_norm_out", kGroups, eps); + m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "vae.decoder.conv_out"); + if (!m.dec_out.buf) return RAD_E_INVAL; + for (const VOp& o : v.ops) if (!o.op) return RAD_E_INVAL; + const int64_t px = NT * 64; + m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST); + m.op_rgb = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_img }); + return m.op_rgb ? RAD_OK : RAD_E_INVAL; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + if (ctx->world_size > 1) { + fprintf(stderr, "radiance: sdxl runs on one card; serve it with a tensor-parallel size " + "of 1\n"); + return RAD_E_UNSUPPORTED; + } + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + Names& nm = m.nm; + m.pred = rad_meta_gets(meta, "sdxl.prediction", "eps"); + m.zero_snr = rad_meta_geti(meta, "sdxl.zero_snr", 0) != 0; + if (m.pred != "eps" && m.pred != "v") { + fprintf(stderr, "radiance: sdxl: prediction '%s' is neither eps nor v\n", m.pred.c_str()); + return RAD_E_UNSUPPORTED; + } + /* The weights are served bf16; the release's f16 is cast by the recipe. The first UNet weight + * is mapped here and declared with the embeddings. */ + { + const char* probe = nm.ckpt("%s.time_embed.0.weight", kUnet); + if (map_copy(b, probe, probe) < 0) return RAD_E_INVAL; + const uint32_t dt = weight_codes_dtype(b, probe, RAD_BF16); + if (dt != RAD_BF16) { + fprintf(stderr, "radiance: sdxl: the UNet is stored %s; convert with " + "data/recipes/sdxl-bf16.recipe, which casts the release to bf16\n", + rad_dtype_name(dt)); + return RAD_E_UNSUPPORTED; + } + } + const int64_t max_img = std::max(ctx->max_tok, kMaxImageTokens); + const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens; + m.b_state = decl_b(b, nm.f("lat_state"), RAD_F32, { lane_rows, kLatC }, RAD_BUF_PERSIST); + m.b_hist = decl_b(b, nm.f("lat_hist"), RAD_F32, { lane_rows, kLatC }, RAD_BUF_PERSIST); + m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_F32, { lane_rows, kLatC }, RAD_BUF_PERSIST); + m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16, + { 2 * (int64_t)kMaxLanes * kCondRows, kCtx }, RAD_BUF_PERSIST); + m.b_pstore = decl_b(b, nm.f("pooled_store"), RAD_BF16, { 2 * (int64_t)kMaxLanes, kPooled }, + RAD_BUF_PERSIST); + m.b_xin = decl_b(b, nm.f("unet_in"), RAD_BF16, { max_img, kLatC }, RAD_BUF_PERSIST); + m.b_eps = decl_b(b, nm.f("unet_out"), RAD_BF16, { max_img, kLatC }, RAD_BUF_PERSIST); + m.b_iota = decl_b(b, nm.f("iota"), RAD_I32, { kMaxImageTokens + 1 }, RAD_BUF_PERSIST); + m.b_zf = decl_b(b, nm.f("zeros_f32"), RAD_F32, { 1, 2 }, RAD_BUF_PERSIST); + /* ---- adapter key names: kohya's `lora_unet_` over the UNet's own single-file paths, and + * `lora_te1_` / `lora_te2_` over the two text encoders, whose layers are named as + * transformers' CLIPTextModel names them in both. */ + RAD_ARCH_TRY(lora_names(b, "model.diffusion_model.", kLoraDiffusionSpellings, {})); + RAD_ARCH_TRY(lora_names(b, "conditioner.embedders.0.transformer.", "lora_te1_", {})); + RAD_ARCH_TRY(lora_names(b, "conditioner.embedders.1.transformer.", "lora_te2_", {})); + RAD_ARCH_TRY(declare_cond(b, m)); + + /* ---- a denoising pass: the tables, the model input, then per entry the embeddings and the + * UNet, then the sampler */ + m.op_iota = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kMaxImageTokens + 1), + RAD_INT("start", 0), RAD_INT("step", 1)), + RAD_NOWEIGHTS), + {}, { m.b_iota }); + m.op_zf = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 2), + RAD_STR("dtype", "f32"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_zf }); + m.op_kdin = rw(b, RAD_OP(b, "kd_input", + RAD_PARAMS(RAD_RANGE("M", 1, max_img), RAD_INT("n", kLatC), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_state, m.b_xin }); + if (!m.op_iota || !m.op_zf || !m.op_kdin) return RAD_E_INVAL; + RAD_ARCH_TRY(declare_emb(b, m)); + RAD_ARCH_TRY(declare_unet(b, m)); + m.op_kdstep = rw(b, RAD_OP(b, "kd_step", + RAD_PARAMS(RAD_RANGE("M", 1, max_img), RAD_INT("n", kLatC), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("pred", m.pred.c_str()), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_eps, m.b_state, m.b_hist, m.b_prev }, + { m.b_state, m.b_hist, m.b_prev }); + if (!m.op_kdstep) return RAD_E_INVAL; + RAD_ARCH_TRY(declare_decoder(b, m)); + + /* ---- what the core drives */ + if (!ctx->shape_probe) { + RadGeneratorDecl d{}; + d.name = "sdxl"; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.tmpl_text = "{prompt}"; + d.tmpl_edit = "{prompt}"; + d.drop_prefix = ""; + d.latent_channels = kLatC; + d.latent_scale = 8; + /* Two 2x downsamplings: the latent's sides are multiples of 4. */ + d.size_multiple = 32; + d.pixel_channels = 3; + d.slot_rows = 1; + d.max_tokens = kMaxImageTokens; + d.max_refs = 0; + d.ref_area = 1; + d.default_width = 1024; + d.default_height = 1024; + d.default_steps = 28; + d.n_sigmas = 0; + d.sigmas = nullptr; + d.shift = 1.0; + d.default_cfg = 6.0; + d.cfg_original = 0; + d.default_negative = ""; + d.max_lanes = kMaxLanes; + d.image_out = m.b_img; + d.cond_rows = kCondRows; + d.rope_hw_scale = 1.0; + d.pad_multiple = 0; + d.pad_token = kEos; + d.train_steps = 1000; + d.beta_schedule = RAD_GEN_BETAS_SCALED_LINEAR; + d.beta_start = 0.00085; + d.beta_end = 0.012; + d.zero_snr = m.zero_snr ? 1 : 0; + d.samplers = (1u << RAD_GEN_SAMPLER_EULER) | (1u << RAD_GEN_SAMPLER_EULER_ANCESTRAL) | + (1u << RAD_GEN_SAMPLER_DPMPP_2M); + d.default_sampler = RAD_GEN_SAMPLER_EULER_ANCESTRAL; + d.default_scheduler = RAD_GEN_SCHED_NORMAL; + d.chunk_tokens = kWin - 2; + d.chunk_bos = kBos; + d.chunk_eos = kEos; + RAD_ARCH_TRY(rad_declare_generator(b, &d)); + } + rad_note(b, "Stable Diffusion XL -- CLIP ViT-L and bigG, UNet %zu ops (%s prediction%s), " + "VAE %zu ops, bf16", + m.net.ops.size(), m.pred.c_str(), m.zero_snr ? ", zero terminal SNR" : "", + m.dec.ops.size()); + return RAD_OK; +} + +/* ================================================================== step */ +static void step_text(RadCtx* c, const RadBatch* batch, const Model& m, const TextEnc& E, + int64_t T, const std::vector& eos) { + const int64_t D = E.D, nw = T / kWin; + const RadOperand cu = brows(m.b_wcu, nw + 1); + RAD_ISSUE_N(c, E.op_tok, T, praw(batch->token_ids, RAD_I32, T), RAD_W(E.tok), brows(E.x, T)); + if (E.op_pad) + for (int64_t w = 0; w < nw; ++w) { + const int64_t first = w * kWin + eos[(size_t)w] + 1, n = (w + 1) * kWin - first; + if (n > 0) + RAD_ISSUE_N(c, E.op_pad, n, brows(m.b_zero, n), RAD_W(E.tok), + brow_slice(E.x, first, n, D)); + } + RAD_ISSUE_N(c, E.op_pos, T, brows(m.b_pos, T), RAD_W(E.pos), brows(E.pe, T)); + RAD_ISSUE_N(c, E.op_pe, T, brows(E.x, T), brows(E.pe, T), brows(E.x, T)); + for (int64_t l = 0; l < E.L; ++l) { + const TextLayer& Y = E.layers[(size_t)l]; + RAD_ISSUE_N(c, Y.op_ln1, T, brows(E.x, T), RAD_W(Y.ln1w), RAD_W(Y.ln1b), brows(E.h, T)); + RAD_ISSUE_N(c, Y.op_q, T, brows(E.h, T), RAD_W(Y.qw), RAD_W(Y.qb), RAD_NONE, brows(E.q, T)); + RAD_ISSUE_N(c, Y.op_k, T, brows(E.h, T), RAD_W(Y.kw), RAD_W(Y.kb), RAD_NONE, brows(E.k, T)); + RAD_ISSUE_N(c, Y.op_v, T, brows(E.h, T), RAD_W(Y.vw), RAD_W(Y.vb), RAD_NONE, brows(E.v, T)); + RAD_ISSUE_N(c, Y.op_attn, T, brows(E.q, T), brows(E.k, T), brows(E.v, T), cu, + brows(E.a, T)); + RAD_ISSUE_N(c, Y.op_o, T, brows(E.a, T), RAD_W(Y.ow), RAD_W(Y.ob), brows(E.x, T), + brows(E.x, T)); + RAD_ISSUE_N(c, Y.op_ln2, T, brows(E.x, T), RAD_W(Y.ln2w), RAD_W(Y.ln2b), brows(E.h, T)); + RAD_ISSUE_N(c, Y.op_f1, T, brows(E.h, T), RAD_W(Y.f1w), RAD_W(Y.f1b), RAD_NONE, + brows(E.f1, T)); + RAD_ISSUE_N(c, Y.op_act, T, brows(E.f1, T), brows(E.f2, T)); + RAD_ISSUE_N(c, Y.op_f2, T, brows(E.f2, T), RAD_W(Y.f2w), RAD_W(Y.f2b), brows(E.x, T), + brows(E.x, T)); + if (l == E.tap) + RAD_ISSUE_N(c, E.op_tap, T, brows(E.x, T), bcol(m.b_ctx, E.ctx_col, D, T)); + } + if (!E.op_eos) return; + /* b_pos holds 0..76 in its first window: row k of it is the index k. */ + RAD_ISSUE_N(c, E.op_eos, 1, brows(E.x, T), brow_slice(m.b_pos, eos[0], 1, 1), brows(E.e1, 1)); + RAD_ISSUE_N(c, E.op_fn, 1, brows(E.e1, 1), RAD_W(E.fnw), RAD_W(E.fnb), brows(E.e2, 1)); + RAD_ISSUE_N(c, E.op_proj, 1, brows(E.e2, 1), RAD_W(E.proj), brows(m.b_pooled, 1)); +} + +/* Both text encoders over the prompt's windows, the context and pooled vector into every lane + * of the request at this branch. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t T = batch->n_tok; + if (T <= 0 || T % kWin || T > kCondRows || !G->tokens_h) { + rad_step_fail(c, "sdxl: a conditioning pass is not whole 77-token windows"); + return; + } + const int64_t nw = T / kWin; + /* Each window's end-of-text marker: the first after its start marker. */ + std::vector eos((size_t)nw, kWin - 1); + for (int64_t w = 0; w < nw; ++w) + for (int64_t k = 1; k < kWin; ++k) + if (G->tokens_h[w * kWin + k] == kEos) { eos[(size_t)w] = k; break; } + RAD_ISSUE_N(c, m.op_pos, T, brows(m.b_pos, T)); + RAD_ISSUE_N(c, m.op_wcu, nw + 1, brows(m.b_wcu, nw + 1)); + RAD_ISSUE_N(c, m.op_zero, kWin, brows(m.b_zero, kWin)); + step_text(c, batch, m, m.te1, T, eos); + step_text(c, batch, m, m.te2, T, eos); + const int64_t br = G->branch; + RAD_ISSUE_N(c, m.op_store, T, brows(m.b_ctx, T), praw(G->lane, RAD_I32, G->n_lane), + brow_slice(m.b_store, br * kCondRows, + 2 * (int64_t)kMaxLanes * kCondRows - br * kCondRows, kCtx)); + RAD_ISSUE_N(c, m.op_pstore, 1, brows(m.b_pooled, 1), praw(G->lane, RAD_I32, G->n_lane), + brow_slice(m.b_pstore, br, 2 * (int64_t)kMaxLanes - br, kPooled)); +} + +/* The model input of every entry, then each entry's embeddings and UNet at its own size, then the + * sampler's step over every entry. */ +static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t S = batch->n_seq, NI = G->n_img; + if (!G->entry_h || !G->timestep || !G->size_px) { + rad_step_fail(c, "sdxl: a denoising pass without its per-entry geometry"); + return; + } + const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens; + const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1); + RAD_ISSUE_N(c, m.op_iota, kMaxImageTokens + 1, brows(m.b_iota, kMaxImageTokens + 1)); + RAD_ISSUE_N(c, m.op_zf, 1, brows(m.b_zf, 1)); + RAD_ISSUE_N(c, m.op_kdin, NI, praw(G->sigma, RAD_F32, S), praw(G->pair, RAD_I32, S), + praw(G->lane, RAD_I32, S), praw(G->flags, RAD_I32, S), + praw(G->seed, RAD_U32, 2 * S), icu, brows(m.b_state, LR), brows(m.b_xin, NI)); + int64_t row0 = 0; + for (int64_t e = 0; e < S; ++e) { + const int32_t* eh = G->entry_h + 4 * e; + Geo g; + g.cond = eh[0]; + g.h = eh[1] / 8; + g.w = eh[2] / 8; + g.row0 = row0; + const int64_t lane = G->lane_dh[e], br = eh[3]; + g.store_row = (2 * lane + br) * kCondRows; + g.pool_row = 2 * lane + br; + if (g.h % 4 || g.w % 4 || g.px(0) > kMaxImageTokens || g.cond > kCondRows) { + rad_step_fail(c, "sdxl: an entry's size is not one this model takes"); + return; + } + /* ---- the time and added embeddings */ + RAD_ISSUE_N(c, m.op_tproj, 1, praw(G->timestep + e, RAD_F32, 1), brows(m.b_tproj, 1)); + RAD_ISSUE_N(c, m.op_t1, 1, brows(m.b_tproj, 1), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, + brows(m.b_te1, 1)); + RAD_ISSUE_N(c, m.op_ts, 1, brows(m.b_te1, 1), brows(m.b_te1s, 1)); + RAD_ISSUE_N(c, m.op_t2, 1, brows(m.b_te1s, 1), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, + brows(m.b_temb, 1)); + char* add = (char*)rad_buf_ptr(c, m.b_add); + RAD_ISSUE_N(c, m.op_pool, 1, brow_slice(m.b_pstore, g.pool_row, 1, kPooled), + RAD_P_T2(add, RAD_BF16, 1, kPooled)); + RAD_ISSUE_N(c, m.op_szo, 2, praw(G->size_px + 2 * e, RAD_F32, 2), + RAD_P_T2(add + 2 * kPooled, RAD_BF16, 2, 256)); + RAD_ISSUE_N(c, m.op_szc, 2, praw(rad_buf_ptr(c, m.b_zf), RAD_F32, 2), + RAD_P_T2(add + 2 * (kPooled + 512), RAD_BF16, 2, 256)); + RAD_ISSUE_N(c, m.op_szt, 2, praw(G->size_px + 2 * e, RAD_F32, 2), + RAD_P_T2(add + 2 * (kPooled + 1024), RAD_BF16, 2, 256)); + RAD_ISSUE_N(c, m.op_l1, 1, brows(m.b_add, 1), RAD_W(m.w_l1), RAD_W(m.b_l1), RAD_NONE, + brows(m.b_le1, 1)); + RAD_ISSUE_N(c, m.op_ls, 1, brows(m.b_le1, 1), brows(m.b_le1s, 1)); + RAD_ISSUE_N(c, m.op_l2, 1, brows(m.b_le1s, 1), RAD_W(m.w_l2), RAD_W(m.b_l2), + brows(m.b_temb, 1), brows(m.b_emb, 1)); + RAD_ISSUE_N(c, m.op_es, 1, brows(m.b_emb, 1), brows(m.b_embs, 1)); + /* ---- the UNet */ + m.net.issue(c, g); + row0 += g.px(0); + } + if (row0 != NI) { + rad_step_fail(c, "sdxl: the entries' images do not add up to the pass's image rows"); + return; + } + RAD_ISSUE_N(c, m.op_kdstep, NI, brows(m.b_eps, NI), praw(G->sigma, RAD_F32, S), + praw(G->sigma_next, RAD_F32, S), praw(G->sigma_prev, RAD_F32, S), + praw(G->cfg, RAD_F32, S), praw(G->pair, RAD_I32, S), praw(G->lane, RAD_I32, S), + praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S), + praw(G->sampler, RAD_I32, S), praw(G->step, RAD_I32, S), icu, + brows(m.b_state, LR), brows(m.b_hist, LR), brows(m.b_prev, LR)); +} + +/* One image's latent to RGB. */ +static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t H = G->dec_height / 8, W = G->dec_width / 8, n = H * W; + const rad_buf src = G->dec_preview ? m.b_prev : m.b_state; + RAD_ISSUE_N(c, m.op_dscale, n, + brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, kLatC), + brows(m.b_dlf, n)); + RAD_ISSUE_N(c, m.op_dcast, n, brows(m.b_dlf, n), brows(m.b_decin, n)); + m.dec.issue(c, H, W, praw(batch->cu_seqlens, RAD_I32, 2), nullptr); + const int64_t npx = (int64_t)G->dec_height * G->dec_width; + RAD_ISSUE_N(c, m.op_rgb, npx, RAD_P_T2(rad_buf_ptr(c, m.dec_out.buf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->gen_b) { + rad_step_fail(c, "sdxl is an image generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_COND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_DENOISE: step_denoise(c, batch, m); return; + case RAD_GEN_PASS_DECODE: step_decode(c, batch, m); return; + default: rad_step_fail(c, "sdxl: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries: one image at the largest size with guidance, its conditioning both + * ways. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kCondRows); + out->gen_patches = 0; + return RAD_OK; +} + +} /* namespace sdxl */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(sdxl) +RAD_ARCH_PLUGIN(sdxl, "sdxl", "", "0.1.0", + "Stable Diffusion XL and its finetunes (Illustrious, NoobAI, Pony): CLIP ViT-L and " + "OpenCLIP bigG text encoders, a 2.6B UNet sampled by k-diffusion's Euler, Euler " + "ancestral or DPM++ 2M, and the SDXL VAE; bf16, from the single-file checkpoint") +#endif diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 6559f969..3b008686 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -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); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 236f2c4c..e97cac62 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -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); diff --git a/core/config.cpp b/core/config.cpp index 56c2f91a..47c147b4 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -23,6 +23,7 @@ #include #include #include +#include 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; diff --git a/core/engine.cpp b/core/engine.cpp index 1b15d259..3256f380 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -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>& u, + int32_t* slot, std::shared_ptr* hold, std::string* note, + std::string* e) { + std::vector 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* 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 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 diff --git a/core/engine.h b/core/engine.h index 7ffa8bab..4b07a680 100644 --- a/core/engine.h +++ b/core/engine.h @@ -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 @@ -155,6 +156,30 @@ public: int lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid, std::shared_ptr* hold); std::vector 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& uses, int32_t* slot, + std::shared_ptr* hold, std::string* note, std::string* err); + /* The adapter files a generator request may name: --lora's and those under --lora-dir. */ + std::vector 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* 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>& packed, + std::string* err); + bool lora_gen_ = false; + std::unique_ptr lora_keys_; + mutable std::mutex lora_lib_mu_; + std::map>> lora_lib_; private: std::atomic 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 vocab_; std::unique_ptr 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 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 diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 55252355..7192f0a0 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -3663,6 +3663,14 @@ int Engine::load_vocab() { auto v = std::make_shared(); 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(); + 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(); RAD_TRY(view->init(vocab_)); diff --git a/core/engine_gen.cpp b/core/engine_gen.cpp index f1a6daf0..27b286da 100644 --- a/core/engine_gen.cpp +++ b/core/engine_gen.cpp @@ -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 */ diff --git a/core/engine_lora.cpp b/core/engine_lora.cpp index 43b78c73..81ffec81 100644 --- a/core/engine_lora.cpp +++ b/core/engine_lora.cpp @@ -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 +#include #include +#include #include +#include #include #include +#include #include namespace rad { @@ -50,13 +59,41 @@ int read_targets(const std::string& dir, std::set* 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& 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(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 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 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 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(); + 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 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 infos(ranks_.size()); std::vector> 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>& 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 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 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 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(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* out, + std::string* err) { + { + std::lock_guard 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(); + 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 lk(lora_lib_mu_); + lora_lib_[name] = { path, f }; + *out = f; + return RAD_OK; +} + +std::vector Engine::gen_lora_names() const { + std::set n; + { + std::lock_guard 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 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(n.begin(), n.end()); +} + +int Engine::gen_lora_acquire(const std::vector& uses_in, int32_t* slot, + std::shared_ptr* 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 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 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 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 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 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 mods = lora::as_modules(comp, *lora_keys_); + std::vector> 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(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 */ diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 800c549d..f195e778 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -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 add; + std::vector 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((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. */ + 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 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& 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& 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 srcs; diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 72e20805..3846d1cb 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -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& tensors() const { return tensors_; } @@ -177,12 +185,13 @@ private: const std::unordered_map* 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> shards_; @@ -249,7 +258,7 @@ struct CkptWeight { * (the values change), so a recipe rule stores it. */ bool wnorm = false; std::vector 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 derived; diff --git a/core/format/radfile.cpp b/core/format/radfile.cpp index f36329bd..c8167e96 100644 --- a/core/format/radfile.cpp +++ b/core/format/radfile.cpp @@ -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& 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 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. */ diff --git a/core/format/radfile.h b/core/format/radfile.h index adec085e..b381f8ed 100644 --- a/core/format/radfile.h +++ b/core/format/radfile.h @@ -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 groups_; std::unordered_map 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 vocab_blob_; bool have_vocab_ = false; + std::vector aux_vocab_blob_; + bool have_aux_vocab_ = false; int64_t blob_bytes_ = 0; /* the blob's reserved length */ diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index c4d09ab0..001883cf 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -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& 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 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 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 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 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(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(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(ri, R_LANE) : nullptr; + G.n_aux = n_aux; + G.aux_cu = n_aux ? dptr(ri, R_AUX) : nullptr; + G.aux_ids = n_aux ? dptr(ri, R_AUX) + 2 : nullptr; + G.tokens_h = hptr(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& take, int step uint32_t* seed = hptr(R_SEED); int32_t* btab = hptr(R_BT); int32_t* used = hptr(R_USED); + float* sigp = hptr(R_SIGP); + float* tstep = hptr(R_TSTEP); + int32_t* samp = hptr(R_SAMP); + int32_t* stepi = hptr(R_STEPI); + float* size = hptr(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& 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& 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& take, int step G.lane_h = nullptr; G.rope = joint() ? nullptr : dptr(ri, R_GROPE); G.lane_dh = hptr(R_LANE); + G.sigma_prev = dptr(ri, R_SIGP); + G.timestep = dptr(ri, R_TSTEP); + G.sampler = dptr(ri, R_SAMP); + G.step = dptr(ri, R_STEPI); + G.size_px = dptr(ri, R_SIZE); + G.entry_h = host_entry_.data(); if (joint()) { G.src = dptr(ri, R_SRC); G.n_img = n_img; diff --git a/core/gen/driver.h b/core/gen/driver.h index 6bd715d6..701fed38 100644 --- a/core/gen/driver.h +++ b/core/gen/driver.h @@ -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& 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 sigmas; + /* A discrete-time model's: each step's timestep, beside `sigmas`. */ + std::vector tsteps; std::vector lanes; std::vector> ref_hw; int32_t images_done = 0; @@ -112,13 +115,15 @@ private: bool preview = false; std::vector lanes; /* DENOISE: the lanes it stepped, one per image */ std::vector 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 T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } @@ -147,6 +152,9 @@ private: RadGeneratorDecl decl_{}; std::vector 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 host_bidi_, host_px_, host_lanes_; + /* A DENOISE pass's per-entry host array (RadGenBatch::entry_h). */ + std::vector host_entry_; int64_t host_nmode_[3] = { 0, 0, 0 }; mutable std::mutex mu_; diff --git a/core/gen/gen.cpp b/core/gen/gen.cpp index 89e7eb2b..0ce151dd 100644 --- a/core/gen/gen.cpp +++ b/core/gen/gen.cpp @@ -67,6 +67,16 @@ std::vector schedule(const RadGeneratorDecl& d, const std::vector std::vector 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 schedule(const RadGeneratorDecl& d, const std::vector 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 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 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 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 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); diff --git a/core/gen/gen.h b/core/gen/gen.h index 6ad9af96..597f9361 100644 --- a/core/gen/gen.h +++ b/core/gen/gen.h @@ -48,6 +48,9 @@ struct Branch { std::vector tokens; std::shared_ptr 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 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 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 lora_hold; std::shared_ptr ticket; }; @@ -119,6 +128,31 @@ struct Request { std::vector schedule(const RadGeneratorDecl& d, const std::vector& 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 sigmas; /* [train_steps], ascending: sigmas[t] is timestep t's */ + std::vector 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 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. */ diff --git a/core/gen/pass.h b/core/gen/pass.h index 0577382d..e567c8bc 100644 --- a/core/gen/pass.h +++ b/core/gen/pass.h @@ -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& readbacks() const = 0; /* The pass has run on every rank, its streams are drained and the readbacks have landed. */ diff --git a/core/gen/video.h b/core/gen/video.h index eb0daf14..1d00161b 100644 --- a/core/gen/video.h +++ b/core/gen/video.h @@ -95,6 +95,11 @@ struct VideoRequest { std::vector 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 lora_hold; std::shared_ptr ticket; }; diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index e702188c..34853e59 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -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]; } diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index 2962d229..d61b7a55 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -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& 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. */ diff --git a/core/lora/adapter.cpp b/core/lora/adapter.cpp new file mode 100644 index 00000000..66dbeada --- /dev/null +++ b/core/lora/adapter.cpp @@ -0,0 +1,986 @@ +/* lora/adapter.cpp -- see adapter.h. Host code only. */ +#include "adapter.h" + +#include "rad_plugin.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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& 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* 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 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 G, int64_t l, std::vector* w, std::vector* 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 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 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& B, const std::vector& A, int64_t n, int64_t r, + int64_t k) { + std::vector 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 by; + std::map 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 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 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 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 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>(); + auto W2a = std::make_shared>(); + auto W2b = std::make_shared>(); + 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::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 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 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>(); + 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* B, std::vector* A, double* kept) { + const int64_t N = d.N, K = d.K; + r = std::max(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 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 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 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 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 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 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& 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& 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::pieces(const std::string& module) const { + static const std::vector 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* 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 KeyMap::resolve(const std::string& key, std::string* why) const { + struct Cand { size_t root; size_t len; bool kohya; }; + std::vector 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 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 d; + int64_t from_lo = 0, n = 0, to_lo = 0; +}; + +} /* namespace */ + +int compose(const KeyMap& km, const std::vector& ads, int max_rank, + std::map* out, ComposeReport* rep, std::string* err) { + out->clear(); + *rep = ComposeReport{}; + std::map> 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 ts = km.resolve(fm.key, &why); + if (ts.empty()) { rep->unplaced.push_back(s.name + ": " + fm.key + ": " + why); continue; } + auto d = std::make_shared(); + 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 names; + for (auto& [k, v] : by) { names.push_back(k); (*out)[k]; } + std::vector errs(names.size()); + std::vector kept(names.size(), 1.0); + std::vector exact(names.size(), 1); + std::atomic next{ 0 }; + auto work = [&]() { + for (size_t i; (i = next.fetch_add(1)) < names.size();) { + const std::string& mod = names[i]; + const std::vector& 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 y((size_t)(d.N * l)); + if (d.low_rank) { + std::vector 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 x((size_t)(K * l)); + for (const Part& p : ps) { + const Delta& d = *p.d; + std::vector 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 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 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 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 as_modules(std::map& c, const KeyMap& km) { + std::map m; + for (auto& [name, x] : c) { + if (x.r <= 0) continue; + const std::vector& 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 */ diff --git a/core/lora/adapter.h b/core/lora/adapter.h new file mode 100644 index 00000000..b0faf017 --- /dev/null +++ b/core/lora/adapter.h @@ -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 `.lora_down.weight` / `.lora_up.weight` (+ `.alpha`): kohya, ComfyUI; + * `.lora_A[.default].weight` / `.lora_B[...]` (+ `.alpha`): PEFT, diffusers, ai-toolkit; + * `.lora.down.weight` / `.lora.up.weight`; `.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 `.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 `.lokr_w1` or `_w1_a`/`_w1_b`, `.lokr_w2` or `_w2_a`/`_w2_b` (+ alpha): + * delta = scale * kron(w1, w2), scale alpha / rank of a decomposed factor, else 1. + * full `.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 +#include +#include +#include +#include +#include +#include +#include + +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& modules() const { return mods_; } + /* Tensors that change no linear (a trained bias, a norm's weight), with why; reported, not + * applied. */ + const std::vector>& 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 mods_; + std::vector> 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 B, A; + std::function 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* B, std::vector* 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& sites); + /* The targets of a file's module key; empty with `why` when it lands nowhere adaptable. */ + std::vector 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 + * `@+`), 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& 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 spellings; + std::unordered_map 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* out, + std::string* why) const; + + const Program* prog_; + std::vector roots_; + std::vector aliases_; + std::unordered_map> adaptable_; /* -> rows, cols */ + std::unordered_map known_; /* module -> why not adaptable */ + std::unordered_map> pieces_; + std::set whole_; +}; + +/* One adapter at a strength, for compose(). */ +struct Strength { + std::string name; + std::shared_ptr 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 unplaced; /* ": : why" */ + std::vector skipped; /* ": : 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 B, A; + StTensor tA, tB; + std::vector 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& ads, int max_rank, + std::map* 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 as_modules(std::map& c, const KeyMap& km); + +} /* namespace lora */ +} /* namespace rad */ diff --git a/core/lora/config.h b/core/lora/config.h index fa8ad018..bf081209 100644 --- a/core/lora/config.h +++ b/core/lora/config.h @@ -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 #include @@ -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> 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 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); } }; diff --git a/core/lora/declare.cpp b/core/lora/declare.cpp index 970e0f7f..ad04866b 100644 --- a/core/lora/declare.cpp +++ b/core/lora/declare.cpp @@ -3,6 +3,7 @@ #include "build/rad_build.h" #include "rad_internal.h" +#include #include #include #include @@ -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(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 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 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 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; } diff --git a/core/lora/lora.cpp b/core/lora/lora.cpp index 777d625c..640f9a32 100644 --- a/core/lora/lora.cpp +++ b/core/lora/lora.cpp @@ -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> 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& 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* 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& 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 srcs; + /* A row piece of a checkpoint tensor (RAD_MAP_ROWS) is a source of its own, named + * `@+`: the adapter's B rows it takes are that range of the + * module's. */ + std::vector 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 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 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* 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 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 pool_of; std::vector 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& 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& sites, int max_rank, + const std::map& mods, AdapterInfo* info, + std::vector* 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& sites, int max } std::unordered_map> 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& 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& 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 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& 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; } } diff --git a/core/lora/lora.h b/core/lora/lora.h index 9538343c..11156ce2 100644 --- a/core/lora/lora.h +++ b/core/lora/lora.h @@ -19,12 +19,14 @@ #include "../rad_core.h" #include +#include #include #include #include #include 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 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& sites, int max_rank, AdapterInfo* info, std::vector* 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& sites, int max_rank, + const std::map& mods, AdapterInfo* info, + std::vector* 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& per_rank, std::string* err, diff --git a/core/lora/slots.cpp b/core/lora/slots.cpp index 18d10014..f14c94f6 100644 --- a/core/lora/slots.cpp +++ b/core/lora/slots.cpp @@ -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 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 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 SlotTable::names() const { std::lock_guard lk(mu_); std::vector out; diff --git a/core/lora/slots.h b/core/lora/slots.h index f5e63cbc..a3381428 100644 --- a/core/lora/slots.h +++ b/core/lora/slots.h @@ -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 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 slots_; std::map refs_; /* uid -> holds */ uint64_t next_uid_ = 1; + uint64_t uses_ = 0; const std::atomic* epoch_ = nullptr; }; diff --git a/core/rad_core.h b/core/rad_core.h index c552cf73..6185bf76 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -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 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 lora_sites; std::vector lora_pools; std::vector 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 lora_roots; + std::vector 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 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 diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 66daed98..95ea0caf 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -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; diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 05f33e02..086dc7b7 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -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) { diff --git a/core/server/iface.h b/core/server/iface.h index e492463a..8cd70dd4 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -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* 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* 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 diff --git a/core/server/images.cpp b/core/server/images.cpp index f8c888ab..15b44357 100644 --- a/core/server/images.cpp +++ b/core/server/images.cpp @@ -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 tags, which leave the prompt. */ + std::vector> 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(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 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 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); diff --git a/core/server/loras.cpp b/core/server/loras.cpp new file mode 100644 index 00000000..05188744 --- /dev/null +++ b/core/server/loras.cpp @@ -0,0 +1,117 @@ +/* loras.cpp -- see loras.h. */ +#include "loras.h" +#include "rad_internal.h" + +#include +#include + +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>* 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(), &name, &w)) return false; + } else if (e.is_object()) { + if (!e.contains("name") || !e["name"].is_string()) return false; + name = e["name"].get(); + 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(); + } + } 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())) { + *why = "a {name: strength} object's strengths are numbers"; + return RAD_E_INVAL; + } + out->push_back({ it.key(), it.value().get() }); + } + } else if (!entry(v)) { + *why = "expected a list of adapters (names, \"name:strength\" or {\"name\", \"weight\"})"; + return RAD_E_INVAL; + } + } + /* tags in the prompt. */ + if (prompt) { + std::string p; + size_t at = 0; + for (;;) { + const size_t open = prompt->find("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 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 */ diff --git a/core/server/loras.h b/core/server/loras.h new file mode 100644 index 00000000..904cfdb0 --- /dev/null +++ b/core/server/loras.h @@ -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. + * + * or 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 + +#include +#include +#include + +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>* out, std::string* field, + std::string* why); + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/server.cpp b/core/server/server.cpp index d72dc82d..49361853 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -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 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) { diff --git a/core/server/server.h b/core/server/server.h index f1cded21..353c9939 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -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 lora_load; std::function lora_unload; + /* A generator's adapters (Engine::gen_lora_acquire): the images and videos endpoints' `loras` + * and 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>&, int32_t*, + std::shared_ptr*, std::string*, std::string*)> gen_lora_acquire; + std::function()> 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 refuse_text(const std::string& peer, ApiShape shape = ApiShape::OpenAI); diff --git a/core/server/videos.cpp b/core/server/videos.cpp index b1de899f..e33182f2 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -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().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 prompt = body["prompt"].get(); + /* Runtime LoRA adapters: `loras` and tags, which leave the prompt. */ + std::vector> 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, ¬e, &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(); j->id = new_video_id(); diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index 3be3237b..41924cf7 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -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 re, re2; + /* Precompiled: the decoded character map. */ + std::unique_ptr pmap; }; std::vector 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 types; @@ -419,6 +428,10 @@ struct TokEncoder { std::unique_ptr[]> 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& special); @@ -443,11 +456,19 @@ int TokEncoder::build(const VocabBuild& b, const std::vector& 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(); + 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& 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& 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& 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& 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 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[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 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& 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& 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& 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& 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& 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& 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& 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& 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& 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 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& 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 v) { @@ -1372,14 +1492,17 @@ int Tokenizer::encode(std::string_view text, std::vector& 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); } diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h index e7c5aaae..96a2c822 100644 --- a/core/text/tokenizer.h +++ b/core/text/tokenizer.h @@ -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& 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); diff --git a/core/text/tokenizer_grapheme.cpp b/core/text/tokenizer_grapheme.cpp new file mode 100644 index 00000000..a43ef72b --- /dev/null +++ b/core/text/tokenizer_grapheme.cpp @@ -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 +#include + +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 cps; + std::vector 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 */ diff --git a/core/text/tokenizer_grapheme.h b/core/text/tokenizer_grapheme.h new file mode 100644 index 00000000..c0109836 --- /dev/null +++ b/core/text/tokenizer_grapheme.h @@ -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 +#include +#include +#include +#include + +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 trie_; + std::string blob_; +}; + +} /* namespace rad */ diff --git a/core/text/tokenizer_grapheme_ucd.cpp b/core/text/tokenizer_grapheme_ucd.cpp new file mode 100644 index 00000000..a0549450 --- /dev/null +++ b/core/text/tokenizer_grapheme_ucd.cpp @@ -0,0 +1,1878 @@ +/* tokenizer_grapheme_ucd.cpp -- GENERATED by tools/gen_grapheme_ucd.py from the Unicode 16.0.0 UCD; + * do not edit. The properties UAX #29's extended grapheme cluster rules read (tokenizer_grapheme.h). */ +#include "text/tokenizer_grapheme.h" + +namespace rad { +namespace ucd { + +const GbRange k_gcb[] = { + { 0x0, 0x9, 3 }, + { 0xA, 0xA, 2 }, + { 0xB, 0xC, 3 }, + { 0xD, 0xD, 1 }, + { 0xE, 0x1F, 3 }, + { 0x7F, 0x9F, 3 }, + { 0xAD, 0xAD, 3 }, + { 0x300, 0x36F, 4 }, + { 0x483, 0x489, 4 }, + { 0x591, 0x5BD, 4 }, + { 0x5BF, 0x5BF, 4 }, + { 0x5C1, 0x5C2, 4 }, + { 0x5C4, 0x5C5, 4 }, + { 0x5C7, 0x5C7, 4 }, + { 0x600, 0x605, 7 }, + { 0x610, 0x61A, 4 }, + { 0x61C, 0x61C, 3 }, + { 0x64B, 0x65F, 4 }, + { 0x670, 0x670, 4 }, + { 0x6D6, 0x6DC, 4 }, + { 0x6DD, 0x6DD, 7 }, + { 0x6DF, 0x6E4, 4 }, + { 0x6E7, 0x6E8, 4 }, + { 0x6EA, 0x6ED, 4 }, + { 0x70F, 0x70F, 7 }, + { 0x711, 0x711, 4 }, + { 0x730, 0x74A, 4 }, + { 0x7A6, 0x7B0, 4 }, + { 0x7EB, 0x7F3, 4 }, + { 0x7FD, 0x7FD, 4 }, + { 0x816, 0x819, 4 }, + { 0x81B, 0x823, 4 }, + { 0x825, 0x827, 4 }, + { 0x829, 0x82D, 4 }, + { 0x859, 0x85B, 4 }, + { 0x890, 0x891, 7 }, + { 0x897, 0x89F, 4 }, + { 0x8CA, 0x8E1, 4 }, + { 0x8E2, 0x8E2, 7 }, + { 0x8E3, 0x902, 4 }, + { 0x903, 0x903, 8 }, + { 0x93A, 0x93A, 4 }, + { 0x93B, 0x93B, 8 }, + { 0x93C, 0x93C, 4 }, + { 0x93E, 0x940, 8 }, + { 0x941, 0x948, 4 }, + { 0x949, 0x94C, 8 }, + { 0x94D, 0x94D, 4 }, + { 0x94E, 0x94F, 8 }, + { 0x951, 0x957, 4 }, + { 0x962, 0x963, 4 }, + { 0x981, 0x981, 4 }, + { 0x982, 0x983, 8 }, + { 0x9BC, 0x9BC, 4 }, + { 0x9BE, 0x9BE, 4 }, + { 0x9BF, 0x9C0, 8 }, + { 0x9C1, 0x9C4, 4 }, + { 0x9C7, 0x9C8, 8 }, + { 0x9CB, 0x9CC, 8 }, + { 0x9CD, 0x9CD, 4 }, + { 0x9D7, 0x9D7, 4 }, + { 0x9E2, 0x9E3, 4 }, + { 0x9FE, 0x9FE, 4 }, + { 0xA01, 0xA02, 4 }, + { 0xA03, 0xA03, 8 }, + { 0xA3C, 0xA3C, 4 }, + { 0xA3E, 0xA40, 8 }, + { 0xA41, 0xA42, 4 }, + { 0xA47, 0xA48, 4 }, + { 0xA4B, 0xA4D, 4 }, + { 0xA51, 0xA51, 4 }, + { 0xA70, 0xA71, 4 }, + { 0xA75, 0xA75, 4 }, + { 0xA81, 0xA82, 4 }, + { 0xA83, 0xA83, 8 }, + { 0xABC, 0xABC, 4 }, + { 0xABE, 0xAC0, 8 }, + { 0xAC1, 0xAC5, 4 }, + { 0xAC7, 0xAC8, 4 }, + { 0xAC9, 0xAC9, 8 }, + { 0xACB, 0xACC, 8 }, + { 0xACD, 0xACD, 4 }, + { 0xAE2, 0xAE3, 4 }, + { 0xAFA, 0xAFF, 4 }, + { 0xB01, 0xB01, 4 }, + { 0xB02, 0xB03, 8 }, + { 0xB3C, 0xB3C, 4 }, + { 0xB3E, 0xB3F, 4 }, + { 0xB40, 0xB40, 8 }, + { 0xB41, 0xB44, 4 }, + { 0xB47, 0xB48, 8 }, + { 0xB4B, 0xB4C, 8 }, + { 0xB4D, 0xB4D, 4 }, + { 0xB55, 0xB57, 4 }, + { 0xB62, 0xB63, 4 }, + { 0xB82, 0xB82, 4 }, + { 0xBBE, 0xBBE, 4 }, + { 0xBBF, 0xBBF, 8 }, + { 0xBC0, 0xBC0, 4 }, + { 0xBC1, 0xBC2, 8 }, + { 0xBC6, 0xBC8, 8 }, + { 0xBCA, 0xBCC, 8 }, + { 0xBCD, 0xBCD, 4 }, + { 0xBD7, 0xBD7, 4 }, + { 0xC00, 0xC00, 4 }, + { 0xC01, 0xC03, 8 }, + { 0xC04, 0xC04, 4 }, + { 0xC3C, 0xC3C, 4 }, + { 0xC3E, 0xC40, 4 }, + { 0xC41, 0xC44, 8 }, + { 0xC46, 0xC48, 4 }, + { 0xC4A, 0xC4D, 4 }, + { 0xC55, 0xC56, 4 }, + { 0xC62, 0xC63, 4 }, + { 0xC81, 0xC81, 4 }, + { 0xC82, 0xC83, 8 }, + { 0xCBC, 0xCBC, 4 }, + { 0xCBE, 0xCBE, 8 }, + { 0xCBF, 0xCC0, 4 }, + { 0xCC1, 0xCC1, 8 }, + { 0xCC2, 0xCC2, 4 }, + { 0xCC3, 0xCC4, 8 }, + { 0xCC6, 0xCC8, 4 }, + { 0xCCA, 0xCCD, 4 }, + { 0xCD5, 0xCD6, 4 }, + { 0xCE2, 0xCE3, 4 }, + { 0xCF3, 0xCF3, 8 }, + { 0xD00, 0xD01, 4 }, + { 0xD02, 0xD03, 8 }, + { 0xD3B, 0xD3C, 4 }, + { 0xD3E, 0xD3E, 4 }, + { 0xD3F, 0xD40, 8 }, + { 0xD41, 0xD44, 4 }, + { 0xD46, 0xD48, 8 }, + { 0xD4A, 0xD4C, 8 }, + { 0xD4D, 0xD4D, 4 }, + { 0xD4E, 0xD4E, 7 }, + { 0xD57, 0xD57, 4 }, + { 0xD62, 0xD63, 4 }, + { 0xD81, 0xD81, 4 }, + { 0xD82, 0xD83, 8 }, + { 0xDCA, 0xDCA, 4 }, + { 0xDCF, 0xDCF, 4 }, + { 0xDD0, 0xDD1, 8 }, + { 0xDD2, 0xDD4, 4 }, + { 0xDD6, 0xDD6, 4 }, + { 0xDD8, 0xDDE, 8 }, + { 0xDDF, 0xDDF, 4 }, + { 0xDF2, 0xDF3, 8 }, + { 0xE31, 0xE31, 4 }, + { 0xE33, 0xE33, 8 }, + { 0xE34, 0xE3A, 4 }, + { 0xE47, 0xE4E, 4 }, + { 0xEB1, 0xEB1, 4 }, + { 0xEB3, 0xEB3, 8 }, + { 0xEB4, 0xEBC, 4 }, + { 0xEC8, 0xECE, 4 }, + { 0xF18, 0xF19, 4 }, + { 0xF35, 0xF35, 4 }, + { 0xF37, 0xF37, 4 }, + { 0xF39, 0xF39, 4 }, + { 0xF3E, 0xF3F, 8 }, + { 0xF71, 0xF7E, 4 }, + { 0xF7F, 0xF7F, 8 }, + { 0xF80, 0xF84, 4 }, + { 0xF86, 0xF87, 4 }, + { 0xF8D, 0xF97, 4 }, + { 0xF99, 0xFBC, 4 }, + { 0xFC6, 0xFC6, 4 }, + { 0x102D, 0x1030, 4 }, + { 0x1031, 0x1031, 8 }, + { 0x1032, 0x1037, 4 }, + { 0x1039, 0x103A, 4 }, + { 0x103B, 0x103C, 8 }, + { 0x103D, 0x103E, 4 }, + { 0x1056, 0x1057, 8 }, + { 0x1058, 0x1059, 4 }, + { 0x105E, 0x1060, 4 }, + { 0x1071, 0x1074, 4 }, + { 0x1082, 0x1082, 4 }, + { 0x1084, 0x1084, 8 }, + { 0x1085, 0x1086, 4 }, + { 0x108D, 0x108D, 4 }, + { 0x109D, 0x109D, 4 }, + { 0x1100, 0x115F, 9 }, + { 0x1160, 0x11A7, 10 }, + { 0x11A8, 0x11FF, 11 }, + { 0x135D, 0x135F, 4 }, + { 0x1712, 0x1715, 4 }, + { 0x1732, 0x1734, 4 }, + { 0x1752, 0x1753, 4 }, + { 0x1772, 0x1773, 4 }, + { 0x17B4, 0x17B5, 4 }, + { 0x17B6, 0x17B6, 8 }, + { 0x17B7, 0x17BD, 4 }, + { 0x17BE, 0x17C5, 8 }, + { 0x17C6, 0x17C6, 4 }, + { 0x17C7, 0x17C8, 8 }, + { 0x17C9, 0x17D3, 4 }, + { 0x17DD, 0x17DD, 4 }, + { 0x180B, 0x180D, 4 }, + { 0x180E, 0x180E, 3 }, + { 0x180F, 0x180F, 4 }, + { 0x1885, 0x1886, 4 }, + { 0x18A9, 0x18A9, 4 }, + { 0x1920, 0x1922, 4 }, + { 0x1923, 0x1926, 8 }, + { 0x1927, 0x1928, 4 }, + { 0x1929, 0x192B, 8 }, + { 0x1930, 0x1931, 8 }, + { 0x1932, 0x1932, 4 }, + { 0x1933, 0x1938, 8 }, + { 0x1939, 0x193B, 4 }, + { 0x1A17, 0x1A18, 4 }, + { 0x1A19, 0x1A1A, 8 }, + { 0x1A1B, 0x1A1B, 4 }, + { 0x1A55, 0x1A55, 8 }, + { 0x1A56, 0x1A56, 4 }, + { 0x1A57, 0x1A57, 8 }, + { 0x1A58, 0x1A5E, 4 }, + { 0x1A60, 0x1A60, 4 }, + { 0x1A62, 0x1A62, 4 }, + { 0x1A65, 0x1A6C, 4 }, + { 0x1A6D, 0x1A72, 8 }, + { 0x1A73, 0x1A7C, 4 }, + { 0x1A7F, 0x1A7F, 4 }, + { 0x1AB0, 0x1ACE, 4 }, + { 0x1B00, 0x1B03, 4 }, + { 0x1B04, 0x1B04, 8 }, + { 0x1B34, 0x1B3D, 4 }, + { 0x1B3E, 0x1B41, 8 }, + { 0x1B42, 0x1B44, 4 }, + { 0x1B6B, 0x1B73, 4 }, + { 0x1B80, 0x1B81, 4 }, + { 0x1B82, 0x1B82, 8 }, + { 0x1BA1, 0x1BA1, 8 }, + { 0x1BA2, 0x1BA5, 4 }, + { 0x1BA6, 0x1BA7, 8 }, + { 0x1BA8, 0x1BAD, 4 }, + { 0x1BE6, 0x1BE6, 4 }, + { 0x1BE7, 0x1BE7, 8 }, + { 0x1BE8, 0x1BE9, 4 }, + { 0x1BEA, 0x1BEC, 8 }, + { 0x1BED, 0x1BED, 4 }, + { 0x1BEE, 0x1BEE, 8 }, + { 0x1BEF, 0x1BF3, 4 }, + { 0x1C24, 0x1C2B, 8 }, + { 0x1C2C, 0x1C33, 4 }, + { 0x1C34, 0x1C35, 8 }, + { 0x1C36, 0x1C37, 4 }, + { 0x1CD0, 0x1CD2, 4 }, + { 0x1CD4, 0x1CE0, 4 }, + { 0x1CE1, 0x1CE1, 8 }, + { 0x1CE2, 0x1CE8, 4 }, + { 0x1CED, 0x1CED, 4 }, + { 0x1CF4, 0x1CF4, 4 }, + { 0x1CF7, 0x1CF7, 8 }, + { 0x1CF8, 0x1CF9, 4 }, + { 0x1DC0, 0x1DFF, 4 }, + { 0x200B, 0x200B, 3 }, + { 0x200C, 0x200C, 4 }, + { 0x200D, 0x200D, 5 }, + { 0x200E, 0x200F, 3 }, + { 0x2028, 0x202E, 3 }, + { 0x2060, 0x206F, 3 }, + { 0x20D0, 0x20F0, 4 }, + { 0x2CEF, 0x2CF1, 4 }, + { 0x2D7F, 0x2D7F, 4 }, + { 0x2DE0, 0x2DFF, 4 }, + { 0x302A, 0x302F, 4 }, + { 0x3099, 0x309A, 4 }, + { 0xA66F, 0xA672, 4 }, + { 0xA674, 0xA67D, 4 }, + { 0xA69E, 0xA69F, 4 }, + { 0xA6F0, 0xA6F1, 4 }, + { 0xA802, 0xA802, 4 }, + { 0xA806, 0xA806, 4 }, + { 0xA80B, 0xA80B, 4 }, + { 0xA823, 0xA824, 8 }, + { 0xA825, 0xA826, 4 }, + { 0xA827, 0xA827, 8 }, + { 0xA82C, 0xA82C, 4 }, + { 0xA880, 0xA881, 8 }, + { 0xA8B4, 0xA8C3, 8 }, + { 0xA8C4, 0xA8C5, 4 }, + { 0xA8E0, 0xA8F1, 4 }, + { 0xA8FF, 0xA8FF, 4 }, + { 0xA926, 0xA92D, 4 }, + { 0xA947, 0xA951, 4 }, + { 0xA952, 0xA952, 8 }, + { 0xA953, 0xA953, 4 }, + { 0xA960, 0xA97C, 9 }, + { 0xA980, 0xA982, 4 }, + { 0xA983, 0xA983, 8 }, + { 0xA9B3, 0xA9B3, 4 }, + { 0xA9B4, 0xA9B5, 8 }, + { 0xA9B6, 0xA9B9, 4 }, + { 0xA9BA, 0xA9BB, 8 }, + { 0xA9BC, 0xA9BD, 4 }, + { 0xA9BE, 0xA9BF, 8 }, + { 0xA9C0, 0xA9C0, 4 }, + { 0xA9E5, 0xA9E5, 4 }, + { 0xAA29, 0xAA2E, 4 }, + { 0xAA2F, 0xAA30, 8 }, + { 0xAA31, 0xAA32, 4 }, + { 0xAA33, 0xAA34, 8 }, + { 0xAA35, 0xAA36, 4 }, + { 0xAA43, 0xAA43, 4 }, + { 0xAA4C, 0xAA4C, 4 }, + { 0xAA4D, 0xAA4D, 8 }, + { 0xAA7C, 0xAA7C, 4 }, + { 0xAAB0, 0xAAB0, 4 }, + { 0xAAB2, 0xAAB4, 4 }, + { 0xAAB7, 0xAAB8, 4 }, + { 0xAABE, 0xAABF, 4 }, + { 0xAAC1, 0xAAC1, 4 }, + { 0xAAEB, 0xAAEB, 8 }, + { 0xAAEC, 0xAAED, 4 }, + { 0xAAEE, 0xAAEF, 8 }, + { 0xAAF5, 0xAAF5, 8 }, + { 0xAAF6, 0xAAF6, 4 }, + { 0xABE3, 0xABE4, 8 }, + { 0xABE5, 0xABE5, 4 }, + { 0xABE6, 0xABE7, 8 }, + { 0xABE8, 0xABE8, 4 }, + { 0xABE9, 0xABEA, 8 }, + { 0xABEC, 0xABEC, 8 }, + { 0xABED, 0xABED, 4 }, + { 0xAC00, 0xAC00, 12 }, + { 0xAC01, 0xAC1B, 13 }, + { 0xAC1C, 0xAC1C, 12 }, + { 0xAC1D, 0xAC37, 13 }, + { 0xAC38, 0xAC38, 12 }, + { 0xAC39, 0xAC53, 13 }, + { 0xAC54, 0xAC54, 12 }, + { 0xAC55, 0xAC6F, 13 }, + { 0xAC70, 0xAC70, 12 }, + { 0xAC71, 0xAC8B, 13 }, + { 0xAC8C, 0xAC8C, 12 }, + { 0xAC8D, 0xACA7, 13 }, + { 0xACA8, 0xACA8, 12 }, + { 0xACA9, 0xACC3, 13 }, + { 0xACC4, 0xACC4, 12 }, + { 0xACC5, 0xACDF, 13 }, + { 0xACE0, 0xACE0, 12 }, + { 0xACE1, 0xACFB, 13 }, + { 0xACFC, 0xACFC, 12 }, + { 0xACFD, 0xAD17, 13 }, + { 0xAD18, 0xAD18, 12 }, + { 0xAD19, 0xAD33, 13 }, + { 0xAD34, 0xAD34, 12 }, + { 0xAD35, 0xAD4F, 13 }, + { 0xAD50, 0xAD50, 12 }, + { 0xAD51, 0xAD6B, 13 }, + { 0xAD6C, 0xAD6C, 12 }, + { 0xAD6D, 0xAD87, 13 }, + { 0xAD88, 0xAD88, 12 }, + { 0xAD89, 0xADA3, 13 }, + { 0xADA4, 0xADA4, 12 }, + { 0xADA5, 0xADBF, 13 }, + { 0xADC0, 0xADC0, 12 }, + { 0xADC1, 0xADDB, 13 }, + { 0xADDC, 0xADDC, 12 }, + { 0xADDD, 0xADF7, 13 }, + { 0xADF8, 0xADF8, 12 }, + { 0xADF9, 0xAE13, 13 }, + { 0xAE14, 0xAE14, 12 }, + { 0xAE15, 0xAE2F, 13 }, + { 0xAE30, 0xAE30, 12 }, + { 0xAE31, 0xAE4B, 13 }, + { 0xAE4C, 0xAE4C, 12 }, + { 0xAE4D, 0xAE67, 13 }, + { 0xAE68, 0xAE68, 12 }, + { 0xAE69, 0xAE83, 13 }, + { 0xAE84, 0xAE84, 12 }, + { 0xAE85, 0xAE9F, 13 }, + { 0xAEA0, 0xAEA0, 12 }, + { 0xAEA1, 0xAEBB, 13 }, + { 0xAEBC, 0xAEBC, 12 }, + { 0xAEBD, 0xAED7, 13 }, + { 0xAED8, 0xAED8, 12 }, + { 0xAED9, 0xAEF3, 13 }, + { 0xAEF4, 0xAEF4, 12 }, + { 0xAEF5, 0xAF0F, 13 }, + { 0xAF10, 0xAF10, 12 }, + { 0xAF11, 0xAF2B, 13 }, + { 0xAF2C, 0xAF2C, 12 }, + { 0xAF2D, 0xAF47, 13 }, + { 0xAF48, 0xAF48, 12 }, + { 0xAF49, 0xAF63, 13 }, + { 0xAF64, 0xAF64, 12 }, + { 0xAF65, 0xAF7F, 13 }, + { 0xAF80, 0xAF80, 12 }, + { 0xAF81, 0xAF9B, 13 }, + { 0xAF9C, 0xAF9C, 12 }, + { 0xAF9D, 0xAFB7, 13 }, + { 0xAFB8, 0xAFB8, 12 }, + { 0xAFB9, 0xAFD3, 13 }, + { 0xAFD4, 0xAFD4, 12 }, + { 0xAFD5, 0xAFEF, 13 }, + { 0xAFF0, 0xAFF0, 12 }, + { 0xAFF1, 0xB00B, 13 }, + { 0xB00C, 0xB00C, 12 }, + { 0xB00D, 0xB027, 13 }, + { 0xB028, 0xB028, 12 }, + { 0xB029, 0xB043, 13 }, + { 0xB044, 0xB044, 12 }, + { 0xB045, 0xB05F, 13 }, + { 0xB060, 0xB060, 12 }, + { 0xB061, 0xB07B, 13 }, + { 0xB07C, 0xB07C, 12 }, + { 0xB07D, 0xB097, 13 }, + { 0xB098, 0xB098, 12 }, + { 0xB099, 0xB0B3, 13 }, + { 0xB0B4, 0xB0B4, 12 }, + { 0xB0B5, 0xB0CF, 13 }, + { 0xB0D0, 0xB0D0, 12 }, + { 0xB0D1, 0xB0EB, 13 }, + { 0xB0EC, 0xB0EC, 12 }, + { 0xB0ED, 0xB107, 13 }, + { 0xB108, 0xB108, 12 }, + { 0xB109, 0xB123, 13 }, + { 0xB124, 0xB124, 12 }, + { 0xB125, 0xB13F, 13 }, + { 0xB140, 0xB140, 12 }, + { 0xB141, 0xB15B, 13 }, + { 0xB15C, 0xB15C, 12 }, + { 0xB15D, 0xB177, 13 }, + { 0xB178, 0xB178, 12 }, + { 0xB179, 0xB193, 13 }, + { 0xB194, 0xB194, 12 }, + { 0xB195, 0xB1AF, 13 }, + { 0xB1B0, 0xB1B0, 12 }, + { 0xB1B1, 0xB1CB, 13 }, + { 0xB1CC, 0xB1CC, 12 }, + { 0xB1CD, 0xB1E7, 13 }, + { 0xB1E8, 0xB1E8, 12 }, + { 0xB1E9, 0xB203, 13 }, + { 0xB204, 0xB204, 12 }, + { 0xB205, 0xB21F, 13 }, + { 0xB220, 0xB220, 12 }, + { 0xB221, 0xB23B, 13 }, + { 0xB23C, 0xB23C, 12 }, + { 0xB23D, 0xB257, 13 }, + { 0xB258, 0xB258, 12 }, + { 0xB259, 0xB273, 13 }, + { 0xB274, 0xB274, 12 }, + { 0xB275, 0xB28F, 13 }, + { 0xB290, 0xB290, 12 }, + { 0xB291, 0xB2AB, 13 }, + { 0xB2AC, 0xB2AC, 12 }, + { 0xB2AD, 0xB2C7, 13 }, + { 0xB2C8, 0xB2C8, 12 }, + { 0xB2C9, 0xB2E3, 13 }, + { 0xB2E4, 0xB2E4, 12 }, + { 0xB2E5, 0xB2FF, 13 }, + { 0xB300, 0xB300, 12 }, + { 0xB301, 0xB31B, 13 }, + { 0xB31C, 0xB31C, 12 }, + { 0xB31D, 0xB337, 13 }, + { 0xB338, 0xB338, 12 }, + { 0xB339, 0xB353, 13 }, + { 0xB354, 0xB354, 12 }, + { 0xB355, 0xB36F, 13 }, + { 0xB370, 0xB370, 12 }, + { 0xB371, 0xB38B, 13 }, + { 0xB38C, 0xB38C, 12 }, + { 0xB38D, 0xB3A7, 13 }, + { 0xB3A8, 0xB3A8, 12 }, + { 0xB3A9, 0xB3C3, 13 }, + { 0xB3C4, 0xB3C4, 12 }, + { 0xB3C5, 0xB3DF, 13 }, + { 0xB3E0, 0xB3E0, 12 }, + { 0xB3E1, 0xB3FB, 13 }, + { 0xB3FC, 0xB3FC, 12 }, + { 0xB3FD, 0xB417, 13 }, + { 0xB418, 0xB418, 12 }, + { 0xB419, 0xB433, 13 }, + { 0xB434, 0xB434, 12 }, + { 0xB435, 0xB44F, 13 }, + { 0xB450, 0xB450, 12 }, + { 0xB451, 0xB46B, 13 }, + { 0xB46C, 0xB46C, 12 }, + { 0xB46D, 0xB487, 13 }, + { 0xB488, 0xB488, 12 }, + { 0xB489, 0xB4A3, 13 }, + { 0xB4A4, 0xB4A4, 12 }, + { 0xB4A5, 0xB4BF, 13 }, + { 0xB4C0, 0xB4C0, 12 }, + { 0xB4C1, 0xB4DB, 13 }, + { 0xB4DC, 0xB4DC, 12 }, + { 0xB4DD, 0xB4F7, 13 }, + { 0xB4F8, 0xB4F8, 12 }, + { 0xB4F9, 0xB513, 13 }, + { 0xB514, 0xB514, 12 }, + { 0xB515, 0xB52F, 13 }, + { 0xB530, 0xB530, 12 }, + { 0xB531, 0xB54B, 13 }, + { 0xB54C, 0xB54C, 12 }, + { 0xB54D, 0xB567, 13 }, + { 0xB568, 0xB568, 12 }, + { 0xB569, 0xB583, 13 }, + { 0xB584, 0xB584, 12 }, + { 0xB585, 0xB59F, 13 }, + { 0xB5A0, 0xB5A0, 12 }, + { 0xB5A1, 0xB5BB, 13 }, + { 0xB5BC, 0xB5BC, 12 }, + { 0xB5BD, 0xB5D7, 13 }, + { 0xB5D8, 0xB5D8, 12 }, + { 0xB5D9, 0xB5F3, 13 }, + { 0xB5F4, 0xB5F4, 12 }, + { 0xB5F5, 0xB60F, 13 }, + { 0xB610, 0xB610, 12 }, + { 0xB611, 0xB62B, 13 }, + { 0xB62C, 0xB62C, 12 }, + { 0xB62D, 0xB647, 13 }, + { 0xB648, 0xB648, 12 }, + { 0xB649, 0xB663, 13 }, + { 0xB664, 0xB664, 12 }, + { 0xB665, 0xB67F, 13 }, + { 0xB680, 0xB680, 12 }, + { 0xB681, 0xB69B, 13 }, + { 0xB69C, 0xB69C, 12 }, + { 0xB69D, 0xB6B7, 13 }, + { 0xB6B8, 0xB6B8, 12 }, + { 0xB6B9, 0xB6D3, 13 }, + { 0xB6D4, 0xB6D4, 12 }, + { 0xB6D5, 0xB6EF, 13 }, + { 0xB6F0, 0xB6F0, 12 }, + { 0xB6F1, 0xB70B, 13 }, + { 0xB70C, 0xB70C, 12 }, + { 0xB70D, 0xB727, 13 }, + { 0xB728, 0xB728, 12 }, + { 0xB729, 0xB743, 13 }, + { 0xB744, 0xB744, 12 }, + { 0xB745, 0xB75F, 13 }, + { 0xB760, 0xB760, 12 }, + { 0xB761, 0xB77B, 13 }, + { 0xB77C, 0xB77C, 12 }, + { 0xB77D, 0xB797, 13 }, + { 0xB798, 0xB798, 12 }, + { 0xB799, 0xB7B3, 13 }, + { 0xB7B4, 0xB7B4, 12 }, + { 0xB7B5, 0xB7CF, 13 }, + { 0xB7D0, 0xB7D0, 12 }, + { 0xB7D1, 0xB7EB, 13 }, + { 0xB7EC, 0xB7EC, 12 }, + { 0xB7ED, 0xB807, 13 }, + { 0xB808, 0xB808, 12 }, + { 0xB809, 0xB823, 13 }, + { 0xB824, 0xB824, 12 }, + { 0xB825, 0xB83F, 13 }, + { 0xB840, 0xB840, 12 }, + { 0xB841, 0xB85B, 13 }, + { 0xB85C, 0xB85C, 12 }, + { 0xB85D, 0xB877, 13 }, + { 0xB878, 0xB878, 12 }, + { 0xB879, 0xB893, 13 }, + { 0xB894, 0xB894, 12 }, + { 0xB895, 0xB8AF, 13 }, + { 0xB8B0, 0xB8B0, 12 }, + { 0xB8B1, 0xB8CB, 13 }, + { 0xB8CC, 0xB8CC, 12 }, + { 0xB8CD, 0xB8E7, 13 }, + { 0xB8E8, 0xB8E8, 12 }, + { 0xB8E9, 0xB903, 13 }, + { 0xB904, 0xB904, 12 }, + { 0xB905, 0xB91F, 13 }, + { 0xB920, 0xB920, 12 }, + { 0xB921, 0xB93B, 13 }, + { 0xB93C, 0xB93C, 12 }, + { 0xB93D, 0xB957, 13 }, + { 0xB958, 0xB958, 12 }, + { 0xB959, 0xB973, 13 }, + { 0xB974, 0xB974, 12 }, + { 0xB975, 0xB98F, 13 }, + { 0xB990, 0xB990, 12 }, + { 0xB991, 0xB9AB, 13 }, + { 0xB9AC, 0xB9AC, 12 }, + { 0xB9AD, 0xB9C7, 13 }, + { 0xB9C8, 0xB9C8, 12 }, + { 0xB9C9, 0xB9E3, 13 }, + { 0xB9E4, 0xB9E4, 12 }, + { 0xB9E5, 0xB9FF, 13 }, + { 0xBA00, 0xBA00, 12 }, + { 0xBA01, 0xBA1B, 13 }, + { 0xBA1C, 0xBA1C, 12 }, + { 0xBA1D, 0xBA37, 13 }, + { 0xBA38, 0xBA38, 12 }, + { 0xBA39, 0xBA53, 13 }, + { 0xBA54, 0xBA54, 12 }, + { 0xBA55, 0xBA6F, 13 }, + { 0xBA70, 0xBA70, 12 }, + { 0xBA71, 0xBA8B, 13 }, + { 0xBA8C, 0xBA8C, 12 }, + { 0xBA8D, 0xBAA7, 13 }, + { 0xBAA8, 0xBAA8, 12 }, + { 0xBAA9, 0xBAC3, 13 }, + { 0xBAC4, 0xBAC4, 12 }, + { 0xBAC5, 0xBADF, 13 }, + { 0xBAE0, 0xBAE0, 12 }, + { 0xBAE1, 0xBAFB, 13 }, + { 0xBAFC, 0xBAFC, 12 }, + { 0xBAFD, 0xBB17, 13 }, + { 0xBB18, 0xBB18, 12 }, + { 0xBB19, 0xBB33, 13 }, + { 0xBB34, 0xBB34, 12 }, + { 0xBB35, 0xBB4F, 13 }, + { 0xBB50, 0xBB50, 12 }, + { 0xBB51, 0xBB6B, 13 }, + { 0xBB6C, 0xBB6C, 12 }, + { 0xBB6D, 0xBB87, 13 }, + { 0xBB88, 0xBB88, 12 }, + { 0xBB89, 0xBBA3, 13 }, + { 0xBBA4, 0xBBA4, 12 }, + { 0xBBA5, 0xBBBF, 13 }, + { 0xBBC0, 0xBBC0, 12 }, + { 0xBBC1, 0xBBDB, 13 }, + { 0xBBDC, 0xBBDC, 12 }, + { 0xBBDD, 0xBBF7, 13 }, + { 0xBBF8, 0xBBF8, 12 }, + { 0xBBF9, 0xBC13, 13 }, + { 0xBC14, 0xBC14, 12 }, + { 0xBC15, 0xBC2F, 13 }, + { 0xBC30, 0xBC30, 12 }, + { 0xBC31, 0xBC4B, 13 }, + { 0xBC4C, 0xBC4C, 12 }, + { 0xBC4D, 0xBC67, 13 }, + { 0xBC68, 0xBC68, 12 }, + { 0xBC69, 0xBC83, 13 }, + { 0xBC84, 0xBC84, 12 }, + { 0xBC85, 0xBC9F, 13 }, + { 0xBCA0, 0xBCA0, 12 }, + { 0xBCA1, 0xBCBB, 13 }, + { 0xBCBC, 0xBCBC, 12 }, + { 0xBCBD, 0xBCD7, 13 }, + { 0xBCD8, 0xBCD8, 12 }, + { 0xBCD9, 0xBCF3, 13 }, + { 0xBCF4, 0xBCF4, 12 }, + { 0xBCF5, 0xBD0F, 13 }, + { 0xBD10, 0xBD10, 12 }, + { 0xBD11, 0xBD2B, 13 }, + { 0xBD2C, 0xBD2C, 12 }, + { 0xBD2D, 0xBD47, 13 }, + { 0xBD48, 0xBD48, 12 }, + { 0xBD49, 0xBD63, 13 }, + { 0xBD64, 0xBD64, 12 }, + { 0xBD65, 0xBD7F, 13 }, + { 0xBD80, 0xBD80, 12 }, + { 0xBD81, 0xBD9B, 13 }, + { 0xBD9C, 0xBD9C, 12 }, + { 0xBD9D, 0xBDB7, 13 }, + { 0xBDB8, 0xBDB8, 12 }, + { 0xBDB9, 0xBDD3, 13 }, + { 0xBDD4, 0xBDD4, 12 }, + { 0xBDD5, 0xBDEF, 13 }, + { 0xBDF0, 0xBDF0, 12 }, + { 0xBDF1, 0xBE0B, 13 }, + { 0xBE0C, 0xBE0C, 12 }, + { 0xBE0D, 0xBE27, 13 }, + { 0xBE28, 0xBE28, 12 }, + { 0xBE29, 0xBE43, 13 }, + { 0xBE44, 0xBE44, 12 }, + { 0xBE45, 0xBE5F, 13 }, + { 0xBE60, 0xBE60, 12 }, + { 0xBE61, 0xBE7B, 13 }, + { 0xBE7C, 0xBE7C, 12 }, + { 0xBE7D, 0xBE97, 13 }, + { 0xBE98, 0xBE98, 12 }, + { 0xBE99, 0xBEB3, 13 }, + { 0xBEB4, 0xBEB4, 12 }, + { 0xBEB5, 0xBECF, 13 }, + { 0xBED0, 0xBED0, 12 }, + { 0xBED1, 0xBEEB, 13 }, + { 0xBEEC, 0xBEEC, 12 }, + { 0xBEED, 0xBF07, 13 }, + { 0xBF08, 0xBF08, 12 }, + { 0xBF09, 0xBF23, 13 }, + { 0xBF24, 0xBF24, 12 }, + { 0xBF25, 0xBF3F, 13 }, + { 0xBF40, 0xBF40, 12 }, + { 0xBF41, 0xBF5B, 13 }, + { 0xBF5C, 0xBF5C, 12 }, + { 0xBF5D, 0xBF77, 13 }, + { 0xBF78, 0xBF78, 12 }, + { 0xBF79, 0xBF93, 13 }, + { 0xBF94, 0xBF94, 12 }, + { 0xBF95, 0xBFAF, 13 }, + { 0xBFB0, 0xBFB0, 12 }, + { 0xBFB1, 0xBFCB, 13 }, + { 0xBFCC, 0xBFCC, 12 }, + { 0xBFCD, 0xBFE7, 13 }, + { 0xBFE8, 0xBFE8, 12 }, + { 0xBFE9, 0xC003, 13 }, + { 0xC004, 0xC004, 12 }, + { 0xC005, 0xC01F, 13 }, + { 0xC020, 0xC020, 12 }, + { 0xC021, 0xC03B, 13 }, + { 0xC03C, 0xC03C, 12 }, + { 0xC03D, 0xC057, 13 }, + { 0xC058, 0xC058, 12 }, + { 0xC059, 0xC073, 13 }, + { 0xC074, 0xC074, 12 }, + { 0xC075, 0xC08F, 13 }, + { 0xC090, 0xC090, 12 }, + { 0xC091, 0xC0AB, 13 }, + { 0xC0AC, 0xC0AC, 12 }, + { 0xC0AD, 0xC0C7, 13 }, + { 0xC0C8, 0xC0C8, 12 }, + { 0xC0C9, 0xC0E3, 13 }, + { 0xC0E4, 0xC0E4, 12 }, + { 0xC0E5, 0xC0FF, 13 }, + { 0xC100, 0xC100, 12 }, + { 0xC101, 0xC11B, 13 }, + { 0xC11C, 0xC11C, 12 }, + { 0xC11D, 0xC137, 13 }, + { 0xC138, 0xC138, 12 }, + { 0xC139, 0xC153, 13 }, + { 0xC154, 0xC154, 12 }, + { 0xC155, 0xC16F, 13 }, + { 0xC170, 0xC170, 12 }, + { 0xC171, 0xC18B, 13 }, + { 0xC18C, 0xC18C, 12 }, + { 0xC18D, 0xC1A7, 13 }, + { 0xC1A8, 0xC1A8, 12 }, + { 0xC1A9, 0xC1C3, 13 }, + { 0xC1C4, 0xC1C4, 12 }, + { 0xC1C5, 0xC1DF, 13 }, + { 0xC1E0, 0xC1E0, 12 }, + { 0xC1E1, 0xC1FB, 13 }, + { 0xC1FC, 0xC1FC, 12 }, + { 0xC1FD, 0xC217, 13 }, + { 0xC218, 0xC218, 12 }, + { 0xC219, 0xC233, 13 }, + { 0xC234, 0xC234, 12 }, + { 0xC235, 0xC24F, 13 }, + { 0xC250, 0xC250, 12 }, + { 0xC251, 0xC26B, 13 }, + { 0xC26C, 0xC26C, 12 }, + { 0xC26D, 0xC287, 13 }, + { 0xC288, 0xC288, 12 }, + { 0xC289, 0xC2A3, 13 }, + { 0xC2A4, 0xC2A4, 12 }, + { 0xC2A5, 0xC2BF, 13 }, + { 0xC2C0, 0xC2C0, 12 }, + { 0xC2C1, 0xC2DB, 13 }, + { 0xC2DC, 0xC2DC, 12 }, + { 0xC2DD, 0xC2F7, 13 }, + { 0xC2F8, 0xC2F8, 12 }, + { 0xC2F9, 0xC313, 13 }, + { 0xC314, 0xC314, 12 }, + { 0xC315, 0xC32F, 13 }, + { 0xC330, 0xC330, 12 }, + { 0xC331, 0xC34B, 13 }, + { 0xC34C, 0xC34C, 12 }, + { 0xC34D, 0xC367, 13 }, + { 0xC368, 0xC368, 12 }, + { 0xC369, 0xC383, 13 }, + { 0xC384, 0xC384, 12 }, + { 0xC385, 0xC39F, 13 }, + { 0xC3A0, 0xC3A0, 12 }, + { 0xC3A1, 0xC3BB, 13 }, + { 0xC3BC, 0xC3BC, 12 }, + { 0xC3BD, 0xC3D7, 13 }, + { 0xC3D8, 0xC3D8, 12 }, + { 0xC3D9, 0xC3F3, 13 }, + { 0xC3F4, 0xC3F4, 12 }, + { 0xC3F5, 0xC40F, 13 }, + { 0xC410, 0xC410, 12 }, + { 0xC411, 0xC42B, 13 }, + { 0xC42C, 0xC42C, 12 }, + { 0xC42D, 0xC447, 13 }, + { 0xC448, 0xC448, 12 }, + { 0xC449, 0xC463, 13 }, + { 0xC464, 0xC464, 12 }, + { 0xC465, 0xC47F, 13 }, + { 0xC480, 0xC480, 12 }, + { 0xC481, 0xC49B, 13 }, + { 0xC49C, 0xC49C, 12 }, + { 0xC49D, 0xC4B7, 13 }, + { 0xC4B8, 0xC4B8, 12 }, + { 0xC4B9, 0xC4D3, 13 }, + { 0xC4D4, 0xC4D4, 12 }, + { 0xC4D5, 0xC4EF, 13 }, + { 0xC4F0, 0xC4F0, 12 }, + { 0xC4F1, 0xC50B, 13 }, + { 0xC50C, 0xC50C, 12 }, + { 0xC50D, 0xC527, 13 }, + { 0xC528, 0xC528, 12 }, + { 0xC529, 0xC543, 13 }, + { 0xC544, 0xC544, 12 }, + { 0xC545, 0xC55F, 13 }, + { 0xC560, 0xC560, 12 }, + { 0xC561, 0xC57B, 13 }, + { 0xC57C, 0xC57C, 12 }, + { 0xC57D, 0xC597, 13 }, + { 0xC598, 0xC598, 12 }, + { 0xC599, 0xC5B3, 13 }, + { 0xC5B4, 0xC5B4, 12 }, + { 0xC5B5, 0xC5CF, 13 }, + { 0xC5D0, 0xC5D0, 12 }, + { 0xC5D1, 0xC5EB, 13 }, + { 0xC5EC, 0xC5EC, 12 }, + { 0xC5ED, 0xC607, 13 }, + { 0xC608, 0xC608, 12 }, + { 0xC609, 0xC623, 13 }, + { 0xC624, 0xC624, 12 }, + { 0xC625, 0xC63F, 13 }, + { 0xC640, 0xC640, 12 }, + { 0xC641, 0xC65B, 13 }, + { 0xC65C, 0xC65C, 12 }, + { 0xC65D, 0xC677, 13 }, + { 0xC678, 0xC678, 12 }, + { 0xC679, 0xC693, 13 }, + { 0xC694, 0xC694, 12 }, + { 0xC695, 0xC6AF, 13 }, + { 0xC6B0, 0xC6B0, 12 }, + { 0xC6B1, 0xC6CB, 13 }, + { 0xC6CC, 0xC6CC, 12 }, + { 0xC6CD, 0xC6E7, 13 }, + { 0xC6E8, 0xC6E8, 12 }, + { 0xC6E9, 0xC703, 13 }, + { 0xC704, 0xC704, 12 }, + { 0xC705, 0xC71F, 13 }, + { 0xC720, 0xC720, 12 }, + { 0xC721, 0xC73B, 13 }, + { 0xC73C, 0xC73C, 12 }, + { 0xC73D, 0xC757, 13 }, + { 0xC758, 0xC758, 12 }, + { 0xC759, 0xC773, 13 }, + { 0xC774, 0xC774, 12 }, + { 0xC775, 0xC78F, 13 }, + { 0xC790, 0xC790, 12 }, + { 0xC791, 0xC7AB, 13 }, + { 0xC7AC, 0xC7AC, 12 }, + { 0xC7AD, 0xC7C7, 13 }, + { 0xC7C8, 0xC7C8, 12 }, + { 0xC7C9, 0xC7E3, 13 }, + { 0xC7E4, 0xC7E4, 12 }, + { 0xC7E5, 0xC7FF, 13 }, + { 0xC800, 0xC800, 12 }, + { 0xC801, 0xC81B, 13 }, + { 0xC81C, 0xC81C, 12 }, + { 0xC81D, 0xC837, 13 }, + { 0xC838, 0xC838, 12 }, + { 0xC839, 0xC853, 13 }, + { 0xC854, 0xC854, 12 }, + { 0xC855, 0xC86F, 13 }, + { 0xC870, 0xC870, 12 }, + { 0xC871, 0xC88B, 13 }, + { 0xC88C, 0xC88C, 12 }, + { 0xC88D, 0xC8A7, 13 }, + { 0xC8A8, 0xC8A8, 12 }, + { 0xC8A9, 0xC8C3, 13 }, + { 0xC8C4, 0xC8C4, 12 }, + { 0xC8C5, 0xC8DF, 13 }, + { 0xC8E0, 0xC8E0, 12 }, + { 0xC8E1, 0xC8FB, 13 }, + { 0xC8FC, 0xC8FC, 12 }, + { 0xC8FD, 0xC917, 13 }, + { 0xC918, 0xC918, 12 }, + { 0xC919, 0xC933, 13 }, + { 0xC934, 0xC934, 12 }, + { 0xC935, 0xC94F, 13 }, + { 0xC950, 0xC950, 12 }, + { 0xC951, 0xC96B, 13 }, + { 0xC96C, 0xC96C, 12 }, + { 0xC96D, 0xC987, 13 }, + { 0xC988, 0xC988, 12 }, + { 0xC989, 0xC9A3, 13 }, + { 0xC9A4, 0xC9A4, 12 }, + { 0xC9A5, 0xC9BF, 13 }, + { 0xC9C0, 0xC9C0, 12 }, + { 0xC9C1, 0xC9DB, 13 }, + { 0xC9DC, 0xC9DC, 12 }, + { 0xC9DD, 0xC9F7, 13 }, + { 0xC9F8, 0xC9F8, 12 }, + { 0xC9F9, 0xCA13, 13 }, + { 0xCA14, 0xCA14, 12 }, + { 0xCA15, 0xCA2F, 13 }, + { 0xCA30, 0xCA30, 12 }, + { 0xCA31, 0xCA4B, 13 }, + { 0xCA4C, 0xCA4C, 12 }, + { 0xCA4D, 0xCA67, 13 }, + { 0xCA68, 0xCA68, 12 }, + { 0xCA69, 0xCA83, 13 }, + { 0xCA84, 0xCA84, 12 }, + { 0xCA85, 0xCA9F, 13 }, + { 0xCAA0, 0xCAA0, 12 }, + { 0xCAA1, 0xCABB, 13 }, + { 0xCABC, 0xCABC, 12 }, + { 0xCABD, 0xCAD7, 13 }, + { 0xCAD8, 0xCAD8, 12 }, + { 0xCAD9, 0xCAF3, 13 }, + { 0xCAF4, 0xCAF4, 12 }, + { 0xCAF5, 0xCB0F, 13 }, + { 0xCB10, 0xCB10, 12 }, + { 0xCB11, 0xCB2B, 13 }, + { 0xCB2C, 0xCB2C, 12 }, + { 0xCB2D, 0xCB47, 13 }, + { 0xCB48, 0xCB48, 12 }, + { 0xCB49, 0xCB63, 13 }, + { 0xCB64, 0xCB64, 12 }, + { 0xCB65, 0xCB7F, 13 }, + { 0xCB80, 0xCB80, 12 }, + { 0xCB81, 0xCB9B, 13 }, + { 0xCB9C, 0xCB9C, 12 }, + { 0xCB9D, 0xCBB7, 13 }, + { 0xCBB8, 0xCBB8, 12 }, + { 0xCBB9, 0xCBD3, 13 }, + { 0xCBD4, 0xCBD4, 12 }, + { 0xCBD5, 0xCBEF, 13 }, + { 0xCBF0, 0xCBF0, 12 }, + { 0xCBF1, 0xCC0B, 13 }, + { 0xCC0C, 0xCC0C, 12 }, + { 0xCC0D, 0xCC27, 13 }, + { 0xCC28, 0xCC28, 12 }, + { 0xCC29, 0xCC43, 13 }, + { 0xCC44, 0xCC44, 12 }, + { 0xCC45, 0xCC5F, 13 }, + { 0xCC60, 0xCC60, 12 }, + { 0xCC61, 0xCC7B, 13 }, + { 0xCC7C, 0xCC7C, 12 }, + { 0xCC7D, 0xCC97, 13 }, + { 0xCC98, 0xCC98, 12 }, + { 0xCC99, 0xCCB3, 13 }, + { 0xCCB4, 0xCCB4, 12 }, + { 0xCCB5, 0xCCCF, 13 }, + { 0xCCD0, 0xCCD0, 12 }, + { 0xCCD1, 0xCCEB, 13 }, + { 0xCCEC, 0xCCEC, 12 }, + { 0xCCED, 0xCD07, 13 }, + { 0xCD08, 0xCD08, 12 }, + { 0xCD09, 0xCD23, 13 }, + { 0xCD24, 0xCD24, 12 }, + { 0xCD25, 0xCD3F, 13 }, + { 0xCD40, 0xCD40, 12 }, + { 0xCD41, 0xCD5B, 13 }, + { 0xCD5C, 0xCD5C, 12 }, + { 0xCD5D, 0xCD77, 13 }, + { 0xCD78, 0xCD78, 12 }, + { 0xCD79, 0xCD93, 13 }, + { 0xCD94, 0xCD94, 12 }, + { 0xCD95, 0xCDAF, 13 }, + { 0xCDB0, 0xCDB0, 12 }, + { 0xCDB1, 0xCDCB, 13 }, + { 0xCDCC, 0xCDCC, 12 }, + { 0xCDCD, 0xCDE7, 13 }, + { 0xCDE8, 0xCDE8, 12 }, + { 0xCDE9, 0xCE03, 13 }, + { 0xCE04, 0xCE04, 12 }, + { 0xCE05, 0xCE1F, 13 }, + { 0xCE20, 0xCE20, 12 }, + { 0xCE21, 0xCE3B, 13 }, + { 0xCE3C, 0xCE3C, 12 }, + { 0xCE3D, 0xCE57, 13 }, + { 0xCE58, 0xCE58, 12 }, + { 0xCE59, 0xCE73, 13 }, + { 0xCE74, 0xCE74, 12 }, + { 0xCE75, 0xCE8F, 13 }, + { 0xCE90, 0xCE90, 12 }, + { 0xCE91, 0xCEAB, 13 }, + { 0xCEAC, 0xCEAC, 12 }, + { 0xCEAD, 0xCEC7, 13 }, + { 0xCEC8, 0xCEC8, 12 }, + { 0xCEC9, 0xCEE3, 13 }, + { 0xCEE4, 0xCEE4, 12 }, + { 0xCEE5, 0xCEFF, 13 }, + { 0xCF00, 0xCF00, 12 }, + { 0xCF01, 0xCF1B, 13 }, + { 0xCF1C, 0xCF1C, 12 }, + { 0xCF1D, 0xCF37, 13 }, + { 0xCF38, 0xCF38, 12 }, + { 0xCF39, 0xCF53, 13 }, + { 0xCF54, 0xCF54, 12 }, + { 0xCF55, 0xCF6F, 13 }, + { 0xCF70, 0xCF70, 12 }, + { 0xCF71, 0xCF8B, 13 }, + { 0xCF8C, 0xCF8C, 12 }, + { 0xCF8D, 0xCFA7, 13 }, + { 0xCFA8, 0xCFA8, 12 }, + { 0xCFA9, 0xCFC3, 13 }, + { 0xCFC4, 0xCFC4, 12 }, + { 0xCFC5, 0xCFDF, 13 }, + { 0xCFE0, 0xCFE0, 12 }, + { 0xCFE1, 0xCFFB, 13 }, + { 0xCFFC, 0xCFFC, 12 }, + { 0xCFFD, 0xD017, 13 }, + { 0xD018, 0xD018, 12 }, + { 0xD019, 0xD033, 13 }, + { 0xD034, 0xD034, 12 }, + { 0xD035, 0xD04F, 13 }, + { 0xD050, 0xD050, 12 }, + { 0xD051, 0xD06B, 13 }, + { 0xD06C, 0xD06C, 12 }, + { 0xD06D, 0xD087, 13 }, + { 0xD088, 0xD088, 12 }, + { 0xD089, 0xD0A3, 13 }, + { 0xD0A4, 0xD0A4, 12 }, + { 0xD0A5, 0xD0BF, 13 }, + { 0xD0C0, 0xD0C0, 12 }, + { 0xD0C1, 0xD0DB, 13 }, + { 0xD0DC, 0xD0DC, 12 }, + { 0xD0DD, 0xD0F7, 13 }, + { 0xD0F8, 0xD0F8, 12 }, + { 0xD0F9, 0xD113, 13 }, + { 0xD114, 0xD114, 12 }, + { 0xD115, 0xD12F, 13 }, + { 0xD130, 0xD130, 12 }, + { 0xD131, 0xD14B, 13 }, + { 0xD14C, 0xD14C, 12 }, + { 0xD14D, 0xD167, 13 }, + { 0xD168, 0xD168, 12 }, + { 0xD169, 0xD183, 13 }, + { 0xD184, 0xD184, 12 }, + { 0xD185, 0xD19F, 13 }, + { 0xD1A0, 0xD1A0, 12 }, + { 0xD1A1, 0xD1BB, 13 }, + { 0xD1BC, 0xD1BC, 12 }, + { 0xD1BD, 0xD1D7, 13 }, + { 0xD1D8, 0xD1D8, 12 }, + { 0xD1D9, 0xD1F3, 13 }, + { 0xD1F4, 0xD1F4, 12 }, + { 0xD1F5, 0xD20F, 13 }, + { 0xD210, 0xD210, 12 }, + { 0xD211, 0xD22B, 13 }, + { 0xD22C, 0xD22C, 12 }, + { 0xD22D, 0xD247, 13 }, + { 0xD248, 0xD248, 12 }, + { 0xD249, 0xD263, 13 }, + { 0xD264, 0xD264, 12 }, + { 0xD265, 0xD27F, 13 }, + { 0xD280, 0xD280, 12 }, + { 0xD281, 0xD29B, 13 }, + { 0xD29C, 0xD29C, 12 }, + { 0xD29D, 0xD2B7, 13 }, + { 0xD2B8, 0xD2B8, 12 }, + { 0xD2B9, 0xD2D3, 13 }, + { 0xD2D4, 0xD2D4, 12 }, + { 0xD2D5, 0xD2EF, 13 }, + { 0xD2F0, 0xD2F0, 12 }, + { 0xD2F1, 0xD30B, 13 }, + { 0xD30C, 0xD30C, 12 }, + { 0xD30D, 0xD327, 13 }, + { 0xD328, 0xD328, 12 }, + { 0xD329, 0xD343, 13 }, + { 0xD344, 0xD344, 12 }, + { 0xD345, 0xD35F, 13 }, + { 0xD360, 0xD360, 12 }, + { 0xD361, 0xD37B, 13 }, + { 0xD37C, 0xD37C, 12 }, + { 0xD37D, 0xD397, 13 }, + { 0xD398, 0xD398, 12 }, + { 0xD399, 0xD3B3, 13 }, + { 0xD3B4, 0xD3B4, 12 }, + { 0xD3B5, 0xD3CF, 13 }, + { 0xD3D0, 0xD3D0, 12 }, + { 0xD3D1, 0xD3EB, 13 }, + { 0xD3EC, 0xD3EC, 12 }, + { 0xD3ED, 0xD407, 13 }, + { 0xD408, 0xD408, 12 }, + { 0xD409, 0xD423, 13 }, + { 0xD424, 0xD424, 12 }, + { 0xD425, 0xD43F, 13 }, + { 0xD440, 0xD440, 12 }, + { 0xD441, 0xD45B, 13 }, + { 0xD45C, 0xD45C, 12 }, + { 0xD45D, 0xD477, 13 }, + { 0xD478, 0xD478, 12 }, + { 0xD479, 0xD493, 13 }, + { 0xD494, 0xD494, 12 }, + { 0xD495, 0xD4AF, 13 }, + { 0xD4B0, 0xD4B0, 12 }, + { 0xD4B1, 0xD4CB, 13 }, + { 0xD4CC, 0xD4CC, 12 }, + { 0xD4CD, 0xD4E7, 13 }, + { 0xD4E8, 0xD4E8, 12 }, + { 0xD4E9, 0xD503, 13 }, + { 0xD504, 0xD504, 12 }, + { 0xD505, 0xD51F, 13 }, + { 0xD520, 0xD520, 12 }, + { 0xD521, 0xD53B, 13 }, + { 0xD53C, 0xD53C, 12 }, + { 0xD53D, 0xD557, 13 }, + { 0xD558, 0xD558, 12 }, + { 0xD559, 0xD573, 13 }, + { 0xD574, 0xD574, 12 }, + { 0xD575, 0xD58F, 13 }, + { 0xD590, 0xD590, 12 }, + { 0xD591, 0xD5AB, 13 }, + { 0xD5AC, 0xD5AC, 12 }, + { 0xD5AD, 0xD5C7, 13 }, + { 0xD5C8, 0xD5C8, 12 }, + { 0xD5C9, 0xD5E3, 13 }, + { 0xD5E4, 0xD5E4, 12 }, + { 0xD5E5, 0xD5FF, 13 }, + { 0xD600, 0xD600, 12 }, + { 0xD601, 0xD61B, 13 }, + { 0xD61C, 0xD61C, 12 }, + { 0xD61D, 0xD637, 13 }, + { 0xD638, 0xD638, 12 }, + { 0xD639, 0xD653, 13 }, + { 0xD654, 0xD654, 12 }, + { 0xD655, 0xD66F, 13 }, + { 0xD670, 0xD670, 12 }, + { 0xD671, 0xD68B, 13 }, + { 0xD68C, 0xD68C, 12 }, + { 0xD68D, 0xD6A7, 13 }, + { 0xD6A8, 0xD6A8, 12 }, + { 0xD6A9, 0xD6C3, 13 }, + { 0xD6C4, 0xD6C4, 12 }, + { 0xD6C5, 0xD6DF, 13 }, + { 0xD6E0, 0xD6E0, 12 }, + { 0xD6E1, 0xD6FB, 13 }, + { 0xD6FC, 0xD6FC, 12 }, + { 0xD6FD, 0xD717, 13 }, + { 0xD718, 0xD718, 12 }, + { 0xD719, 0xD733, 13 }, + { 0xD734, 0xD734, 12 }, + { 0xD735, 0xD74F, 13 }, + { 0xD750, 0xD750, 12 }, + { 0xD751, 0xD76B, 13 }, + { 0xD76C, 0xD76C, 12 }, + { 0xD76D, 0xD787, 13 }, + { 0xD788, 0xD788, 12 }, + { 0xD789, 0xD7A3, 13 }, + { 0xD7B0, 0xD7C6, 10 }, + { 0xD7CB, 0xD7FB, 11 }, + { 0xFB1E, 0xFB1E, 4 }, + { 0xFE00, 0xFE0F, 4 }, + { 0xFE20, 0xFE2F, 4 }, + { 0xFEFF, 0xFEFF, 3 }, + { 0xFF9E, 0xFF9F, 4 }, + { 0xFFF0, 0xFFFB, 3 }, + { 0x101FD, 0x101FD, 4 }, + { 0x102E0, 0x102E0, 4 }, + { 0x10376, 0x1037A, 4 }, + { 0x10A01, 0x10A03, 4 }, + { 0x10A05, 0x10A06, 4 }, + { 0x10A0C, 0x10A0F, 4 }, + { 0x10A38, 0x10A3A, 4 }, + { 0x10A3F, 0x10A3F, 4 }, + { 0x10AE5, 0x10AE6, 4 }, + { 0x10D24, 0x10D27, 4 }, + { 0x10D69, 0x10D6D, 4 }, + { 0x10EAB, 0x10EAC, 4 }, + { 0x10EFC, 0x10EFF, 4 }, + { 0x10F46, 0x10F50, 4 }, + { 0x10F82, 0x10F85, 4 }, + { 0x11000, 0x11000, 8 }, + { 0x11001, 0x11001, 4 }, + { 0x11002, 0x11002, 8 }, + { 0x11038, 0x11046, 4 }, + { 0x11070, 0x11070, 4 }, + { 0x11073, 0x11074, 4 }, + { 0x1107F, 0x11081, 4 }, + { 0x11082, 0x11082, 8 }, + { 0x110B0, 0x110B2, 8 }, + { 0x110B3, 0x110B6, 4 }, + { 0x110B7, 0x110B8, 8 }, + { 0x110B9, 0x110BA, 4 }, + { 0x110BD, 0x110BD, 7 }, + { 0x110C2, 0x110C2, 4 }, + { 0x110CD, 0x110CD, 7 }, + { 0x11100, 0x11102, 4 }, + { 0x11127, 0x1112B, 4 }, + { 0x1112C, 0x1112C, 8 }, + { 0x1112D, 0x11134, 4 }, + { 0x11145, 0x11146, 8 }, + { 0x11173, 0x11173, 4 }, + { 0x11180, 0x11181, 4 }, + { 0x11182, 0x11182, 8 }, + { 0x111B3, 0x111B5, 8 }, + { 0x111B6, 0x111BE, 4 }, + { 0x111BF, 0x111BF, 8 }, + { 0x111C0, 0x111C0, 4 }, + { 0x111C2, 0x111C3, 7 }, + { 0x111C9, 0x111CC, 4 }, + { 0x111CE, 0x111CE, 8 }, + { 0x111CF, 0x111CF, 4 }, + { 0x1122C, 0x1122E, 8 }, + { 0x1122F, 0x11231, 4 }, + { 0x11232, 0x11233, 8 }, + { 0x11234, 0x11237, 4 }, + { 0x1123E, 0x1123E, 4 }, + { 0x11241, 0x11241, 4 }, + { 0x112DF, 0x112DF, 4 }, + { 0x112E0, 0x112E2, 8 }, + { 0x112E3, 0x112EA, 4 }, + { 0x11300, 0x11301, 4 }, + { 0x11302, 0x11303, 8 }, + { 0x1133B, 0x1133C, 4 }, + { 0x1133E, 0x1133E, 4 }, + { 0x1133F, 0x1133F, 8 }, + { 0x11340, 0x11340, 4 }, + { 0x11341, 0x11344, 8 }, + { 0x11347, 0x11348, 8 }, + { 0x1134B, 0x1134C, 8 }, + { 0x1134D, 0x1134D, 4 }, + { 0x11357, 0x11357, 4 }, + { 0x11362, 0x11363, 8 }, + { 0x11366, 0x1136C, 4 }, + { 0x11370, 0x11374, 4 }, + { 0x113B8, 0x113B8, 4 }, + { 0x113B9, 0x113BA, 8 }, + { 0x113BB, 0x113C0, 4 }, + { 0x113C2, 0x113C2, 4 }, + { 0x113C5, 0x113C5, 4 }, + { 0x113C7, 0x113C9, 4 }, + { 0x113CA, 0x113CA, 8 }, + { 0x113CC, 0x113CD, 8 }, + { 0x113CE, 0x113D0, 4 }, + { 0x113D1, 0x113D1, 7 }, + { 0x113D2, 0x113D2, 4 }, + { 0x113E1, 0x113E2, 4 }, + { 0x11435, 0x11437, 8 }, + { 0x11438, 0x1143F, 4 }, + { 0x11440, 0x11441, 8 }, + { 0x11442, 0x11444, 4 }, + { 0x11445, 0x11445, 8 }, + { 0x11446, 0x11446, 4 }, + { 0x1145E, 0x1145E, 4 }, + { 0x114B0, 0x114B0, 4 }, + { 0x114B1, 0x114B2, 8 }, + { 0x114B3, 0x114B8, 4 }, + { 0x114B9, 0x114B9, 8 }, + { 0x114BA, 0x114BA, 4 }, + { 0x114BB, 0x114BC, 8 }, + { 0x114BD, 0x114BD, 4 }, + { 0x114BE, 0x114BE, 8 }, + { 0x114BF, 0x114C0, 4 }, + { 0x114C1, 0x114C1, 8 }, + { 0x114C2, 0x114C3, 4 }, + { 0x115AF, 0x115AF, 4 }, + { 0x115B0, 0x115B1, 8 }, + { 0x115B2, 0x115B5, 4 }, + { 0x115B8, 0x115BB, 8 }, + { 0x115BC, 0x115BD, 4 }, + { 0x115BE, 0x115BE, 8 }, + { 0x115BF, 0x115C0, 4 }, + { 0x115DC, 0x115DD, 4 }, + { 0x11630, 0x11632, 8 }, + { 0x11633, 0x1163A, 4 }, + { 0x1163B, 0x1163C, 8 }, + { 0x1163D, 0x1163D, 4 }, + { 0x1163E, 0x1163E, 8 }, + { 0x1163F, 0x11640, 4 }, + { 0x116AB, 0x116AB, 4 }, + { 0x116AC, 0x116AC, 8 }, + { 0x116AD, 0x116AD, 4 }, + { 0x116AE, 0x116AF, 8 }, + { 0x116B0, 0x116B7, 4 }, + { 0x1171D, 0x1171D, 4 }, + { 0x1171E, 0x1171E, 8 }, + { 0x1171F, 0x1171F, 4 }, + { 0x11722, 0x11725, 4 }, + { 0x11726, 0x11726, 8 }, + { 0x11727, 0x1172B, 4 }, + { 0x1182C, 0x1182E, 8 }, + { 0x1182F, 0x11837, 4 }, + { 0x11838, 0x11838, 8 }, + { 0x11839, 0x1183A, 4 }, + { 0x11930, 0x11930, 4 }, + { 0x11931, 0x11935, 8 }, + { 0x11937, 0x11938, 8 }, + { 0x1193B, 0x1193E, 4 }, + { 0x1193F, 0x1193F, 7 }, + { 0x11940, 0x11940, 8 }, + { 0x11941, 0x11941, 7 }, + { 0x11942, 0x11942, 8 }, + { 0x11943, 0x11943, 4 }, + { 0x119D1, 0x119D3, 8 }, + { 0x119D4, 0x119D7, 4 }, + { 0x119DA, 0x119DB, 4 }, + { 0x119DC, 0x119DF, 8 }, + { 0x119E0, 0x119E0, 4 }, + { 0x119E4, 0x119E4, 8 }, + { 0x11A01, 0x11A0A, 4 }, + { 0x11A33, 0x11A38, 4 }, + { 0x11A39, 0x11A39, 8 }, + { 0x11A3A, 0x11A3A, 7 }, + { 0x11A3B, 0x11A3E, 4 }, + { 0x11A47, 0x11A47, 4 }, + { 0x11A51, 0x11A56, 4 }, + { 0x11A57, 0x11A58, 8 }, + { 0x11A59, 0x11A5B, 4 }, + { 0x11A84, 0x11A89, 7 }, + { 0x11A8A, 0x11A96, 4 }, + { 0x11A97, 0x11A97, 8 }, + { 0x11A98, 0x11A99, 4 }, + { 0x11C2F, 0x11C2F, 8 }, + { 0x11C30, 0x11C36, 4 }, + { 0x11C38, 0x11C3D, 4 }, + { 0x11C3E, 0x11C3E, 8 }, + { 0x11C3F, 0x11C3F, 4 }, + { 0x11C92, 0x11CA7, 4 }, + { 0x11CA9, 0x11CA9, 8 }, + { 0x11CAA, 0x11CB0, 4 }, + { 0x11CB1, 0x11CB1, 8 }, + { 0x11CB2, 0x11CB3, 4 }, + { 0x11CB4, 0x11CB4, 8 }, + { 0x11CB5, 0x11CB6, 4 }, + { 0x11D31, 0x11D36, 4 }, + { 0x11D3A, 0x11D3A, 4 }, + { 0x11D3C, 0x11D3D, 4 }, + { 0x11D3F, 0x11D45, 4 }, + { 0x11D46, 0x11D46, 7 }, + { 0x11D47, 0x11D47, 4 }, + { 0x11D8A, 0x11D8E, 8 }, + { 0x11D90, 0x11D91, 4 }, + { 0x11D93, 0x11D94, 8 }, + { 0x11D95, 0x11D95, 4 }, + { 0x11D96, 0x11D96, 8 }, + { 0x11D97, 0x11D97, 4 }, + { 0x11EF3, 0x11EF4, 4 }, + { 0x11EF5, 0x11EF6, 8 }, + { 0x11F00, 0x11F01, 4 }, + { 0x11F02, 0x11F02, 7 }, + { 0x11F03, 0x11F03, 8 }, + { 0x11F34, 0x11F35, 8 }, + { 0x11F36, 0x11F3A, 4 }, + { 0x11F3E, 0x11F3F, 8 }, + { 0x11F40, 0x11F42, 4 }, + { 0x11F5A, 0x11F5A, 4 }, + { 0x13430, 0x1343F, 3 }, + { 0x13440, 0x13440, 4 }, + { 0x13447, 0x13455, 4 }, + { 0x1611E, 0x16129, 4 }, + { 0x1612A, 0x1612C, 8 }, + { 0x1612D, 0x1612F, 4 }, + { 0x16AF0, 0x16AF4, 4 }, + { 0x16B30, 0x16B36, 4 }, + { 0x16D63, 0x16D63, 10 }, + { 0x16D67, 0x16D6A, 10 }, + { 0x16F4F, 0x16F4F, 4 }, + { 0x16F51, 0x16F87, 8 }, + { 0x16F8F, 0x16F92, 4 }, + { 0x16FE4, 0x16FE4, 4 }, + { 0x16FF0, 0x16FF1, 4 }, + { 0x1BC9D, 0x1BC9E, 4 }, + { 0x1BCA0, 0x1BCA3, 3 }, + { 0x1CF00, 0x1CF2D, 4 }, + { 0x1CF30, 0x1CF46, 4 }, + { 0x1D165, 0x1D169, 4 }, + { 0x1D16D, 0x1D172, 4 }, + { 0x1D173, 0x1D17A, 3 }, + { 0x1D17B, 0x1D182, 4 }, + { 0x1D185, 0x1D18B, 4 }, + { 0x1D1AA, 0x1D1AD, 4 }, + { 0x1D242, 0x1D244, 4 }, + { 0x1DA00, 0x1DA36, 4 }, + { 0x1DA3B, 0x1DA6C, 4 }, + { 0x1DA75, 0x1DA75, 4 }, + { 0x1DA84, 0x1DA84, 4 }, + { 0x1DA9B, 0x1DA9F, 4 }, + { 0x1DAA1, 0x1DAAF, 4 }, + { 0x1E000, 0x1E006, 4 }, + { 0x1E008, 0x1E018, 4 }, + { 0x1E01B, 0x1E021, 4 }, + { 0x1E023, 0x1E024, 4 }, + { 0x1E026, 0x1E02A, 4 }, + { 0x1E08F, 0x1E08F, 4 }, + { 0x1E130, 0x1E136, 4 }, + { 0x1E2AE, 0x1E2AE, 4 }, + { 0x1E2EC, 0x1E2EF, 4 }, + { 0x1E4EC, 0x1E4EF, 4 }, + { 0x1E5EE, 0x1E5EF, 4 }, + { 0x1E8D0, 0x1E8D6, 4 }, + { 0x1E944, 0x1E94A, 4 }, + { 0x1F1E6, 0x1F1FF, 6 }, + { 0x1F3FB, 0x1F3FF, 4 }, + { 0xE0000, 0xE001F, 3 }, + { 0xE0020, 0xE007F, 4 }, + { 0xE0080, 0xE00FF, 3 }, + { 0xE0100, 0xE01EF, 4 }, + { 0xE01F0, 0xE0FFF, 3 }, +}; +const size_t k_gcb_n = sizeof k_gcb / sizeof k_gcb[0]; + +const GbRange k_ext_pict[] = { + { 0xA9, 0xA9, 1 }, + { 0xAE, 0xAE, 1 }, + { 0x203C, 0x203C, 1 }, + { 0x2049, 0x2049, 1 }, + { 0x2122, 0x2122, 1 }, + { 0x2139, 0x2139, 1 }, + { 0x2194, 0x2199, 1 }, + { 0x21A9, 0x21AA, 1 }, + { 0x231A, 0x231B, 1 }, + { 0x2328, 0x2328, 1 }, + { 0x2388, 0x2388, 1 }, + { 0x23CF, 0x23CF, 1 }, + { 0x23E9, 0x23F3, 1 }, + { 0x23F8, 0x23FA, 1 }, + { 0x24C2, 0x24C2, 1 }, + { 0x25AA, 0x25AB, 1 }, + { 0x25B6, 0x25B6, 1 }, + { 0x25C0, 0x25C0, 1 }, + { 0x25FB, 0x25FE, 1 }, + { 0x2600, 0x2605, 1 }, + { 0x2607, 0x2612, 1 }, + { 0x2614, 0x2685, 1 }, + { 0x2690, 0x2705, 1 }, + { 0x2708, 0x2712, 1 }, + { 0x2714, 0x2714, 1 }, + { 0x2716, 0x2716, 1 }, + { 0x271D, 0x271D, 1 }, + { 0x2721, 0x2721, 1 }, + { 0x2728, 0x2728, 1 }, + { 0x2733, 0x2734, 1 }, + { 0x2744, 0x2744, 1 }, + { 0x2747, 0x2747, 1 }, + { 0x274C, 0x274C, 1 }, + { 0x274E, 0x274E, 1 }, + { 0x2753, 0x2755, 1 }, + { 0x2757, 0x2757, 1 }, + { 0x2763, 0x2767, 1 }, + { 0x2795, 0x2797, 1 }, + { 0x27A1, 0x27A1, 1 }, + { 0x27B0, 0x27B0, 1 }, + { 0x27BF, 0x27BF, 1 }, + { 0x2934, 0x2935, 1 }, + { 0x2B05, 0x2B07, 1 }, + { 0x2B1B, 0x2B1C, 1 }, + { 0x2B50, 0x2B50, 1 }, + { 0x2B55, 0x2B55, 1 }, + { 0x3030, 0x3030, 1 }, + { 0x303D, 0x303D, 1 }, + { 0x3297, 0x3297, 1 }, + { 0x3299, 0x3299, 1 }, + { 0x1F000, 0x1F0FF, 1 }, + { 0x1F10D, 0x1F10F, 1 }, + { 0x1F12F, 0x1F12F, 1 }, + { 0x1F16C, 0x1F171, 1 }, + { 0x1F17E, 0x1F17F, 1 }, + { 0x1F18E, 0x1F18E, 1 }, + { 0x1F191, 0x1F19A, 1 }, + { 0x1F1AD, 0x1F1E5, 1 }, + { 0x1F201, 0x1F20F, 1 }, + { 0x1F21A, 0x1F21A, 1 }, + { 0x1F22F, 0x1F22F, 1 }, + { 0x1F232, 0x1F23A, 1 }, + { 0x1F23C, 0x1F23F, 1 }, + { 0x1F249, 0x1F3FA, 1 }, + { 0x1F400, 0x1F53D, 1 }, + { 0x1F546, 0x1F64F, 1 }, + { 0x1F680, 0x1F6FF, 1 }, + { 0x1F774, 0x1F77F, 1 }, + { 0x1F7D5, 0x1F7FF, 1 }, + { 0x1F80C, 0x1F80F, 1 }, + { 0x1F848, 0x1F84F, 1 }, + { 0x1F85A, 0x1F85F, 1 }, + { 0x1F888, 0x1F88F, 1 }, + { 0x1F8AE, 0x1F8FF, 1 }, + { 0x1F90C, 0x1F93A, 1 }, + { 0x1F93C, 0x1F945, 1 }, + { 0x1F947, 0x1FAFF, 1 }, + { 0x1FC00, 0x1FFFD, 1 }, +}; +const size_t k_ext_pict_n = sizeof k_ext_pict / sizeof k_ext_pict[0]; + +const GbRange k_incb[] = { + { 0x300, 0x36F, 3 }, + { 0x483, 0x489, 3 }, + { 0x591, 0x5BD, 3 }, + { 0x5BF, 0x5BF, 3 }, + { 0x5C1, 0x5C2, 3 }, + { 0x5C4, 0x5C5, 3 }, + { 0x5C7, 0x5C7, 3 }, + { 0x610, 0x61A, 3 }, + { 0x64B, 0x65F, 3 }, + { 0x670, 0x670, 3 }, + { 0x6D6, 0x6DC, 3 }, + { 0x6DF, 0x6E4, 3 }, + { 0x6E7, 0x6E8, 3 }, + { 0x6EA, 0x6ED, 3 }, + { 0x711, 0x711, 3 }, + { 0x730, 0x74A, 3 }, + { 0x7A6, 0x7B0, 3 }, + { 0x7EB, 0x7F3, 3 }, + { 0x7FD, 0x7FD, 3 }, + { 0x816, 0x819, 3 }, + { 0x81B, 0x823, 3 }, + { 0x825, 0x827, 3 }, + { 0x829, 0x82D, 3 }, + { 0x859, 0x85B, 3 }, + { 0x897, 0x89F, 3 }, + { 0x8CA, 0x8E1, 3 }, + { 0x8E3, 0x902, 3 }, + { 0x915, 0x939, 2 }, + { 0x93A, 0x93A, 3 }, + { 0x93C, 0x93C, 3 }, + { 0x941, 0x948, 3 }, + { 0x94D, 0x94D, 1 }, + { 0x951, 0x957, 3 }, + { 0x958, 0x95F, 2 }, + { 0x962, 0x963, 3 }, + { 0x978, 0x97F, 2 }, + { 0x981, 0x981, 3 }, + { 0x995, 0x9A8, 2 }, + { 0x9AA, 0x9B0, 2 }, + { 0x9B2, 0x9B2, 2 }, + { 0x9B6, 0x9B9, 2 }, + { 0x9BC, 0x9BC, 3 }, + { 0x9BE, 0x9BE, 3 }, + { 0x9C1, 0x9C4, 3 }, + { 0x9CD, 0x9CD, 1 }, + { 0x9D7, 0x9D7, 3 }, + { 0x9DC, 0x9DD, 2 }, + { 0x9DF, 0x9DF, 2 }, + { 0x9E2, 0x9E3, 3 }, + { 0x9F0, 0x9F1, 2 }, + { 0x9FE, 0x9FE, 3 }, + { 0xA01, 0xA02, 3 }, + { 0xA3C, 0xA3C, 3 }, + { 0xA41, 0xA42, 3 }, + { 0xA47, 0xA48, 3 }, + { 0xA4B, 0xA4D, 3 }, + { 0xA51, 0xA51, 3 }, + { 0xA70, 0xA71, 3 }, + { 0xA75, 0xA75, 3 }, + { 0xA81, 0xA82, 3 }, + { 0xA95, 0xAA8, 2 }, + { 0xAAA, 0xAB0, 2 }, + { 0xAB2, 0xAB3, 2 }, + { 0xAB5, 0xAB9, 2 }, + { 0xABC, 0xABC, 3 }, + { 0xAC1, 0xAC5, 3 }, + { 0xAC7, 0xAC8, 3 }, + { 0xACD, 0xACD, 1 }, + { 0xAE2, 0xAE3, 3 }, + { 0xAF9, 0xAF9, 2 }, + { 0xAFA, 0xAFF, 3 }, + { 0xB01, 0xB01, 3 }, + { 0xB15, 0xB28, 2 }, + { 0xB2A, 0xB30, 2 }, + { 0xB32, 0xB33, 2 }, + { 0xB35, 0xB39, 2 }, + { 0xB3C, 0xB3C, 3 }, + { 0xB3E, 0xB3F, 3 }, + { 0xB41, 0xB44, 3 }, + { 0xB4D, 0xB4D, 1 }, + { 0xB55, 0xB57, 3 }, + { 0xB5C, 0xB5D, 2 }, + { 0xB5F, 0xB5F, 2 }, + { 0xB62, 0xB63, 3 }, + { 0xB71, 0xB71, 2 }, + { 0xB82, 0xB82, 3 }, + { 0xBBE, 0xBBE, 3 }, + { 0xBC0, 0xBC0, 3 }, + { 0xBCD, 0xBCD, 3 }, + { 0xBD7, 0xBD7, 3 }, + { 0xC00, 0xC00, 3 }, + { 0xC04, 0xC04, 3 }, + { 0xC15, 0xC28, 2 }, + { 0xC2A, 0xC39, 2 }, + { 0xC3C, 0xC3C, 3 }, + { 0xC3E, 0xC40, 3 }, + { 0xC46, 0xC48, 3 }, + { 0xC4A, 0xC4C, 3 }, + { 0xC4D, 0xC4D, 1 }, + { 0xC55, 0xC56, 3 }, + { 0xC58, 0xC5A, 2 }, + { 0xC62, 0xC63, 3 }, + { 0xC81, 0xC81, 3 }, + { 0xCBC, 0xCBC, 3 }, + { 0xCBF, 0xCC0, 3 }, + { 0xCC2, 0xCC2, 3 }, + { 0xCC6, 0xCC8, 3 }, + { 0xCCA, 0xCCD, 3 }, + { 0xCD5, 0xCD6, 3 }, + { 0xCE2, 0xCE3, 3 }, + { 0xD00, 0xD01, 3 }, + { 0xD15, 0xD3A, 2 }, + { 0xD3B, 0xD3C, 3 }, + { 0xD3E, 0xD3E, 3 }, + { 0xD41, 0xD44, 3 }, + { 0xD4D, 0xD4D, 1 }, + { 0xD57, 0xD57, 3 }, + { 0xD62, 0xD63, 3 }, + { 0xD81, 0xD81, 3 }, + { 0xDCA, 0xDCA, 3 }, + { 0xDCF, 0xDCF, 3 }, + { 0xDD2, 0xDD4, 3 }, + { 0xDD6, 0xDD6, 3 }, + { 0xDDF, 0xDDF, 3 }, + { 0xE31, 0xE31, 3 }, + { 0xE34, 0xE3A, 3 }, + { 0xE47, 0xE4E, 3 }, + { 0xEB1, 0xEB1, 3 }, + { 0xEB4, 0xEBC, 3 }, + { 0xEC8, 0xECE, 3 }, + { 0xF18, 0xF19, 3 }, + { 0xF35, 0xF35, 3 }, + { 0xF37, 0xF37, 3 }, + { 0xF39, 0xF39, 3 }, + { 0xF71, 0xF7E, 3 }, + { 0xF80, 0xF84, 3 }, + { 0xF86, 0xF87, 3 }, + { 0xF8D, 0xF97, 3 }, + { 0xF99, 0xFBC, 3 }, + { 0xFC6, 0xFC6, 3 }, + { 0x102D, 0x1030, 3 }, + { 0x1032, 0x1037, 3 }, + { 0x1039, 0x103A, 3 }, + { 0x103D, 0x103E, 3 }, + { 0x1058, 0x1059, 3 }, + { 0x105E, 0x1060, 3 }, + { 0x1071, 0x1074, 3 }, + { 0x1082, 0x1082, 3 }, + { 0x1085, 0x1086, 3 }, + { 0x108D, 0x108D, 3 }, + { 0x109D, 0x109D, 3 }, + { 0x135D, 0x135F, 3 }, + { 0x1712, 0x1715, 3 }, + { 0x1732, 0x1734, 3 }, + { 0x1752, 0x1753, 3 }, + { 0x1772, 0x1773, 3 }, + { 0x17B4, 0x17B5, 3 }, + { 0x17B7, 0x17BD, 3 }, + { 0x17C6, 0x17C6, 3 }, + { 0x17C9, 0x17D3, 3 }, + { 0x17DD, 0x17DD, 3 }, + { 0x180B, 0x180D, 3 }, + { 0x180F, 0x180F, 3 }, + { 0x1885, 0x1886, 3 }, + { 0x18A9, 0x18A9, 3 }, + { 0x1920, 0x1922, 3 }, + { 0x1927, 0x1928, 3 }, + { 0x1932, 0x1932, 3 }, + { 0x1939, 0x193B, 3 }, + { 0x1A17, 0x1A18, 3 }, + { 0x1A1B, 0x1A1B, 3 }, + { 0x1A56, 0x1A56, 3 }, + { 0x1A58, 0x1A5E, 3 }, + { 0x1A60, 0x1A60, 3 }, + { 0x1A62, 0x1A62, 3 }, + { 0x1A65, 0x1A6C, 3 }, + { 0x1A73, 0x1A7C, 3 }, + { 0x1A7F, 0x1A7F, 3 }, + { 0x1AB0, 0x1ACE, 3 }, + { 0x1B00, 0x1B03, 3 }, + { 0x1B34, 0x1B3D, 3 }, + { 0x1B42, 0x1B44, 3 }, + { 0x1B6B, 0x1B73, 3 }, + { 0x1B80, 0x1B81, 3 }, + { 0x1BA2, 0x1BA5, 3 }, + { 0x1BA8, 0x1BAD, 3 }, + { 0x1BE6, 0x1BE6, 3 }, + { 0x1BE8, 0x1BE9, 3 }, + { 0x1BED, 0x1BED, 3 }, + { 0x1BEF, 0x1BF3, 3 }, + { 0x1C2C, 0x1C33, 3 }, + { 0x1C36, 0x1C37, 3 }, + { 0x1CD0, 0x1CD2, 3 }, + { 0x1CD4, 0x1CE0, 3 }, + { 0x1CE2, 0x1CE8, 3 }, + { 0x1CED, 0x1CED, 3 }, + { 0x1CF4, 0x1CF4, 3 }, + { 0x1CF8, 0x1CF9, 3 }, + { 0x1DC0, 0x1DFF, 3 }, + { 0x200D, 0x200D, 3 }, + { 0x20D0, 0x20F0, 3 }, + { 0x2CEF, 0x2CF1, 3 }, + { 0x2D7F, 0x2D7F, 3 }, + { 0x2DE0, 0x2DFF, 3 }, + { 0x302A, 0x302F, 3 }, + { 0x3099, 0x309A, 3 }, + { 0xA66F, 0xA672, 3 }, + { 0xA674, 0xA67D, 3 }, + { 0xA69E, 0xA69F, 3 }, + { 0xA6F0, 0xA6F1, 3 }, + { 0xA802, 0xA802, 3 }, + { 0xA806, 0xA806, 3 }, + { 0xA80B, 0xA80B, 3 }, + { 0xA825, 0xA826, 3 }, + { 0xA82C, 0xA82C, 3 }, + { 0xA8C4, 0xA8C5, 3 }, + { 0xA8E0, 0xA8F1, 3 }, + { 0xA8FF, 0xA8FF, 3 }, + { 0xA926, 0xA92D, 3 }, + { 0xA947, 0xA951, 3 }, + { 0xA953, 0xA953, 3 }, + { 0xA980, 0xA982, 3 }, + { 0xA9B3, 0xA9B3, 3 }, + { 0xA9B6, 0xA9B9, 3 }, + { 0xA9BC, 0xA9BD, 3 }, + { 0xA9C0, 0xA9C0, 3 }, + { 0xA9E5, 0xA9E5, 3 }, + { 0xAA29, 0xAA2E, 3 }, + { 0xAA31, 0xAA32, 3 }, + { 0xAA35, 0xAA36, 3 }, + { 0xAA43, 0xAA43, 3 }, + { 0xAA4C, 0xAA4C, 3 }, + { 0xAA7C, 0xAA7C, 3 }, + { 0xAAB0, 0xAAB0, 3 }, + { 0xAAB2, 0xAAB4, 3 }, + { 0xAAB7, 0xAAB8, 3 }, + { 0xAABE, 0xAABF, 3 }, + { 0xAAC1, 0xAAC1, 3 }, + { 0xAAEC, 0xAAED, 3 }, + { 0xAAF6, 0xAAF6, 3 }, + { 0xABE5, 0xABE5, 3 }, + { 0xABE8, 0xABE8, 3 }, + { 0xABED, 0xABED, 3 }, + { 0xFB1E, 0xFB1E, 3 }, + { 0xFE00, 0xFE0F, 3 }, + { 0xFE20, 0xFE2F, 3 }, + { 0xFF9E, 0xFF9F, 3 }, + { 0x101FD, 0x101FD, 3 }, + { 0x102E0, 0x102E0, 3 }, + { 0x10376, 0x1037A, 3 }, + { 0x10A01, 0x10A03, 3 }, + { 0x10A05, 0x10A06, 3 }, + { 0x10A0C, 0x10A0F, 3 }, + { 0x10A38, 0x10A3A, 3 }, + { 0x10A3F, 0x10A3F, 3 }, + { 0x10AE5, 0x10AE6, 3 }, + { 0x10D24, 0x10D27, 3 }, + { 0x10D69, 0x10D6D, 3 }, + { 0x10EAB, 0x10EAC, 3 }, + { 0x10EFC, 0x10EFF, 3 }, + { 0x10F46, 0x10F50, 3 }, + { 0x10F82, 0x10F85, 3 }, + { 0x11001, 0x11001, 3 }, + { 0x11038, 0x11046, 3 }, + { 0x11070, 0x11070, 3 }, + { 0x11073, 0x11074, 3 }, + { 0x1107F, 0x11081, 3 }, + { 0x110B3, 0x110B6, 3 }, + { 0x110B9, 0x110BA, 3 }, + { 0x110C2, 0x110C2, 3 }, + { 0x11100, 0x11102, 3 }, + { 0x11127, 0x1112B, 3 }, + { 0x1112D, 0x11134, 3 }, + { 0x11173, 0x11173, 3 }, + { 0x11180, 0x11181, 3 }, + { 0x111B6, 0x111BE, 3 }, + { 0x111C0, 0x111C0, 3 }, + { 0x111C9, 0x111CC, 3 }, + { 0x111CF, 0x111CF, 3 }, + { 0x1122F, 0x11231, 3 }, + { 0x11234, 0x11237, 3 }, + { 0x1123E, 0x1123E, 3 }, + { 0x11241, 0x11241, 3 }, + { 0x112DF, 0x112DF, 3 }, + { 0x112E3, 0x112EA, 3 }, + { 0x11300, 0x11301, 3 }, + { 0x1133B, 0x1133C, 3 }, + { 0x1133E, 0x1133E, 3 }, + { 0x11340, 0x11340, 3 }, + { 0x1134D, 0x1134D, 3 }, + { 0x11357, 0x11357, 3 }, + { 0x11366, 0x1136C, 3 }, + { 0x11370, 0x11374, 3 }, + { 0x113B8, 0x113B8, 3 }, + { 0x113BB, 0x113C0, 3 }, + { 0x113C2, 0x113C2, 3 }, + { 0x113C5, 0x113C5, 3 }, + { 0x113C7, 0x113C9, 3 }, + { 0x113CE, 0x113D0, 3 }, + { 0x113D2, 0x113D2, 3 }, + { 0x113E1, 0x113E2, 3 }, + { 0x11438, 0x1143F, 3 }, + { 0x11442, 0x11444, 3 }, + { 0x11446, 0x11446, 3 }, + { 0x1145E, 0x1145E, 3 }, + { 0x114B0, 0x114B0, 3 }, + { 0x114B3, 0x114B8, 3 }, + { 0x114BA, 0x114BA, 3 }, + { 0x114BD, 0x114BD, 3 }, + { 0x114BF, 0x114C0, 3 }, + { 0x114C2, 0x114C3, 3 }, + { 0x115AF, 0x115AF, 3 }, + { 0x115B2, 0x115B5, 3 }, + { 0x115BC, 0x115BD, 3 }, + { 0x115BF, 0x115C0, 3 }, + { 0x115DC, 0x115DD, 3 }, + { 0x11633, 0x1163A, 3 }, + { 0x1163D, 0x1163D, 3 }, + { 0x1163F, 0x11640, 3 }, + { 0x116AB, 0x116AB, 3 }, + { 0x116AD, 0x116AD, 3 }, + { 0x116B0, 0x116B7, 3 }, + { 0x1171D, 0x1171D, 3 }, + { 0x1171F, 0x1171F, 3 }, + { 0x11722, 0x11725, 3 }, + { 0x11727, 0x1172B, 3 }, + { 0x1182F, 0x11837, 3 }, + { 0x11839, 0x1183A, 3 }, + { 0x11930, 0x11930, 3 }, + { 0x1193B, 0x1193E, 3 }, + { 0x11943, 0x11943, 3 }, + { 0x119D4, 0x119D7, 3 }, + { 0x119DA, 0x119DB, 3 }, + { 0x119E0, 0x119E0, 3 }, + { 0x11A01, 0x11A0A, 3 }, + { 0x11A33, 0x11A38, 3 }, + { 0x11A3B, 0x11A3E, 3 }, + { 0x11A47, 0x11A47, 3 }, + { 0x11A51, 0x11A56, 3 }, + { 0x11A59, 0x11A5B, 3 }, + { 0x11A8A, 0x11A96, 3 }, + { 0x11A98, 0x11A99, 3 }, + { 0x11C30, 0x11C36, 3 }, + { 0x11C38, 0x11C3D, 3 }, + { 0x11C3F, 0x11C3F, 3 }, + { 0x11C92, 0x11CA7, 3 }, + { 0x11CAA, 0x11CB0, 3 }, + { 0x11CB2, 0x11CB3, 3 }, + { 0x11CB5, 0x11CB6, 3 }, + { 0x11D31, 0x11D36, 3 }, + { 0x11D3A, 0x11D3A, 3 }, + { 0x11D3C, 0x11D3D, 3 }, + { 0x11D3F, 0x11D45, 3 }, + { 0x11D47, 0x11D47, 3 }, + { 0x11D90, 0x11D91, 3 }, + { 0x11D95, 0x11D95, 3 }, + { 0x11D97, 0x11D97, 3 }, + { 0x11EF3, 0x11EF4, 3 }, + { 0x11F00, 0x11F01, 3 }, + { 0x11F36, 0x11F3A, 3 }, + { 0x11F40, 0x11F42, 3 }, + { 0x11F5A, 0x11F5A, 3 }, + { 0x13440, 0x13440, 3 }, + { 0x13447, 0x13455, 3 }, + { 0x1611E, 0x16129, 3 }, + { 0x1612D, 0x1612F, 3 }, + { 0x16AF0, 0x16AF4, 3 }, + { 0x16B30, 0x16B36, 3 }, + { 0x16F4F, 0x16F4F, 3 }, + { 0x16F8F, 0x16F92, 3 }, + { 0x16FE4, 0x16FE4, 3 }, + { 0x16FF0, 0x16FF1, 3 }, + { 0x1BC9D, 0x1BC9E, 3 }, + { 0x1CF00, 0x1CF2D, 3 }, + { 0x1CF30, 0x1CF46, 3 }, + { 0x1D165, 0x1D169, 3 }, + { 0x1D16D, 0x1D172, 3 }, + { 0x1D17B, 0x1D182, 3 }, + { 0x1D185, 0x1D18B, 3 }, + { 0x1D1AA, 0x1D1AD, 3 }, + { 0x1D242, 0x1D244, 3 }, + { 0x1DA00, 0x1DA36, 3 }, + { 0x1DA3B, 0x1DA6C, 3 }, + { 0x1DA75, 0x1DA75, 3 }, + { 0x1DA84, 0x1DA84, 3 }, + { 0x1DA9B, 0x1DA9F, 3 }, + { 0x1DAA1, 0x1DAAF, 3 }, + { 0x1E000, 0x1E006, 3 }, + { 0x1E008, 0x1E018, 3 }, + { 0x1E01B, 0x1E021, 3 }, + { 0x1E023, 0x1E024, 3 }, + { 0x1E026, 0x1E02A, 3 }, + { 0x1E08F, 0x1E08F, 3 }, + { 0x1E130, 0x1E136, 3 }, + { 0x1E2AE, 0x1E2AE, 3 }, + { 0x1E2EC, 0x1E2EF, 3 }, + { 0x1E4EC, 0x1E4EF, 3 }, + { 0x1E5EE, 0x1E5EF, 3 }, + { 0x1E8D0, 0x1E8D6, 3 }, + { 0x1E944, 0x1E94A, 3 }, + { 0x1F3FB, 0x1F3FF, 3 }, + { 0xE0020, 0xE007F, 3 }, + { 0xE0100, 0xE01EF, 3 }, +}; +const size_t k_incb_n = sizeof k_incb / sizeof k_incb[0]; + +} /* namespace ucd */ +} /* namespace rad */ diff --git a/core/text/tokenizer_json.cpp b/core/text/tokenizer_json.cpp index 10cc61ca..4ce100ea 100644 --- a/core/text/tokenizer_json.cpp +++ b/core/text/tokenizer_json.cpp @@ -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& 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() > 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 "") 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& norm) { + const bool has_normalizer = !norm.empty(); + std::vector 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"); }; diff --git a/data/recipes/anima-bf16.recipe b/data/recipes/anima-bf16.recipe new file mode 100644 index 00000000..571ae96c --- /dev/null +++ b/data/recipes/anima-bf16.recipe @@ -0,0 +1,16 @@ +# anima-bf16.recipe -- Anima (Base, Aesthetic or Turbo) at bf16. +# +# rad-convert /split_files/diffusion_models/anima-aesthetic-v1.1.safetensors \ +# --add /split_files/text_encoders/qwen_3_06b_base.safetensors \ +# --add /split_files/vae/qwen_image_vae.safetensors \ +# --config --tokenizer2 /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 diff --git a/data/recipes/anima-fp8.recipe b/data/recipes/anima-fp8.recipe new file mode 100644 index 00000000..b91d1bfd --- /dev/null +++ b/data/recipes/anima-fp8.recipe @@ -0,0 +1,31 @@ +# anima-fp8.recipe -- Anima (Base, Aesthetic or Turbo) with block-scaled fp8 linears. +# +# rad-convert /split_files/diffusion_models/anima-aesthetic-v1.1.safetensors \ +# --add /split_files/text_encoders/qwen_3_06b_base.safetensors \ +# --add /split_files/vae/qwen_image_vae.safetensors \ +# --config --tokenizer2 /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 diff --git a/data/recipes/krea-2-fp8-unscaled.recipe b/data/recipes/krea-2-fp8-unscaled.recipe new file mode 100644 index 00000000..11a12f07 --- /dev/null +++ b/data/recipes/krea-2-fp8-unscaled.recipe @@ -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 \ +# --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 diff --git a/data/recipes/q38-27b-mxfp4-df2.recipe b/data/recipes/q38-27b-mxfp4-df2.recipe new file mode 100644 index 00000000..0c39e4ca --- /dev/null +++ b/data/recipes/q38-27b-mxfp4-df2.recipe @@ -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 --draft-model \ +# --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 diff --git a/data/recipes/sdxl-bf16.recipe b/data/recipes/sdxl-bf16.recipe new file mode 100644 index 00000000..66902a70 --- /dev/null +++ b/data/recipes/sdxl-bf16.recipe @@ -0,0 +1,9 @@ +# sdxl-bf16.recipe -- Stable Diffusion XL (and its finetunes: Illustrious, NoobAI, Pony, ...) at bf16. +# +# rad-convert .safetensors --tokenizer \ +# --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 diff --git a/deploy/compose/anima.yaml b/deploy/compose/anima.yaml new file mode 100644 index 00000000..794863e3 --- /dev/null +++ b/deploy/compose/anima.yaml @@ -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 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 diff --git a/deploy/compose/fasth3.yaml b/deploy/compose/fasth3.yaml index 921fc5f6..f6c265b3 100644 --- a/deploy/compose/fasth3.yaml +++ b/deploy/compose/fasth3.yaml @@ -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 in its prompt. name: radiance-fasth3 services: radiance: diff --git a/deploy/compose/flux-3-klein.yaml b/deploy/compose/flux-3-klein.yaml index b3214063..ecc70aba 100644 --- a/deploy/compose/flux-3-klein.yaml +++ b/deploy/compose/flux-3-klein.yaml @@ -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 in its prompt. name: radiance-flux-3-klein services: radiance: diff --git a/deploy/compose/krea-2-raw.yaml b/deploy/compose/krea-2-raw.yaml index f65e554a..527cadf6 100644 --- a/deploy/compose/krea-2-raw.yaml +++ b/deploy/compose/krea-2-raw.yaml @@ -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 in its prompt. name: radiance-krea-2-raw services: radiance: diff --git a/deploy/compose/krea-2-turbo.yaml b/deploy/compose/krea-2-turbo.yaml index 87b6f3cc..c15e9223 100644 --- a/deploy/compose/krea-2-turbo.yaml +++ b/deploy/compose/krea-2-turbo.yaml @@ -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 in its prompt. name: radiance-krea-2-turbo services: radiance: diff --git a/deploy/compose/ltx-2.5.yaml b/deploy/compose/ltx-2.5.yaml index 0c737922..287f1dd3 100644 --- a/deploy/compose/ltx-2.5.yaml +++ b/deploy/compose/ltx-2.5.yaml @@ -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 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: diff --git a/deploy/compose/minimax-h3.yaml b/deploy/compose/minimax-h3.yaml index ad684a2e..548a7e71 100644 --- a/deploy/compose/minimax-h3.yaml +++ b/deploy/compose/minimax-h3.yaml @@ -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 in its prompt. name: radiance-minimax-h3 services: radiance: diff --git a/deploy/compose/qwen-image-2.1-turbo.yaml b/deploy/compose/qwen-image-2.1-turbo.yaml index e1916d52..0df9ae68 100644 --- a/deploy/compose/qwen-image-2.1-turbo.yaml +++ b/deploy/compose/qwen-image-2.1-turbo.yaml @@ -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 in its prompt. name: radiance-qwen-image-turbo services: radiance: diff --git a/deploy/compose/qwen-image-2.1.yaml b/deploy/compose/qwen-image-2.1.yaml index 233841c3..3febe137 100644 --- a/deploy/compose/qwen-image-2.1.yaml +++ b/deploy/compose/qwen-image-2.1.yaml @@ -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 in its prompt. name: radiance-qwen-image services: radiance: diff --git a/deploy/compose/sdxl.yaml b/deploy/compose/sdxl.yaml new file mode 100644 index 00000000..a7bf5d82 --- /dev/null +++ b/deploy/compose/sdxl.yaml @@ -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 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index dadd297e..9c11fd90 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -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 + 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 diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 99f58bb1..4d1bbb43 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -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 | diff --git a/docs/GUIDE.md b/docs/GUIDE.md index cad2fee6..6c89aebb 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -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, ``, + 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] diff --git a/docs/OPS.md b/docs/OPS.md index 94348275..0897ac51 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -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: diff --git a/docs/TOOLS.md b/docs/TOOLS.md index 40bd4843..443d2266 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -107,6 +107,12 @@ rad-convert [options] -o 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. diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 67460da9..cdc34b1b 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -314,8 +314,9 @@ std::vector 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 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 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 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) }); diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index 2898a0c0..dc50cbc5 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -1913,6 +1913,51 @@ void gen_cases(std::vector& 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)) diff --git a/libavx/avx_gen.cpp b/libavx/avx_gen.cpp index f49025db..8edbefac 100644 --- a/libavx/avx_gen.cpp +++ b/libavx/avx_gen.cpp @@ -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 diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index e5b14941..57fac4df 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -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) \ diff --git a/libavx/avx_lora.cpp b/libavx/avx_lora.cpp index 1e43dcd7..fbf6c51d 100644 --- a/libavx/avx_lora.cpp +++ b/libavx/avx_lora.cpp @@ -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); } diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 602ac0c6..11470960 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -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", diff --git a/libr4d/r4d_gen.hip b/libr4d/r4d_gen.hip index 97a4cfde..8f9d5877 100644 --- a/libr4d/r4d_gen.hip +++ b/libr4d/r4d_gen.hip @@ -17,6 +17,7 @@ #include "r4d_q8.h" #include "rad_philox.h" +#include #include #include #include @@ -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 +__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 +__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), 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, 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, 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); diff --git a/libr4d/r4d_lora_bf16.hip b/libr4d/r4d_lora_bf16.hip index bce778f2..0eb48bac 100644 --- a/libr4d/r4d_lora_bf16.hip +++ b/libr4d/r4d_lora_bf16.hip @@ -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 +__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(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 +static void launch_expand_mm(const ExpandTArgs& P, dim3 grid, RadStream stream) { + (void)stream; + R4D_KLAUNCH(R4D_KNAME(lora_expand_mm_kernel), 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(T, grid, stream) + : launch_expand_mm(T, grid, stream); break; + case kF16: v ? launch_expand_mm(T, grid, stream) + : launch_expand_mm(T, grid, stream); break; + default: v ? launch_expand_mm(T, grid, stream) + : launch_expand_mm(T, grid, stream); break; + } + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + } /* extern "C" */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 6b74b26f..18c7625a 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -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); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 4cd29805..a2930559 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -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, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 1e7e0e69..afb0e265 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -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 x = randv((size_t)(c.H * ld), 1.0f); + void* dx = up_bf16(x); + std::vector 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 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 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 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 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 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 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 pair = { 1, -2, -1, -1, -1 }, lane = { 3, 0, 1, 4, 2 }; + std::vector cu(S + 1); + for (int64_t e = 0; e <= S; ++e) cu[(size_t)e] = (int32_t)(e * len); + const std::vector seeds = { 0x9e3779b9u, 7u, 0, 0, 5u, 1u, 77u, 0, 0xdeadbeefu, 3u }; + std::vector sdw(seeds.begin(), seeds.end()); + const std::vector sg = { 14.6f, 14.6f, 3.5f, 1.25f, 0.4f }; + const std::vector sgn = { 11.0f, 11.0f, 2.0f, 0.7f, 0.0f }; + const std::vector sgp = { 0.0f, 0.0f, 5.0f, 2.0f, 0.9f }; + const std::vector cfg = { 6.0f, 1.0f, 1.0f, 1.0f, 1.0f }; + const std::vector step = { 0, 0, 7, 4, 20 }; + std::vector 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 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 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 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 fl = { 5, 0, 0, 1, 0 }; + const std::vector 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 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(bytes, (size_t)16 << 20); + std::vector 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 ts, std::vector 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 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 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; } diff --git a/libr4d/r4d_upscaler.hip b/libr4d/r4d_upscaler.hip index 6e51b0ec..1fcd604b 100644 --- a/libr4d/r4d_upscaler.hip +++ b/libr4d/r4d_upscaler.hip @@ -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 __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(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(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 __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), 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), 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) diff --git a/libref/ref_gen.cpp b/libref/ref_gen.cpp index 4c42ed12..16d662b5 100644 --- a/libref/ref_gen.cpp +++ b/libref/ref_gen.cpp @@ -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; diff --git a/libref/ref_lora.cpp b/libref/ref_lora.cpp index de8b521c..54ec5046 100644 --- a/libref/ref_lora.cpp +++ b/libref/ref_lora.cpp @@ -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); } diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 3c72d4cc..4c164a65 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -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); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index fbf5cbe3..827188ca 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -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", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index efa78320..f1fd4d8a 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -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); diff --git a/scripts/README.md b/scripts/README.md index 1133f833..591a6198 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -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=`: 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 ` 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 diff --git a/scripts/krea2_native.py b/scripts/krea2_native.py new file mode 100755 index 00000000..d4e8a0cb --- /dev/null +++ b/scripts/krea2_native.py @@ -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 /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 ") + src, dst = sys.argv[1], sys.argv[2] + with open(src, "rb") as f: + n = struct.unpack(" {dst}") + + +if __name__ == "__main__": + main() diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 9d8dcd1f..0abae8bf 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -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) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 6fc89cfb..9ff6bc7a 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -1,4 +1,4 @@ -/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 24 and +/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 25 and * RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot * of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it * from the test's printout only together with a version bump. */ @@ -315,7 +315,7 @@ { "RadFuseStep", "n_p", 584, 4 }, { "RadFuseStep", "from", 588, 32 }, { "RadFuseStep", "n_from", 620, 4 }, -{ "RadGenBatch", "", 0, 320 }, +{ "RadGenBatch", "", 0, 400 }, { "RadGenBatch", "rows", 0, 8 }, { "RadGenBatch", "src", 8, 8 }, { "RadGenBatch", "rope", 16, 8 }, @@ -359,7 +359,17 @@ { "RadGenBatch", "mode_ccu", 296, 8 }, { "RadGenBatch", "n_mode_h", 304, 8 }, { "RadGenBatch", "mode_rope_f", 312, 8 }, -{ "RadGeneratorDecl", "", 0, 296 }, +{ "RadGenBatch", "n_aux", 320, 8 }, +{ "RadGenBatch", "aux_ids", 328, 8 }, +{ "RadGenBatch", "aux_cu", 336, 8 }, +{ "RadGenBatch", "sigma_prev", 344, 8 }, +{ "RadGenBatch", "timestep", 352, 8 }, +{ "RadGenBatch", "sampler", 360, 8 }, +{ "RadGenBatch", "step", 368, 8 }, +{ "RadGenBatch", "size_px", 376, 8 }, +{ "RadGenBatch", "entry_h", 384, 8 }, +{ "RadGenBatch", "tokens_h", 392, 8 }, +{ "RadGeneratorDecl", "", 0, 376 }, { "RadGeneratorDecl", "name", 0, 8 }, { "RadGeneratorDecl", "layout", 8, 4 }, { "RadGeneratorDecl", "tmpl_text", 16, 8 }, @@ -400,6 +410,21 @@ { "RadGeneratorDecl", "cfg_original", 276, 4 }, { "RadGeneratorDecl", "default_negative", 280, 8 }, { "RadGeneratorDecl", "ref_shrink_only", 288, 4 }, +{ "RadGeneratorDecl", "aux_max_tokens", 296, 8 }, +{ "RadGeneratorDecl", "sigma_grid", 304, 4 }, +{ "RadGeneratorDecl", "min_tokens", 308, 4 }, +{ "RadGeneratorDecl", "aux_tokens", 312, 4 }, +{ "RadGeneratorDecl", "beta_start", 320, 8 }, +{ "RadGeneratorDecl", "beta_end", 328, 8 }, +{ "RadGeneratorDecl", "train_steps", 336, 4 }, +{ "RadGeneratorDecl", "beta_schedule", 340, 4 }, +{ "RadGeneratorDecl", "zero_snr", 344, 4 }, +{ "RadGeneratorDecl", "samplers", 348, 4 }, +{ "RadGeneratorDecl", "default_sampler", 352, 4 }, +{ "RadGeneratorDecl", "default_scheduler", 356, 4 }, +{ "RadGeneratorDecl", "chunk_tokens", 360, 4 }, +{ "RadGeneratorDecl", "chunk_bos", 364, 4 }, +{ "RadGeneratorDecl", "chunk_eos", 368, 4 }, { "RadKVGroupBatch", "", 0, 72 }, { "RadKVGroupBatch", "group", 0, 4 }, { "RadKVGroupBatch", "slot_mapping", 8, 8 }, diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index bc51ff46..76e49048 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -8,7 +8,7 @@ * * Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every * struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and - * the layout agrees with the table below, taken at RAD_ABI_VERSION 24 and RAD_FORMAT_VER 2. Under + * the layout agrees with the table below, taken at RAD_ABI_VERSION 25 and RAD_FORMAT_VER 2. Under * those versions a listed field may not move or change size, an ABI struct may only grow by fields * past its old end, and an on-disk struct may not change at all. The table is a snapshot of the * headers: nothing else states the layout. When it disagrees the test prints the live table. @@ -57,8 +57,8 @@ std::vector cpp_rows() { }; } -/* The layout at RAD_ABI_VERSION 24 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 24, kTableFormat = 2; +/* The layout at RAD_ABI_VERSION 25 / RAD_FORMAT_VER 2 (see the file header). */ +constexpr uint32_t kTableAbi = 25, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 39ba088c..8d34b009 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -128,6 +128,12 @@ struct RadBuilder { RadGeneratorDecl generator{}; std::string generator_name; + /* Adapter key names (rad_lora_root, rad_lora_alias): (native, spellings), and each alias as + * (native, from, to, from_lo, from_hi, to_lo). */ + std::vector> lora_roots; + struct LoraAliasRec { std::string native, from, to; int64_t from_lo, from_hi, to_lo; }; + std::vector lora_aliases; + /* What rad_weight_encoding answers: the first entry whose key the source name contains. Empty * means no model, so every weight is plain in its declared dtype. */ std::vector> encs; @@ -269,6 +275,19 @@ extern "C" int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) { return RAD_OK; } +/* Recorded: a generator's adapter key names. */ +extern "C" int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) { + if (!b || !native || !*native) return RAD_E_INVAL; + b->lora_roots.push_back({ native, spellings ? spellings : "" }); + return RAD_OK; +} +extern "C" 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 || !native || !from || !to) return RAD_E_INVAL; + b->lora_aliases.push_back({ native, from, to, from_lo, from_hi, to_lo }); + return RAD_OK; +} + /* Recorded: gemma4's prefill overlap names the buffers its second lane reduces in place. */ extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { if (!b || !buf) return RAD_E_INVAL; @@ -482,6 +501,8 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s #include "../arch/embgemma2/embgemma2.cpp" /* Qwen-Image 2.1: a generator conditioned by Qwen3-VL. */ #include "../arch/qwenimage21/qwenimage21.cpp" +/* Anima: a cross-attention generator conditioned through two tokenizers. */ +#include "../arch/anima/anima.cpp" /* GLM-5.3-Flash: its connection, router, attention and cache blocks, and the plugin. */ #include #include @@ -8428,6 +8449,30 @@ TEST(qwenimage21_declares_a_generator_with_one_shared_modulation) { /* Every collective follows --tp-wire: exact unless the lossy wire was accepted, and the floor * under which a message stays exact is the deployment's. */ +/* The DiT's adapter names: one root before any GEMM, and every alias lands on a checkpoint tensor + * the plugin maps, with the gate half of ComfyUI's `gate_up` on `gate_layer`. */ +TEST(qwenimage21_names_its_adapter_keys_onto_mapped_tensors) { + MetaKV mk = qimg_meta(); + RadBuilder b; + const RadBuildCtx ctx = qimg_ctx(0, 1); + REQUIRE_EQ(qwenimage21::declare(&b, mk.meta(), &ctx), RAD_OK); + REQUIRE_EQ(b.lora_roots.size(), (size_t)1); + CHECK_EQ(b.lora_roots[0].first, std::string("transformer.")); + CHECK(b.lora_roots[0].second.find("lora_unet_") != std::string::npos); + std::set srcs; + for (const RecMap& m : b.maps) for (const std::string& x : m.src) srcs.insert(x); + REQUIRE_EQ(b.lora_aliases.size(), (size_t)2); + for (const auto& a : b.lora_aliases) { + std::string to = a.native + a.to; + const size_t h = to.find('#'); + if (h != std::string::npos) to.replace(h, 1, "0"); + CHECK(srcs.count(to + ".weight")); + } + CHECK(b.lora_aliases[0].to.find("gate_layer") != std::string::npos); + CHECK_EQ(b.lora_aliases[0].from_lo, (int64_t)0); + CHECK_EQ(b.lora_aliases[1].from_lo, b.lora_aliases[0].from_hi); +} + TEST(qwenimage21_collectives_follow_the_tp_wire) { MetaKV mk = qimg_meta(); for (int lossy : { 0, 1 }) { @@ -8473,6 +8518,314 @@ TEST(qwenimage21_generator_passes_lint_clean) { } } +/* ==================================================================== anima */ + +namespace { + +/* Anima's text encoder (Qwen3-0.6B-Base) as the container's config states it; the DiT, adapter + * and VAE are the plugin's own constants. */ +MetaKV anima_meta(const char* variant) { + RadModelMeta m{}; + m.arch_id = "anima"; m.name = "test-anima"; m.quant = ""; + m.n_layers = 28; m.n_embd = 1024; m.n_head = 16; m.n_head_kv = 8; m.head_dim = 128; + m.n_ff = 3072; m.n_vocab = 151936; m.n_ctx_train = 32768; + m.rms_eps = 1e-6f; m.rope_theta = 1e6f; m.rope_scale = 1.0f; + MetaKV k(m); + k.set("num_hidden_layers", "28").set("hidden_size", "1024").set("anima.variant", variant); + return k; +} + +RadBuildCtx anima_ctx() { + RadBuildCtx c = build_ctx(0, 1); + c.max_tok = 2 * (4096 + 512); + c.max_seqs = 4; + return c; +} + +/* A JOINT_STEP pass as the driver lays one out for Anima: COND over a prompt of `nq` Qwen3 tokens + * (padded to 512) and `nt` T5 ids, DENOISE over `entries` entries of 512 context rows and `ni` + * image rows each, or DECODE of a 64 x 64 picture. */ +struct AnimaKit { + std::vector tok, pos, cu, src, lane, flags, pair, aux, aux_cu, valid_cu; + std::vector img_cu, img_rows, mode_cu, mode_rows, mode_src, mode_ccu; + std::vector n_mode; + std::vector seed; + std::vector sigma, sigma_next, cfg, rope_f, mode_rope_f; + RadGenBatch g{}; + RadBatch b{}; +}; + +std::unique_ptr anima_pass(int pass, int64_t nq = 12, int64_t nt = 9, int64_t ni = 16, + int64_t entries = 1) { + auto k = std::make_unique(); + RadGenBatch& g = k->g; + RadBatch& b = k->b; + b.gen = pass; + b.gen_b = &k->g; + if (pass == RAD_GEN_PASS_COND) { + for (int64_t i = 0; i < 512; ++i) { + k->tok.push_back(i < nq ? (int32_t)(100 + i) : 151643); + k->pos.push_back(i < nq ? (int32_t)i : 1); + } + for (int64_t i = 0; i < nt; ++i) k->aux.push_back((int32_t)(3 + i)); + k->aux_cu = { 0, (int32_t)nt }; + k->valid_cu = { 0, (int32_t)nq }; + k->cu = { 0, 512 }; + k->lane = { 0, 1 }; + k->sigma = { 0.0f }; + b.n_tok = 512; + b.n_seq = 1; + b.token_ids = k->tok.data(); + b.positions = k->pos.data(); + b.cu_seqlens = k->cu.data(); + g.rows = 512; + g.n_pad = (int32_t)(512 - nq); + g.valid_cu = k->valid_cu.data(); + g.n_lane = 2; + g.lane = k->lane.data(); + g.lane_h = k->lane.data(); + g.branch = 1; + g.sigma = k->sigma.data(); + g.n_aux = nt; + g.aux_ids = k->aux.data(); + g.aux_cu = k->aux_cu.data(); + return k; + } + if (pass == RAD_GEN_PASS_DECODE) { + k->cu = { 0, 16 }; + b.n_tok = 16; + b.n_seq = 1; + b.cu_seqlens = k->cu.data(); + g.dec_lane = 1; + g.dec_height = g.dec_width = 64; + return k; + } + const int64_t S = entries, N = S * (512 + ni); + k->cu.push_back(0); + k->img_cu.push_back(0); + for (int64_t s = 0; s < S; ++s) { + k->mode_cu.push_back((int32_t)(s * (512 + ni))); + k->mode_cu.push_back((int32_t)(s * (512 + ni) + 512)); + k->mode_cu.push_back((int32_t)(s * (512 + ni) + 512)); + for (int64_t r = 0; r < 512; ++r) k->src.push_back((int32_t)(s * 512 + r)); + for (int64_t r = 0; r < ni; ++r) { + k->src.push_back((int32_t)(-1 - (s * ni + r))); + k->img_rows.push_back((int32_t)(s * (512 + ni) + 512 + r)); + } + k->cu.push_back((int32_t)((s + 1) * (512 + ni))); + k->img_cu.push_back((int32_t)((s + 1) * ni)); + k->lane.push_back((int32_t)(s / 2)); + k->pair.push_back(S > 1 ? (s % 2 ? -2 : (int32_t)(s + 1)) : -1); + } + k->mode_cu.push_back((int32_t)N); + for (int64_t s = 0; s < S; ++s) + for (int64_t r = 0; r < 512; ++r) { + k->mode_rows.push_back((int32_t)(s * (512 + ni) + r)); + k->mode_src.push_back((int32_t)(s * 512 + r)); + } + for (int64_t s = 0; s < S; ++s) + for (int64_t r = 0; r < ni; ++r) { + k->mode_rows.push_back((int32_t)(s * (512 + ni) + 512 + r)); + k->mode_src.push_back((int32_t)(-1 - (s * ni + r))); + } + k->n_mode = { 512 * S, 0, ni * S }; + for (int m = 0; m < 3; ++m) + for (int64_t s = 0; s <= S; ++s) + k->mode_ccu.push_back((int32_t)(s * (m == 0 ? 512 : m == 1 ? 0 : ni))); + k->rope_f.assign((size_t)(4 * N), 0.0f); + k->mode_rope_f.assign((size_t)(4 * N), 0.0f); + k->tok.assign((size_t)N, 0); + k->pos.assign((size_t)N, 0); + k->sigma.assign((size_t)S, 0.75f); + k->sigma_next.assign((size_t)S, 0.5f); + k->cfg.assign((size_t)S, 4.0f); + k->flags.assign((size_t)S, RAD_GEN_F_FIRST); + k->seed.assign((size_t)(2 * S), 7u); + b.n_tok = N; + b.n_seq = S; + b.token_ids = k->tok.data(); + b.positions = k->pos.data(); + b.cu_seqlens = k->cu.data(); + g.src = k->src.data(); + g.n_img = ni * S; + g.img_cu = k->img_cu.data(); + g.img_rows = k->img_rows.data(); + g.mode_cu = k->mode_cu.data(); + g.rope_f = k->rope_f.data(); + g.mode_rows = k->mode_rows.data(); + g.mode_src = k->mode_src.data(); + g.mode_ccu = k->mode_ccu.data(); + g.n_mode_h = k->n_mode.data(); + g.mode_rope_f = k->mode_rope_f.data(); + g.sigma = k->sigma.data(); + g.sigma_next = k->sigma_next.data(); + g.cfg = k->cfg.data(); + g.pair = k->pair.data(); + g.lane = k->lane.data(); + g.lane_dh = k->lane.data(); + g.flags = k->flags.data(); + g.seed = k->seed.data(); + return k; +} + +/* The linears a LoRA for Anima names: every DiT block's attention, MLP and modulation linears + * and the text encoder's. */ +bool anima_lora_target(const std::string& w) { + for (const char* t : { "attn_qkv", "attn_output", "cross_q", "cross_k", "cross_v", + "cross_output", "mlp_layer1", "mlp_layer2", ".mod_", "ffn_gate_up", + "ffn_down" }) + if (has(w, t) && !has(w, ".scale")) return true; + return false; +} + +} /* namespace */ + +/* A JOINT_STEP generator that reads a second tokenizer, pads an empty prompt to one token and + * samples on ComfyUI's simple schedule; the variant sets its defaults and the DiT keys' prefix is + * the checkpoint's, `model.diffusion_model.` here and `net.` for Base. */ +TEST(anima_declares_a_two_tokenizer_generator_under_the_checkpoints_prefix) { + const RadEncoding plain = rad_enc_plain(RAD_BF16); + RadBuildCtx ctx = anima_ctx(); + MetaKV mk = anima_meta("aesthetic"); + RadBuilder b; + b.encs = { { "dit.t_norm.mdm", plain }, { "dit.blk.0.attn_qkv", plain } }; + REQUIRE_EQ(anima::declare(&b, mk.meta(), &ctx), RAD_OK); + CHECK_EQ(b.logits, (rad_buf)0); + CHECK_EQ(b.generator_name, std::string("anima-aesthetic")); + const RadGeneratorDecl& d = b.generator; + CHECK_EQ(d.layout, (int32_t)RAD_GEN_LAYOUT_JOINT_STEP); + CHECK_EQ(d.aux_tokens, 1); + CHECK_EQ(d.aux_max_tokens, (int64_t)512); + CHECK_EQ(d.min_tokens, 1); + CHECK_EQ(d.pad_multiple, 512); + CHECK_EQ(d.cond_rows, (int64_t)512); + CHECK_EQ(d.sigma_grid, 1000); + CHECK_EQ(d.shift, 3.0); + CHECK_EQ(d.dyn_shift, 0); + CHECK_EQ(d.cfg_original, 0); + CHECK_EQ(d.default_steps, (int64_t)30); + CHECK_EQ(d.default_cfg, 4.0); + CHECK_EQ(d.latent_channels, (int64_t)64); + CHECK(b.kv_groups.empty()); + const RecMap* q = find_map(b, "dit.blk.27.attn_qkv.weight"); + REQUIRE(q != nullptr); + REQUIRE_EQ(q->src.size(), (size_t)3); + CHECK_EQ(q->src[0], std::string("model.diffusion_model.blocks.27.self_attn.q_proj.weight")); + const RecMap* te = find_map(b, "te.blk.3.ffn_gate_up.weight"); + REQUIRE(te != nullptr); + CHECK_EQ(te->src[1], std::string("model.layers.3.mlp.up_proj.weight")); + /* The patch embedding over its first 64 columns, the final linear's rows in eight pieces. */ + const RecMap* xe = find_map(b, "dit.x_embed.weight"); + REQUIRE(xe != nullptr); + CHECK_EQ(xe->mode, (int)RAD_MAP_COLS); + int final_maps = 0; + for (const auto& m : b.maps) + if (m.declared == "dit.final.weight") { ++final_maps; CHECK_EQ(m.mode, (int)RAD_MAP_ROWS); } + CHECK_EQ(final_maps, 8); + /* The DiT's rotary: 22, 21 and 21 pairs, NeoX, over (frame, row, column). */ + int axial = 0; + for (const auto& o : b.ops) + if (o.op == "qk_norm_rope" && pstr(&o, "mode") == "axial") { + CHECK_EQ(pstr(&o, "sections"), std::string("22 21 21")); + ++axial; + } + CHECK_EQ(axial, 28); + + MetaKV turbo = anima_meta("turbo"); + RadBuilder bt; + bt.encs = { { "dit.t_norm.mdm", plain } }; + REQUIRE_EQ(anima::declare(&bt, turbo.meta(), &ctx), RAD_OK); + CHECK_EQ(bt.generator_name, std::string("anima-turbo")); + CHECK_EQ(bt.generator.default_steps, (int64_t)10); + CHECK_EQ(bt.generator.default_cfg, 1.0); + + MetaKV base = anima_meta("base"); + RadBuilder bb; + bb.encs = { { "dit.t_norm.net", plain } }; + REQUIRE_EQ(anima::declare(&bb, base.meta(), &ctx), RAD_OK); + const RecMap* nq = find_map(bb, "dit.blk.0.mlp_layer1.weight"); + REQUIRE(nq != nullptr); + CHECK_EQ(nq->src[0], std::string("net.blocks.0.mlp.layer1.weight")); + + /* Neither spelling, or an unknown variant, is refused. */ + RadBuilder none; + CHECK(anima::declare(&none, mk.meta(), &ctx) < 0); + MetaKV odd = anima_meta("deluxe"); + RadBuilder bo; + bo.encs = { { "dit.t_norm.mdm", plain } }; + CHECK(anima::declare(&bo, odd.meta(), &ctx) < 0); +} + +/* Every linear a LoRA for Anima names is read by a plain GEMM a runtime LoRA can follow: gemm_nt + * in a bf16 container, gemm_nt_q without rotated parts in a block-fp8 one, its activation a + * separate op. */ +TEST(anima_lora_targets_are_plain_gemms) { + const RadEncoding plain = rad_enc_plain(RAD_BF16); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); + RadBuildCtx ctx = anima_ctx(); + MetaKV mk = anima_meta("base"); + for (bool q : { false, true }) { + RadBuilder b; + b.encs = { { "dit.t_norm.net", plain } }; + if (!q) b.encs.push_back({ "dit.blk.0.attn_qkv", plain }); + if (q) + for (const char* t : { "attn_qkv", "attn_output", "cross_q", "cross_k", "cross_v", + "cross_output", "mlp_layer1", "mlp_layer2", "ffn_gate_up", + "ffn_down" }) + b.encs.push_back({ t, fp8 }); + REQUIRE_EQ(anima::declare(&b, mk.meta(), &ctx), RAD_OK); + int targets = 0; + for (const auto& o : b.ops) + for (rad_weight w : o.w) { + const std::string& n = b.weights[w - 1].name; + if (!anima_lora_target(n)) continue; + ++targets; + const bool ok = o.op == "gemm_nt" || (q && o.op == "gemm_nt_q" && + pint(&o, "pb1") <= 0 && pint(&o, "pb2") <= 0); + if (!ok) fprintf(stderr, " '%s' read by %s\n", n.c_str(), o.op.c_str()); + CHECK(ok); + CHECK(o.op != "gemm_nt_bias"); + } + /* 28 blocks of 8 linears (two views a block-fp8 one) and 6 modulation linears; 28 text + * encoder layers of 4. */ + CHECK(targets >= 28 * (8 + 6) + 28 * 4); + } +} + +/* The three passes the core drives (a conditioning with its T5 ids, denoising one image or a + * guided pair, decoding one) lint clean in a bf16 and a block-fp8 container. */ +TEST(anima_generator_passes_lint_clean) { + const RadEncoding plain = rad_enc_plain(RAD_BF16); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); + RadBuildCtx ctx = anima_ctx(); + MetaKV mk = anima_meta("aesthetic"); + for (bool q : { false, true }) { + RadBuilder b; + b.encs = { { "dit.t_norm.mdm", plain } }; + if (!q) b.encs.push_back({ "dit.blk.0.attn_qkv", plain }); + if (q) b.encs.push_back({ "attn_qkv", fp8 }), b.encs.push_back({ "attn_output", fp8 }), + b.encs.push_back({ "cross_", fp8 }), b.encs.push_back({ "mlp_layer", fp8 }), + b.encs.push_back({ "ffn_", fp8 }); + REQUIRE_EQ(anima::declare(&b, mk.meta(), &ctx), RAD_OK); + for (const auto& k : { anima_pass(RAD_GEN_PASS_COND, 12, 9), + anima_pass(RAD_GEN_PASS_COND, 3, 40), + anima_pass(RAD_GEN_PASS_DENOISE, 12, 9, 16, 1), + anima_pass(RAD_GEN_PASS_DENOISE, 12, 9, 16, 2), + anima_pass(RAD_GEN_PASS_DECODE) }) { + RadCtx c{ .b = &b, .batch = &k->b, .rank = 0, .world = 1 }; + anima::step(&c, &k->b); + CHECK(c.step_fail.empty()); + if (!c.step_fail.empty()) fprintf(stderr, " %s\n", c.step_fail.c_str()); + CHECK(!c.issues.empty()); + CHECK_LINT(b, &c); + } + const auto tok = kit(b, { 1 }, {}); + RadCtx c{ .b = &b, .batch = &tok->b, .rank = 0, .world = 1 }; + anima::step(&c, &tok->b); + CHECK(!c.step_fail.empty()); + } +} + /* ======================================================== the conventional vocabulary */ namespace { diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index ffa42b6c..88ccbc51 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -180,6 +180,78 @@ TEST(a_plain_tensor_is_its_own_encoding_and_reads_back_as_itself) { CHECK_EQ(std::memcmp(raw.data(), (const uint8_t*)ck.find("a.weight")->data + 32, 16), 0); } +/* A single-file SDXL checkpoint (Stability's sgm layout) is read under the names its adapters use: + * the UNet and CLIP ViT-L as they are, OpenCLIP bigG in transformers' names with its fused + * in_proj split into q/k/v rows and its (in, out) text_projection transposed, the VAE decoder in + * diffusers' names with up blocks counted the other way, a v_pred marker as the prediction type, + * and bigG's dimensions as the model's. */ +TEST(a_single_file_sdxl_checkpoint_is_read_in_its_adapters_names) { + const std::string g = "conditioner.embedders.1.model."; + T proj{ g + "text_projection", "F32", { 2, 3 }, {} }; + proj.bytes.resize(6 * 4); + for (int i = 0; i < 6; ++i) rad_store_f32(proj.bytes.data(), RAD_F32, i, (float)i); + const std::string dir = fresh_dir(); + const std::string file = dir + "/sdxl.safetensors"; + write_shard(file, { + bf16("model.diffusion_model.label_emb.0.0.weight", { 2, 4 }, 1.0f), + bf16("conditioner.embedders.0.transformer.text_model.final_layer_norm.weight", { 4 }, 2.0f), + bf16(g + "transformer.resblocks.3.attn.in_proj_weight", { 6, 4 }, 0.0f), + bf16(g + "transformer.resblocks.3.attn.in_proj_bias", { 6 }, 0.0f), + bf16(g + "transformer.resblocks.3.mlp.c_fc.weight", { 8, 4 }, 3.0f), + bf16(g + "transformer.resblocks.3.ln_2.bias", { 4 }, 4.0f), + bf16(g + "ln_final.weight", { 4 }, 5.0f), + bf16(g + "token_embedding.weight", { 16, 4 }, 0.0f), + bf16(g + "transformer.resblocks.0.ln_1.weight", { 4 }, 0.0f), + bf16(g + "transformer.resblocks.0.mlp.c_fc.weight", { 8, 4 }, 0.0f), + bf16(g + "positional_embedding", { 77, 4 }, 6.0f), + proj, + bf16("first_stage_model.decoder.up.0.block.2.nin_shortcut.weight", { 4, 8, 1, 1 }, 7.0f), + bf16("first_stage_model.decoder.up.3.upsample.conv.bias", { 4 }, 8.0f), + bf16("first_stage_model.decoder.mid.attn_1.proj_out.weight", { 4, 4, 1, 1 }, 9.0f), + bf16("first_stage_model.encoder.conv_in.weight", { 4, 3, 3, 3 }, 10.0f), + T{ "v_pred", "F32", { 0 }, {} }, + }); + Checkpoint ck; + REQUIRE_EQ(ck.open(file), RAD_OK); + CHECK_EQ(ck.meta().arch, std::string("sdxl")); + REQUIRE(ck.meta().get("sdxl.prediction") != nullptr); + CHECK_EQ(std::string(ck.meta().get("sdxl.prediction")), std::string("v")); + /* The typed dimensions are bigG's: its width, vocabulary and feed-forward off its tensors, + * its layers counted from 0 while they run on. */ + CHECK_EQ(ck.meta().m.n_embd, (int64_t)4); + CHECK_EQ(ck.meta().m.n_vocab, (int64_t)16); + CHECK_EQ(ck.meta().m.n_ff, (int64_t)8); + CHECK_EQ(ck.meta().m.n_layers, (int64_t)1); + CHECK(ck.find("model.diffusion_model.label_emb.0.0.weight") != nullptr); + CHECK(ck.find("conditioner.embedders.0.transformer.text_model.final_layer_norm.weight") != nullptr); + const std::string t = "conditioner.embedders.1.transformer."; + const std::string l = t + "text_model.encoder.layers.3."; + const SrcTensor* q = ck.find(l + "self_attn.q_proj.weight"); + const SrcTensor* v = ck.find(l + "self_attn.v_proj.weight"); + const SrcTensor* vb = ck.find(l + "self_attn.v_proj.bias"); + REQUIRE(q && v && vb); + CHECK(q->shape == std::vector({ 2, 4 })); + /* v is rows 4..5 of in_proj: elements 16..23, each its index (mod 64) in bf16. */ + CHECK_EQ(rad_load_f32(v->data, RAD_BF16, 0), 16.0f); + CHECK_EQ(rad_load_f32(vb->data, RAD_BF16, 1), 5.0f); + CHECK(ck.find(g + "transformer.resblocks.3.attn.in_proj_weight") == nullptr); + CHECK(ck.find(l + "mlp.fc1.weight") != nullptr); + CHECK(ck.find(l + "layer_norm2.bias") != nullptr); + CHECK(ck.find(t + "text_model.final_layer_norm.weight") != nullptr); + CHECK(ck.find(t + "text_model.embeddings.position_embedding.weight") != nullptr); + const SrcTensor* p = ck.find(t + "text_projection.weight"); + REQUIRE(p != nullptr); + CHECK(p->shape == std::vector({ 3, 2 })); + /* P^T: element (j, i) is P(i, j) = 3 i + j. */ + for (int j = 0; j < 3; ++j) + for (int i = 0; i < 2; ++i) + CHECK_EQ(rad_load_f32(p->data, RAD_F32, j * 2 + i), (float)(3 * i + j)); + CHECK(ck.find("vae.decoder.up_blocks.3.resnets.2.conv_shortcut.weight") != nullptr); + CHECK(ck.find("vae.decoder.up_blocks.0.upsamplers.0.conv.bias") != nullptr); + CHECK(ck.find("vae.decoder.mid_block.attentions.0.to_out.0.weight") != nullptr); + CHECK(ck.find("first_stage_model.encoder.conv_in.weight") != nullptr); +} + /* Block-scaled FP8 is one weight of two planes; each value is its code times the scale of the * block containing it along both axes. */ TEST(block_fp8_is_the_codes_and_their_scale_plane) { @@ -2735,4 +2807,82 @@ TEST(a_companion_folder_is_read_under_its_name) { CHECK_EQ(mget("codec.decoder_config.dim"), std::string("7")); } +namespace { + +/* A RAD_MAP_ROWS or RAD_MAP_COLS map: source k starts at index[k] and spans rows[k]. */ +RadNameMap ranged(const char* declared, int mode, std::vector src, + std::vector index, std::vector rows) { + RadNameMap m = map(declared, mode, std::move(src), std::move(index)); + for (size_t i = 0; i < rows.size(); ++i) m.src_rows[i] = rows[i]; + return m; +} + +} /* namespace */ + +/* A column range of the last dimension, in every leading slice; a range past the end is + * refused. */ +TEST(a_column_range_is_those_columns_of_every_row) { + const std::string dir = write_checkpoint({ bf16("x.weight", { 3, 5 }, 0.0f) }, kConfig); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + Program prog; + prog.name_map.push_back(ranged("xc", RAD_MAP_COLS, { "x.weight" }, { 1 }, { 3 })); + prog.name_map.push_back(ranged("far", RAD_MAP_COLS, { "x.weight" }, { 3 }, { 3 })); + CkptWeight w; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "xc", false, &w, &why), RAD_OK); + CHECK(!w.trivial); + REQUIRE_EQ(w.rank, (uint32_t)2); + CHECK_EQ(w.shape[0], (int64_t)3); + CHECK_EQ(w.shape[1], (int64_t)3); + std::vector f(9); + REQUIRE_EQ(ckpt_rows_f32(w, 0, 3, f.data(), &why), RAD_OK); + for (int r = 0; r < 3; ++r) + for (int c = 0; c < 3; ++c) CHECK_EQ(f[(size_t)(r * 3 + c)], (float)(r * 5 + 1 + c)); + CHECK_EQ(ckpt_resolve(ck, prog, "far", false, &w, &why), (int)RAD_E_SHAPE); +} + +/* Row pieces declared over several maps of one name join in declaration order, so a permutation + * of a weight's rows can be stated one row at a time. */ +TEST(row_pieces_over_several_maps_join_in_order) { + const std::string dir = write_checkpoint({ bf16("w", { 4, 3 }, 0.0f) }, kConfig); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + Program prog; + prog.name_map.push_back(ranged("p", RAD_MAP_ROWS, { "w" }, { 2 }, { 1 })); + prog.name_map.push_back(ranged("p", RAD_MAP_ROWS, { "w", "w" }, { 0, 3 }, { 1, 1 })); + CkptWeight w; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK); + CHECK_EQ(w.shape[0], (int64_t)3); + CHECK_EQ(w.shape[1], (int64_t)3); + std::vector f(9); + REQUIRE_EQ(ckpt_rows_f32(w, 0, 3, f.data(), &why), RAD_OK); + const int order[3] = { 2, 0, 3 }; + for (int r = 0; r < 3; ++r) + for (int c = 0; c < 3; ++c) CHECK_EQ(f[(size_t)(r * 3 + c)], (float)(order[r] * 3 + c)); +} + +/* A release split into single files merges them under their own names; a name two files share + * is refused. The metadata and tokenizer come from the directory set before open(). */ +TEST(single_files_merge_by_name_and_read_their_metadata_elsewhere) { + const std::string dir = fresh_dir(); + write_shard(dir + "/dit.safetensors", { bf16("net.a", { 2, 2 }, 1.0f) }); + write_shard(dir + "/te.safetensors", { bf16("model.b", { 2, 2 }, 2.0f) }); + write_shard(dir + "/dup.safetensors", { bf16("net.a", { 2, 2 }, 3.0f) }); + const std::string meta = fresh_dir(); + write_file(meta + "/config.json", "{\"model_type\":\"qwen3\",\"hidden_size\":64}"); + write_file(meta + "/tokenizer.json", "{}"); + Checkpoint ck; + ck.set_meta_dir(meta); + REQUIRE_EQ(ck.open(dir + "/dit.safetensors"), RAD_OK); + REQUIRE_EQ(ck.add_file(dir + "/te.safetensors"), RAD_OK); + CHECK(ck.find("net.a") != nullptr); + CHECK(ck.find("model.b") != nullptr); + CHECK(ck.add_file(dir + "/dup.safetensors") < 0); + const char* mt = ck.meta().get("model_type"); + CHECK_EQ(std::string(mt ? mt : ""), std::string("qwen3")); + CHECK_EQ(ck.tok_dir(), meta); +} + RAD_TEST_MAIN() diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 78af66f2..49883424 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -129,7 +130,8 @@ TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) { /* Runtime LoRA: the adapters reach their fields in order, the targets as sorted leaf names, and a * combination that would size slots no adapter uses, or name an adapter that is not served, is - * refused by name. */ + * refused by name. A text model's slot count against its adapters, and its targets, are checked + * at startup, where the engine knows whether the model generates text. */ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) { Config c; CHECK_OK(parse({ "--lora", "b=/ad/b", "--lora", "a=/ad/a", "--max-loras", "3", @@ -144,6 +146,15 @@ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) { Config d; CHECK_OK(parse({}, &d)); CHECK(!d.lora.enabled()); + CHECK_EQ(d.lora.rank(false), 16); + CHECK_EQ(d.lora.rank(true), 64); + Config e; + const std::string dir = radtest::tmp_path("loradir"); + mkdir(dir.c_str(), 0755); + CHECK_OK(parse({ "--lora-dir", dir.c_str() }, &e)); + CHECK(e.lora.enabled()); + CHECK_EQ(e.lora.slots(), 2); + CHECK_EQ(e.lora.rank(true), 64); auto refused = [](std::initializer_list v, const char* why) { int st = RAD_OK; @@ -157,10 +168,9 @@ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) { refused({ "--lora", "/ad/a" }, "NAME=PATH"); refused({ "--lora", "a=" }, "NAME=PATH"); refused({ "--lora", "a=/x", "--lora", "a=/y" }, "names the adapter 'a' twice"); - refused({ "--lora", "a=/x", "--lora", "b=/y", "--max-loras", "1" }, "fewer adapters"); refused({ "--max-lora-rank", "32" }, "--max-lora-rank sizes runtime LoRA slots"); refused({ "--lora-target-modules", "q_proj" }, "--lora-target-modules sizes"); - refused({ "--max-loras", "2" }, "names no module an adapter may target"); + refused({ "--lora-dir", "/no/such/dir" }, "is not a directory"); refused({ "--lora", "a=/x", "--lora-target-modules", "self_attn.q_proj" }, "leaf names"); refused({ "--lora", "a=/x", "--lora-target-modules", ".*proj" }, "leaf names"); refused({ "--lora", "a=/x", "--lora-target-modules", " , " }, "names no module"); @@ -454,6 +464,7 @@ const std::map>& legal_values() { { "--kld-corpus", { "/c.jsonl", "--kld-record", "/r" } }, { "--kld-out", { "/o.json", "--kld-ref", "/r" } }, { "--lora", { "a=/adapters/a" } }, + { "--lora-dir", { "/" } }, { "--max-loras", { "2", "--lora-target-modules", "q_proj" } }, { "--max-lora-rank", { "32", "--lora", "a=/adapters/a" } }, { "--lora-target-modules", { "q_proj,v_proj", "--max-loras", "1" } }, diff --git a/tests/gen_lora_test.cpp b/tests/gen_lora_test.cpp new file mode 100644 index 00000000..5fb7eece --- /dev/null +++ b/tests/gen_lora_test.cpp @@ -0,0 +1,585 @@ +/* gen_lora_test.cpp -- runtime LoRA for generators: adapter files in every spelling and kind + * (core/lora/adapter.h), their keys mapped through a generator's declared names, stacked at + * strengths, packed per rank; and the request fields that name them (core/server/loras.h). + * + * Host only, no kernel plugin: the Program is made by the core Builder over an empty Registry, as + * lora_test.cpp makes its own, with the generator's names declared through the builder (the calls + * rad_lora_root / rad_lora_alias make). The reference is the test's own dense delta of every + * checkpoint module, placed by model semantics -- which rows of which tensor a rank's declared + * weight holds -- never by anything adapter.cpp or lora.cpp computes. + */ +#include "rad_test.h" + +#include "build/rad_build.h" +#include "lora/adapter.h" +#include "lora/lora.h" +#include "plugin/registry.h" +#include "rad_plugin.h" +#include "server/loras.h" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rad; +namespace AR = rad::arch; +using ojson = nlohmann::ordered_json; + +namespace { + +Registry& empty_registry() { + static Registry r; + return r; +} + +float val(uint32_t seed, uint64_t i) { + uint64_t x = (uint64_t)seed * 0x9E3779B97F4A7C15ull + i * 0xBF58476D1CE4E5B9ull + 1; + x ^= x >> 31; x *= 0x94D049BB133111EBull; x ^= x >> 29; + return (float)((double)(x >> 11) / (double)(1ull << 53) - 0.5) * 0.5f; +} + +/* ------------------------------------------------------------------ safetensors */ +struct TW { + std::string name, dtype; + std::vector shape; + std::vector v; /* written as dtype */ +}; +void write_st(const std::string& path, const std::vector& ts) { + ojson h = ojson::object(); + std::vector> bytes; + uint64_t off = 0; + for (const TW& t : ts) { + std::vector b; + if (t.dtype == "I64") { const int64_t v = 4; b.resize(8); std::memcpy(b.data(), &v, 8); } + for (float f : t.v) { + if (t.dtype == "F32") { uint8_t x[4]; std::memcpy(x, &f, 4); b.insert(b.end(), x, x + 4); } + else { + const uint16_t u = t.dtype == "F16" ? rad_f32_to_f16(f) : rad_f32_to_bf16(f); + uint8_t x[2]; std::memcpy(x, &u, 2); b.insert(b.end(), x, x + 2); + } + } + h[t.name] = { { "dtype", t.dtype }, { "shape", t.shape }, + { "data_offsets", { off, off + b.size() } } }; + off += b.size(); + bytes.push_back(std::move(b)); + } + h["__metadata__"] = { { "format", "pt" } }; + std::string s = h.dump(); + while (s.size() % 8) s += ' '; + std::ofstream f(path, std::ios::binary); + const uint64_t n = s.size(); + f.write((const char*)&n, 8); + f.write(s.data(), (std::streamsize)s.size()); + for (const auto& b : bytes) f.write((const char*)b.data(), (std::streamsize)b.size()); +} +/* A tensor of seeded values, and the values as the file holds them. */ +TW tensor(const std::string& name, const std::string& dt, std::vector shape, uint32_t seed, + float mul = 1.0f) { + TW t{ name, dt, shape, {} }; + int64_t n = 1; + for (int64_t d : shape) n *= d; + for (int64_t i = 0; i < n; ++i) { + float f = val(seed, (uint64_t)i) * mul; + if (dt == "F16") f = rad_f16_to_f32(rad_f32_to_f16(f)); + else if (dt == "BF16") f = rad_bf16_to_f32(rad_f32_to_bf16(f)); + t.v.push_back(f); + } + return t; +} +TW scalar(const std::string& name, float f) { return TW{ name, "F32", {}, { f } }; } + +/* ------------------------------------------------------------------ dense helpers */ +struct Dense { + int64_t N = 0, K = 0; + std::vector d; + void add(const Dense& o, double w) { + if (d.empty()) { N = o.N; K = o.K; d.assign(o.d.size(), 0.0); } + for (size_t i = 0; i < d.size(); ++i) d[i] += w * o.d[i]; + } +}; +Dense mul(const std::vector& B, const std::vector& A, int64_t N, int64_t r, int64_t K, + double s) { + Dense o{ N, K, std::vector((size_t)(N * K), 0.0) }; + for (int64_t n = 0; n < N; ++n) + for (int64_t j = 0; j < r; ++j) + for (int64_t k = 0; k < K; ++k) + o.d[(size_t)(n * K + k)] += s * (double)B[(size_t)(n * r + j)] * A[(size_t)(j * K + k)]; + return o; +} + +/* ------------------------------------------------------------------ the generator */ +/* A two-block DiT under "transformer.", as an image generator's plugin declares one: a fused + * [q|k|v] (row parts, ROW), the output (COL), a SwiGLU re-laid from one checkpoint tensor whose + * value half comes first (RAD_MAP_ROWS: the gate half moved first), the down projection (COL); a + * text encoder's linear outside the root; and a DiT weight a fused GEMM reads. */ +const int64_t kD = 128, kHD = 32, kNH = 8, kF = 512, kQ = kNH * kHD; + +RadModelMeta gen_meta() { + RadModelMeta m{}; + m.arch_id = "gentest"; m.name = "lora-test-gen"; m.quant = "fp8_e4m3"; + m.n_layers = 2; m.n_embd = kD; m.n_head = kNH; m.n_head_kv = kNH; m.head_dim = kHD; + m.n_ff = kF; m.n_vocab = 512; m.n_ctx_train = 1024; + m.rms_eps = 1e-5f; m.rope_theta = 1e4f; m.rope_scale = 1.0f; + return m; +} + +OpInfo gemm_op(const char* name, int64_t N, int64_t K, const char* dtype, int64_t hi, + std::vector w, std::vector opd) { + OpInfo o; + o.op = name; + o.base.set_i("N", N); + o.base.set_i("K", K); + o.base.set_i("group", AR::RAD_FP8_BLOCK); + o.base.set_s("dtype", dtype); + o.ranged_key = "M"; + o.range_lo = 1; + o.range_hi = hi; + o.weights = std::move(w); + o.weight_opd = std::move(opd); + return o; +} +void push_op(Builder& b, OpInfo o) { + o.index = (int32_t)b.program().ops.size(); + b.program().ops.push_back(std::move(o)); +} + +int linear(Builder& b, AR::Names& nm, const AR::Geom& g, const char* base, int64_t N, int64_t K, + int shard, int layer, std::initializer_list src, + std::initializer_list parts = {}, bool mapped = false, + const char* op = "gemm_nt_q") { + AR::LinearFP8 lin{}; + AR::ActFP8 act{}; + lin.mapped = mapped; + const int st = lin.declare((RadBuilder*)&b, nm, g, base, N, K, shard, AR::grp_layer(layer), src, + act, 0, 0, parts); + if (st < 0 || !lin.w || !lin.ws) return st < 0 ? st : RAD_E_INVAL; + push_op(b, gemm_op(op, N, K, "fp8a8", g.max_tok, { lin.w, lin.ws }, { 2, 3 })); + return RAD_OK; +} + +RadBuildCtx ctx_for(int rank, int world) { + RadBuildCtx c{}; + c.rank = rank; + c.world_size = world; + c.max_tok = 256; + c.max_seqs = 8; + c.max_ctx = 1024; + c.scope = ""; + return c; +} + +/* Where a declared weight's rows on one rank come from: (checkpoint module, its full rows) per + * row of y, and the full K columns of x. */ +struct Truth { + std::vector> rows; + std::vector cols; +}; + +int build_gen(int rank, int world, Program* out, std::map* truth) { + const RadModelMeta meta = gen_meta(); + const RadBuildCtx ctx = ctx_for(rank, world); + AR::Geom g{}; + RAD_ARCH_TRY(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16)); + Builder b(empty_registry(), meta, ctx); + b.program().generator.layout = RAD_GEN_LAYOUT_JOINT_STEP; + RAD_ARCH_TRY(AR::lora_names((RadBuilder*)&b, "transformer.", AR::kLoraDiffusionSpellings, + { { "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_q", 0, kQ, 0 }, + { "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_k", kQ, 2 * kQ, 0 }, + { "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_v", 2 * kQ, 3 * kQ, 0 }, + { "blocks.#.attn.out_proj", "transformer_blocks.#.attn.to_out.0" }, + { "blocks.#.mlp.fc1", "transformer_blocks.#.ff.net.0.proj", 0, kF, kF }, + { "blocks.#.mlp.fc1", "transformer_blocks.#.ff.net.0.proj", kF, 2 * kF, 0 }, + { "blocks.#.mlp.fc2", "transformer_blocks.#.ff.net.2" } })); + AR::Names nm(""); + const int64_t qr = g.q_dim(), fr = g.n_ff; + for (int l = 0; l < 2; ++l) { + const std::string P = "transformer.transformer_blocks." + std::to_string(l) + "."; + auto ck = [&](const char* leaf) { return nm.ckpt("%s%s.weight", P.c_str(), leaf); }; + RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.qkv", l), 3 * qr, kD, RAD_SHARD_ROW, l, + { ck("attn.to_q"), ck("attn.to_k"), ck("attn.to_v") }, { qr, qr, qr })); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.o", l), kD, qr, RAD_SHARD_COL, l, + { ck("attn.to_out.0") })); + const char* fsrc = ck("ff.net.0.proj"); + RAD_ARCH_TRY(AR::map_rows((RadBuilder*)&b, nm.f("dit.%d.gate_up.weight", l), + { { fsrc, (int)kF, kF }, { fsrc, 0, kF } })); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.gate_up", l), 2 * fr, kD, RAD_SHARD_ROW, l, + { fsrc }, { fr, fr }, true)); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.down", l), kD, fr, RAD_SHARD_COL, l, + { ck("ff.net.2") })); + + Truth q, o, gu, dn; + const char* part[3] = { "attn.to_q", "attn.to_k", "attn.to_v" }; + for (const char* p : part) + for (int64_t i = rank * qr; i < (rank + 1) * qr; ++i) q.rows.push_back({ P + p, i }); + for (int64_t k = 0; k < kD; ++k) q.cols.push_back(k); + for (int64_t i = 0; i < kD; ++i) o.rows.push_back({ P + "attn.to_out.0", i }); + for (int64_t k = rank * qr; k < (rank + 1) * qr; ++k) o.cols.push_back(k); + for (int64_t i = rank * fr; i < (rank + 1) * fr; ++i) gu.rows.push_back({ P + "ff.net.0.proj", kF + i }); + for (int64_t i = rank * fr; i < (rank + 1) * fr; ++i) gu.rows.push_back({ P + "ff.net.0.proj", i }); + for (int64_t k = 0; k < kD; ++k) gu.cols.push_back(k); + for (int64_t i = 0; i < kD; ++i) dn.rows.push_back({ P + "ff.net.2", i }); + for (int64_t k = rank * fr; k < (rank + 1) * fr; ++k) dn.cols.push_back(k); + const std::string L = std::to_string(l); + (*truth)["dit." + L + ".qkv.weight"] = q; + (*truth)["dit." + L + ".o.weight"] = o; + (*truth)["dit." + L + ".gate_up.weight"] = gu; + (*truth)["dit." + L + ".down.weight"] = dn; + } + /* Outside the root: a text encoder's projection. */ + RAD_ARCH_TRY(linear(b, nm, g, "te.0.q", kD, kD, RAD_SHARD_NONE, 0, + { "text_encoder.layers.0.q_proj.weight" })); + /* Under the root, read by a fused GEMM: it stays the base. */ + RAD_ARCH_TRY(linear(b, nm, g, "dit.fused", kD, kD, RAD_SHARD_NONE, 0, + { "transformer.proj_out.weight" }, {}, false, "gemm_nt_q_swiglu")); + *out = std::move(b.program()); + return RAD_OK; +} + +std::string new_dir(const std::string& name) { + const std::string d = radtest::tmp_path(name); + mkdir(d.c_str(), 0755); + return d; +} + +/* ------------------------------------------------------------------ the adapter files */ +/* Two files, every spelling and kind, and the dense delta of every checkpoint module they reach + * (strength 1). File 1: kohya LoRA on block 0's fused qkv; ComfyUI LoRA on block 0's fc1 (gate + * half first); PEFT LoRA on block 1's down projection under the checkpoint's own name; LoHa on + * block 1's out_proj; a full delta on block 0's fc2; a module of no model; a bias delta. File 2: + * LoKr on block 1's qkv; a bare-keyed LoRA on block 0's qkv, stacking with file 1's. */ +struct Files { + std::string f1, f2; + std::map d1, d2; /* by checkpoint module, full rows */ +}; + +void place(std::map* m, const std::string& mod, int64_t N_full, const Dense& d, + int64_t from_lo, int64_t n, int64_t to_lo) { + Dense& t = (*m)[mod]; + if (t.d.empty()) { t.N = N_full; t.K = d.K; t.d.assign((size_t)(N_full * d.K), 0.0); } + for (int64_t r = 0; r < n; ++r) + for (int64_t k = 0; k < d.K; ++k) + t.d[(size_t)((to_lo + r) * d.K + k)] += d.d[(size_t)((from_lo + r) * d.K + k)]; +} + +Files make_files() { + Files f; + const std::string dir = new_dir("genlora"); + const std::string B0 = "transformer.transformer_blocks.0.", B1 = "transformer.transformer_blocks.1."; + std::vector ts; + { /* kohya LoRA, rank 8, alpha 4: qkv of block 0 */ + TW dn = tensor("lora_unet_blocks_0_attn_qkv.lora_down.weight", "F16", { 8, kD }, 1); + TW up = tensor("lora_unet_blocks_0_attn_qkv.lora_up.weight", "BF16", { 3 * kQ, 8 }, 2); + const Dense d = mul(up.v, dn.v, 3 * kQ, 8, kD, 4.0 / 8.0); + place(&f.d1, B0 + "attn.to_q", kQ, d, 0, kQ, 0); + place(&f.d1, B0 + "attn.to_k", kQ, d, kQ, kQ, 0); + place(&f.d1, B0 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0); + ts.push_back(dn); ts.push_back(up); + TW al{ "lora_unet_blocks_0_attn_qkv.alpha", "I64", {}, {} }; /* as kohya writes some */ + ts.push_back(al); + } + { /* ComfyUI LoRA, rank 4, no alpha: fc1 of block 0, [gate; up] */ + TW a = tensor("diffusion_model.blocks.0.mlp.fc1.lora_A.weight", "BF16", { 4, kD }, 3); + TW b = tensor("diffusion_model.blocks.0.mlp.fc1.lora_B.weight", "F32", { 2 * kF, 4 }, 4); + const Dense d = mul(b.v, a.v, 2 * kF, 4, kD, 1.0); + place(&f.d1, B0 + "ff.net.0.proj", 2 * kF, d, 0, kF, kF); + place(&f.d1, B0 + "ff.net.0.proj", 2 * kF, d, kF, kF, 0); + ts.push_back(a); ts.push_back(b); + } + { /* PEFT LoRA under the checkpoint's own name, rank 6, alpha 12 */ + TW a = tensor(B1 + "ff.net.2.lora_A.default.weight", "F32", { 6, kF }, 5); + TW b = tensor(B1 + "ff.net.2.lora_B.default.weight", "F32", { kD, 6 }, 6); + place(&f.d1, B1 + "ff.net.2", kD, mul(b.v, a.v, kD, 6, kF, 12.0 / 6.0), 0, kD, 0); + ts.push_back(a); ts.push_back(b); ts.push_back(scalar(B1 + "ff.net.2.alpha", 12.0f)); + } + { /* LoHa, ranks 4 and 3, alpha 2: out_proj of block 1 */ + const std::string k = "diffusion_model.blocks.1.attn.out_proj."; + TW w1a = tensor(k + "hada_w1_a", "F32", { kD, 4 }, 7), w1b = tensor(k + "hada_w1_b", "F32", { 4, kQ }, 8); + TW w2a = tensor(k + "hada_w2_a", "F32", { kD, 3 }, 9), w2b = tensor(k + "hada_w2_b", "F32", { 3, kQ }, 10); + const Dense p1 = mul(w1a.v, w1b.v, kD, 4, kQ, 1.0), p2 = mul(w2a.v, w2b.v, kD, 3, kQ, 1.0); + Dense d{ kD, kQ, std::vector(p1.d.size()) }; + for (size_t i = 0; i < d.d.size(); ++i) d.d[i] = 0.5 * p1.d[i] * p2.d[i]; + place(&f.d1, B1 + "attn.to_out.0", kD, d, 0, kD, 0); + ts.insert(ts.end(), { w1a, w1b, w2a, w2b, scalar(k + "alpha", 2.0f) }); + } + { /* a full delta: fc2 of block 0 */ + TW df = tensor("diffusion_model.blocks.0.mlp.fc2.diff", "F32", { kD, kF }, 11, 0.1f); + Dense d{ kD, kF, std::vector(df.v.begin(), df.v.end()) }; + place(&f.d1, B0 + "ff.net.2", kD, d, 0, kD, 0); + ts.push_back(df); + } + ts.push_back(tensor("diffusion_model.nowhere.lora_A.weight", "F32", { 2, 8 }, 12)); + ts.push_back(tensor("diffusion_model.nowhere.lora_B.weight", "F32", { 8, 2 }, 13)); + ts.push_back(tensor("diffusion_model.blocks.0.mlp.fc2.diff_b", "F32", { kD }, 14)); + f.f1 = dir + "/one.safetensors"; + write_st(f.f1, ts); + + ts.clear(); + { /* LoKr: w1 [3, 2] full, w2 = w2_a [kQ, 4] @ w2_b [4, kD / 2], alpha 8 (scale 8 / 4) */ + const std::string k = "lora_unet_blocks_1_attn_qkv."; + TW w1 = tensor(k + "lokr_w1", "F32", { 3, 2 }, 15); + TW w2a = tensor(k + "lokr_w2_a", "F32", { kQ, 4 }, 16), w2b = tensor(k + "lokr_w2_b", "F32", { 4, kD / 2 }, 17); + const Dense w2 = mul(w2a.v, w2b.v, kQ, 4, kD / 2, 1.0); + Dense d{ 3 * kQ, kD, std::vector((size_t)(3 * kQ * kD)) }; + for (int64_t i1 = 0; i1 < 3; ++i1) + for (int64_t j1 = 0; j1 < 2; ++j1) + for (int64_t i2 = 0; i2 < kQ; ++i2) + for (int64_t j2 = 0; j2 < kD / 2; ++j2) + d.d[(size_t)((i1 * kQ + i2) * kD + j1 * (kD / 2) + j2)] = + 2.0 * w1.v[(size_t)(i1 * 2 + j1)] * w2.d[(size_t)(i2 * (kD / 2) + j2)]; + place(&f.d2, B1 + "attn.to_q", kQ, d, 0, kQ, 0); + place(&f.d2, B1 + "attn.to_k", kQ, d, kQ, kQ, 0); + place(&f.d2, B1 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0); + ts.insert(ts.end(), { w1, w2a, w2b, scalar(k + "alpha", 8.0f) }); + } + { /* bare keys, rank 8: qkv of block 0, stacked on file 1's */ + TW a = tensor("blocks.0.attn.qkv.lora_A.weight", "BF16", { 8, kD }, 18); + TW b = tensor("blocks.0.attn.qkv.lora_B.weight", "BF16", { 3 * kQ, 8 }, 19); + const Dense d = mul(b.v, a.v, 3 * kQ, 8, kD, 1.0); + place(&f.d2, B0 + "attn.to_q", kQ, d, 0, kQ, 0); + place(&f.d2, B0 + "attn.to_k", kQ, d, kQ, kQ, 0); + place(&f.d2, B0 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0); + ts.push_back(a); ts.push_back(b); + } + f.f2 = dir + "/two.safetensors"; + write_st(f.f2, ts); + return f; +} + +/* A packed slot's product, [N_r, K_r]. */ +std::vector slot_delta(const lora::Site& s, const lora::PackedSite& p) { + std::vector d((size_t)(s.N_r * s.K_r), 0.0); + for (int64_t y = 0; y < s.N_r; ++y) { + for (int64_t j = 0; j < s.R; ++j) { + const double b = rad_bf16_to_f32(p.b[(size_t)(y * s.R + j)]); + if (b == 0.0) continue; + for (int64_t k = 0; k < s.K_r; ++k) + d[(size_t)(y * s.K_r + k)] += b * rad_bf16_to_f32(p.a[(size_t)(j * s.K_r + k)]); + } + for (int64_t k = 0; k < s.K_r; ++k) d[(size_t)(y * s.K_r + k)] *= p.scale[(size_t)y]; + } + return d; +} + +} /* namespace */ + +/* ================================================================== the files */ +TEST(adapter_files_group_by_module_and_refuse_what_they_cannot_reproduce) { + const Files f = make_files(); + lora::AdapterFile a; + std::string err; + REQUIRE_EQ(a.open(f.f1, &err), RAD_OK); + CHECK_EQ(a.modules().size(), (size_t)6); + CHECK_EQ(a.skipped().size(), (size_t)1); + CHECK_EQ(std::string(a.kind_name()), std::string("LoRA")); + const std::string dir = new_dir("genlora_bad"); + write_st(dir + "/dora.safetensors", { tensor("m.lora_A.weight", "F32", { 2, 4 }, 1), + tensor("m.lora_B.weight", "F32", { 4, 2 }, 2), + tensor("m.dora_scale", "F32", { 4, 1 }, 3) }); + CHECK_EQ(a.open(dir + "/dora.safetensors", &err), (int)RAD_E_UNSUPPORTED); + CHECK(err.find("DoRA") != std::string::npos); + write_st(dir + "/half.safetensors", { tensor("m.lora_A.weight", "F32", { 2, 4 }, 1) }); + CHECK_EQ(a.open(dir + "/half.safetensors", &err), (int)RAD_E_FORMAT); +} + +/* A delta given as an operator truncates to its best rank-r form: exact at or above its rank, and + * otherwise keeping what the sketch says it keeps. */ +TEST(truncation_is_exact_within_the_rank_and_honest_past_it) { + const int64_t N = 96, K = 80; + std::vector D((size_t)(N * K)); + /* rank 12 */ + std::vector U((size_t)(N * 12)), V((size_t)(12 * K)); + for (size_t i = 0; i < U.size(); ++i) U[i] = val(21, i); + for (size_t i = 0; i < V.size(); ++i) V[i] = val(22, i); + const Dense ref = mul(U, V, N, 12, K, 1.0); + for (size_t i = 0; i < D.size(); ++i) D[i] = (float)ref.d[i]; + lora::Delta d; + d.N = N; d.K = K; d.rank_bound = std::min(N, K); + d.apply = [&](const float* X, int64_t l, float* Y) { + for (int64_t n = 0; n < N; ++n) + for (int64_t j = 0; j < l; ++j) { + double a = 0; + for (int64_t k = 0; k < K; ++k) a += (double)D[(size_t)(n * K + k)] * X[k * l + j]; + Y[n * l + j] = (float)a; + } + }; + d.apply_t = [&](const float* Y, int64_t l, float* X) { + for (int64_t k = 0; k < K; ++k) + for (int64_t j = 0; j < l; ++j) { + double a = 0; + for (int64_t n = 0; n < N; ++n) a += (double)D[(size_t)(n * K + k)] * Y[n * l + j]; + X[k * l + j] = (float)a; + } + }; + std::vector B, A; + double kept = 0; + lora::truncate(d, 16, &B, &A, &kept); + const Dense got = mul(B, A, N, 16, K, 1.0); + double e = 0, t = 0; + for (size_t i = 0; i < got.d.size(); ++i) { e += std::pow(got.d[i] - ref.d[i], 2); t += ref.d[i] * ref.d[i]; } + CHECK(e / t < 1e-8); + CHECK_NEAR(kept, 1.0, 1e-6); + /* rank 6 of a rank-12 matrix: what is lost is what the report says is lost */ + lora::truncate(d, 6, &B, &A, &kept); + const Dense g6 = mul(B, A, N, 6, K, 1.0); + e = 0; + for (size_t i = 0; i < g6.d.size(); ++i) e += std::pow(g6.d[i] - ref.d[i], 2); + CHECK(kept < 0.99 && kept > 0.2); + CHECK_NEAR(1.0 - e / t, kept, 0.02); +} + +/* ================================================================== the names */ +TEST(keys_resolve_through_spellings_aliases_and_kohya) { + Program P; + std::map truth; + REQUIRE_EQ(build_gen(0, 1, &P, &truth), RAD_OK); + std::vector sites; + std::string err; + REQUIRE_EQ(lora::build_sites(P, { "*" }, 16, &sites, &err), RAD_OK); + /* 2 blocks x 4 weights; the text encoder's and the fused GEMM's are not sites */ + CHECK_EQ(sites.size(), (size_t)8); + for (const lora::Site& s : sites) CHECK(s.weight.rfind("dit.", 0) == 0 && s.weight != "dit.fused.weight"); + const lora::KeyMap km(P, sites); + std::string why; + auto one = [&](const std::string& k) { return km.resolve(k, &why); }; + std::vector t = one("lora_unet_blocks_1_attn_qkv"); + REQUIRE_EQ(t.size(), (size_t)3); + CHECK_EQ(t[1].module, std::string("transformer.transformer_blocks.1.attn.to_k")); + CHECK_EQ(t[1].from_lo, kQ); + CHECK_EQ(t[1].from_hi, 2 * kQ); + t = one("diffusion_model.blocks.0.mlp.fc2"); + REQUIRE_EQ(t.size(), (size_t)1); + CHECK_EQ(t[0].module, std::string("transformer.transformer_blocks.0.ff.net.2")); + t = one("transformer.transformer_blocks.0.attn.to_out.0"); + REQUIRE_EQ(t.size(), (size_t)1); + t = one("lora_unet_transformer_blocks_0_attn_to_out_0"); + REQUIRE_EQ(t.size(), (size_t)1); + CHECK_EQ(t[0].module, std::string("transformer.transformer_blocks.0.attn.to_out.0")); + t = one("blocks.1.mlp.fc1"); + CHECK_EQ(t.size(), (size_t)2); + CHECK(one("diffusion_model.proj_out").empty()); + CHECK(why.find("no adapter path") != std::string::npos); + CHECK(one("text_encoder.layers.0.q_proj").empty()); + CHECK(one("diffusion_model.blocks.7.attn.qkv").empty()); +} + +/* ================================================================== stacked, packed */ +/* Packed compact, as the engine packs a generator's slot: every pool's product is the dense delta, + * and its ranks are taken from 0. */ +TEST(stacked_adapters_of_every_kind_pack_to_their_dense_delta_on_every_rank) { + const Files f = make_files(); + auto a1 = std::make_shared(), a2 = std::make_shared(); + std::string err; + REQUIRE_EQ(a1->open(f.f1, &err), RAD_OK); + REQUIRE_EQ(a2->open(f.f2, &err), RAD_OK); + const double w1 = 0.8, w2 = -0.5; + std::map want; + for (const auto& [k, d] : f.d1) want[k].add(d, w1); + for (const auto& [k, d] : f.d2) want[k].add(d, w2); + const int R = 24; + for (int world : { 1, 2 }) { + for (int rank = 0; rank < world; ++rank) { + Program P; + std::map truth; + REQUIRE_EQ(build_gen(rank, world, &P, &truth), RAD_OK); + std::vector sites; + std::vector pools; + REQUIRE_EQ(lora::build_sites(P, { "*" }, R, &sites, &err, &pools), RAD_OK); + const lora::KeyMap km(P, sites); + std::map comp; + lora::ComposeReport rep; + const int cs = lora::compose(km, { { "one", a1, w1 }, { "two", a2, w2 } }, R, &comp, &rep, &err); + if (cs != RAD_OK) fprintf(stderr, " world %d rank %d: %s\n", world, rank, err.c_str()); + REQUIRE_EQ(cs, RAD_OK); + CHECK_EQ(rep.unplaced.size(), (size_t)1); + CHECK_EQ(rep.skipped.size(), (size_t)1); + /* block 0's fc2 (a full delta, rank 128) is the one module past rank 24 */ + CHECK_EQ(rep.modules - rep.exact, (int64_t)1); + CHECK_EQ(rep.worst_module, std::string("transformer.transformer_blocks.0.ff.net.2")); + const std::map mods = lora::as_modules(comp, km); + lora::AdapterInfo info; + std::vector packed; + const int ps = lora::pack_modules(sites, R, mods, &info, &packed, &err, /*compact=*/true); + if (ps != RAD_OK) fprintf(stderr, " world %d rank %d: %s\n", world, rank, err.c_str()); + REQUIRE_EQ(ps, RAD_OK); + REQUIRE_EQ(packed.size(), pools.size()); + for (size_t p = 0; p < pools.size(); ++p) { + const lora::Site* sp = nullptr; + for (const lora::Site& x : sites) if (x.pool == (int32_t)p && !sp) sp = &x; + REQUIRE(sp != nullptr); + const lora::Site& s = *sp; + const Truth& t = truth.at(s.weight); + /* compact: the ranks taken from 0, within the pool's R */ + const lora::PackedSite& pk = packed[(size_t)s.pool]; + CHECK(pk.empty || (pk.r_used > 0 && pk.r_used <= s.R)); + for (int64_t y = 0; y < s.N_r && !pk.empty; ++y) + for (int64_t j = pk.r_used; j < s.R; ++j) + CHECK_EQ(pk.b[(size_t)(y * s.R + j)], (uint16_t)0); + REQUIRE_EQ((int64_t)t.rows.size(), s.N_r); + REQUIRE_EQ((int64_t)t.cols.size(), s.K_r); + const std::vector got = slot_delta(s, packed[(size_t)s.pool]); + double e = 0, tot = 0, mx = 0; + bool truncated = false; + for (int64_t y = 0; y < s.N_r; ++y) { + const auto& [mod, row] = t.rows[(size_t)y]; + truncated = truncated || mod == "transformer.transformer_blocks.0.ff.net.2"; + auto it = want.find(mod); + for (int64_t k = 0; k < s.K_r; ++k) { + const double ref = it == want.end() ? 0.0 + : it->second.d[(size_t)(row * it->second.K + t.cols[(size_t)k])]; + const double g = got[(size_t)(y * s.K_r + k)]; + e += (g - ref) * (g - ref); + tot += ref * ref; + mx = std::max(mx, std::fabs(g - ref) / (std::fabs(ref) + 1e-3)); + } + } + const double rel = tot > 0 ? std::sqrt(e / tot) : std::sqrt(e); + if (rel > (truncated ? 0.9 : 0.01)) + fprintf(stderr, " world %d rank %d %s: relative error %.4g\n", world, rank, + s.weight.c_str(), rel); + /* bf16 factors hold a delta to ~0.5%; the truncated one to what its rank keeps */ + CHECK(rel <= (truncated ? 0.9 : 0.01)); + if (truncated && world == 1) + CHECK_NEAR(1.0 - rel * rel, rep.worst_kept, 0.03); + } + } + } +} + +/* ================================================================== the request fields */ +TEST(requests_name_adapters_in_a_field_or_in_prompt_tags) { + std::vector> out; + std::string field, why; + std::string prompt = "a cat, , sitting "; + nlohmann::json body = { { "loras", { "style", "ink:0.5", { { "name", "x:y" }, { "weight", 2 } } } } }; + REQUIRE_EQ(server::parse_loras(body, &prompt, &out, &field, &why), RAD_OK); + REQUIRE_EQ(out.size(), (size_t)5); + CHECK_EQ(out[0].first, std::string("style")); + CHECK_EQ(out[0].second, 1.0); + CHECK_EQ(out[1].first, std::string("ink")); + CHECK_EQ(out[1].second, 0.5); + CHECK_EQ(out[2].first, std::string("x:y")); + CHECK_EQ(out[2].second, 2.0); + CHECK_EQ(out[3].first, std::string("pixel art")); + CHECK_NEAR(out[3].second, 0.7, 1e-12); + CHECK_EQ(out[4].first, std::string("detail")); + CHECK_EQ(prompt, std::string("a cat, sitting")); + body = { { "lora", { { "a", 0.25 }, { "b", 1 } } } }; + prompt = "p"; + REQUIRE_EQ(server::parse_loras(body, &prompt, &out, &field, &why), RAD_OK); + CHECK_EQ(out.size(), (size_t)2); + body = { { "loras", { 3 } } }; + CHECK_EQ(server::parse_loras(body, &prompt, &out, &field, &why), (int)RAD_E_INVAL); + CHECK_EQ(field, std::string("loras")); +} + +RAD_TEST_MAIN() diff --git a/tests/gen_test.cpp b/tests/gen_test.cpp index 8a2ea500..c31d5549 100644 --- a/tests/gen_test.cpp +++ b/tests/gen_test.cpp @@ -88,6 +88,29 @@ TEST(the_schedule_is_diffusers_flow_match_euler) { CHECK_EQ(gen::schedule(d, {}, 0, 64).size(), (size_t)d.default_steps + 1); } +/* A schedule off a table of timesteps is ComfyUI's `simple` scheduler over its discrete flow + * sampling (1000 timesteps, shift 3, multiplier 1): the sigmas below are what ComfyUI hands its + * sampler, as f32. */ +TEST(a_sigma_grid_is_comfyui_simple_schedule) { + RadGeneratorDecl d = decl_base(); + d.dyn_shift = 0; d.shift_terminal = 0; d.shift = 3.0; + d.sigma_grid = 1000; + const double want30[] = { 1, 0.988752544, 0.976987481, 0.964285672, 0.951353252, 0.937781036, + 0.923076987, 0.908050597, 0.892220497, 0.87499994, 0.857326388, + 0.838624299, 0.818181813, 0.797094703, 0.774661541, 0.75, + 0.724405408, 0.697002113, 0.666666687, 0.634948134, 0.600719392, + 0.5625, 0.522164285, 0.478201658, 0.428571463, 0.375562221, + 0.317034721, 0.25, 0.177248672, 0.095505625, 0 }; + const std::vector s = gen::schedule(d, {}, 30, 4096); + REQUIRE_EQ(s.size(), (size_t)31); + for (size_t i = 0; i < s.size(); ++i) CHECK_NEAR(s[i], want30[i], 1e-8); + const double want7[] = { 1, 0.94771713, 0.882716119, 0.800373137, 0.69268024, 0.54580152, + 0.333592534, 0 }; + const std::vector s7 = gen::schedule(d, {}, 7, 1024); + REQUIRE_EQ(s7.size(), (size_t)8); + for (size_t i = 0; i < s7.size(); ++i) CHECK_NEAR(s7[i], want7[i], 1e-8); +} + /* A fixed schedule is taken as declared (with shift 1), then closed with 0. */ TEST(a_fixed_schedule_is_used_as_declared) { RadGeneratorDecl d = decl_base(); @@ -96,6 +119,146 @@ TEST(a_fixed_schedule_is_used_as_declared) { CHECK_EQ(s[0], 0.9f); CHECK_EQ(s[1], 0.5f); CHECK_EQ(s[2], 0.125f); CHECK_EQ(s[3], 0.0f); } +/* ================================================================== a discrete-time schedule */ +/* Stable Diffusion XL's: 1000 timesteps, scaled-linear betas 0.00085..0.012. */ +RadGeneratorDecl decl_discrete() { + RadGeneratorDecl d = decl_base(); + d.train_steps = 1000; + d.beta_schedule = RAD_GEN_BETAS_SCALED_LINEAR; + d.beta_start = 0.00085; + d.beta_end = 0.012; + d.samplers = (1u << RAD_GEN_SAMPLER_COUNT) - 1; + d.default_steps = 5; + return d; +} + +/* Each scheduler places five sigmas as ComfyUI's ModelSamplingDiscrete does (reference values + * from its schedulers over the same table), and each sigma is conditioned at the timestep + * ComfyUI picks for it. The table's ends are SDXL's sigma_min and sigma_max. */ +TEST(a_discrete_schedule_is_comfyuis) { + const RadGeneratorDecl d = decl_discrete(); + gen::DiscreteTable t; + std::string why; + REQUIRE_EQ(gen::discrete_table(d, &t, &why), (int)RAD_OK); + CHECK_NEAR(t.sigma_min(), 0.0291671585, 1e-8); + CHECK_NEAR(t.sigma_max(), 14.6146412, 2e-5); + struct Want { int32_t sched; double s[5]; int32_t ts[5]; }; + const Want want[] = { + { RAD_GEN_SCHED_NORMAL, { 14.6146402, 4.08608103, 1.61558032, 0.695149541, 0.0291671604 }, + { 999, 749, 500, 250, 0 } }, + { RAD_GEN_SCHED_KARRAS, { 14.6146431, 4.79653454, 1.27410078, 0.247949973, 0.0291671772 }, + { 999, 786, 427, 59, 0 } }, + { RAD_GEN_SCHED_EXPONENTIAL, + { 14.6146402, 3.08897638, 0.652891755, 0.137996376, 0.0291671604 }, + { 999, 681, 233, 20, 0 } }, + { RAD_GEN_SCHED_SGM_UNIFORM, + { 14.6146402, 5.09240818, 2.27973056, 1.16286457, 0.571188867 }, + { 999, 799, 599, 400, 200 } }, + { RAD_GEN_SCHED_SIMPLE, { 14.6146412, 5.08776331, 2.27646303, 1.16057837, 0.569284916 }, + { 999, 799, 599, 399, 199 } }, + }; + for (const Want& w : want) { + const std::vector s = gen::schedule_discrete(d, t, w.sched, 0); + REQUIRE_EQ(s.size(), (size_t)6); + for (int i = 0; i < 5; ++i) { + CHECK_NEAR(s[(size_t)i], w.s[i], 2e-6 * w.s[i] + 1e-7); + CHECK_EQ(t.timestep(s[(size_t)i]), w.ts[i]); + } + CHECK_EQ(s[5], 0.0f); + CHECK_EQ(std::string(gen::scheduler_name(w.sched)).empty(), false); + CHECK_EQ(gen::scheduler_id(gen::scheduler_name(w.sched)), w.sched); + } + /* Zero terminal SNR keeps the smallest sigma and makes the largest ComfyUI's 4518.76. */ + RadGeneratorDecl z = d; + z.zero_snr = 1; + gen::DiscreteTable tz; + REQUIRE_EQ(gen::discrete_table(z, &tz, &why), (int)RAD_OK); + CHECK_NEAR(tz.sigma_min(), 0.0291671585, 1e-8); + CHECK_NEAR(tz.sigma_max(), 4518.76367, 0.01); + CHECK_EQ(gen::sampler_id("dpmpp_2m"), (int32_t)RAD_GEN_SAMPLER_DPMPP_2M); + CHECK_EQ(gen::sampler_id("ddim"), (int32_t)-1); +} + +/* A discrete-time model's step carries, per entry, its sigmas (the one before included), the + * timestep, the request's sampler, the step, the image's size, and on the host the entry's + * conditioning rows, size and branch; the conditioning pass carries its tokens on the host. */ +TEST(a_discrete_step_carries_its_sampler_and_each_entrys_geometry) { + Program prog; + prog.generator = decl_discrete(); + RadGeneratorDecl& d = prog.generator; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.latent_scale = 8; + d.cond_rows = 2 * 77; + d.rope_hw_scale = 1.0; + d.chunk_tokens = 75; + d.chunk_bos = 49406; + d.chunk_eos = 49407; + d.pad_token = 49407; + prog.ctx.max_tok = 4096; + prog.ctx.max_seqs = 8; + prog.kv_groups.emplace_back(); + gen::Driver drv; + REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK); + auto r = std::make_unique(); + r->width = 64; + r->height = 32; + r->steps = 3; + r->sampler = RAD_GEN_SAMPLER_DPMPP_2M; + r->scheduler = RAD_GEN_SCHED_KARRAS; + r->pos.tokens.assign(77, 5); + r->has_neg = true; + r->neg.tokens.assign(77, 6); + r->cfg = 6.0f; + r->ticket = std::make_shared(); + std::string why; + REQUIRE_EQ(drv.submit(std::move(r), &why), (int)RAD_OK); + const RadBatch* b = drv.next(0); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND); + REQUIRE(b->gen_b->tokens_h != nullptr); + CHECK_EQ(b->gen_b->tokens_h[76], (int32_t)5); + CHECK_OK(drv.done()); + REQUIRE(drv.next(1) != nullptr); + CHECK_OK(drv.done()); + gen::DiscreteTable t; + REQUIRE_EQ(gen::discrete_table(d, &t, &why), (int)RAD_OK); + const std::vector s = gen::schedule_discrete(d, t, RAD_GEN_SCHED_KARRAS, 3); + for (int step = 0; step < 3; ++step) { + b = drv.next(2 + step); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE); + const RadGenBatch* G = b->gen_b; + REQUIRE_EQ(b->n_seq, (int64_t)2); + CHECK_EQ(b->n_tok, (int64_t)(2 * (77 + 32))); + for (int e = 0; e < 2; ++e) { + CHECK_EQ(G->sigma[e], s[(size_t)step]); + CHECK_EQ(G->sigma_next[e], s[(size_t)step + 1]); + CHECK_EQ(G->sigma_prev[e], step ? s[(size_t)step - 1] : 0.0f); + CHECK_EQ(G->timestep[e], (float)t.timestep(s[(size_t)step])); + CHECK_EQ(G->sampler[e], (int32_t)RAD_GEN_SAMPLER_DPMPP_2M); + CHECK_EQ(G->step[e], (int32_t)step); + CHECK_EQ(G->size_px[2 * e], 32.0f); + CHECK_EQ(G->size_px[2 * e + 1], 64.0f); + CHECK_EQ(G->entry_h[4 * e], (int32_t)77); + CHECK_EQ(G->entry_h[4 * e + 1], (int32_t)32); + CHECK_EQ(G->entry_h[4 * e + 2], (int32_t)64); + CHECK_EQ(G->entry_h[4 * e + 3], (int32_t)e); + } + CHECK_OK(drv.done()); + } + /* A sampler the model does not serve is refused at submit. */ + d.samplers = 1u << RAD_GEN_SAMPLER_EULER; + gen::Driver drv2; + REQUIRE_EQ(drv2.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK); + auto r2 = std::make_unique(); + r2->width = 64; + r2->height = 32; + r2->sampler = RAD_GEN_SAMPLER_EULER_ANCESTRAL; + r2->pos.tokens.assign(77, 5); + r2->ticket = std::make_shared(); + CHECK_EQ(drv2.submit(std::move(r2), &why), (int)RAD_E_INVAL); +} + /* ================================================================== the sequence */ /* An h x w image at frame `pos`: every row at that frame, height and width centred on zero. */ TEST(image_rotary_positions_centre_the_grid_on_its_frame) { @@ -422,4 +585,65 @@ TEST(the_joint_layout_carries_the_conditioning_in_every_step) { CHECK_OK(drv.done()); } +/* A generator that reads its prompt through a second tokenizer (RadGeneratorDecl::aux_tokens): + * each branch's COND pass carries that branch's ids and {0, n} on the device, and no other pass + * does; a branch with none, or more than declared, is refused at submission. */ +TEST(a_second_tokenizers_ids_ride_in_each_conditioning) { + Program prog; + prog.generator = decl_base(); + RadGeneratorDecl& d = prog.generator; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.cond_rows = 16; + d.pad_multiple = 16; + d.pad_token = 99; + d.aux_tokens = 1; + d.aux_max_tokens = 6; + prog.ctx.max_tok = 2048; + prog.ctx.max_seqs = 8; + prog.kv_groups.emplace_back(); + gen::Driver drv; + REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK); + auto mk = [](std::vector aux, std::vector neg_aux) { + auto r = std::make_unique(); + r->width = 64; + r->height = 64; + r->pos.tokens = { 1, 2, 3 }; + r->pos.aux = std::move(aux); + r->has_neg = true; + r->neg.tokens = { 5 }; + r->neg.aux = std::move(neg_aux); + r->cfg = 4.0f; + r->ticket = std::make_shared(); + return r; + }; + std::string why; + CHECK_EQ(drv.submit(mk({ 7, 8 }, {}), &why), (int)RAD_E_INVAL); + CHECK(has(why, "second tokenizer")); + CHECK_EQ(drv.submit(mk({ 1, 2, 3, 4, 5, 6, 7 }, { 1 }), &why), (int)RAD_E_INVAL); + REQUIRE_EQ(drv.submit(mk({ 7, 8, 1 }, { 1 }), &why), (int)RAD_OK); + + const RadBatch* b = drv.next(0); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND); + const RadGenBatch* G = b->gen_b; + REQUIRE_EQ(G->n_aux, (int64_t)3); + CHECK_EQ(G->aux_ids[0], (int32_t)7); + CHECK_EQ(G->aux_ids[2], (int32_t)1); + CHECK_EQ(G->aux_cu[0], (int32_t)0); + CHECK_EQ(G->aux_cu[1], (int32_t)3); + CHECK_OK(drv.done()); + b = drv.next(1); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen_b->n_aux, (int64_t)1); + CHECK_EQ(b->gen_b->aux_ids[0], (int32_t)1); + CHECK_EQ(b->gen_b->aux_cu[1], (int32_t)1); + CHECK_OK(drv.done()); + b = drv.next(2); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE); + CHECK_EQ(b->gen_b->n_aux, (int64_t)0); + CHECK(b->gen_b->aux_ids == nullptr); + CHECK_OK(drv.done()); +} + RAD_TEST_MAIN() diff --git a/tests/images_test.cpp b/tests/images_test.cpp index 2cc5b814..b7ad1fd6 100644 --- a/tests/images_test.cpp +++ b/tests/images_test.cpp @@ -169,6 +169,78 @@ TEST(usage_counts_each_pictures_tokens_in_every_branch) { CHECK(s.last().has_neg); } +/* A model that reads its prompt through a second tokenizer gets the user's prompt as that tokenizer + * encodes it, in each branch, and a prompt longer than it reads is refused under `prompt`. A + * prompt shorter than the model's minimum after the fixed prefix is padded with its padding token + * (an empty prompt is one, and is not turned into " " first). */ +TEST(a_second_tokenizer_and_a_minimum_prompt_reach_the_generator) { + Images s; + s.img.inf.aux_tokens = true; + s.img.inf.aux_max_tokens = 4; + s.img.inf.min_tokens = 2; + s.img.inf.pad_token = 9; + s.gen({ { "prompt", "ab" }, { "negative_prompt", "c" }, { "true_cfg_scale", 4.0 } }); + REQUIRE(!s.img.got.empty()); + CHECK(s.last().pos.aux == std::vector({ 100 + 'a', 100 + 'b', 1 })); + CHECK(s.last().neg.aux == std::vector({ 100 + 'c', 1 })); + /* "c" is one token after the prefix, padded to two. */ + const gen::Branch& n = s.last().neg; + REQUIRE((int64_t)n.tokens.size() - n.n_drop == 2); + CHECK_EQ(n.tokens[(size_t)n.n_drop], (int32_t)'c'); + CHECK_EQ(n.tokens.back(), (int32_t)9); + s.gen({ { "prompt", "" } }); + const gen::Branch& p = s.last().pos; + REQUIRE((int64_t)p.tokens.size() - p.n_drop == 2); + CHECK_EQ(p.tokens[(size_t)p.n_drop], (int32_t)9); + CHECK(p.aux == std::vector({ 1 })); + /* An empty negative prompt stays empty for such a model: all padding. */ + s.gen({ { "prompt", "x" }, { "negative_prompt", "" }, { "true_cfg_scale", 4.0 } }); + const gen::Branch& e = s.last().neg; + REQUIRE((int64_t)e.tokens.size() - e.n_drop == 2); + CHECK_EQ(e.tokens[(size_t)e.n_drop], (int32_t)9); + CHECK(e.aux == std::vector({ 1 })); + const json longp = s.gen({ { "prompt", "abcd" } }, 400); + CHECK_EQ(str_at(longp["error"], "param"), std::string("prompt")); +} + +/* A discrete-time model takes `sampler` and `scheduler` by ComfyUI's names, defaulting to its + * own, and refuses one it does not serve; a flow-matching model refuses both. A prompt read in + * windows reaches the generator cut into runs between their markers, each padded to the window, + * after the template's fixed prefix, and a prompt that fills its last window exactly takes no + * empty one after it. */ +TEST(a_discrete_model_takes_its_sampler_and_reads_the_prompt_in_windows) { + Images s; + const json flow = s.gen({ { "prompt", "x" }, { "sampler", "euler" } }, 400); + CHECK_EQ(str_at(flow["error"], "param"), std::string("sampler")); + s.img.inf.samplers = (1u << RAD_GEN_SAMPLER_EULER) | (1u << RAD_GEN_SAMPLER_DPMPP_2M); + s.img.inf.default_sampler = RAD_GEN_SAMPLER_EULER; + s.img.inf.default_scheduler = RAD_GEN_SCHED_NORMAL; + s.img.inf.chunk_tokens = 4; + s.img.inf.chunk_bos = 2; + s.img.inf.chunk_eos = 3; + s.img.inf.chunk_pad = 9; + s.gen({ { "prompt", "abcdefghij" } }); + REQUIRE(!s.img.got.empty()); + CHECK_EQ(s.last().sampler, (int32_t)RAD_GEN_SAMPLER_EULER); + CHECK_EQ(s.last().scheduler, (int32_t)RAD_GEN_SCHED_NORMAL); + const std::vector want = { '<', 's', '>', 2, 'a', 'b', 'c', 'd', 3, + 2, 'e', 'f', 'g', 'h', 3, 2, 'i', 'j', 3, 9, 9 }; + CHECK(s.last().pos.tokens == want); + CHECK_EQ(s.last().pos.n_drop, (int32_t)3); + s.gen({ { "prompt", "x" }, { "sampler", "dpmpp_2m" }, { "scheduler", "karras" } }); + CHECK_EQ(s.last().sampler, (int32_t)RAD_GEN_SAMPLER_DPMPP_2M); + CHECK_EQ(s.last().scheduler, (int32_t)RAD_GEN_SCHED_KARRAS); + /* A prompt that fills a window takes no second one. */ + s.gen({ { "prompt", "abcd" } }); + const std::vector one = { '<', 's', '>', 2, 'a', 'b', 'c', 'd', 3 }; + CHECK(s.last().pos.tokens == one); + const json bad = s.gen({ { "prompt", "x" }, { "sampler", "euler_ancestral" } }, 400); + CHECK_EQ(str_at(bad["error"], "param"), std::string("sampler")); + CHECK(bad["error"]["supported"] == json::array({ "euler", "dpmpp_2m" })); + const json badk = s.gen({ { "prompt", "x" }, { "scheduler", "ddim_uniform" } }, 400); + CHECK_EQ(str_at(badk["error"], "param"), std::string("scheduler")); +} + /* `background: auto` keeps an edited picture's transparency and is opaque otherwise; a mask must * be the first picture's size. */ /* A model whose card states guidance as cond + s (cond - uncond) and guides by default (Krea 2): diff --git a/tests/lora_test.cpp b/tests/lora_test.cpp index c214b381..59584686 100644 --- a/tests/lora_test.cpp +++ b/tests/lora_test.cpp @@ -1032,8 +1032,9 @@ TEST(a_transformed_or_rotated_weight_is_not_a_site) { CHECK(has(lora::explain_module(b.program(), t, "model.layers.0.self_attn.q_proj"), "perm")); } -/* Adapters serve the token steps of a model that writes logits: declare refuses a generator, an - * embedding model and a program with no logits by name, and lets a text model through. */ +/* Adapters serve the token steps of a model that writes logits, or a generator that names its + * adapter keys: declare refuses a generator that names none, an embedding model and a program with + * no logits by name, and lets a text model through. */ TEST(declare_refuses_a_model_that_does_not_generate_text) { const RadModelMeta meta = llama_meta(); const RadBuildCtx ctx = ctx_for(0, 1); @@ -1044,7 +1045,7 @@ TEST(declare_refuses_a_model_that_does_not_generate_text) { d.cfg = &cfg; d.targets = { "q_proj" }; const struct { const char* what; void (*set)(Program&); } kinds[] = { - { "is an image, audio or video generator", + { "declares no adapter key names", [](Program& p) { p.logits_buf = 1; p.generator.layout = 1; } }, { "makes embeddings", [](Program& p) { p.pooled_buf = 1; } }, { "declares no logits", [](Program&) {} }, diff --git a/tests/mk_precompiled_goldens.py b/tests/mk_precompiled_goldens.py new file mode 100644 index 00000000..6b1412fa --- /dev/null +++ b/tests/mk_precompiled_goldens.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Writes tests/precompiled_golden.h: expected outputs for precompiled_test.cpp. + + - Unicode 16.0.0's GraphemeBreakTest.txt cases, each a codepoint sequence and the boundaries + UAX #29 puts in it (core/text/tokenizer_grapheme.h's grapheme_end); + - a small SentencePiece character map and what HuggingFace `tokenizers`' Precompiled normaliser + makes of a set of strings through it, clusters that map whole and clusters that do not among + them (PrecompiledMap::normalize). + +The map below was built with sentencepiece 0.2 from the rules + A -> a, U+FF21 -> A, U+FF41 -> a, e U+0301 -> U+00E9, LF -> space, U+2160 -> I +and is kept as base64 so regenerating needs only `tokenizers` (0.23.3 produced the current file): + + python3 tests/mk_precompiled_goldens.py GraphemeBreakTest.txt > tests/precompiled_golden.h +""" +import base64 +import sys + +import tokenizers +from tokenizers import normalizers + +CHARSMAP = ( + "AAQAAAAsAAAKDQAAAAAAgAYAAIDMAAIAgQ0AAAgAAICFvAIAoAUAAAQAAIC8nAIAvRACAKEFAAACAACAgTUAAA4AAAARAA" + "AAEAAAABMAAAASAAAAFQAAABQAAAAXAAAAFgAAABkAAAAYAAAAGwAAABoAAAAdAAAAHAAAAB8AAAAeAAAAIQAAACAAAAAj" + "AAAAIgAAACUAAAAkAAAAJwAAACYAAAApAAAAKAAAACsAAAAqAAAALQAAACwAAAAvAAAALgAAADEAAAAwAAAAMwAAADIAAA" + "A1AAAANAAAADcAAAA2AAAAOQAAADgAAAA7AAAAOgAAAD0AAAA8AAAAPwAAAD4AAABBAAAAQAAAAEMAAABCAAAARQAAAEQA" + "AABHAAAARgAAAEkAAABIAAAAQSUBAEoAAABNAAAATAAAAE8AAABOAAAAUQAAAFAAAABTAAAAUgAAAFUAAABUAAAAVwAAAF" + "YAAABZAAAAWAAAAFsAAABaAAAAXQAAAFwAAABfAAAAXgAAAGEAAABgAAAAYwAAAGIAAABlAAAAZAAAAGcAAABmAAAAaQAA" + "AGgAAABrAAAAagAAAG0AAABsAAAAZZgCAG4AAABxAAAAcAAAAHMAAAByAAAAdQAAAHQAAAB3AAAAdgAAAHkAAAB4AAAAew" + "AAAHoAAAB9AAAAfAAAAH8AAAB+AAAAgQAAAIAAAACDAAAAggAAAIUAAACEAAAAhwAAAIYAAACJAAAAiAAAAIsAAACKAAAA" + "jQAAAIwAAACPAAAAjgAAAJEAAACQAAAAkwAAAJIAAACVAAAAlAAAAJcAAACWAAAAmQAAAJgAAACbAAAAmgAAAJ0AAACcAA" + "AAnwAAAJ4AAAChAAAAoAAAAKMAAACiAAAApQAAAKQAAACnAAAApgAAAKkAAACoAAAAqwAAAKoAAACtAAAArAAAAK8AAACu" + "AAAAsQAAALAAAACzAAAAsgAAALUAAAC0AAAAtwAAALYAAAC5AAAAuAAAALsAAAC6AAAAvQAAALwAAAC/AAAAvgAAAMEAAA" + "DAAAAAwwAAAMIAAADFAAAAxAAAAMcAAADGAAAAyQAAAMgAAADLAAAAygAAAM0AAADMAAAAzwAAAM4AAADRAAAA0AAAANMA" + "AADSAAAA1QAAANQAAADXAAAA1gAAANkAAADYAAAA2wAAANoAAADdAAAA3AAAAN8AAADeAAAA4QAAAOAAAADjAAAA4gAAAO" + "9IAQDkAAAA5wAAAOYAAADpAAAA4qwBAOsAAADqAAAA7QAAAOwAAADvAAAA7gAAAPEAAADwAAAA8wAAAPIAAAD1AAAA9AAA" + "APcAAAD2AAAA+QAAAPgAAAD7AAAA+gAAAP0AAAD8AAAA/wAAAP4AAAAgAEEASQBhAMOpAA==" +) + +INPUTS = [ + "", "plain ascii", "A big Apple", "Abc a", "line one\nline two\n", + "café", "éé", "Áx", "Á", "Ⅰ Ⅰ́", + "é vs é", "1️⃣ keycap", "\U0001F469‍\U0001F4BB", + "\U0001F1EF\U0001F1F5\U0001F1FA", "각 jamo", "\r\nCRLF\r\n", + "क्ष conjunct", "a‍‍b", "tab\there", "กำ thai", + "ẍ̈̈̈", "Ä̈", +] + + +def cstr(s): + out = '"' + prev_hex = False + for b in s.encode("utf-8"): + c = chr(b) + if c == '"': + out += '\\"'; prev_hex = False + elif c == "\\": + out += "\\\\"; prev_hex = False + elif 0x20 <= b < 0x7F: + if prev_hex and c in "0123456789abcdefABCDEF": + out += '" "' + out += c; prev_hex = False + else: + out += "\\x%02x" % b; prev_hex = True + return out + '"' + + +def grapheme_cases(path): + """(codepoints, bitmask of the positions a cluster starts at, beyond the first).""" + cases = [] + for line in open(path, encoding="utf-8"): + line = line.split("#", 1)[0].strip() + if not line: + continue + toks = line.split() + cps, mask = [], 0 + for t in toks[1:-1]: + if t in ("÷", "×"): + if t == "÷": + mask |= 1 << len(cps) + continue + cps.append(int(t, 16)) + cases.append((cps, mask)) + return cases + + +def main(): + pc = normalizers.Precompiled(base64.b64decode(CHARSMAP)) + w = sys.stdout.write + w("/* precompiled_golden.h -- GENERATED by mk_precompiled_goldens.py from tokenizers %s and " + "the\n * Unicode 16.0.0 GraphemeBreakTest.txt; do not edit. */\n" % tokenizers.__version__) + w("#pragma once\n#include \n\n") + w("static const char* kPcCharsmap =\n") + for i in range(0, len(CHARSMAP), 96): + w(" \"%s\"\n" % CHARSMAP[i:i + 96]) + w(" ;\n\n") + w("struct PcCase { const char* in; const char* out; };\n") + w("static const PcCase kPcCases[] = {\n") + for s in INPUTS: + w(" { %s, %s },\n" % (cstr(s), cstr(pc.normalize_str(s)))) + w("};\n\n") + cases = grapheme_cases(sys.argv[1]) + w("/* A cluster starts at codepoint i (i > 0) where bit i of `starts` is set. */\n") + w("struct GbCase { uint32_t cp[8]; uint32_t n; uint32_t starts; };\n") + w("static const GbCase kGbCases[] = {\n") + for cps, mask in cases: + if len(cps) > 8: + continue + w(" { { %s }, %d, 0x%x },\n" % (", ".join("0x%X" % c for c in cps), len(cps), + mask & ~1)) + w("};\n") + + +if __name__ == "__main__": + main() diff --git a/tests/mk_tokenizer_goldens.py b/tests/mk_tokenizer_goldens.py index b8f8a7d5..4305d51e 100644 --- a/tests/mk_tokenizer_goldens.py +++ b/tests/mk_tokenizer_goldens.py @@ -246,6 +246,104 @@ def metaspace_specials(scheme): "vocab": vocab, "merges": [[MS, "H"], ["H", "i"], [MS + "H", "i"]]}} +# ---------------------------------------------------------------------------- CLIP-shaped + +CLIP_SPLIT = r"""'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""" + + +def gpt2_alphabet(): + """GPT-2's byte -> character map, in CLIP's vocabulary order.""" + bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("\xa1"), ord("\xac") + 1)) + \ + list(range(ord("\xae"), ord("\xff") + 1)) + cs = bs[:] + n = 0 + for b in range(256): + if b not in bs: + bs.append(b) + cs.append(256 + n) + n += 1 + return [chr(c) for c in cs] + + +CLIP_TRAIN = ("a photo of a cat, a painting of a dog, best quality, masterpiece, 1girl, solo, " + "looking at viewer, it's a photograph of the mountains at sunset, don't stop, " + "highly detailed digital art, portrait of an astronaut riding a horse, ") * 3 + + +def clip_like(): + """CLIP ViT-L/14's tokenizer.json with its vocabulary cut down: the real normaliser, Split, + ByteLevel, RobertaProcessing and decoder, the 512 byte tokens with and without the "" + end-of-word suffix in CLIP's order, and merges trained here (most frequent pair, then the + smallest) over a few prompts, each merged token's id 512 + its rank as in CLIP's own file.""" + from tokenizers import normalizers, pre_tokenizers, Regex + norm = normalizers.Sequence([normalizers.NFC(), normalizers.Replace(Regex(r"\s+"), " "), + normalizers.Lowercase()]) + pre = pre_tokenizers.Sequence([ + pre_tokenizers.Split(Regex(CLIP_SPLIT), behavior="removed", invert=True), + pre_tokenizers.ByteLevel(add_prefix_space=False)]) + alpha = gpt2_alphabet() + vocab = alpha + [c + "" for c in alpha] + words = {} + for w, _ in pre.pre_tokenize_str(norm.normalize_str(CLIP_TRAIN)): + sym = tuple(list(w[:-1]) + [w[-1] + ""]) + words[sym] = words.get(sym, 0) + 1 + merges = [] + for _ in range(160): + pairs = {} + for sym, n in words.items(): + for a, b in zip(sym, sym[1:]): + pairs[(a, b)] = pairs.get((a, b), 0) + n + if not pairs: + break + best = min(pairs, key=lambda k: (-pairs[k], k)) + merges.append(best) + vocab.append(best[0] + best[1]) + nw = {} + for sym, n in words.items(): + out, i = [], 0 + while i < len(sym): + if i + 1 < len(sym) and (sym[i], sym[i + 1]) == best: + out.append(sym[i] + sym[i + 1]) + i += 2 + else: + out.append(sym[i]) + i += 1 + nw[tuple(out)] = nw.get(tuple(out), 0) + n + words = nw + bos, eos = len(vocab), len(vocab) + 1 + vocab += ["<|startoftext|>", "<|endoftext|>"] + return { + "added_tokens": [ + {"id": bos, "content": "<|startoftext|>", "single_word": False, "lstrip": False, + "rstrip": False, "normalized": True, "special": True}, + {"id": eos, "content": "<|endoftext|>", "single_word": False, "lstrip": False, + "rstrip": False, "normalized": False, "special": True}], + "normalizer": {"type": "Sequence", "normalizers": [ + {"type": "NFC"}, {"type": "Replace", "pattern": {"Regex": r"\s+"}, "content": " "}, + {"type": "Lowercase"}]}, + "pre_tokenizer": {"type": "Sequence", "pretokenizers": [ + {"type": "Split", "pattern": {"Regex": CLIP_SPLIT}, "behavior": "Removed", + "invert": True}, + {"type": "ByteLevel", "add_prefix_space": False, "trim_offsets": True}]}, + "post_processor": {"type": "RobertaProcessing", "sep": ["<|endoftext|>", eos], + "cls": ["<|startoftext|>", bos], "trim_offsets": False, + "add_prefix_space": False}, + "decoder": {"type": "ByteLevel", "add_prefix_space": True, "trim_offsets": True}, + "model": {"type": "BPE", "dropout": None, "unk_token": "<|endoftext|>", + "continuing_subword_prefix": "", "end_of_word_suffix": "", + "fuse_unk": False, "vocab": {t: i for i, t in enumerate(vocab)}, + "merges": [a + " " + b for a, b in merges]}, + } + + +CLIP_TEXTS = ["a photo of a cat", "1girl, solo, masterpiece, best quality, (absurdres:1.2), " + "looking_at_viewer, hatsune_miku", "A Photograph of the Mountains, it's DON'T stop", + "1024x1024 2.5 v1.0", "Café naïve 東京タワー 서울 🍣👩‍👩‍👧 İstanbul ΣΊΣΥΦΟΣ", + " many spaces\t\ttabs\n\nnewlines ", "...!!!??? ((()))[[]]", "", "a", + "<|startoftext|>a cat<|endoftext|>", "x<|StartOfText|>y", "ab catcat", + "photographphotograph", "it'sit's'll"] + + SPECIAL_TEXTS = ["Hi", "[INST]Hi", "[INST] Hi", "Hi[INST]Hi", "Hi", "Hi Hi[INST]Hi"] GEMMA_TEXTS = ["hello", " hello", "hello world", "hello world", "the cat", "\nthe\n\ncat", @@ -341,6 +439,30 @@ def main(): print(" return v;") print("}") print() + c = clip_like() + tok = Tokenizer.from_str(json.dumps(c)) + print("const char* const kClipLike = R\"JSON(%s)JSON\";" % json.dumps(c, ensure_ascii=False)) + print() + print("const std::vector& clip_goldens() {") + print(" static const std::vector v = {") + for t in CLIP_TEXTS: + a = tok.encode(t, add_special_tokens=False).ids + b = tok.encode(t, add_special_tokens=True).ids + print(" { %s, %s, %s }," % (cstr(t), ids_cpp(a), ids_cpp(b))) + print(" };") + print(" return v;") + print("}") + print() + print("/* The decode of every CLIP golden with special tokens skipped, as HF reports it. */") + print("const std::vector& clip_decoded() {") + print(" static const std::vector v = {") + for t in CLIP_TEXTS: + print(" %s," % cstr(tok.decode(tok.encode(t, add_special_tokens=True).ids, + skip_special_tokens=True))) + print(" };") + print(" return v;") + print("}") + print() print("/* END generated by mk_tokenizer_goldens.py */") diff --git a/tests/precompiled_golden.h b/tests/precompiled_golden.h new file mode 100644 index 00000000..3acddb40 --- /dev/null +++ b/tests/precompiled_golden.h @@ -0,0 +1,1146 @@ +/* precompiled_golden.h -- GENERATED by mk_precompiled_goldens.py from tokenizers 0.23.3 and the + * Unicode 16.0.0 GraphemeBreakTest.txt; do not edit. */ +#pragma once +#include + +static const char* kPcCharsmap = + "AAQAAAAsAAAKDQAAAAAAgAYAAIDMAAIAgQ0AAAgAAICFvAIAoAUAAAQAAIC8nAIAvRACAKEFAAACAACAgTUAAA4AAAARAAAA" + "EAAAABMAAAASAAAAFQAAABQAAAAXAAAAFgAAABkAAAAYAAAAGwAAABoAAAAdAAAAHAAAAB8AAAAeAAAAIQAAACAAAAAjAAAA" + "IgAAACUAAAAkAAAAJwAAACYAAAApAAAAKAAAACsAAAAqAAAALQAAACwAAAAvAAAALgAAADEAAAAwAAAAMwAAADIAAAA1AAAA" + "NAAAADcAAAA2AAAAOQAAADgAAAA7AAAAOgAAAD0AAAA8AAAAPwAAAD4AAABBAAAAQAAAAEMAAABCAAAARQAAAEQAAABHAAAA" + "RgAAAEkAAABIAAAAQSUBAEoAAABNAAAATAAAAE8AAABOAAAAUQAAAFAAAABTAAAAUgAAAFUAAABUAAAAVwAAAFYAAABZAAAA" + "WAAAAFsAAABaAAAAXQAAAFwAAABfAAAAXgAAAGEAAABgAAAAYwAAAGIAAABlAAAAZAAAAGcAAABmAAAAaQAAAGgAAABrAAAA" + "agAAAG0AAABsAAAAZZgCAG4AAABxAAAAcAAAAHMAAAByAAAAdQAAAHQAAAB3AAAAdgAAAHkAAAB4AAAAewAAAHoAAAB9AAAA" + "fAAAAH8AAAB+AAAAgQAAAIAAAACDAAAAggAAAIUAAACEAAAAhwAAAIYAAACJAAAAiAAAAIsAAACKAAAAjQAAAIwAAACPAAAA" + "jgAAAJEAAACQAAAAkwAAAJIAAACVAAAAlAAAAJcAAACWAAAAmQAAAJgAAACbAAAAmgAAAJ0AAACcAAAAnwAAAJ4AAAChAAAA" + "oAAAAKMAAACiAAAApQAAAKQAAACnAAAApgAAAKkAAACoAAAAqwAAAKoAAACtAAAArAAAAK8AAACuAAAAsQAAALAAAACzAAAA" + "sgAAALUAAAC0AAAAtwAAALYAAAC5AAAAuAAAALsAAAC6AAAAvQAAALwAAAC/AAAAvgAAAMEAAADAAAAAwwAAAMIAAADFAAAA" + "xAAAAMcAAADGAAAAyQAAAMgAAADLAAAAygAAAM0AAADMAAAAzwAAAM4AAADRAAAA0AAAANMAAADSAAAA1QAAANQAAADXAAAA" + "1gAAANkAAADYAAAA2wAAANoAAADdAAAA3AAAAN8AAADeAAAA4QAAAOAAAADjAAAA4gAAAO9IAQDkAAAA5wAAAOYAAADpAAAA" + "4qwBAOsAAADqAAAA7QAAAOwAAADvAAAA7gAAAPEAAADwAAAA8wAAAPIAAAD1AAAA9AAAAPcAAAD2AAAA+QAAAPgAAAD7AAAA" + "+gAAAP0AAAD8AAAA/wAAAP4AAAAgAEEASQBhAMOpAA==" + ; + +struct PcCase { const char* in; const char* out; }; +static const PcCase kPcCases[] = { + { "", "" }, + { "plain ascii", "plain ascii" }, + { "A big Apple", "a big apple" }, + { "\xef\xbc\xa1\xef\xbd\x82\xef\xbd\x83 \xef\xbd\x81", "A\xef\xbd\x82\xef\xbd\x83 a" }, + { "line one\x0aline two\x0a", "line one line two " }, + { "cafe\xcc\x81", "caf\xc3\xa9" }, + { "e\xcc\x81" "e\xcc\x81", "\xc3\xa9\xc3\xa9" }, + { "\xef\xbc\xa1\xcc\x81x", "Ax" }, + { "A\xcc\x81", "a" }, + { "\xe2\x85\xa0 \xe2\x85\xa0\xcc\x81", "I I" }, + { "\xc3\xa9 vs e\xcc\x81", "\xc3\xa9 vs \xc3\xa9" }, + { "1\xef\xb8\x8f\xe2\x83\xa3 keycap", "1\xef\xb8\x8f\xe2\x83\xa3 keycap" }, + { "\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb", "\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb" }, + { "\xf0\x9f\x87\xaf\xf0\x9f\x87\xb5\xf0\x9f\x87\xba", "\xf0\x9f\x87\xaf\xf0\x9f\x87\xb5\xf0\x9f\x87\xba" }, + { "\xe1\x84\x80\xe1\x85\xa1\xe1\x86\xa8 jamo", "\xe1\x84\x80\xe1\x85\xa1\xe1\x86\xa8 jamo" }, + { "\x0d\x0a" "CRLF\x0d\x0a", "\x0d CRLF\x0d " }, + { "\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7 conjunct", "\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7 conjunct" }, + { "a\xe2\x80\x8d\xe2\x80\x8d" "b", "a\xe2\x80\x8d\xe2\x80\x8d" "b" }, + { "tab\x09here", "tab\x09here" }, + { "\xe0\xb8\x81\xe0\xb8\xb3 thai", "\xe0\xb8\x81\xe0\xb8\xb3 thai" }, + { "x\xcc\x88\xcc\x88\xcc\x88\xcc\x88", "x\xcc\x88\xcc\x88\xcc\x88\xcc\x88" }, + { "\xef\xbc\xa1\xcc\x88\xcc\x88", "A\xcc\x88\xcc\x88" }, +}; + +/* A cluster starts at codepoint i (i > 0) where bit i of `starts` is set. */ +struct GbCase { uint32_t cp[8]; uint32_t n; uint32_t starts; }; +static const GbCase kGbCases[] = { + { { 0x20, 0x20 }, 2, 0x2 }, + { { 0x20, 0x308, 0x20 }, 3, 0x4 }, + { { 0x20, 0xD }, 2, 0x2 }, + { { 0x20, 0x308, 0xD }, 3, 0x4 }, + { { 0x20, 0xA }, 2, 0x2 }, + { { 0x20, 0x308, 0xA }, 3, 0x4 }, + { { 0x20, 0x1 }, 2, 0x2 }, + { { 0x20, 0x308, 0x1 }, 3, 0x4 }, + { { 0x20, 0x200C }, 2, 0x0 }, + { { 0x20, 0x308, 0x200C }, 3, 0x0 }, + { { 0x20, 0x1F1E6 }, 2, 0x2 }, + { { 0x20, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x20, 0x600 }, 2, 0x2 }, + { { 0x20, 0x308, 0x600 }, 3, 0x4 }, + { { 0x20, 0xA03 }, 2, 0x0 }, + { { 0x20, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x20, 0x1100 }, 2, 0x2 }, + { { 0x20, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x20, 0x1160 }, 2, 0x2 }, + { { 0x20, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x20, 0x11A8 }, 2, 0x2 }, + { { 0x20, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x20, 0xAC00 }, 2, 0x2 }, + { { 0x20, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x20, 0xAC01 }, 2, 0x2 }, + { { 0x20, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x20, 0x903 }, 2, 0x0 }, + { { 0x20, 0x308, 0x903 }, 3, 0x0 }, + { { 0x20, 0x904 }, 2, 0x2 }, + { { 0x20, 0x308, 0x904 }, 3, 0x4 }, + { { 0x20, 0xD4E }, 2, 0x2 }, + { { 0x20, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x20, 0x915 }, 2, 0x2 }, + { { 0x20, 0x308, 0x915 }, 3, 0x4 }, + { { 0x20, 0x231A }, 2, 0x2 }, + { { 0x20, 0x308, 0x231A }, 3, 0x4 }, + { { 0x20, 0x300 }, 2, 0x0 }, + { { 0x20, 0x308, 0x300 }, 3, 0x0 }, + { { 0x20, 0x900 }, 2, 0x0 }, + { { 0x20, 0x308, 0x900 }, 3, 0x0 }, + { { 0x20, 0x94D }, 2, 0x0 }, + { { 0x20, 0x308, 0x94D }, 3, 0x0 }, + { { 0x20, 0x200D }, 2, 0x0 }, + { { 0x20, 0x308, 0x200D }, 3, 0x0 }, + { { 0x20, 0x378 }, 2, 0x2 }, + { { 0x20, 0x308, 0x378 }, 3, 0x4 }, + { { 0xD, 0x20 }, 2, 0x2 }, + { { 0xD, 0x308, 0x20 }, 3, 0x6 }, + { { 0xD, 0xD }, 2, 0x2 }, + { { 0xD, 0x308, 0xD }, 3, 0x6 }, + { { 0xD, 0xA }, 2, 0x0 }, + { { 0xD, 0x308, 0xA }, 3, 0x6 }, + { { 0xD, 0x1 }, 2, 0x2 }, + { { 0xD, 0x308, 0x1 }, 3, 0x6 }, + { { 0xD, 0x200C }, 2, 0x2 }, + { { 0xD, 0x308, 0x200C }, 3, 0x2 }, + { { 0xD, 0x1F1E6 }, 2, 0x2 }, + { { 0xD, 0x308, 0x1F1E6 }, 3, 0x6 }, + { { 0xD, 0x600 }, 2, 0x2 }, + { { 0xD, 0x308, 0x600 }, 3, 0x6 }, + { { 0xD, 0xA03 }, 2, 0x2 }, + { { 0xD, 0x308, 0xA03 }, 3, 0x2 }, + { { 0xD, 0x1100 }, 2, 0x2 }, + { { 0xD, 0x308, 0x1100 }, 3, 0x6 }, + { { 0xD, 0x1160 }, 2, 0x2 }, + { { 0xD, 0x308, 0x1160 }, 3, 0x6 }, + { { 0xD, 0x11A8 }, 2, 0x2 }, + { { 0xD, 0x308, 0x11A8 }, 3, 0x6 }, + { { 0xD, 0xAC00 }, 2, 0x2 }, + { { 0xD, 0x308, 0xAC00 }, 3, 0x6 }, + { { 0xD, 0xAC01 }, 2, 0x2 }, + { { 0xD, 0x308, 0xAC01 }, 3, 0x6 }, + { { 0xD, 0x903 }, 2, 0x2 }, + { { 0xD, 0x308, 0x903 }, 3, 0x2 }, + { { 0xD, 0x904 }, 2, 0x2 }, + { { 0xD, 0x308, 0x904 }, 3, 0x6 }, + { { 0xD, 0xD4E }, 2, 0x2 }, + { { 0xD, 0x308, 0xD4E }, 3, 0x6 }, + { { 0xD, 0x915 }, 2, 0x2 }, + { { 0xD, 0x308, 0x915 }, 3, 0x6 }, + { { 0xD, 0x231A }, 2, 0x2 }, + { { 0xD, 0x308, 0x231A }, 3, 0x6 }, + { { 0xD, 0x300 }, 2, 0x2 }, + { { 0xD, 0x308, 0x300 }, 3, 0x2 }, + { { 0xD, 0x900 }, 2, 0x2 }, + { { 0xD, 0x308, 0x900 }, 3, 0x2 }, + { { 0xD, 0x94D }, 2, 0x2 }, + { { 0xD, 0x308, 0x94D }, 3, 0x2 }, + { { 0xD, 0x200D }, 2, 0x2 }, + { { 0xD, 0x308, 0x200D }, 3, 0x2 }, + { { 0xD, 0x378 }, 2, 0x2 }, + { { 0xD, 0x308, 0x378 }, 3, 0x6 }, + { { 0xA, 0x20 }, 2, 0x2 }, + { { 0xA, 0x308, 0x20 }, 3, 0x6 }, + { { 0xA, 0xD }, 2, 0x2 }, + { { 0xA, 0x308, 0xD }, 3, 0x6 }, + { { 0xA, 0xA }, 2, 0x2 }, + { { 0xA, 0x308, 0xA }, 3, 0x6 }, + { { 0xA, 0x1 }, 2, 0x2 }, + { { 0xA, 0x308, 0x1 }, 3, 0x6 }, + { { 0xA, 0x200C }, 2, 0x2 }, + { { 0xA, 0x308, 0x200C }, 3, 0x2 }, + { { 0xA, 0x1F1E6 }, 2, 0x2 }, + { { 0xA, 0x308, 0x1F1E6 }, 3, 0x6 }, + { { 0xA, 0x600 }, 2, 0x2 }, + { { 0xA, 0x308, 0x600 }, 3, 0x6 }, + { { 0xA, 0xA03 }, 2, 0x2 }, + { { 0xA, 0x308, 0xA03 }, 3, 0x2 }, + { { 0xA, 0x1100 }, 2, 0x2 }, + { { 0xA, 0x308, 0x1100 }, 3, 0x6 }, + { { 0xA, 0x1160 }, 2, 0x2 }, + { { 0xA, 0x308, 0x1160 }, 3, 0x6 }, + { { 0xA, 0x11A8 }, 2, 0x2 }, + { { 0xA, 0x308, 0x11A8 }, 3, 0x6 }, + { { 0xA, 0xAC00 }, 2, 0x2 }, + { { 0xA, 0x308, 0xAC00 }, 3, 0x6 }, + { { 0xA, 0xAC01 }, 2, 0x2 }, + { { 0xA, 0x308, 0xAC01 }, 3, 0x6 }, + { { 0xA, 0x903 }, 2, 0x2 }, + { { 0xA, 0x308, 0x903 }, 3, 0x2 }, + { { 0xA, 0x904 }, 2, 0x2 }, + { { 0xA, 0x308, 0x904 }, 3, 0x6 }, + { { 0xA, 0xD4E }, 2, 0x2 }, + { { 0xA, 0x308, 0xD4E }, 3, 0x6 }, + { { 0xA, 0x915 }, 2, 0x2 }, + { { 0xA, 0x308, 0x915 }, 3, 0x6 }, + { { 0xA, 0x231A }, 2, 0x2 }, + { { 0xA, 0x308, 0x231A }, 3, 0x6 }, + { { 0xA, 0x300 }, 2, 0x2 }, + { { 0xA, 0x308, 0x300 }, 3, 0x2 }, + { { 0xA, 0x900 }, 2, 0x2 }, + { { 0xA, 0x308, 0x900 }, 3, 0x2 }, + { { 0xA, 0x94D }, 2, 0x2 }, + { { 0xA, 0x308, 0x94D }, 3, 0x2 }, + { { 0xA, 0x200D }, 2, 0x2 }, + { { 0xA, 0x308, 0x200D }, 3, 0x2 }, + { { 0xA, 0x378 }, 2, 0x2 }, + { { 0xA, 0x308, 0x378 }, 3, 0x6 }, + { { 0x1, 0x20 }, 2, 0x2 }, + { { 0x1, 0x308, 0x20 }, 3, 0x6 }, + { { 0x1, 0xD }, 2, 0x2 }, + { { 0x1, 0x308, 0xD }, 3, 0x6 }, + { { 0x1, 0xA }, 2, 0x2 }, + { { 0x1, 0x308, 0xA }, 3, 0x6 }, + { { 0x1, 0x1 }, 2, 0x2 }, + { { 0x1, 0x308, 0x1 }, 3, 0x6 }, + { { 0x1, 0x200C }, 2, 0x2 }, + { { 0x1, 0x308, 0x200C }, 3, 0x2 }, + { { 0x1, 0x1F1E6 }, 2, 0x2 }, + { { 0x1, 0x308, 0x1F1E6 }, 3, 0x6 }, + { { 0x1, 0x600 }, 2, 0x2 }, + { { 0x1, 0x308, 0x600 }, 3, 0x6 }, + { { 0x1, 0xA03 }, 2, 0x2 }, + { { 0x1, 0x308, 0xA03 }, 3, 0x2 }, + { { 0x1, 0x1100 }, 2, 0x2 }, + { { 0x1, 0x308, 0x1100 }, 3, 0x6 }, + { { 0x1, 0x1160 }, 2, 0x2 }, + { { 0x1, 0x308, 0x1160 }, 3, 0x6 }, + { { 0x1, 0x11A8 }, 2, 0x2 }, + { { 0x1, 0x308, 0x11A8 }, 3, 0x6 }, + { { 0x1, 0xAC00 }, 2, 0x2 }, + { { 0x1, 0x308, 0xAC00 }, 3, 0x6 }, + { { 0x1, 0xAC01 }, 2, 0x2 }, + { { 0x1, 0x308, 0xAC01 }, 3, 0x6 }, + { { 0x1, 0x903 }, 2, 0x2 }, + { { 0x1, 0x308, 0x903 }, 3, 0x2 }, + { { 0x1, 0x904 }, 2, 0x2 }, + { { 0x1, 0x308, 0x904 }, 3, 0x6 }, + { { 0x1, 0xD4E }, 2, 0x2 }, + { { 0x1, 0x308, 0xD4E }, 3, 0x6 }, + { { 0x1, 0x915 }, 2, 0x2 }, + { { 0x1, 0x308, 0x915 }, 3, 0x6 }, + { { 0x1, 0x231A }, 2, 0x2 }, + { { 0x1, 0x308, 0x231A }, 3, 0x6 }, + { { 0x1, 0x300 }, 2, 0x2 }, + { { 0x1, 0x308, 0x300 }, 3, 0x2 }, + { { 0x1, 0x900 }, 2, 0x2 }, + { { 0x1, 0x308, 0x900 }, 3, 0x2 }, + { { 0x1, 0x94D }, 2, 0x2 }, + { { 0x1, 0x308, 0x94D }, 3, 0x2 }, + { { 0x1, 0x200D }, 2, 0x2 }, + { { 0x1, 0x308, 0x200D }, 3, 0x2 }, + { { 0x1, 0x378 }, 2, 0x2 }, + { { 0x1, 0x308, 0x378 }, 3, 0x6 }, + { { 0x200C, 0x20 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x20 }, 3, 0x4 }, + { { 0x200C, 0xD }, 2, 0x2 }, + { { 0x200C, 0x308, 0xD }, 3, 0x4 }, + { { 0x200C, 0xA }, 2, 0x2 }, + { { 0x200C, 0x308, 0xA }, 3, 0x4 }, + { { 0x200C, 0x1 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x1 }, 3, 0x4 }, + { { 0x200C, 0x200C }, 2, 0x0 }, + { { 0x200C, 0x308, 0x200C }, 3, 0x0 }, + { { 0x200C, 0x1F1E6 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x200C, 0x600 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x600 }, 3, 0x4 }, + { { 0x200C, 0xA03 }, 2, 0x0 }, + { { 0x200C, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x200C, 0x1100 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x200C, 0x1160 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x200C, 0x11A8 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x200C, 0xAC00 }, 2, 0x2 }, + { { 0x200C, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x200C, 0xAC01 }, 2, 0x2 }, + { { 0x200C, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x200C, 0x903 }, 2, 0x0 }, + { { 0x200C, 0x308, 0x903 }, 3, 0x0 }, + { { 0x200C, 0x904 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x904 }, 3, 0x4 }, + { { 0x200C, 0xD4E }, 2, 0x2 }, + { { 0x200C, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x200C, 0x915 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x915 }, 3, 0x4 }, + { { 0x200C, 0x231A }, 2, 0x2 }, + { { 0x200C, 0x308, 0x231A }, 3, 0x4 }, + { { 0x200C, 0x300 }, 2, 0x0 }, + { { 0x200C, 0x308, 0x300 }, 3, 0x0 }, + { { 0x200C, 0x900 }, 2, 0x0 }, + { { 0x200C, 0x308, 0x900 }, 3, 0x0 }, + { { 0x200C, 0x94D }, 2, 0x0 }, + { { 0x200C, 0x308, 0x94D }, 3, 0x0 }, + { { 0x200C, 0x200D }, 2, 0x0 }, + { { 0x200C, 0x308, 0x200D }, 3, 0x0 }, + { { 0x200C, 0x378 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x378 }, 3, 0x4 }, + { { 0x1F1E6, 0x20 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x20 }, 3, 0x4 }, + { { 0x1F1E6, 0xD }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xD }, 3, 0x4 }, + { { 0x1F1E6, 0xA }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xA }, 3, 0x4 }, + { { 0x1F1E6, 0x1 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x1 }, 3, 0x4 }, + { { 0x1F1E6, 0x200C }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x200C }, 3, 0x0 }, + { { 0x1F1E6, 0x1F1E6 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x1F1E6, 0x600 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x600 }, 3, 0x4 }, + { { 0x1F1E6, 0xA03 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x1F1E6, 0x1100 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x1F1E6, 0x1160 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x1F1E6, 0x11A8 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x1F1E6, 0xAC00 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x1F1E6, 0xAC01 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x1F1E6, 0x903 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x903 }, 3, 0x0 }, + { { 0x1F1E6, 0x904 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x904 }, 3, 0x4 }, + { { 0x1F1E6, 0xD4E }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x1F1E6, 0x915 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x915 }, 3, 0x4 }, + { { 0x1F1E6, 0x231A }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x231A }, 3, 0x4 }, + { { 0x1F1E6, 0x300 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x300 }, 3, 0x0 }, + { { 0x1F1E6, 0x900 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x900 }, 3, 0x0 }, + { { 0x1F1E6, 0x94D }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x94D }, 3, 0x0 }, + { { 0x1F1E6, 0x200D }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x200D }, 3, 0x0 }, + { { 0x1F1E6, 0x378 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x378 }, 3, 0x4 }, + { { 0x600, 0x20 }, 2, 0x0 }, + { { 0x600, 0x308, 0x20 }, 3, 0x4 }, + { { 0x600, 0xD }, 2, 0x2 }, + { { 0x600, 0x308, 0xD }, 3, 0x4 }, + { { 0x600, 0xA }, 2, 0x2 }, + { { 0x600, 0x308, 0xA }, 3, 0x4 }, + { { 0x600, 0x1 }, 2, 0x2 }, + { { 0x600, 0x308, 0x1 }, 3, 0x4 }, + { { 0x600, 0x200C }, 2, 0x0 }, + { { 0x600, 0x308, 0x200C }, 3, 0x0 }, + { { 0x600, 0x1F1E6 }, 2, 0x0 }, + { { 0x600, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x600, 0x600 }, 2, 0x0 }, + { { 0x600, 0x308, 0x600 }, 3, 0x4 }, + { { 0x600, 0xA03 }, 2, 0x0 }, + { { 0x600, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x600, 0x1100 }, 2, 0x0 }, + { { 0x600, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x600, 0x1160 }, 2, 0x0 }, + { { 0x600, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x600, 0x11A8 }, 2, 0x0 }, + { { 0x600, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x600, 0xAC00 }, 2, 0x0 }, + { { 0x600, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x600, 0xAC01 }, 2, 0x0 }, + { { 0x600, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x600, 0x903 }, 2, 0x0 }, + { { 0x600, 0x308, 0x903 }, 3, 0x0 }, + { { 0x600, 0x904 }, 2, 0x0 }, + { { 0x600, 0x308, 0x904 }, 3, 0x4 }, + { { 0x600, 0xD4E }, 2, 0x0 }, + { { 0x600, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x600, 0x915 }, 2, 0x0 }, + { { 0x600, 0x308, 0x915 }, 3, 0x4 }, + { { 0x600, 0x231A }, 2, 0x0 }, + { { 0x600, 0x308, 0x231A }, 3, 0x4 }, + { { 0x600, 0x300 }, 2, 0x0 }, + { { 0x600, 0x308, 0x300 }, 3, 0x0 }, + { { 0x600, 0x900 }, 2, 0x0 }, + { { 0x600, 0x308, 0x900 }, 3, 0x0 }, + { { 0x600, 0x94D }, 2, 0x0 }, + { { 0x600, 0x308, 0x94D }, 3, 0x0 }, + { { 0x600, 0x200D }, 2, 0x0 }, + { { 0x600, 0x308, 0x200D }, 3, 0x0 }, + { { 0x600, 0x378 }, 2, 0x0 }, + { { 0x600, 0x308, 0x378 }, 3, 0x4 }, + { { 0xA03, 0x20 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x20 }, 3, 0x4 }, + { { 0xA03, 0xD }, 2, 0x2 }, + { { 0xA03, 0x308, 0xD }, 3, 0x4 }, + { { 0xA03, 0xA }, 2, 0x2 }, + { { 0xA03, 0x308, 0xA }, 3, 0x4 }, + { { 0xA03, 0x1 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x1 }, 3, 0x4 }, + { { 0xA03, 0x200C }, 2, 0x0 }, + { { 0xA03, 0x308, 0x200C }, 3, 0x0 }, + { { 0xA03, 0x1F1E6 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0xA03, 0x600 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x600 }, 3, 0x4 }, + { { 0xA03, 0xA03 }, 2, 0x0 }, + { { 0xA03, 0x308, 0xA03 }, 3, 0x0 }, + { { 0xA03, 0x1100 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x1100 }, 3, 0x4 }, + { { 0xA03, 0x1160 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x1160 }, 3, 0x4 }, + { { 0xA03, 0x11A8 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0xA03, 0xAC00 }, 2, 0x2 }, + { { 0xA03, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0xA03, 0xAC01 }, 2, 0x2 }, + { { 0xA03, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0xA03, 0x903 }, 2, 0x0 }, + { { 0xA03, 0x308, 0x903 }, 3, 0x0 }, + { { 0xA03, 0x904 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x904 }, 3, 0x4 }, + { { 0xA03, 0xD4E }, 2, 0x2 }, + { { 0xA03, 0x308, 0xD4E }, 3, 0x4 }, + { { 0xA03, 0x915 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x915 }, 3, 0x4 }, + { { 0xA03, 0x231A }, 2, 0x2 }, + { { 0xA03, 0x308, 0x231A }, 3, 0x4 }, + { { 0xA03, 0x300 }, 2, 0x0 }, + { { 0xA03, 0x308, 0x300 }, 3, 0x0 }, + { { 0xA03, 0x900 }, 2, 0x0 }, + { { 0xA03, 0x308, 0x900 }, 3, 0x0 }, + { { 0xA03, 0x94D }, 2, 0x0 }, + { { 0xA03, 0x308, 0x94D }, 3, 0x0 }, + { { 0xA03, 0x200D }, 2, 0x0 }, + { { 0xA03, 0x308, 0x200D }, 3, 0x0 }, + { { 0xA03, 0x378 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x378 }, 3, 0x4 }, + { { 0x1100, 0x20 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x20 }, 3, 0x4 }, + { { 0x1100, 0xD }, 2, 0x2 }, + { { 0x1100, 0x308, 0xD }, 3, 0x4 }, + { { 0x1100, 0xA }, 2, 0x2 }, + { { 0x1100, 0x308, 0xA }, 3, 0x4 }, + { { 0x1100, 0x1 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x1 }, 3, 0x4 }, + { { 0x1100, 0x200C }, 2, 0x0 }, + { { 0x1100, 0x308, 0x200C }, 3, 0x0 }, + { { 0x1100, 0x1F1E6 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x1100, 0x600 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x600 }, 3, 0x4 }, + { { 0x1100, 0xA03 }, 2, 0x0 }, + { { 0x1100, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x1100, 0x1100 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x1100, 0x1160 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x1100, 0x11A8 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x1100, 0xAC00 }, 2, 0x0 }, + { { 0x1100, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x1100, 0xAC01 }, 2, 0x0 }, + { { 0x1100, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x1100, 0x903 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x903 }, 3, 0x0 }, + { { 0x1100, 0x904 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x904 }, 3, 0x4 }, + { { 0x1100, 0xD4E }, 2, 0x2 }, + { { 0x1100, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x1100, 0x915 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x915 }, 3, 0x4 }, + { { 0x1100, 0x231A }, 2, 0x2 }, + { { 0x1100, 0x308, 0x231A }, 3, 0x4 }, + { { 0x1100, 0x300 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x300 }, 3, 0x0 }, + { { 0x1100, 0x900 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x900 }, 3, 0x0 }, + { { 0x1100, 0x94D }, 2, 0x0 }, + { { 0x1100, 0x308, 0x94D }, 3, 0x0 }, + { { 0x1100, 0x200D }, 2, 0x0 }, + { { 0x1100, 0x308, 0x200D }, 3, 0x0 }, + { { 0x1100, 0x378 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x378 }, 3, 0x4 }, + { { 0x1160, 0x20 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x20 }, 3, 0x4 }, + { { 0x1160, 0xD }, 2, 0x2 }, + { { 0x1160, 0x308, 0xD }, 3, 0x4 }, + { { 0x1160, 0xA }, 2, 0x2 }, + { { 0x1160, 0x308, 0xA }, 3, 0x4 }, + { { 0x1160, 0x1 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x1 }, 3, 0x4 }, + { { 0x1160, 0x200C }, 2, 0x0 }, + { { 0x1160, 0x308, 0x200C }, 3, 0x0 }, + { { 0x1160, 0x1F1E6 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x1160, 0x600 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x600 }, 3, 0x4 }, + { { 0x1160, 0xA03 }, 2, 0x0 }, + { { 0x1160, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x1160, 0x1100 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x1160, 0x1160 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x1160, 0x11A8 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x1160, 0xAC00 }, 2, 0x2 }, + { { 0x1160, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x1160, 0xAC01 }, 2, 0x2 }, + { { 0x1160, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x1160, 0x903 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x903 }, 3, 0x0 }, + { { 0x1160, 0x904 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x904 }, 3, 0x4 }, + { { 0x1160, 0xD4E }, 2, 0x2 }, + { { 0x1160, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x1160, 0x915 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x915 }, 3, 0x4 }, + { { 0x1160, 0x231A }, 2, 0x2 }, + { { 0x1160, 0x308, 0x231A }, 3, 0x4 }, + { { 0x1160, 0x300 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x300 }, 3, 0x0 }, + { { 0x1160, 0x900 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x900 }, 3, 0x0 }, + { { 0x1160, 0x94D }, 2, 0x0 }, + { { 0x1160, 0x308, 0x94D }, 3, 0x0 }, + { { 0x1160, 0x200D }, 2, 0x0 }, + { { 0x1160, 0x308, 0x200D }, 3, 0x0 }, + { { 0x1160, 0x378 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x378 }, 3, 0x4 }, + { { 0x11A8, 0x20 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x20 }, 3, 0x4 }, + { { 0x11A8, 0xD }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xD }, 3, 0x4 }, + { { 0x11A8, 0xA }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xA }, 3, 0x4 }, + { { 0x11A8, 0x1 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x1 }, 3, 0x4 }, + { { 0x11A8, 0x200C }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x200C }, 3, 0x0 }, + { { 0x11A8, 0x1F1E6 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x11A8, 0x600 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x600 }, 3, 0x4 }, + { { 0x11A8, 0xA03 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x11A8, 0x1100 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x11A8, 0x1160 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x11A8, 0x11A8 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x11A8, 0xAC00 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x11A8, 0xAC01 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x11A8, 0x903 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x903 }, 3, 0x0 }, + { { 0x11A8, 0x904 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x904 }, 3, 0x4 }, + { { 0x11A8, 0xD4E }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x11A8, 0x915 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x915 }, 3, 0x4 }, + { { 0x11A8, 0x231A }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x231A }, 3, 0x4 }, + { { 0x11A8, 0x300 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x300 }, 3, 0x0 }, + { { 0x11A8, 0x900 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x900 }, 3, 0x0 }, + { { 0x11A8, 0x94D }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x94D }, 3, 0x0 }, + { { 0x11A8, 0x200D }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x200D }, 3, 0x0 }, + { { 0x11A8, 0x378 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x378 }, 3, 0x4 }, + { { 0xAC00, 0x20 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x20 }, 3, 0x4 }, + { { 0xAC00, 0xD }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xD }, 3, 0x4 }, + { { 0xAC00, 0xA }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xA }, 3, 0x4 }, + { { 0xAC00, 0x1 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x1 }, 3, 0x4 }, + { { 0xAC00, 0x200C }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x200C }, 3, 0x0 }, + { { 0xAC00, 0x1F1E6 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0xAC00, 0x600 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x600 }, 3, 0x4 }, + { { 0xAC00, 0xA03 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0xA03 }, 3, 0x0 }, + { { 0xAC00, 0x1100 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x1100 }, 3, 0x4 }, + { { 0xAC00, 0x1160 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x1160 }, 3, 0x4 }, + { { 0xAC00, 0x11A8 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0xAC00, 0xAC00 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0xAC00, 0xAC01 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0xAC00, 0x903 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x903 }, 3, 0x0 }, + { { 0xAC00, 0x904 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x904 }, 3, 0x4 }, + { { 0xAC00, 0xD4E }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xD4E }, 3, 0x4 }, + { { 0xAC00, 0x915 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x915 }, 3, 0x4 }, + { { 0xAC00, 0x231A }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x231A }, 3, 0x4 }, + { { 0xAC00, 0x300 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x300 }, 3, 0x0 }, + { { 0xAC00, 0x900 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x900 }, 3, 0x0 }, + { { 0xAC00, 0x94D }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x94D }, 3, 0x0 }, + { { 0xAC00, 0x200D }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x200D }, 3, 0x0 }, + { { 0xAC00, 0x378 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x378 }, 3, 0x4 }, + { { 0xAC01, 0x20 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x20 }, 3, 0x4 }, + { { 0xAC01, 0xD }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xD }, 3, 0x4 }, + { { 0xAC01, 0xA }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xA }, 3, 0x4 }, + { { 0xAC01, 0x1 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x1 }, 3, 0x4 }, + { { 0xAC01, 0x200C }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x200C }, 3, 0x0 }, + { { 0xAC01, 0x1F1E6 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0xAC01, 0x600 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x600 }, 3, 0x4 }, + { { 0xAC01, 0xA03 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0xA03 }, 3, 0x0 }, + { { 0xAC01, 0x1100 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x1100 }, 3, 0x4 }, + { { 0xAC01, 0x1160 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x1160 }, 3, 0x4 }, + { { 0xAC01, 0x11A8 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0xAC01, 0xAC00 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0xAC01, 0xAC01 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0xAC01, 0x903 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x903 }, 3, 0x0 }, + { { 0xAC01, 0x904 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x904 }, 3, 0x4 }, + { { 0xAC01, 0xD4E }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xD4E }, 3, 0x4 }, + { { 0xAC01, 0x915 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x915 }, 3, 0x4 }, + { { 0xAC01, 0x231A }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x231A }, 3, 0x4 }, + { { 0xAC01, 0x300 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x300 }, 3, 0x0 }, + { { 0xAC01, 0x900 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x900 }, 3, 0x0 }, + { { 0xAC01, 0x94D }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x94D }, 3, 0x0 }, + { { 0xAC01, 0x200D }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x200D }, 3, 0x0 }, + { { 0xAC01, 0x378 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x378 }, 3, 0x4 }, + { { 0x903, 0x20 }, 2, 0x2 }, + { { 0x903, 0x308, 0x20 }, 3, 0x4 }, + { { 0x903, 0xD }, 2, 0x2 }, + { { 0x903, 0x308, 0xD }, 3, 0x4 }, + { { 0x903, 0xA }, 2, 0x2 }, + { { 0x903, 0x308, 0xA }, 3, 0x4 }, + { { 0x903, 0x1 }, 2, 0x2 }, + { { 0x903, 0x308, 0x1 }, 3, 0x4 }, + { { 0x903, 0x200C }, 2, 0x0 }, + { { 0x903, 0x308, 0x200C }, 3, 0x0 }, + { { 0x903, 0x1F1E6 }, 2, 0x2 }, + { { 0x903, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x903, 0x600 }, 2, 0x2 }, + { { 0x903, 0x308, 0x600 }, 3, 0x4 }, + { { 0x903, 0xA03 }, 2, 0x0 }, + { { 0x903, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x903, 0x1100 }, 2, 0x2 }, + { { 0x903, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x903, 0x1160 }, 2, 0x2 }, + { { 0x903, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x903, 0x11A8 }, 2, 0x2 }, + { { 0x903, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x903, 0xAC00 }, 2, 0x2 }, + { { 0x903, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x903, 0xAC01 }, 2, 0x2 }, + { { 0x903, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x903, 0x903 }, 2, 0x0 }, + { { 0x903, 0x308, 0x903 }, 3, 0x0 }, + { { 0x903, 0x904 }, 2, 0x2 }, + { { 0x903, 0x308, 0x904 }, 3, 0x4 }, + { { 0x903, 0xD4E }, 2, 0x2 }, + { { 0x903, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x903, 0x915 }, 2, 0x2 }, + { { 0x903, 0x308, 0x915 }, 3, 0x4 }, + { { 0x903, 0x231A }, 2, 0x2 }, + { { 0x903, 0x308, 0x231A }, 3, 0x4 }, + { { 0x903, 0x300 }, 2, 0x0 }, + { { 0x903, 0x308, 0x300 }, 3, 0x0 }, + { { 0x903, 0x900 }, 2, 0x0 }, + { { 0x903, 0x308, 0x900 }, 3, 0x0 }, + { { 0x903, 0x94D }, 2, 0x0 }, + { { 0x903, 0x308, 0x94D }, 3, 0x0 }, + { { 0x903, 0x200D }, 2, 0x0 }, + { { 0x903, 0x308, 0x200D }, 3, 0x0 }, + { { 0x903, 0x378 }, 2, 0x2 }, + { { 0x903, 0x308, 0x378 }, 3, 0x4 }, + { { 0x904, 0x20 }, 2, 0x2 }, + { { 0x904, 0x308, 0x20 }, 3, 0x4 }, + { { 0x904, 0xD }, 2, 0x2 }, + { { 0x904, 0x308, 0xD }, 3, 0x4 }, + { { 0x904, 0xA }, 2, 0x2 }, + { { 0x904, 0x308, 0xA }, 3, 0x4 }, + { { 0x904, 0x1 }, 2, 0x2 }, + { { 0x904, 0x308, 0x1 }, 3, 0x4 }, + { { 0x904, 0x200C }, 2, 0x0 }, + { { 0x904, 0x308, 0x200C }, 3, 0x0 }, + { { 0x904, 0x1F1E6 }, 2, 0x2 }, + { { 0x904, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x904, 0x600 }, 2, 0x2 }, + { { 0x904, 0x308, 0x600 }, 3, 0x4 }, + { { 0x904, 0xA03 }, 2, 0x0 }, + { { 0x904, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x904, 0x1100 }, 2, 0x2 }, + { { 0x904, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x904, 0x1160 }, 2, 0x2 }, + { { 0x904, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x904, 0x11A8 }, 2, 0x2 }, + { { 0x904, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x904, 0xAC00 }, 2, 0x2 }, + { { 0x904, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x904, 0xAC01 }, 2, 0x2 }, + { { 0x904, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x904, 0x903 }, 2, 0x0 }, + { { 0x904, 0x308, 0x903 }, 3, 0x0 }, + { { 0x904, 0x904 }, 2, 0x2 }, + { { 0x904, 0x308, 0x904 }, 3, 0x4 }, + { { 0x904, 0xD4E }, 2, 0x2 }, + { { 0x904, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x904, 0x915 }, 2, 0x2 }, + { { 0x904, 0x308, 0x915 }, 3, 0x4 }, + { { 0x904, 0x231A }, 2, 0x2 }, + { { 0x904, 0x308, 0x231A }, 3, 0x4 }, + { { 0x904, 0x300 }, 2, 0x0 }, + { { 0x904, 0x308, 0x300 }, 3, 0x0 }, + { { 0x904, 0x900 }, 2, 0x0 }, + { { 0x904, 0x308, 0x900 }, 3, 0x0 }, + { { 0x904, 0x94D }, 2, 0x0 }, + { { 0x904, 0x308, 0x94D }, 3, 0x0 }, + { { 0x904, 0x200D }, 2, 0x0 }, + { { 0x904, 0x308, 0x200D }, 3, 0x0 }, + { { 0x904, 0x378 }, 2, 0x2 }, + { { 0x904, 0x308, 0x378 }, 3, 0x4 }, + { { 0xD4E, 0x20 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x20 }, 3, 0x4 }, + { { 0xD4E, 0xD }, 2, 0x2 }, + { { 0xD4E, 0x308, 0xD }, 3, 0x4 }, + { { 0xD4E, 0xA }, 2, 0x2 }, + { { 0xD4E, 0x308, 0xA }, 3, 0x4 }, + { { 0xD4E, 0x1 }, 2, 0x2 }, + { { 0xD4E, 0x308, 0x1 }, 3, 0x4 }, + { { 0xD4E, 0x200C }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x200C }, 3, 0x0 }, + { { 0xD4E, 0x1F1E6 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0xD4E, 0x600 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x600 }, 3, 0x4 }, + { { 0xD4E, 0xA03 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0xA03 }, 3, 0x0 }, + { { 0xD4E, 0x1100 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x1100 }, 3, 0x4 }, + { { 0xD4E, 0x1160 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x1160 }, 3, 0x4 }, + { { 0xD4E, 0x11A8 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0xD4E, 0xAC00 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0xD4E, 0xAC01 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0xD4E, 0x903 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x903 }, 3, 0x0 }, + { { 0xD4E, 0x904 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x904 }, 3, 0x4 }, + { { 0xD4E, 0xD4E }, 2, 0x0 }, + { { 0xD4E, 0x308, 0xD4E }, 3, 0x4 }, + { { 0xD4E, 0x915 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x915 }, 3, 0x4 }, + { { 0xD4E, 0x231A }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x231A }, 3, 0x4 }, + { { 0xD4E, 0x300 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x300 }, 3, 0x0 }, + { { 0xD4E, 0x900 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x900 }, 3, 0x0 }, + { { 0xD4E, 0x94D }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x94D }, 3, 0x0 }, + { { 0xD4E, 0x200D }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x200D }, 3, 0x0 }, + { { 0xD4E, 0x378 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x378 }, 3, 0x4 }, + { { 0x915, 0x20 }, 2, 0x2 }, + { { 0x915, 0x308, 0x20 }, 3, 0x4 }, + { { 0x915, 0xD }, 2, 0x2 }, + { { 0x915, 0x308, 0xD }, 3, 0x4 }, + { { 0x915, 0xA }, 2, 0x2 }, + { { 0x915, 0x308, 0xA }, 3, 0x4 }, + { { 0x915, 0x1 }, 2, 0x2 }, + { { 0x915, 0x308, 0x1 }, 3, 0x4 }, + { { 0x915, 0x200C }, 2, 0x0 }, + { { 0x915, 0x308, 0x200C }, 3, 0x0 }, + { { 0x915, 0x1F1E6 }, 2, 0x2 }, + { { 0x915, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x915, 0x600 }, 2, 0x2 }, + { { 0x915, 0x308, 0x600 }, 3, 0x4 }, + { { 0x915, 0xA03 }, 2, 0x0 }, + { { 0x915, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x915, 0x1100 }, 2, 0x2 }, + { { 0x915, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x915, 0x1160 }, 2, 0x2 }, + { { 0x915, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x915, 0x11A8 }, 2, 0x2 }, + { { 0x915, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x915, 0xAC00 }, 2, 0x2 }, + { { 0x915, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x915, 0xAC01 }, 2, 0x2 }, + { { 0x915, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x915, 0x903 }, 2, 0x0 }, + { { 0x915, 0x308, 0x903 }, 3, 0x0 }, + { { 0x915, 0x904 }, 2, 0x2 }, + { { 0x915, 0x308, 0x904 }, 3, 0x4 }, + { { 0x915, 0xD4E }, 2, 0x2 }, + { { 0x915, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x915, 0x915 }, 2, 0x2 }, + { { 0x915, 0x308, 0x915 }, 3, 0x4 }, + { { 0x915, 0x231A }, 2, 0x2 }, + { { 0x915, 0x308, 0x231A }, 3, 0x4 }, + { { 0x915, 0x300 }, 2, 0x0 }, + { { 0x915, 0x308, 0x300 }, 3, 0x0 }, + { { 0x915, 0x900 }, 2, 0x0 }, + { { 0x915, 0x308, 0x900 }, 3, 0x0 }, + { { 0x915, 0x94D }, 2, 0x0 }, + { { 0x915, 0x308, 0x94D }, 3, 0x0 }, + { { 0x915, 0x200D }, 2, 0x0 }, + { { 0x915, 0x308, 0x200D }, 3, 0x0 }, + { { 0x915, 0x378 }, 2, 0x2 }, + { { 0x915, 0x308, 0x378 }, 3, 0x4 }, + { { 0x231A, 0x20 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x20 }, 3, 0x4 }, + { { 0x231A, 0xD }, 2, 0x2 }, + { { 0x231A, 0x308, 0xD }, 3, 0x4 }, + { { 0x231A, 0xA }, 2, 0x2 }, + { { 0x231A, 0x308, 0xA }, 3, 0x4 }, + { { 0x231A, 0x1 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x1 }, 3, 0x4 }, + { { 0x231A, 0x200C }, 2, 0x0 }, + { { 0x231A, 0x308, 0x200C }, 3, 0x0 }, + { { 0x231A, 0x1F1E6 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x231A, 0x600 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x600 }, 3, 0x4 }, + { { 0x231A, 0xA03 }, 2, 0x0 }, + { { 0x231A, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x231A, 0x1100 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x231A, 0x1160 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x231A, 0x11A8 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x231A, 0xAC00 }, 2, 0x2 }, + { { 0x231A, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x231A, 0xAC01 }, 2, 0x2 }, + { { 0x231A, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x231A, 0x903 }, 2, 0x0 }, + { { 0x231A, 0x308, 0x903 }, 3, 0x0 }, + { { 0x231A, 0x904 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x904 }, 3, 0x4 }, + { { 0x231A, 0xD4E }, 2, 0x2 }, + { { 0x231A, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x231A, 0x915 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x915 }, 3, 0x4 }, + { { 0x231A, 0x231A }, 2, 0x2 }, + { { 0x231A, 0x308, 0x231A }, 3, 0x4 }, + { { 0x231A, 0x300 }, 2, 0x0 }, + { { 0x231A, 0x308, 0x300 }, 3, 0x0 }, + { { 0x231A, 0x900 }, 2, 0x0 }, + { { 0x231A, 0x308, 0x900 }, 3, 0x0 }, + { { 0x231A, 0x94D }, 2, 0x0 }, + { { 0x231A, 0x308, 0x94D }, 3, 0x0 }, + { { 0x231A, 0x200D }, 2, 0x0 }, + { { 0x231A, 0x308, 0x200D }, 3, 0x0 }, + { { 0x231A, 0x378 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x378 }, 3, 0x4 }, + { { 0x300, 0x20 }, 2, 0x2 }, + { { 0x300, 0x308, 0x20 }, 3, 0x4 }, + { { 0x300, 0xD }, 2, 0x2 }, + { { 0x300, 0x308, 0xD }, 3, 0x4 }, + { { 0x300, 0xA }, 2, 0x2 }, + { { 0x300, 0x308, 0xA }, 3, 0x4 }, + { { 0x300, 0x1 }, 2, 0x2 }, + { { 0x300, 0x308, 0x1 }, 3, 0x4 }, + { { 0x300, 0x200C }, 2, 0x0 }, + { { 0x300, 0x308, 0x200C }, 3, 0x0 }, + { { 0x300, 0x1F1E6 }, 2, 0x2 }, + { { 0x300, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x300, 0x600 }, 2, 0x2 }, + { { 0x300, 0x308, 0x600 }, 3, 0x4 }, + { { 0x300, 0xA03 }, 2, 0x0 }, + { { 0x300, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x300, 0x1100 }, 2, 0x2 }, + { { 0x300, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x300, 0x1160 }, 2, 0x2 }, + { { 0x300, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x300, 0x11A8 }, 2, 0x2 }, + { { 0x300, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x300, 0xAC00 }, 2, 0x2 }, + { { 0x300, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x300, 0xAC01 }, 2, 0x2 }, + { { 0x300, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x300, 0x903 }, 2, 0x0 }, + { { 0x300, 0x308, 0x903 }, 3, 0x0 }, + { { 0x300, 0x904 }, 2, 0x2 }, + { { 0x300, 0x308, 0x904 }, 3, 0x4 }, + { { 0x300, 0xD4E }, 2, 0x2 }, + { { 0x300, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x300, 0x915 }, 2, 0x2 }, + { { 0x300, 0x308, 0x915 }, 3, 0x4 }, + { { 0x300, 0x231A }, 2, 0x2 }, + { { 0x300, 0x308, 0x231A }, 3, 0x4 }, + { { 0x300, 0x300 }, 2, 0x0 }, + { { 0x300, 0x308, 0x300 }, 3, 0x0 }, + { { 0x300, 0x900 }, 2, 0x0 }, + { { 0x300, 0x308, 0x900 }, 3, 0x0 }, + { { 0x300, 0x94D }, 2, 0x0 }, + { { 0x300, 0x308, 0x94D }, 3, 0x0 }, + { { 0x300, 0x200D }, 2, 0x0 }, + { { 0x300, 0x308, 0x200D }, 3, 0x0 }, + { { 0x300, 0x378 }, 2, 0x2 }, + { { 0x300, 0x308, 0x378 }, 3, 0x4 }, + { { 0x900, 0x20 }, 2, 0x2 }, + { { 0x900, 0x308, 0x20 }, 3, 0x4 }, + { { 0x900, 0xD }, 2, 0x2 }, + { { 0x900, 0x308, 0xD }, 3, 0x4 }, + { { 0x900, 0xA }, 2, 0x2 }, + { { 0x900, 0x308, 0xA }, 3, 0x4 }, + { { 0x900, 0x1 }, 2, 0x2 }, + { { 0x900, 0x308, 0x1 }, 3, 0x4 }, + { { 0x900, 0x200C }, 2, 0x0 }, + { { 0x900, 0x308, 0x200C }, 3, 0x0 }, + { { 0x900, 0x1F1E6 }, 2, 0x2 }, + { { 0x900, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x900, 0x600 }, 2, 0x2 }, + { { 0x900, 0x308, 0x600 }, 3, 0x4 }, + { { 0x900, 0xA03 }, 2, 0x0 }, + { { 0x900, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x900, 0x1100 }, 2, 0x2 }, + { { 0x900, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x900, 0x1160 }, 2, 0x2 }, + { { 0x900, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x900, 0x11A8 }, 2, 0x2 }, + { { 0x900, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x900, 0xAC00 }, 2, 0x2 }, + { { 0x900, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x900, 0xAC01 }, 2, 0x2 }, + { { 0x900, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x900, 0x903 }, 2, 0x0 }, + { { 0x900, 0x308, 0x903 }, 3, 0x0 }, + { { 0x900, 0x904 }, 2, 0x2 }, + { { 0x900, 0x308, 0x904 }, 3, 0x4 }, + { { 0x900, 0xD4E }, 2, 0x2 }, + { { 0x900, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x900, 0x915 }, 2, 0x2 }, + { { 0x900, 0x308, 0x915 }, 3, 0x4 }, + { { 0x900, 0x231A }, 2, 0x2 }, + { { 0x900, 0x308, 0x231A }, 3, 0x4 }, + { { 0x900, 0x300 }, 2, 0x0 }, + { { 0x900, 0x308, 0x300 }, 3, 0x0 }, + { { 0x900, 0x900 }, 2, 0x0 }, + { { 0x900, 0x308, 0x900 }, 3, 0x0 }, + { { 0x900, 0x94D }, 2, 0x0 }, + { { 0x900, 0x308, 0x94D }, 3, 0x0 }, + { { 0x900, 0x200D }, 2, 0x0 }, + { { 0x900, 0x308, 0x200D }, 3, 0x0 }, + { { 0x900, 0x378 }, 2, 0x2 }, + { { 0x900, 0x308, 0x378 }, 3, 0x4 }, + { { 0x94D, 0x20 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x20 }, 3, 0x4 }, + { { 0x94D, 0xD }, 2, 0x2 }, + { { 0x94D, 0x308, 0xD }, 3, 0x4 }, + { { 0x94D, 0xA }, 2, 0x2 }, + { { 0x94D, 0x308, 0xA }, 3, 0x4 }, + { { 0x94D, 0x1 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x1 }, 3, 0x4 }, + { { 0x94D, 0x200C }, 2, 0x0 }, + { { 0x94D, 0x308, 0x200C }, 3, 0x0 }, + { { 0x94D, 0x1F1E6 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x94D, 0x600 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x600 }, 3, 0x4 }, + { { 0x94D, 0xA03 }, 2, 0x0 }, + { { 0x94D, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x94D, 0x1100 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x94D, 0x1160 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x94D, 0x11A8 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x94D, 0xAC00 }, 2, 0x2 }, + { { 0x94D, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x94D, 0xAC01 }, 2, 0x2 }, + { { 0x94D, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x94D, 0x903 }, 2, 0x0 }, + { { 0x94D, 0x308, 0x903 }, 3, 0x0 }, + { { 0x94D, 0x904 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x904 }, 3, 0x4 }, + { { 0x94D, 0xD4E }, 2, 0x2 }, + { { 0x94D, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x94D, 0x915 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x915 }, 3, 0x4 }, + { { 0x94D, 0x231A }, 2, 0x2 }, + { { 0x94D, 0x308, 0x231A }, 3, 0x4 }, + { { 0x94D, 0x300 }, 2, 0x0 }, + { { 0x94D, 0x308, 0x300 }, 3, 0x0 }, + { { 0x94D, 0x900 }, 2, 0x0 }, + { { 0x94D, 0x308, 0x900 }, 3, 0x0 }, + { { 0x94D, 0x94D }, 2, 0x0 }, + { { 0x94D, 0x308, 0x94D }, 3, 0x0 }, + { { 0x94D, 0x200D }, 2, 0x0 }, + { { 0x94D, 0x308, 0x200D }, 3, 0x0 }, + { { 0x94D, 0x378 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x378 }, 3, 0x4 }, + { { 0x200D, 0x20 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x20 }, 3, 0x4 }, + { { 0x200D, 0xD }, 2, 0x2 }, + { { 0x200D, 0x308, 0xD }, 3, 0x4 }, + { { 0x200D, 0xA }, 2, 0x2 }, + { { 0x200D, 0x308, 0xA }, 3, 0x4 }, + { { 0x200D, 0x1 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x1 }, 3, 0x4 }, + { { 0x200D, 0x200C }, 2, 0x0 }, + { { 0x200D, 0x308, 0x200C }, 3, 0x0 }, + { { 0x200D, 0x1F1E6 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x200D, 0x600 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x600 }, 3, 0x4 }, + { { 0x200D, 0xA03 }, 2, 0x0 }, + { { 0x200D, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x200D, 0x1100 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x200D, 0x1160 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x200D, 0x11A8 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x200D, 0xAC00 }, 2, 0x2 }, + { { 0x200D, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x200D, 0xAC01 }, 2, 0x2 }, + { { 0x200D, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x200D, 0x903 }, 2, 0x0 }, + { { 0x200D, 0x308, 0x903 }, 3, 0x0 }, + { { 0x200D, 0x904 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x904 }, 3, 0x4 }, + { { 0x200D, 0xD4E }, 2, 0x2 }, + { { 0x200D, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x200D, 0x915 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x915 }, 3, 0x4 }, + { { 0x200D, 0x231A }, 2, 0x2 }, + { { 0x200D, 0x308, 0x231A }, 3, 0x4 }, + { { 0x200D, 0x300 }, 2, 0x0 }, + { { 0x200D, 0x308, 0x300 }, 3, 0x0 }, + { { 0x200D, 0x900 }, 2, 0x0 }, + { { 0x200D, 0x308, 0x900 }, 3, 0x0 }, + { { 0x200D, 0x94D }, 2, 0x0 }, + { { 0x200D, 0x308, 0x94D }, 3, 0x0 }, + { { 0x200D, 0x200D }, 2, 0x0 }, + { { 0x200D, 0x308, 0x200D }, 3, 0x0 }, + { { 0x200D, 0x378 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x378 }, 3, 0x4 }, + { { 0x378, 0x20 }, 2, 0x2 }, + { { 0x378, 0x308, 0x20 }, 3, 0x4 }, + { { 0x378, 0xD }, 2, 0x2 }, + { { 0x378, 0x308, 0xD }, 3, 0x4 }, + { { 0x378, 0xA }, 2, 0x2 }, + { { 0x378, 0x308, 0xA }, 3, 0x4 }, + { { 0x378, 0x1 }, 2, 0x2 }, + { { 0x378, 0x308, 0x1 }, 3, 0x4 }, + { { 0x378, 0x200C }, 2, 0x0 }, + { { 0x378, 0x308, 0x200C }, 3, 0x0 }, + { { 0x378, 0x1F1E6 }, 2, 0x2 }, + { { 0x378, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x378, 0x600 }, 2, 0x2 }, + { { 0x378, 0x308, 0x600 }, 3, 0x4 }, + { { 0x378, 0xA03 }, 2, 0x0 }, + { { 0x378, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x378, 0x1100 }, 2, 0x2 }, + { { 0x378, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x378, 0x1160 }, 2, 0x2 }, + { { 0x378, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x378, 0x11A8 }, 2, 0x2 }, + { { 0x378, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x378, 0xAC00 }, 2, 0x2 }, + { { 0x378, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x378, 0xAC01 }, 2, 0x2 }, + { { 0x378, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x378, 0x903 }, 2, 0x0 }, + { { 0x378, 0x308, 0x903 }, 3, 0x0 }, + { { 0x378, 0x904 }, 2, 0x2 }, + { { 0x378, 0x308, 0x904 }, 3, 0x4 }, + { { 0x378, 0xD4E }, 2, 0x2 }, + { { 0x378, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x378, 0x915 }, 2, 0x2 }, + { { 0x378, 0x308, 0x915 }, 3, 0x4 }, + { { 0x378, 0x231A }, 2, 0x2 }, + { { 0x378, 0x308, 0x231A }, 3, 0x4 }, + { { 0x378, 0x300 }, 2, 0x0 }, + { { 0x378, 0x308, 0x300 }, 3, 0x0 }, + { { 0x378, 0x900 }, 2, 0x0 }, + { { 0x378, 0x308, 0x900 }, 3, 0x0 }, + { { 0x378, 0x94D }, 2, 0x0 }, + { { 0x378, 0x308, 0x94D }, 3, 0x0 }, + { { 0x378, 0x200D }, 2, 0x0 }, + { { 0x378, 0x308, 0x200D }, 3, 0x0 }, + { { 0x378, 0x378 }, 2, 0x2 }, + { { 0x378, 0x308, 0x378 }, 3, 0x4 }, + { { 0xD, 0xA, 0x61, 0xA, 0x308 }, 5, 0x1c }, + { { 0x61, 0x308 }, 2, 0x0 }, + { { 0x20, 0x200D, 0x646 }, 3, 0x4 }, + { { 0x646, 0x200D, 0x20 }, 3, 0x4 }, + { { 0x1100, 0x1100 }, 2, 0x0 }, + { { 0xAC00, 0x11A8, 0x1100 }, 3, 0x4 }, + { { 0xAC01, 0x11A8, 0x1100 }, 3, 0x4 }, + { { 0x1F1E6, 0x1F1E7, 0x1F1E8, 0x62 }, 4, 0xc }, + { { 0x61, 0x1F1E6, 0x1F1E7, 0x1F1E8, 0x62 }, 5, 0x1a }, + { { 0x61, 0x1F1E6, 0x1F1E7, 0x200D, 0x1F1E8, 0x62 }, 6, 0x32 }, + { { 0x61, 0x1F1E6, 0x200D, 0x1F1E7, 0x1F1E8, 0x62 }, 6, 0x2a }, + { { 0x61, 0x1F1E6, 0x1F1E7, 0x1F1E8, 0x1F1E9, 0x62 }, 6, 0x2a }, + { { 0x61, 0x200D }, 2, 0x0 }, + { { 0x61, 0x308, 0x62 }, 3, 0x4 }, + { { 0x61, 0x903, 0x62 }, 3, 0x4 }, + { { 0x61, 0x600, 0x62 }, 3, 0x2 }, + { { 0x1F476, 0x1F3FF, 0x1F476 }, 3, 0x4 }, + { { 0x61, 0x1F3FF, 0x1F476 }, 3, 0x4 }, + { { 0x61, 0x1F3FF, 0x1F476, 0x200D, 0x1F6D1 }, 5, 0x4 }, + { { 0x1F476, 0x1F3FF, 0x308, 0x200D, 0x1F476, 0x1F3FF }, 6, 0x0 }, + { { 0x1F6D1, 0x200D, 0x1F6D1 }, 3, 0x0 }, + { { 0x61, 0x200D, 0x1F6D1 }, 3, 0x4 }, + { { 0x2701, 0x200D, 0x2701 }, 3, 0x0 }, + { { 0x61, 0x200D, 0x2701 }, 3, 0x4 }, + { { 0x915, 0x924 }, 2, 0x2 }, + { { 0x915, 0x94D, 0x924 }, 3, 0x0 }, + { { 0x915, 0x94D, 0x94D, 0x924 }, 4, 0x0 }, + { { 0x915, 0x94D, 0x200D, 0x924 }, 4, 0x0 }, + { { 0x915, 0x93C, 0x200D, 0x94D, 0x924 }, 5, 0x0 }, + { { 0x915, 0x93C, 0x94D, 0x200D, 0x924 }, 5, 0x0 }, + { { 0x915, 0x94D, 0x924, 0x94D, 0x92F }, 5, 0x0 }, + { { 0x915, 0x94D, 0x61 }, 3, 0x4 }, + { { 0x61, 0x94D, 0x924 }, 3, 0x4 }, + { { 0x3F, 0x94D, 0x924 }, 3, 0x4 }, + { { 0x915, 0x94D, 0x94D, 0x924 }, 4, 0x0 }, +}; diff --git a/tests/precompiled_test.cpp b/tests/precompiled_test.cpp new file mode 100644 index 00000000..5b3b85b3 --- /dev/null +++ b/tests/precompiled_test.cpp @@ -0,0 +1,103 @@ +/* precompiled_test.cpp -- extended grapheme clusters and SentencePiece's precompiled normaliser + * (core/text/tokenizer_grapheme.h) against Unicode's own test file and HuggingFace tokenizers' + * Precompiled normaliser (goldens: mk_precompiled_goldens.py). */ +#include "rad_test.h" +#include "text/tokenizer.h" +#include "text/tokenizer_grapheme.h" + +#include "precompiled_golden.h" + +#include +#include + +using namespace rad; + +/* Every case of Unicode 16.0.0's GraphemeBreakTest.txt: the clusters grapheme_end walks out of the + * sequence start where the file breaks it. */ +TEST(grapheme_clusters_follow_uax29) { + int bad = 0; + for (const GbCase& g : kGbCases) { + uint32_t starts = 0; + for (size_t i = 0; i < g.n;) { + if (i) starts |= 1u << i; + const size_t e = grapheme_end(g.cp, g.n, i); + if (e <= i || e > g.n) { ++bad; break; } + i = e; + } + if (starts != g.starts) { + if (++bad <= 5) { + std::string s; + for (uint32_t k = 0; k < g.n; ++k) s += fmt(" %04X", g.cp[k]); + fprintf(stderr, " [%s ] starts 0x%x, want 0x%x\n", s.c_str(), starts, g.starts); + } + } + } + CHECK_EQ(bad, 0); + CHECK(sizeof kGbCases / sizeof kGbCases[0] > 1000); +} + +/* A cluster under six bytes goes whole to its shortest mapped prefix's replacement (a combining + * accent after a mapped letter is dropped); otherwise each character goes to its own. */ +TEST(precompiled_normaliser_matches_tokenizers) { + PrecompiledMap pm; + std::string why; + REQUIRE_EQ(pm.load(kPcCharsmap, &why), (int)RAD_OK); + for (const PcCase& c : kPcCases) { + const std::string got = pm.normalize(c.in); + if (got != c.out) fprintf(stderr, " '%s' -> '%s', want '%s'\n", c.in, got.c_str(), c.out); + CHECK(got == c.out); + } +} + +TEST(precompiled_map_refuses_what_does_not_decode) { + PrecompiledMap pm; + std::string why; + CHECK_EQ(pm.load("not base64!", &why), RAD_E_FORMAT); + CHECK_EQ(pm.load("AAA=", &why), RAD_E_FORMAT); + /* A trie byte count past the map's end. */ + CHECK_EQ(pm.load("AAEAAA==", &why), RAD_E_FORMAT); + CHECK(!pm.ready()); +} + +/* The normaliser inside a Unigram vocabulary, as T5's tokenizer.json declares it: Precompiled, + * a right Strip and a Replace of space runs, then Metaspace. With no tokenizer_config.json beside + * it the end token's id is unset, so encoding adds none (HuggingFace's ids: the same pieces, then + * ). */ +TEST(precompiled_runs_in_a_tokenizer_json_chain) { + const std::string json = std::string(R"({ + "version": "1.0", "added_tokens": [ + {"id": 0, "content": "", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}, + {"id": 1, "content": "", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}, + {"id": 2, "content": "", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}], + "normalizer": {"type": "Sequence", "normalizers": [ + {"type": "Precompiled", "precompiled_charsmap": ")") + kPcCharsmap + R"("}, + {"type": "Strip", "strip_left": false, "strip_right": true}, + {"type": "Replace", "pattern": {"Regex": " {2,}"}, "content": "▁"}]}, + "pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "first", "split": true}, + "post_processor": {"type": "TemplateProcessing", + "single": [{"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "", "type_id": 0}}], + "pair": [{"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "", "type_id": 0}}], + "special_tokens": {"": {"id": "", "ids": [1], "tokens": [""]}}}, + "decoder": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true}, + "model": {"type": "Unigram", "unk_id": 2, "vocab": [ + ["", 0.0], ["", 0.0], ["", 0.0], ["▁", -2.0], ["▁a", -3.0], ["a", -4.0], + ["▁big", -3.0], ["b", -5.0], ["i", -5.0], ["g", -5.0], ["▁apple", -3.0], ["p", -5.0], + ["l", -5.0], ["e", -5.0], ["é", -5.0], ["▁café", -3.0], ["c", -5.0], ["f", -5.0]]} + })"; + VocabBuild vb; + REQUIRE_EQ(parse_tokenizer_json_buf(json, "t5-like", vb), (int)RAD_OK); + auto v = std::make_shared(); + REQUIRE_EQ(v->load(std::move(vb)), (int)RAD_OK); + Tokenizer tok; + REQUIRE_EQ(tok.init(v), (int)RAD_OK); + std::vector ids; + REQUIRE_EQ(tok.encode("A big Apple", ids, true, true), (int)RAD_OK); + CHECK(ids == std::vector({ 4, 6, 10 })); + ids.clear(); + /* The fullwidth A normalises to an A the vocabulary lacks, and the decomposed accent to the + * piece it holds. */ + REQUIRE_EQ(tok.encode("\xef\xbc\xa1 cafe\xcc\x81", ids, true, true), (int)RAD_OK); + CHECK(ids == std::vector({ 3, 2, 15 })); +} + +RAD_TEST_MAIN() diff --git a/tests/r4d_emu/test_lora.cpp b/tests/r4d_emu/test_lora.cpp index 5440bb25..6f398751 100644 --- a/tests/r4d_emu/test_lora.cpp +++ b/tests/r4d_emu/test_lora.cpp @@ -511,6 +511,74 @@ static void test_codes() { checked); } +/* lora_expand_mm (the generators' expand): t rounded to bf16 and summed on the WMMA in its own + * order, so each output is held to the double sum over bf16(t) within one rounding of y plus the + * f32 sum's bound; base rows and everything outside the slice untouched, bit for bit. Mixed slots + * in a tile, an odd M and N, R not a multiple of 32, every y dtype, aligned and not. */ +static void test_expand_mm() { + std::mt19937 rng(41); + struct Sh { int M, N, R, S; uint32_t ydt; bool al; int base_pct; }; + const Sh shapes[] = { + { 1, 20, 16, 1, RAD_BF16, true, 0 }, + { 64, 64, 32, 1, RAD_BF16, true, 0 }, + { 130, 300, 48, 2, RAD_BF16, false, 20 }, + { 77, 9216, 192, 1, RAD_BF16, true, 0 }, /* a fused qkv, one adapter */ + { 200, 1000, 64, 3, RAD_F32, false, 30 }, + { 65, 257, 24, 2, RAD_F16, true, 10 }, + { 512, 2048, 128, 1, RAD_BF16, true, 0 }, + }; + int64_t worst_n = 0; + double worst = 0; + for (const Sh& sh : shapes) { + const std::vector slot = rand_slots(rng, sh.M, sh.S, sh.base_pct); + Expand E = make_expand(rng, sh.M, sh.N, sh.R, sh.S, sh.ydt, slot, sh.al); + std::vector got; + if (run_expand(E, r4d_rad_lora_expand_mm, &got) != RAD_OK) { + fail("expand_mm", fmt("rc (M %d N %d R %d)", sh.M, sh.N, sh.R)); + continue; + } + const size_t e = esz(sh.ydt), ny = (size_t)E.yoff + (size_t)sh.M * E.ldy; + int64_t bad_base = 0, bad_val = 0; + for (size_t i = 0; i < ny; ++i) { + const long long q = (long long)i - E.yoff; + const int m = q < 0 ? -1 : (int)(q / E.ldy), n = q < 0 ? -1 : (int)(q % E.ldy); + const int sl = m >= 0 && m < sh.M ? slot[(size_t)m] : -1; + if (m < 0 || m >= sh.M || n >= sh.N || sl < 0 || sl >= sh.S) { + bad_base += std::memcmp(&got[i * e], &E.y0[i * e], e) != 0; + continue; + } + double acc = 0, terms = 0; + for (int j = 0; j < sh.R; ++j) { + const double tv = rad_bf16_to_f32(rad_f32_to_bf16(E.t[(size_t)m * sh.R + j])); + const double bv = rad_bf16_to_f32(E.lb[((size_t)sl * sh.N + n) * sh.R + j]); + acc += tv * bv; + terms += std::fabs(tv * bv); + } + const double sc = E.sc[(size_t)sl * sh.N + n]; + const double y0 = lora_cases::get(sh.ydt, E.y0.data(), i); + const double want = y0 + sc * acc; + const double g = lora_cases::get(sh.ydt, got.data(), i); + if (std::isnan(y0)) { bad_val += !std::isnan(g); continue; } + const double ulp = sh.ydt == RAD_BF16 ? std::ldexp(1.0, -8) + : sh.ydt == RAD_F16 ? std::ldexp(1.0, -10) : std::ldexp(1.0, -23); + const double tol = std::fabs(want) * ulp + sc * terms * (sh.R + 2) * std::ldexp(1.0, -24) + + 1e-30; + const double r = std::fabs(g - want) / tol; + worst = std::max(worst, r); + if (r > 1.0) ++bad_val; + ++worst_n; + } + if (bad_base) + fail("expand_mm", fmt("touched %lld base-row / outside bytes (M %d N %d R %d %s)", + (long long)bad_base, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt))); + if (bad_val) + fail("expand_mm", fmt("%lld outputs outside the bound (M %d N %d R %d %s)", + (long long)bad_val, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt))); + } + std::printf("lora expand_mm: %zu shapes, %lld outputs, worst |err|/bound %.3f\n", + sizeof(shapes) / sizeof(shapes[0]), (long long)worst_n, worst); +} + int main() { LaunchFn rs = nullptr, re = nullptr; load_libref(&rs, &re); @@ -532,6 +600,7 @@ int main() { test_invariance(); test_all_base(); test_codes(); + test_expand_mm(); std::printf("lora tiled rows: %d failure(s)\n", g_fails); return (T.fails != 0 || g_fails != 0) ? 1 : 0; } diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 052f5835..844b5be8 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -939,7 +939,7 @@ TEST(op_vocabulary) { "dequant", "gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed", /* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */ - "lora_shrink", "lora_expand", + "lora_shrink", "lora_expand", "lora_expand_mm", "grid_embed_aa", "attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key", /* The rest of the QSA indexer and DFlash2's convolution: not fusions, so a model that @@ -958,9 +958,12 @@ TEST(op_vocabulary) { /* The image generator's (arch/qwenimage21): a DiT's modulation and gates, the per-lane * sampler state, the VAE's convolutions and shortcuts, attention over a cached prefix. */ "ln_mod", "gate_add", "timestep_embed", "gather_rows2", "lane_gather", "lane_store", - "randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "l2norm_chan", "d2s_add", - "s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self", + "randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "im2col_nhwc", "l2norm_chan", + "d2s_add", "s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self", "ln_mod_quant_fp8", + /* SDXL's (arch/sdxl): CLIP-L's activation and the k-diffusion sampler over a + * discrete-time denoiser. */ + "gelu_quick", "kd_input", "kd_step", /* The music generator's (arch/minimaxmusic3): the codec's convolutions and activation, the * guided frame sampler and the frame embeddings, the window states of the latent * denoiser, and the index helpers that feed them. */ @@ -5554,6 +5557,136 @@ TEST(flow_euler_guides_previews_and_repaints_as_stated) { CHECK_EQ(state.at(8), 7.0f); CHECK_EQ(state.at(9), 8.0f); } +/* kd_input: entry 0's first step fills its lane with the seed's stream times sqrt(1 + sigma^2) + * and writes x / sqrt(sigma^2 + 1) to its rows and its pair's (entry 1, pair -2, writes nothing of + * its own); entry 2 reads its lane as it is. */ +TEST(kd_input_starts_the_lane_and_scales_by_c_in) { + const int64_t n = 2, st = 2; + const uint64_t seed = 0xabcdef12345ull; + T sg(RAD_F32, {3}); sg.f({3, 3, 1}); + T pair(RAD_I32, {3}); pair.n({1, -2, -1}); + T lane(RAD_I32, {3}); lane.n({0, 1, 2}); + T fl(RAD_I32, {3}); fl.n({1, 0, 0}); + T sd(RAD_U32, {3, 2}); sd.n({(int64_t)(seed & 0xffffffffu), (int64_t)(seed >> 32), 0, 0, 5, 0}); + T cu(RAD_I32, {4}); cu.n({0, 2, 4, 5}); + T state(RAD_F32, {3 * st, n}); state.f({0, 0, 0, 0, 7, 7, 7, 7, 4, -2, 9, 9}); + T y(RAD_F32, {5, n}); + A a; a.t(sg).t(pair).t(lane).t(fl).t(sd).t(cu).t(state).t(y).i("M", 5).i("n", n) + .i("stride", st).s("dtype", "f32"); + CHECK_OK(run("kd_input", a)); + const float init = std::sqrt(1.0f + 9.0f), cin = 1.0f / std::sqrt(9.0f + 1.0f); + for (int64_t k = 0; k < 2; ++k) + for (int64_t c = 0; c < n; ++c) { + const float x0 = rad_philox_normal(seed, (uint64_t)(k * n + c)) * init; + CHECK_EQ(state.at(k * n + c), x0); + CHECK_EQ(y.at(k * n + c), x0 * cin); + CHECK_EQ(y.at((2 + k) * n + c), x0 * cin); + CHECK_EQ(state.at((st + k) * n + c), 7.0f); /* the parked entry's lane */ + } + CHECK_NEAR(y.at(8), 4.0f / std::sqrt(2.0f), 1e-6); CHECK_NEAR(y.at(9), -2.0f / std::sqrt(2.0f), 1e-6); + /* A repaint is refused. */ + T fl2(RAD_I32, {3}); fl2.n({2, 0, 0}); + A b; b.t(sg).t(pair).t(lane).t(fl2).t(sd).t(cu).t(state).t(y).i("M", 5).i("n", n) + .i("stride", st).s("dtype", "f32"); + CHECK_EQ(run("kd_input", b), RAD_E_UNSUPPORTED); +} + +/* kd_step, one element an entry: Euler guided against a parked entry with a preview; Euler + * ancestral at sigma_next 0 and above it; DPM++ 2M's first step, its second-order step and its + * last step; and a v-prediction model. */ +TEST(kd_step_denoises_guides_and_steps_each_sampler) { + const int64_t n = 1, st = 1; + /* entry: 0 euler guided, 1 parked, 2 ancestral to 0, 3 ancestral, 4 dpm first, 5 dpm second, + * 6 dpm last */ + T o(RAD_F32, {7, n}); o.f({0.5f, 0.25f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f}); + T sg(RAD_F32, {7}); sg.f({2, 2, 2, 2, 2, 2, 2}); + T sgn(RAD_F32, {7}); sgn.f({1, 1, 0, 1, 1, 1, 0}); + T sgp(RAD_F32, {7}); sgp.f({0, 0, 0, 0, 0, 4, 4}); + T cfg(RAD_F32, {7}); cfg.f({3, 1, 1, 1, 1, 1, 1}); + T pair(RAD_I32, {7}); pair.n({1, -2, -1, -1, -1, -1, -1}); + T lane(RAD_I32, {7}); lane.n({0, 1, 2, 3, 4, 5, 6}); + T fl(RAD_I32, {7}); fl.n({4, 0, 0, 0, 1, 0, 0}); + T sd(RAD_U32, {7, 2}); sd.n({0, 0, 0, 0, 0, 0, 77, 0, 0, 0, 0, 0, 0, 0}); + T smp(RAD_I32, {7}); smp.n({0, 0, 1, 1, 2, 2, 2}); + T stp(RAD_I32, {7}); stp.n({0, 0, 0, 5, 0, 1, 2}); + T cu(RAD_I32, {8}); cu.n({0, 1, 2, 3, 4, 5, 6, 7}); + T state(RAD_F32, {7, n}); state.f({2, 9, 2, 2, 2, 2, 2}); + T hist(RAD_F32, {7, n}); hist.f({0, 0, 0, 0, 0, 0.5f, 0}); + T prev(RAD_F32, {7, n}); + A a; a.t(o).t(sg).t(sgn).t(sgp).t(cfg).t(pair).t(lane).t(fl).t(sd).t(smp).t(stp).t(cu) + .t(state).t(hist).t(prev).i("M", 7).i("n", n).i("stride", st).s("pred", "eps") + .s("dtype", "f32"); + CHECK_OK(run("kd_step", a)); + /* D = x - sigma o: 1 for the positive entry, 1.5 for its negative, guided 1.5 + 3 (1 - 1.5) = + * 0; Euler: x + (1 - 2)(2 - 0) / 2 = 1. */ + CHECK_EQ(prev.at(0), 0.0f); + CHECK_EQ(state.at(0), 1.0f); + CHECK_EQ(hist.at(0), 0.0f); + CHECK_EQ(state.at(1), 9.0f); /* parked */ + CHECK_EQ(state.at(2), 1.0f); /* ancestral to 0: D */ + { + /* sigma_up = min(1, sqrt(1 (4 - 1) / 4)) = sqrt(0.75), sigma_down = sqrt(1 - 0.75). */ + const float sup = std::sqrt(0.75f), sdown = std::sqrt(1.0f - sup * sup); + const float d = (2.0f - 1.0f) / 2.0f; + const float want = 2.0f + d * (sdown - 2.0f) + rad_philox_normal_s(77, 6, 0) * sup; + CHECK_NEAR(state.at(3), want, 1e-6); + } + /* DPM++ 2M: h = ln 2, so x' = x / 2 - expm1(-ln 2) D = 1 + 0.5 D' with D = 1. */ + CHECK_NEAR(state.at(4), 1.5f, 1e-6); + /* r = (ln 4 - ln 2) / ln 2 = 1: D' = 1.5 D - 0.5 hist = 1.25. */ + CHECK_NEAR(state.at(5), 1.625f, 1e-6); + CHECK_EQ(state.at(6), 1.0f); /* to sigma 0: D */ + CHECK_EQ(hist.at(5), 1.0f); + + /* v-prediction at sigma 1: D = x / 2 - o / sqrt(2), so o = sqrt(2) at x = 2 gives D = 0, and + * Euler to 0 lands on it. */ + T ov(RAD_F32, {1, 1}); ov.f({std::sqrt(2.0f)}); + T s1(RAD_F32, {1}); s1.f({1}); + T z1(RAD_F32, {1}); z1.f({0}); + T c1(RAD_F32, {1}); c1.f({1}); + T p1(RAD_I32, {1}); p1.n({-1}); + T l1(RAD_I32, {1}); l1.n({0}); + T f1(RAD_I32, {1}); f1.n({0}); + T d1(RAD_U32, {1, 2}); d1.n({0, 0}); + T m1(RAD_I32, {1}); m1.n({0}); + T cu1(RAD_I32, {2}); cu1.n({0, 1}); + T x1(RAD_F32, {1, 1}); x1.f({2}); + T h1(RAD_F32, {1, 1}); + A b; b.t(ov).t(s1).t(z1).t(z1).t(c1).t(p1).t(l1).t(f1).t(d1).t(m1).t(m1).t(cu1).t(x1).t(h1) + .i("M", 1).i("n", 1).i("stride", 1).s("pred", "v").s("dtype", "f32"); + CHECK_OK(run("kd_step", b)); + CHECK_NEAR(x1.at(0), 0.0f, 1e-6); + + /* An unknown sampler is refused, and so is a preview without its operand. */ + T bad(RAD_I32, {1}); bad.n({3}); + A c; c.t(ov).t(s1).t(z1).t(z1).t(c1).t(p1).t(l1).t(f1).t(d1).t(bad).t(m1).t(cu1).t(x1).t(h1) + .i("M", 1).i("n", 1).i("stride", 1).s("pred", "v").s("dtype", "f32"); + CHECK_EQ(run("kd_step", c), RAD_E_UNSUPPORTED); + T f4(RAD_I32, {1}); f4.n({4}); + A d; d.t(ov).t(s1).t(z1).t(z1).t(c1).t(p1).t(l1).t(f4).t(d1).t(m1).t(m1).t(cu1).t(x1).t(h1) + .i("M", 1).i("n", 1).i("stride", 1).s("pred", "v").s("dtype", "f32"); + CHECK_EQ(run("kd_step", d), RAD_E_INVAL); +} + +/* gelu_quick rounds the scaled input and the sigmoid to y's dtype before the product. */ +TEST(gelu_quick_rounds_like_torch_in_bf16) { + T x(RAD_BF16, {1, 3}); x.f({1.0f, -2.0f, 0.375f}); + T y(RAD_BF16, {1, 3}); + A a; a.t(x).t(y).i("M", 1).i("n", 3).s("dtype", "bf16"); + CHECK_OK(run("gelu_quick", a)); + for (int i = 0; i < 3; ++i) { + const float v = x.at(i); + const float t = round_dt(RAD_BF16, 1.702f * v); + const float s = round_dt(RAD_BF16, 1.0f / (1.0f + std::exp(-t))); + CHECK_EQ(y.at(i), round_dt(RAD_BF16, v * s)); + } + T xf(RAD_F32, {1, 1}); xf.f({0.5f}); + T yf(RAD_F32, {1, 1}); + A b; b.t(xf).t(yf).i("M", 1).i("n", 1).s("dtype", "f32"); + CHECK_OK(run("gelu_quick", b)); + CHECK_EQ(yf.at(0), 0.5f * (1.0f / (1.0f + std::exp(-0.851f)))); +} + /* chan_affine: lists are bf16 values; fma is bf16(bf16(x * mul) + add) and inv its inverse. */ TEST(chan_affine_reads_bf16_lists_and_inverts) { T x(RAD_BF16, {1, 3}); x.f({1, 1, 1}); @@ -5628,6 +5761,56 @@ TEST(conv2d_nhwc_pads_and_upsamples) { for (int i = 0; i < 16; ++i) CHECK_EQ(y2.at(i), want[i]); } +/* im2col_nhwc: its rows times the weight read as [cout, cin k k] are conv2d_nhwc, at both paddings + * of a stride-2 conv, the upsample and a 1x1, with x at a row pitch. Small integers keep every sum + * exact, so the two orders of accumulation agree to the bit. */ +TEST(im2col_nhwc_times_the_weight_is_the_convolution) { + struct Case { const char* pad; int64_t cin, cout, k, stride, up, H, W; }; + for (const Case& c : { Case{ "same", 3, 4, 3, 1, 1, 5, 6 }, Case{ "same", 2, 3, 3, 2, 1, 7, 5 }, + Case{ "down", 3, 2, 3, 2, 1, 6, 8 }, Case{ "same", 2, 3, 3, 1, 2, 3, 4 }, + Case{ "same", 5, 2, 1, 1, 1, 4, 3 } }) { + const bool down = !std::strcmp(c.pad, "down"); + const int64_t Hv = c.H * c.up, Wv = c.W * c.up, pads = down ? 1 : 2 * (c.k / 2); + const int64_t Ho = (Hv + pads - c.k) / c.stride + 1, Wo = (Wv + pads - c.k) / c.stride + 1; + const int64_t KK = c.cin * c.k * c.k, ld = c.W * c.cin + 3; + std::vector xv((size_t)(c.H * ld)), wv((size_t)(c.cout * KK)), bv((size_t)c.cout); + for (size_t i = 0; i < xv.size(); ++i) xv[i] = (float)((int)(i * 7 % 11) - 5); + for (size_t i = 0; i < wv.size(); ++i) wv[i] = (float)((int)(i * 5 % 7) - 3); + for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)i - 1.0f; + T xbuf(RAD_F32, {c.H, ld}); xbuf.f(xv); + T x = xbuf; + x.t.shape[1] = c.W * c.cin; /* [H, W cin] at a row pitch of ld */ + T w(RAD_F32, {c.cout, c.cin, c.k, c.k}); w.f(wv); + T w2(RAD_F32, {c.cout, KK}); w2.f(wv); + T b(RAD_F32, {c.cout}); b.f(bv); + T y(RAD_F32, {Ho, Wo * c.cout}); + A a; a.t(x).t(w).t(b).t(y).i("M", Ho * Wo).i("cin", c.cin).i("cout", c.cout).i("k", c.k) + .i("stride", c.stride).s("pad", c.pad).i("up", c.up).s("dtype", "f32"); + CHECK_OK(run("conv2d_nhwc", a)); + T u(RAD_F32, {Ho * Wo, KK}); + A d; d.t(x).t(u).i("M", Ho * Wo).i("cin", c.cin).i("k", c.k).i("stride", c.stride) + .s("pad", c.pad).i("up", c.up).s("dtype", "f32"); + CHECK_OK(run("im2col_nhwc", d)); + T g(RAD_F32, {Ho * Wo, c.cout}); + A e; e.t(u).t(w2).t(b).tnull().t(g).i("M", Ho * Wo).i("N", c.cout).i("K", KK) + .s("dtype", "f32"); + CHECK_OK(run("gemm_nt_bias", e)); + for (int64_t i = 0; i < Ho * Wo * c.cout; ++i) CHECK_EQ(g.at(i), y.at(i)); + /* Spot the column order: (ci, i, j), the weight's own. */ + const int64_t oy = Ho - 1, ox = 0, ci = c.cin - 1, i = c.k - 1, j = 0; + const int64_t iy = oy * c.stride + i - (down ? 0 : c.k / 2); + const int64_t ix = ox * c.stride + j - (down ? 0 : c.k / 2); + const float want = iy < 0 || iy >= Hv || ix < 0 || ix >= Wv + ? 0.0f : xv[(size_t)((iy / c.up) * ld + (ix / c.up) * c.cin + ci)]; + CHECK_EQ(u.at((oy * Wo + ox) * KK + (ci * c.k + i) * c.k + j), want); + } + /* y must be exactly the output pixels. */ + T x(RAD_F32, {3, 3}), y(RAD_F32, {8, 9}); + A a; a.t(x).t(y).i("M", 8).i("cin", 1).i("k", 3).i("stride", 1).s("pad", "same").i("up", 1) + .s("dtype", "f32"); + CHECK_EQ(run("im2col_nhwc", a), RAD_E_SHAPE); +} + /* l2norm_chan: each pixel to unit L2, times sqrt(n), times gamma, then the optional silu; an * all-zero pixel stays zero (the 1e-12 floor). */ TEST(l2norm_chan_normalises_each_pixel) { @@ -7797,6 +7980,7 @@ std::vector geometries() { .s("dtype", "fp8a8")), G("lora_shrink", "M", 3, a.i("M", R).i("K", 40).i("R", 8).i("S", 2).s("dtype", "f32")), G("lora_expand", "M", 3, a.i("M", R).i("N", 20).i("R", 8).i("S", 2).s("dtype", "f32")), + G("lora_expand_mm", "M", 3, a.i("M", R).i("N", 20).i("R", 8).i("S", 2).s("dtype", "f32")), G("attn_paged", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2).i("block_size", 4) .i("causal", 1).i("window", 0).s("q_dtype", "f32") .s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)), @@ -7886,15 +8070,21 @@ std::vector geometries() { G("lane_store", "M", 4, a.i("M", R).i("n", 8).i("stride", 8).s("dtype", "bf16")), G("randn_lanes", "M", 4, a.i("M", R).i("n", 8).i("stride", 4).s("dtype", "bf16")), G("flow_euler", "M", 4, a.i("M", R).i("n", 8).i("stride", 4).s("dtype", "bf16")), + G("kd_input", "M", 4, a.i("M", R).i("n", 4).i("stride", 4).s("dtype", "bf16")), + G("kd_step", "M", 4, a.i("M", R).i("n", 4).i("stride", 4).s("pred", "eps") + .s("dtype", "bf16")), G("chan_affine", "M", 2, a.i("M", R).i("n", 3).s("mul", "1 2 3").s("add", "0 1 2") .s("mode", "fma").s("dtype", "bf16")), G("conv2d_nhwc", "M", 16, a.i("M", R).i("cin", 2).i("cout", 3).i("k", 3).i("stride", 1) .s("pad", "same").i("up", 1).s("dtype", "bf16")), + G("im2col_nhwc", "M", 16, a.i("M", R).i("cin", 2).i("k", 3).i("stride", 1) + .s("pad", "same").i("up", 1).s("dtype", "bf16")), G("l2norm_chan", "M", 3, a.i("M", R).i("n", 8).s("act", "silu").s("dtype", "f32")), G("d2s_add", "M", 16, a.i("M", R).i("cin", 4).i("cout", 2).i("ft", 1).s("dtype", "bf16")), G("s2d_avg_add", "M", 16, a.i("M", R).i("cin", 2).i("cout", 4).i("ft", 1).s("dtype", "bf16")), G("to_rgba8", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("gelu_tanh", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), + G("gelu_quick", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("scatter_add_rows", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("attn_prefix_self", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2) .i("block_size", 4).i("causal", 1).s("q_dtype", "bf16") diff --git a/tests/runtime_test.cpp b/tests/runtime_test.cpp index da6fbd01..20464eea 100644 --- a/tests/runtime_test.cpp +++ b/tests/runtime_test.cpp @@ -918,7 +918,7 @@ TEST(raw_operand_carries_the_pointer_and_refuses_an_offset) { * lora_shrink and lora_expand over its own activation, output and rows, but only on a step that * has an adapter row (RadBatch::lora_slot non-null). A step without one, or a draft pass, issues * the gemm alone, the pass an engine without adapters runs; an encoder pass reaching a site is - * refused by name. */ + * refused by name; a generator pass runs its one slot in every row. */ static int k_gemm (const RadArgs* a, RadStream s) { return record("gemm", a, s); } static int k_shrink(const RadArgs* a, RadStream s) { return record("shrink", a, s); } static int k_expand(const RadArgs* a, RadStream s) { return record("expand", a, s); } @@ -933,6 +933,7 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) { const rad_buf ps = f.add_buffer("lora.scale", RAD_F32, 2, 8, 1536); const rad_buf t0 = f.add_buffer("lora.t0", RAD_F32, 16, 4, 2048); const rad_buf t1 = f.add_buffer("lora.t1", RAD_F32, 16, 4, 2304); + const rad_buf rows = f.add_buffer("lora.rows", RAD_I32, 32, 1, 2560); /* [S * 16] */ const rad_op g = f.add_op("gemm_nt", "M", { 64 }, { k_gemm }, { "gemm" }, &g_gemm_schema, { w }); const rad_op sh = f.add_op("lora_shrink", "M", { 64 }, { k_shrink }, { "shrink" }, nullptr, {}); const rad_op ex = f.add_op("lora_expand", "M", { 64 }, { k_expand }, { "expand" }, nullptr, {}); @@ -955,6 +956,8 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) { scr.R = 4; scr.lane[0] = t0; scr.lane[1] = t1; f.P.lora_t.push_back(scr); + f.P.lora_rows = rows; + f.P.lora_rows_n = 16; CHECK_OK(f.start()); auto body = [&](Ctx& c) { @@ -1002,8 +1005,38 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) { c.issue(g, opd, 3, RAD_N_BATCH); }); CHECK_EQ(s, RAD_E_UNSUPPORTED); - CHECK(std::strstr(f.ctx.step_error(), "encoder or generator pass") != nullptr); + CHECK(std::strstr(f.ctx.step_error(), "encoder pass") != nullptr); CHECK_EQ(names(), std::string("gemm")); + + /* A generator pass runs one slot in every row, whatever the gemm's rows are: its slot operand + * is that slot's run of the slot-row table; with no slot, the gemm alone. */ + f.batch.enc = 0; + f.batch.gen = RAD_GEN_PASS_DENOISE; + f.batch.lora_slot = nullptr; + f.ctx.set_gen_lora_slot(-1); + g_rec.clear(); + CHECK_OK(f.step(4, 4, body)); + CHECK_EQ(names(), std::string("gemm")); + f.ctx.set_gen_lora_slot(1); + g_rec.clear(); + CHECK_OK(f.step(4, 5, body)); + REQUIRE_EQ(names(), std::string("gemm shrink expand")); + CHECK(g_rec[1].t[2].data == (void*)((char*)f.ctx.buf_ptr(rows) + 1 * 16 * 4)); + CHECK_EQ(g_rec[1].t[2].shape[0], (int64_t)4); + CHECK(g_rec[2].t[1].data == g_rec[1].t[2].data); + /* Rows past the slot table's run are issued in chunks of it, each over its own rows. */ + f.P.lora_rows_n = 3; + g_rec.clear(); + CHECK_OK(f.step(4, 6, body)); + REQUIRE_EQ(names(), std::string("gemm shrink expand shrink expand")); + CHECK_EQ(g_rec[1].t[0].shape[0], (int64_t)3); + CHECK_EQ(g_rec[3].t[0].shape[0], (int64_t)1); + CHECK(g_rec[3].t[0].data == (void*)((char*)g_rec[1].t[0].data + 3 * 4 * 2)); /* x row 3 */ + CHECK(g_rec[4].t[4].data == (void*)((char*)g_rec[2].t[4].data + 3 * 8 * 2)); /* y row 3 */ + CHECK(g_rec[3].t[2].data == (void*)((char*)f.ctx.buf_ptr(rows) + 1 * 3 * 4)); + f.P.lora_rows_n = 16; + f.ctx.set_gen_lora_slot(-1); + f.batch.gen = 0; } /* Site is a property of the weights (spec §5.1). A domain with no kernel in some band is refused, diff --git a/tests/server_fakes.h b/tests/server_fakes.h index 51f183d0..9ccaad88 100644 --- a/tests/server_fakes.h +++ b/tests/server_fakes.h @@ -594,6 +594,14 @@ struct FakeImageGen : IImageGen { } int64_t queued() const override { return 0; } int64_t running() const override { return 0; } + /* The second tokenizer: one id a byte, then 1 (an end token). */ + int encode_aux(const std::string& text, std::vector* out) const override { + if (!inf.aux_tokens) return RAD_E_UNSUPPORTED; + out->clear(); + for (unsigned char c : text) out->push_back(100 + c); + out->push_back(1); + return RAD_OK; + } }; /* An audio generator that finishes every request on submit: `windows` windows of `per_window` diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index 78a8a144..a5a6967b 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -88,13 +88,14 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second); } const std::set> want = { - { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" }, { "flux3distilled", "" }, + { "anima", "" }, { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" }, + { "flux3distilled", "" }, { "gemma3", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, { "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" }, - { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } }; + { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" }, { "sdxl", "" } }; std::set> got; for (const auto& [k, name] : keys) got.insert(k); if (got != want) diff --git a/tests/text_test.cpp b/tests/text_test.cpp index 9e7e9c45..ebbda93d 100644 --- a/tests/text_test.cpp +++ b/tests/text_test.cpp @@ -869,6 +869,40 @@ struct TestStrings : StringSink { }; } /* namespace */ +namespace { + +/* `in` through the .rad's vocab section and back into `out`. */ +int round_trip(const VocabBuild& in, VocabBuild* out) { + TestStrings strings; + std::vector section; + /* Lay the file out as rad-convert does: header, string blob, vocab section. The serialiser + * writes absolute offsets, so the section must know where it lands before it is written, and + * it lands 8-aligned, as the writer places it, because the reader takes the header as a typed + * pointer into the file. */ + const uint64_t str_off = sizeof(RadFileHeader); + RAD_TRY(vocab_serialize(in, strings, 0, section)); /* pass 1: sizes only */ + const uint64_t sec_off = (str_off + strings.blob.size() + 7) & ~(uint64_t)7; + + TestStrings strings2; + section.clear(); + RAD_TRY(vocab_serialize(in, strings2, sec_off, section)); + + std::vector file(sec_off + section.size(), 0); + RadFileHeader* fh = reinterpret_cast(file.data()); + fh->magic = RAD_MAGIC; + fh->version = RAD_FORMAT_VER; + fh->str_off = str_off; + fh->str_bytes = strings2.blob.size(); + fh->vocab_off = sec_off; + fh->vocab_bytes = section.size(); + std::memcpy(file.data() + str_off, strings2.blob.data(), strings2.blob.size()); + std::memcpy(file.data() + sec_off, section.data(), section.size()); + return vocab_deserialize(file.data(), file.size(), + reinterpret_cast(file.data() + sec_off), *out); +} + +} /* namespace */ + TEST(vocab_section_round_trip) { VocabBuild in; in.kind = RAD_TOK_BPE; @@ -885,35 +919,8 @@ TEST(vocab_section_round_trip) { VocabStep s2; s2.kind = RAD_PRE_BYTELEVEL; s2.flags = 2; in.steps.push_back(s2); VocabStep s3; s3.kind = RAD_DEC_BYTELEVEL; in.steps.push_back(s3); - TestStrings strings; - std::vector section; - /* Lay the file out as rad-convert does: header, string blob, vocab section. The serialiser - * writes absolute offsets, so the section must know where it lands before it is written, and - * it lands 8-aligned, as the writer places it, because the reader takes the header as a typed - * pointer into the file. */ - const uint64_t str_off = sizeof(RadFileHeader); - CHECK_OK(vocab_serialize(in, strings, 0, section)); /* pass 1: sizes only */ - const uint64_t sec_off = (str_off + strings.blob.size() + 7) & ~(uint64_t)7; - - TestStrings strings2; - section.clear(); - CHECK_OK(vocab_serialize(in, strings2, sec_off, section)); - - std::vector file(sec_off + section.size(), 0); - RadFileHeader* fh = reinterpret_cast(file.data()); - fh->magic = RAD_MAGIC; - fh->version = RAD_FORMAT_VER; - fh->str_off = str_off; - fh->str_bytes = strings2.blob.size(); - fh->vocab_off = sec_off; - fh->vocab_bytes = section.size(); - std::memcpy(file.data() + str_off, strings2.blob.data(), strings2.blob.size()); - std::memcpy(file.data() + sec_off, section.data(), section.size()); - VocabBuild out; - CHECK_OK(vocab_deserialize(file.data(), file.size(), - reinterpret_cast(file.data() + sec_off), - out)); + CHECK_OK(round_trip(in, &out)); CHECK_EQ(out.kind, in.kind); CHECK(out.tokens == in.tokens); @@ -985,7 +992,7 @@ TEST(parse_tokenizer_json_chain) { * interpreted rather than hashed. */ TEST(parse_tokenizer_json_refuses_unknown_components) { const char* js = R"JSON({ - "normalizer": { "type": "Precompiled", "precompiled_charsmap": "AAAA" }, + "normalizer": { "type": "StripAccents" }, "pre_tokenizer": { "type": "ByteLevel" }, "model": { "type": "BPE", "vocab": {"a": 0}, "merges": [] } })JSON"; @@ -995,7 +1002,7 @@ TEST(parse_tokenizer_json_refuses_unknown_components) { /* A step the tokenizer does not run is refused at load, not passed over on every encode. */ TEST(a_vocab_with_an_unknown_step_does_not_load) { - for (uint32_t kind : { 9u, 39u, 70u, 200u }) { + for (uint32_t kind : { 10u, 41u, 70u, 200u }) { VocabBuild vb; vb.kind = RAD_TOK_BPE; vb.tokens = { "a" }; @@ -1498,7 +1505,7 @@ TEST(decompose_and_compose_are_inverses_over_the_canonical_forms) { namespace { -/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers 0.23.2) */ +/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers 0.23.3) */ struct DecodeGolden { const char* fixture; std::vector ids; const char* text; }; struct PretokGolden { const char* name; const char* json; std::vector ids; }; @@ -1676,6 +1683,49 @@ const std::vector>& metaspace_special_golde return v; } +const char* const kClipLike = R"JSON({"added_tokens": [{"id": 620, "content": "<|startoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": true}, {"id": 621, "content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}], "normalizer": {"type": "Sequence", "normalizers": [{"type": "NFC"}, {"type": "Replace", "pattern": {"Regex": "\\s+"}, "content": " "}, {"type": "Lowercase"}]}, "pre_tokenizer": {"type": "Sequence", "pretokenizers": [{"type": "Split", "pattern": {"Regex": "'s|'t|'re|'ve|'m|'ll|'d|[\\p{L}]+|[\\p{N}]|[^\\s\\p{L}\\p{N}]+"}, "behavior": "Removed", "invert": true}, {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": true}]}, "post_processor": {"type": "RobertaProcessing", "sep": ["<|endoftext|>", 621], "cls": ["<|startoftext|>", 620], "trim_offsets": false, "add_prefix_space": false}, "decoder": {"type": "ByteLevel", "add_prefix_space": true, "trim_offsets": true}, "model": {"type": "BPE", "dropout": null, "unk_token": "<|endoftext|>", "continuing_subword_prefix": "", "end_of_word_suffix": "", "fuse_unk": false, "vocab": {"!": 0, "\"": 1, "#": 2, "$": 3, "%": 4, "&": 5, "'": 6, "(": 7, ")": 8, "*": 9, "+": 10, ",": 11, "-": 12, ".": 13, "/": 14, "0": 15, "1": 16, "2": 17, "3": 18, "4": 19, "5": 20, "6": 21, "7": 22, "8": 23, "9": 24, ":": 25, ";": 26, "<": 27, "=": 28, ">": 29, "?": 30, "@": 31, "A": 32, "B": 33, "C": 34, "D": 35, "E": 36, "F": 37, "G": 38, "H": 39, "I": 40, "J": 41, "K": 42, "L": 43, "M": 44, "N": 45, "O": 46, "P": 47, "Q": 48, "R": 49, "S": 50, "T": 51, "U": 52, "V": 53, "W": 54, "X": 55, "Y": 56, "Z": 57, "[": 58, "\\": 59, "]": 60, "^": 61, "_": 62, "`": 63, "a": 64, "b": 65, "c": 66, "d": 67, "e": 68, "f": 69, "g": 70, "h": 71, "i": 72, "j": 73, "k": 74, "l": 75, "m": 76, "n": 77, "o": 78, "p": 79, "q": 80, "r": 81, "s": 82, "t": 83, "u": 84, "v": 85, "w": 86, "x": 87, "y": 88, "z": 89, "{": 90, "|": 91, "}": 92, "~": 93, "¡": 94, "¢": 95, "£": 96, "¤": 97, "¥": 98, "¦": 99, "§": 100, "¨": 101, "©": 102, "ª": 103, "«": 104, "¬": 105, "®": 106, "¯": 107, "°": 108, "±": 109, "²": 110, "³": 111, "´": 112, "µ": 113, "¶": 114, "·": 115, "¸": 116, "¹": 117, "º": 118, "»": 119, "¼": 120, "½": 121, "¾": 122, "¿": 123, "À": 124, "Á": 125, "Â": 126, "Ã": 127, "Ä": 128, "Å": 129, "Æ": 130, "Ç": 131, "È": 132, "É": 133, "Ê": 134, "Ë": 135, "Ì": 136, "Í": 137, "Î": 138, "Ï": 139, "Ð": 140, "Ñ": 141, "Ò": 142, "Ó": 143, "Ô": 144, "Õ": 145, "Ö": 146, "×": 147, "Ø": 148, "Ù": 149, "Ú": 150, "Û": 151, "Ü": 152, "Ý": 153, "Þ": 154, "ß": 155, "à": 156, "á": 157, "â": 158, "ã": 159, "ä": 160, "å": 161, "æ": 162, "ç": 163, "è": 164, "é": 165, "ê": 166, "ë": 167, "ì": 168, "í": 169, "î": 170, "ï": 171, "ð": 172, "ñ": 173, "ò": 174, "ó": 175, "ô": 176, "õ": 177, "ö": 178, "÷": 179, "ø": 180, "ù": 181, "ú": 182, "û": 183, "ü": 184, "ý": 185, "þ": 186, "ÿ": 187, "Ā": 188, "ā": 189, "Ă": 190, "ă": 191, "Ą": 192, "ą": 193, "Ć": 194, "ć": 195, "Ĉ": 196, "ĉ": 197, "Ċ": 198, "ċ": 199, "Č": 200, "č": 201, "Ď": 202, "ď": 203, "Đ": 204, "đ": 205, "Ē": 206, "ē": 207, "Ĕ": 208, "ĕ": 209, "Ė": 210, "ė": 211, "Ę": 212, "ę": 213, "Ě": 214, "ě": 215, "Ĝ": 216, "ĝ": 217, "Ğ": 218, "ğ": 219, "Ġ": 220, "ġ": 221, "Ģ": 222, "ģ": 223, "Ĥ": 224, "ĥ": 225, "Ħ": 226, "ħ": 227, "Ĩ": 228, "ĩ": 229, "Ī": 230, "ī": 231, "Ĭ": 232, "ĭ": 233, "Į": 234, "į": 235, "İ": 236, "ı": 237, "IJ": 238, "ij": 239, "Ĵ": 240, "ĵ": 241, "Ķ": 242, "ķ": 243, "ĸ": 244, "Ĺ": 245, "ĺ": 246, "Ļ": 247, "ļ": 248, "Ľ": 249, "ľ": 250, "Ŀ": 251, "ŀ": 252, "Ł": 253, "ł": 254, "Ń": 255, "!": 256, "\"": 257, "#": 258, "$": 259, "%": 260, "&": 261, "'": 262, "(": 263, ")": 264, "*": 265, "+": 266, ",": 267, "-": 268, ".": 269, "/": 270, "0": 271, "1": 272, "2": 273, "3": 274, "4": 275, "5": 276, "6": 277, "7": 278, "8": 279, "9": 280, ":": 281, ";": 282, "<": 283, "=": 284, ">": 285, "?": 286, "@": 287, "A": 288, "B": 289, "C": 290, "D": 291, "E": 292, "F": 293, "G": 294, "H": 295, "I": 296, "J": 297, "K": 298, "L": 299, "M": 300, "N": 301, "O": 302, "P": 303, "Q": 304, "R": 305, "S": 306, "T": 307, "U": 308, "V": 309, "W": 310, "X": 311, "Y": 312, "Z": 313, "[": 314, "\\": 315, "]": 316, "^": 317, "_": 318, "`": 319, "a": 320, "b": 321, "c": 322, "d": 323, "e": 324, "f": 325, "g": 326, "h": 327, "i": 328, "j": 329, "k": 330, "l": 331, "m": 332, "n": 333, "o": 334, "p": 335, "q": 336, "r": 337, "s": 338, "t": 339, "u": 340, "v": 341, "w": 342, "x": 343, "y": 344, "z": 345, "{": 346, "|": 347, "}": 348, "~": 349, "¡": 350, "¢": 351, "£": 352, "¤": 353, "¥": 354, "¦": 355, "§": 356, "¨": 357, "©": 358, "ª": 359, "«": 360, "¬": 361, "®": 362, "¯": 363, "°": 364, "±": 365, "²": 366, "³": 367, "´": 368, "µ": 369, "¶": 370, "·": 371, "¸": 372, "¹": 373, "º": 374, "»": 375, "¼": 376, "½": 377, "¾": 378, "¿": 379, "À": 380, "Á": 381, "Â": 382, "Ã": 383, "Ä": 384, "Å": 385, "Æ": 386, "Ç": 387, "È": 388, "É": 389, "Ê": 390, "Ë": 391, "Ì": 392, "Í": 393, "Î": 394, "Ï": 395, "Ð": 396, "Ñ": 397, "Ò": 398, "Ó": 399, "Ô": 400, "Õ": 401, "Ö": 402, "×": 403, "Ø": 404, "Ù": 405, "Ú": 406, "Û": 407, "Ü": 408, "Ý": 409, "Þ": 410, "ß": 411, "à": 412, "á": 413, "â": 414, "ã": 415, "ä": 416, "å": 417, "æ": 418, "ç": 419, "è": 420, "é": 421, "ê": 422, "ë": 423, "ì": 424, "í": 425, "î": 426, "ï": 427, "ð": 428, "ñ": 429, "ò": 430, "ó": 431, "ô": 432, "õ": 433, "ö": 434, "÷": 435, "ø": 436, "ù": 437, "ú": 438, "û": 439, "ü": 440, "ý": 441, "þ": 442, "ÿ": 443, "Ā": 444, "ā": 445, "Ă": 446, "ă": 447, "Ą": 448, "ą": 449, "Ć": 450, "ć": 451, "Ĉ": 452, "ĉ": 453, "Ċ": 454, "ċ": 455, "Č": 456, "č": 457, "Ď": 458, "ď": 459, "Đ": 460, "đ": 461, "Ē": 462, "ē": 463, "Ĕ": 464, "ĕ": 465, "Ė": 466, "ė": 467, "Ę": 468, "ę": 469, "Ě": 470, "ě": 471, "Ĝ": 472, "ĝ": 473, "Ğ": 474, "ğ": 475, "Ġ": 476, "ġ": 477, "Ģ": 478, "ģ": 479, "Ĥ": 480, "ĥ": 481, "Ħ": 482, "ħ": 483, "Ĩ": 484, "ĩ": 485, "Ī": 486, "ī": 487, "Ĭ": 488, "ĭ": 489, "Į": 490, "į": 491, "İ": 492, "ı": 493, "IJ": 494, "ij": 495, "Ĵ": 496, "ĵ": 497, "Ķ": 498, "ķ": 499, "ĸ": 500, "Ĺ": 501, "ĺ": 502, "Ļ": 503, "ļ": 504, "Ľ": 505, "ľ": 506, "Ŀ": 507, "ŀ": 508, "Ł": 509, "ł": 510, "Ń": 511, "in": 512, "of": 513, "at": 514, "ho": 515, "ing": 516, "st": 517, "ta": 518, "ast": 519, "do": 520, "gi": 521, "hot": 522, "ie": 523, "it": 524, "phot": 525, "ra": 526, "un": 527, "'s": 528, "'t": 529, "ain": 530, "al": 531, "an": 532, "ar": 533, "au": 534, "aint": 535, "ainting": 536, "ali": 537, "alit": 538, "ality": 539, "art": 540, "aste": 541, "astr": 542, "aster": 543, "asterp": 544, "asterpie": 545, "asterpiec": 546, "asterpiece": 547, "astro": 548, "astron": 549, "astronau": 550, "astronaut": 551, "be": 552, "bes": 553, "best": 554, "cat": 555, "de": 556, "di": 557, "ding": 558, "deta": 559, "detai": 560, "detail": 561, "detaile": 562, "detailed": 563, "digi": 564, "digita": 565, "digital": 566, "dog": 567, "don": 568, "er": 569, "et": 570, "gh": 571, "gra": 572, "ghl": 573, "ghly": 574, "gir": 575, "girl": 576, "grap": 577, "graph": 578, "he": 579, "hi": 580, "highly": 581, "hor": 582, "hors": 583, "horse": 584, "iding": 585, "iew": 586, "iewer": 587, "ins": 588, "king": 589, "lo": 590, "lo": 591, "loo": 592, "looking": 593, "masterpiece": 594, "mo": 595, "moun": 596, "mounta": 597, "mountains": 598, "ograph": 599, "olo": 600, "op": 601, "or": 602, "ort": 603, "ortra": 604, "ortrait": 605, "painting": 606, "portrait": 607, "photo": 608, "photograph": 609, "qu": 610, "quality": 611, "riding": 612, "set": 613, "solo": 614, "sun": 615, "stop": 616, "sunset": 617, "the": 618, "viewer": 619, "<|startoftext|>": 620, "<|endoftext|>": 621}, "merges": ["i n", "o f", "a t", "h o", "in g", "s t", "t a", "a st", "d o", "g i", "ho t", "i e", "i t", "p hot", "r a", "u n", "' s", "' t", "a in", "a l", "a n", "a r", "a u", "ain t", "aint ing", "al i", "ali t", "alit y", "ar t", "ast e", "ast r", "aste r", "aster p", "asterp ie", "asterpie c", "asterpiec e", "astr o", "astro n", "astron au", "astronau t", "b e", "be s", "bes t", "c at", "d e", "d i", "d ing", "de ta", "deta i", "detai l", "detail e", "detaile d", "di gi", "digi ta", "digita l", "do g", "do n", "e r", "e t", "g h", "g ra", "gh l", "ghl y", "gi r", "gir l", "gra p", "grap h", "h e", "h i", "hi ghly", "ho r", "hor s", "hors e", "i ding", "ie w", "iew er", "in s", "k ing", "l o", "l o", "lo o", "loo king", "m asterpiece", "m o", "mo un", "moun ta", "mounta ins", "o graph", "o lo", "o p", "o r", "or t", "ort ra", "ortra it", "p ainting", "p ortrait", "phot o", "phot ograph", "q u", "qu ality", "r iding", "s et", "s olo", "s un", "st op", "sun set", "t he", "v iewer"]}})JSON"; + +const std::vector& clip_goldens() { + static const std::vector v = { + { "a photo of a cat", { 320, 608, 513, 320, 555 }, { 620, 320, 608, 513, 320, 555, 621 } }, + { "1girl, solo, masterpiece, best quality, (absurdres:1.2), looking_at_viewer, hatsune_miku", { 272, 576, 267, 614, 267, 594, 267, 554, 611, 267, 263, 64, 65, 82, 84, 81, 67, 81, 68, 338, 281, 272, 269, 273, 8, 267, 593, 318, 514, 318, 619, 267, 71, 64, 83, 615, 324, 318, 76, 72, 74, 340 }, { 620, 272, 576, 267, 614, 267, 594, 267, 554, 611, 267, 263, 64, 65, 82, 84, 81, 67, 81, 68, 338, 281, 272, 269, 273, 8, 267, 593, 318, 514, 318, 619, 267, 71, 64, 83, 615, 324, 318, 76, 72, 74, 340, 621 } }, + { "A Photograph of the Mountains, it's DON'T stop", { 320, 609, 513, 618, 598, 267, 524, 528, 568, 529, 616 }, { 620, 320, 609, 513, 618, 598, 267, 524, 528, 568, 529, 616, 621 } }, + { "1024x1024 2.5 v1.0", { 272, 271, 273, 275, 343, 272, 271, 273, 275, 273, 269, 276, 341, 272, 269, 271 }, { 620, 272, 271, 273, 275, 343, 272, 271, 273, 275, 273, 269, 276, 341, 272, 269, 271, 621 } }, + { "Caf\xc3\xa9 na\xc3\xafve \xe6\x9d\xb1\xe4\xba\xac\xe3\x82\xbf\xe3\x83\xaf\xe3\x83\xbc \xec\x84\x9c\xec\x9a\xb8 \xf0\x9f\x8d\xa3\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7 \xc4\xb0stanbul \xce\xa3\xce\x8a\xce\xa3\xce\xa5\xce\xa6\xce\x9f\xce\xa3", { 66, 64, 69, 127, 358, 77, 64, 127, 107, 85, 324, 162, 251, 109, 160, 118, 105, 159, 224, 123, 159, 225, 107, 159, 225, 376, 168, 226, 250, 168, 248, 372, 172, 253, 235, 96, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 356, 328, 136, 485, 517, 64, 77, 65, 84, 331, 139, 225, 138, 107, 139, 225, 139, 227, 139, 228, 138, 123, 139, 481 }, { 620, 66, 64, 69, 127, 358, 77, 64, 127, 107, 85, 324, 162, 251, 109, 160, 118, 105, 159, 224, 123, 159, 225, 107, 159, 225, 376, 168, 226, 250, 168, 248, 372, 172, 253, 235, 96, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 356, 328, 136, 485, 517, 64, 77, 65, 84, 331, 139, 225, 138, 107, 139, 225, 139, 227, 139, 228, 138, 123, 139, 481, 621 } }, + { " many spaces\t\ttabs\n\nnewlines ", { 76, 64, 77, 344, 82, 79, 64, 66, 68, 338, 518, 65, 338, 77, 68, 86, 75, 512, 68, 338 }, { 620, 76, 64, 77, 344, 82, 79, 64, 66, 68, 338, 518, 65, 338, 77, 68, 86, 75, 512, 68, 338, 621 } }, + { "...!!!??? ((()))[[]]", { 13, 13, 13, 0, 0, 0, 30, 30, 286, 7, 7, 7, 8, 8, 8, 58, 58, 60, 316 }, { 620, 13, 13, 13, 0, 0, 0, 30, 30, 286, 7, 7, 7, 8, 8, 8, 58, 58, 60, 316, 621 } }, + { "", { }, { 620, 621 } }, + { "a", { 320 }, { 620, 320, 621 } }, + { "<|startoftext|>a cat<|endoftext|>", { 620, 320, 555, 621 }, { 620, 620, 320, 555, 621, 621 } }, + { "x<|StartOfText|>y", { 343, 620, 344 }, { 620, 343, 620, 344, 621 } }, + { "ab catcat", { 320, 27, 270, 342, 285, 321, 66, 64, 83, 555 }, { 620, 320, 27, 270, 342, 285, 321, 66, 64, 83, 555, 621 } }, + { "photographphotograph", { 525, 78, 577, 71, 609 }, { 620, 525, 78, 577, 71, 609, 621 } }, + { "it'sit's'll", { 524, 528, 524, 528, 6, 75, 331 }, { 620, 524, 528, 524, 528, 6, 75, 331, 621 } }, + }; + return v; +} + +/* The decode of every CLIP golden with special tokens skipped, as HF reports it. */ +const std::vector& clip_decoded() { + static const std::vector v = { + "aphotoofacat", + "1girl,solo,masterpiece,bestquality,(absurdres:1.2),looking_at_viewer,hatsune_miku", + "aphotographofthemountains,it'sdon'tstop", + "1024x10242.5v1.0", + "caf\xc3\xa9na\xc3\xafve\xe6\x9d\xb1\xe4\xba\xac\xe3\x82\xbf\xe3\x83\xaf\xe3\x83\xbc\xec\x84\x9c\xec\x9a\xb8\xf0\x9f\x8d\xa3\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7i\xcc\x87stanbul\xcf\x83\xce\xaf\xcf\x83\xcf\x85\xcf\x86\xce\xbf\xcf\x83", + "manyspacestabsnewlines", + "...!!!???((()))[[]]", + "", + "a", + "acat", + "xy", + "aw>bcatcat", + "photographphotograph", + "it'sit's'll", + }; + return v; +} + /* END generated by mk_tokenizer_goldens.py */ } /* namespace */ @@ -1794,6 +1844,58 @@ TEST(the_gemma_shaped_tokenizer_encodes_as_huggingface) { CHECK_EQ(k, gemma_decoded().size()); } +/* CLIP's shape (Stable Diffusion's text encoders): an NFC / whitespace-collapse / Lowercase + * normaliser, a Split that keeps letter runs, single digits and punctuation runs, ByteLevel, BPE + * whose word-final symbols carry the "" suffix, RobertaProcessing `<|startoftext|> $A + * <|endoftext|>`, and `<|startoftext|>` matched in the normalised text (so `<|StartOfText|>` is it + * too). Encoded with and without the framing and decoded, against HuggingFace. */ +TEST(the_clip_shaped_tokenizer_encodes_as_huggingface) { + VocabBuild vb; + REQUIRE(parse_tokenizer_json_buf(kClipLike, "clip_like", vb) >= 0); + CHECK(vb.add_bos); + CHECK(vb.add_eos); + CHECK_EQ(vb.bos, 620); + CHECK_EQ(vb.eos, 621); + /* Served as a container holds it: the suffix and the normalised added token are steps. */ + VocabBuild baked; + REQUIRE(round_trip(vb, &baked) == RAD_OK); + auto v = std::make_shared(); + REQUIRE(v->load(std::move(baked)) >= 0); + Tokenizer t; + CHECK_OK(t.init(v)); + size_t k = 0; + for (const EncodeGolden& g : clip_goldens()) { + std::vector plain, special; + CHECK_OK(t.encode(g.text, plain, /*add_special=*/false, /*parse_special=*/true)); + CHECK_OK(t.encode(g.text, special, /*add_special=*/true, /*parse_special=*/true)); + CHECK(plain == g.ids); + /* A text opening with the BOS token gets a second one, as in HuggingFace: CLIP's BOS + * is matched in the normalised text, after Tokenizer::encode decides on adding one. */ + CHECK(special == g.with_special); + if (plain != g.ids) { + std::string got; + for (int32_t id : plain) got += std::to_string(id) + ","; + fprintf(stderr, " \"%s\": %s\n", g.text, got.c_str()); + } + CHECK_EQ(t.decode(g.with_special), std::string(clip_decoded()[k])); + CHECK_EQ(streamed(v, g.with_special), std::string(clip_decoded()[k])); + ++k; + } + CHECK_EQ(k, clip_decoded().size()); + + /* A token matched in the normalised text follows parse_special as the raw ones do, through + * the segment cache as well: the same long text with it off and then on. */ + std::string text; + for (int i = 0; i < 30; ++i) text += "a photo of a cat <|StartOfText|> "; + for (int pass = 0; pass < 2; ++pass) { + std::vector off, on; + CHECK_OK(t.encode(text, off, false, /*parse_special=*/false)); + CHECK_OK(t.encode(text, on, false, /*parse_special=*/true)); + CHECK_EQ(std::count(off.begin(), off.end(), 620), (ptrdiff_t)0); + CHECK_EQ(std::count(on.begin(), on.end(), 620), (ptrdiff_t)30); + } +} + /* Metaspace's "first" scheme prepends the replacement only where the text starts: a segment after * a special token ("[INST]Hi", "Hi") has a non-zero original offset in HuggingFace and gets * none, where "always" gives every segment one. Encoded through the segment cache both cold and @@ -1851,7 +1953,6 @@ TEST(parse_tokenizer_json_refuses_values_it_cannot_honour) { bpe(ws, R"(, "decoder": {"type": "Sequence", "decoders": [{"type": "Fuse"},)" R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0},)" R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0}]})"), - bpe(ws, "", R"(, "end_of_word_suffix": "")"), bpe(ws, "", R"(, "continuing_subword_prefix": "##")"), bpe(ws, "", R"(, "dropout": 0.1)"), bpe(ws, added(R"("single_word": true, "lstrip": false, "rstrip": false, "normalized": false)")), @@ -1878,6 +1979,11 @@ TEST(parse_tokenizer_json_refuses_values_it_cannot_honour) { bpe(ws, R"(, "decoder": {"type": "Sequence", "decoders": [{"type": "Fuse"},)" R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0}]})"), bpe(ws, "", R"(, "dropout": null, "continuing_subword_prefix": null, "end_of_word_suffix": null)"), + bpe(ws, "", R"(, "continuing_subword_prefix": "", "end_of_word_suffix": "")"), + /* Lower case already, so the Lowercase normaliser leaves its spelling alone. */ + bpe(ws, R"(, "normalizer": {"type": "Lowercase"}, "added_tokens": [{"id": 3, "content": "x",)" + R"( "special": true, "single_word": false, "lstrip": false, "rstrip": false,)" + R"( "normalized": true}])"), }; for (const std::string& js : accepted) { VocabBuild vb; diff --git a/tools/gen_grapheme_ucd.py b/tools/gen_grapheme_ucd.py new file mode 100644 index 00000000..c30fcb0f --- /dev/null +++ b/tools/gen_grapheme_ucd.py @@ -0,0 +1,76 @@ +"""gen_grapheme_ucd.py -- writes core/text/tokenizer_grapheme_ucd.cpp, the Unicode properties the +extended grapheme cluster rules (UAX #29) read. + +HuggingFace tokenizers' `Precompiled` normaliser walks its text by extended grapheme clusters +(the unicode-segmentation crate, Unicode 16.0.0), so the cluster boundaries are part of what a +SentencePiece-derived tokenizer.json means. The tables come from the UCD files of that version: + + https://www.unicode.org/Public/16.0.0/ucd/auxiliary/GraphemeBreakProperty.txt + https://www.unicode.org/Public/16.0.0/ucd/emoji/emoji-data.txt + https://www.unicode.org/Public/16.0.0/ucd/DerivedCoreProperties.txt + + python3 tools/gen_grapheme_ucd.py > core/text/tokenizer_grapheme_ucd.cpp +""" +import os +import sys + +GCB = ["Other", "CR", "LF", "Control", "Extend", "ZWJ", "Regional_Indicator", "Prepend", + "SpacingMark", "L", "V", "T", "LV", "LVT"] +INCB = ["None", "Linker", "Consonant", "Extend"] + + +def ranges(path, want): + """(first, last, value) for every line whose property is `want(prop)` (a value or None).""" + out = [] + for line in open(path, encoding="utf-8"): + line = line.split("#", 1)[0].strip() + if not line: + continue + f = [x.strip() for x in line.split(";")] + v = want(f[1:]) + if v is None: + continue + a = f[0].split("..") + lo = int(a[0], 16) + hi = int(a[1], 16) if len(a) > 1 else lo + out.append((lo, hi, v)) + out.sort() + merged = [] + for lo, hi, v in out: + if merged and merged[-1][2] == v and merged[-1][1] + 1 == lo: + merged[-1] = (merged[-1][0], hi, v) + else: + merged.append((lo, hi, v)) + return merged + + +def main(): + d = sys.argv[1] + gcb = ranges(os.path.join(d, "GraphemeBreakProperty.txt"), + lambda f: GCB.index(f[0]) if f[0] in GCB else None) + pict = ranges(os.path.join(d, "emoji-data.txt"), + lambda f: 1 if f[0] == "Extended_Pictographic" else None) + incb = ranges(os.path.join(d, "DerivedCoreProperties.txt"), + lambda f: INCB.index(f[1]) if f[0] == "InCB" and f[1] in INCB else None) + w = sys.stdout.write + w("/* tokenizer_grapheme_ucd.cpp -- GENERATED by tools/gen_grapheme_ucd.py from the Unicode " + "16.0.0 UCD;\n * do not edit. The properties UAX #29's extended grapheme cluster rules read " + "(tokenizer_grapheme.h). */\n") + w('#include "text/tokenizer_grapheme.h"\n\nnamespace rad {\nnamespace ucd {\n\n') + w("const GbRange k_gcb[] = {\n") + for lo, hi, v in gcb: + w(" { 0x%X, 0x%X, %d },\n" % (lo, hi, v)) + w("};\nconst size_t k_gcb_n = sizeof k_gcb / sizeof k_gcb[0];\n\n") + w("const GbRange k_ext_pict[] = {\n") + for lo, hi, v in pict: + w(" { 0x%X, 0x%X, %d },\n" % (lo, hi, v)) + w("};\nconst size_t k_ext_pict_n = sizeof k_ext_pict / sizeof k_ext_pict[0];\n\n") + w("const GbRange k_incb[] = {\n") + for lo, hi, v in incb: + w(" { 0x%X, 0x%X, %d },\n" % (lo, hi, v)) + w("};\nconst size_t k_incb_n = sizeof k_incb / sizeof k_incb[0];\n\n") + w("} /* namespace ucd */\n} /* namespace rad */\n") + + +if __name__ == "__main__": + main() diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index b56b93ca..1b5a282f 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -121,6 +121,13 @@ void usage() { " Declare checks the recipe against the kernels it resolves\n" " --tokenizer F tokenizer.json; its declared chain is baked instead of being\n" " reconstructed from a pre-tokenizer name\n" + " --tokenizer2 F a second tokenizer.json, baked as the container's second vocab:\n" + " a generator that reads its prompt through two tokenizers\n" + " --add FILE one more .safetensors file merged into the checkpoint, its tensor\n" + " names kept: a release shipped as separate single files (a\n" + " diffusion model, a text encoder and a VAE). Repeatable\n" + " --config DIR read config.json, generation_config.json and tokenizer.json from\n" + " DIR, for a single-file checkpoint that ships none of them\n" " --imatrix F llama.cpp imatrix: the expert-popularity profile, the column\n" " importances handed to each quantiser, and the weighting of the\n" " error report\n" @@ -180,6 +187,8 @@ int for_row_pieces(int64_t n, bool parallel, std::string* why, F fn) { int main(int argc, char** argv) { std::string in, out, arch_override, home = rad_home(), tokjson, imat_path, draft_dir; + std::string tokjson2, config_dir; + std::vector add_files; std::vector hierarchy = rad_hierarchy_from_env(); std::vector recipe_files, quant_flags; int64_t max_tok = 8192; @@ -214,6 +223,9 @@ int main(int argc, char** argv) { else if (a == "--home") home = next("--home"); else if (a == "--kernels") hierarchy = rad_split_list(next("--kernels")); else if (a == "--tokenizer") tokjson = next("--tokenizer"); + else if (a == "--tokenizer2") tokjson2 = next("--tokenizer2"); + else if (a == "--add") add_files.push_back(next("--add")); + else if (a == "--config") config_dir = next("--config"); else if (a == "--imatrix") imat_path = next("--imatrix"); else if (a == "--set") { const std::string kv = next("--set"); @@ -331,7 +343,12 @@ int main(int argc, char** argv) { /* ---------------------------------------------------------------- source */ Checkpoint ck; + if (!config_dir.empty()) ck.set_meta_dir(config_dir); if (ck.open(in) < 0) return 1; + for (const std::string& f : add_files) { + if (ck.add_file(f) < 0) return 1; + RAD_INFO("added %s", f.c_str()); + } MetaOwn& meta = ck.meta(); /* Merge the drafter before declare: the architecture plugin declares a draft block only if * `draft.architectures` is present. */ @@ -900,6 +917,17 @@ int main(int argc, char** argv) { w.abort(); return 1; } + if (!tokjson2.empty()) { + VocabBuild vb2; + RAD_INFO("vocab 2 %s", tokjson2.c_str()); + if (parse_tokenizer_json(tokjson2.c_str(), vb2) < 0) { w.abort(); return 1; } + std::vector blob2; + if (vocab_serialize(vb2, sink, 0, blob2) < 0 || + w.set_aux_vocab_section(blob2.data(), (int64_t)blob2.size()) < 0) { + w.abort(); + return 1; + } + } /* ---------------------------------------------------------------- expert profile */ if (im.entries().size()) { diff --git a/tools/rad_info.cpp b/tools/rad_info.cpp index 46d9d948..b76c0d91 100644 --- a/tools/rad_info.cpp +++ b/tools/rad_info.cpp @@ -65,6 +65,8 @@ const char* step_name(uint32_t k) { case RAD_PRE_PUNCTUATION: return "pre.Punctuation"; case RAD_PRE_DIGITS: return "pre.Digits"; case RAD_PRE_BYTE_FALLBACK: return "pre.ByteFallback"; + case RAD_PRE_END_OF_WORD: return "pre.EndOfWordSuffix"; + case RAD_PRE_ADDED_NORMALIZED: return "pre.AddedNormalized"; case RAD_DEC_BYTELEVEL: return "dec.ByteLevel"; case RAD_DEC_METASPACE: return "dec.Metaspace"; case RAD_DEC_REPLACE: return "dec.Replace"; diff --git a/tools/rad_tokcheck.cpp b/tools/rad_tokcheck.cpp index a4911ac6..e5621934 100644 --- a/tools/rad_tokcheck.cpp +++ b/tools/rad_tokcheck.cpp @@ -94,9 +94,11 @@ bool report_diff(const Tokenizer& tok, const char* what, const std::vector 60 ? byte - 60 : 0; + /* The pieces' bytes overshoot the text where a piece spells more than it covers (an + * end-of-word suffix), so the window is clamped to the text. */ + const size_t t0 = std::min(text.size(), byte > 60 ? byte - 60 : 0); std::printf(" text '%s'\n", - printable(text.substr(t0, std::min(120, text.size() - std::min(t0, text.size())))).c_str()); + printable(text.substr(t0, std::min(120, text.size() - t0))).c_str()); return true; } diff --git a/tools/tokref.cpp b/tools/tokref.cpp index 0f513d12..ea26a17d 100644 --- a/tools/tokref.cpp +++ b/tools/tokref.cpp @@ -146,7 +146,11 @@ void apply_norm(std::string& text, const VocabStep& s) { std::vector 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)); + /* Rust's char::to_lowercase, as HuggingFace runs it: U+0130 is "i" U+0307. */ + 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; }