This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/core/format/checkpoint.h
T
Deadcode b068190326 radiance 1.6.0
- Qwen-Image 2.1 and 2.1 Turbo: text to image and image edits over OpenAI's images API,
  /v1/images/generations and /v1/images/edits. An edit takes up to ten pictures and an optional
  mask, outside which the picture comes back exactly as it was; `background: transparent`, png,
  jpeg and webp output, `n` pictures from one prompt, streamed previews (`partial_images`), and
  vLLM-Omni's seed, negative_prompt with true_cfg_scale, num_inference_steps, width and height.
  arch/qwenimage21 serves the diffusers pipeline directory, converted with
  data/recipes/qwen-image-2.1-fp8.recipe (block fp8) or qwen-image-2.1-bf16.recipe.
  deploy/compose/qwen-image-2.1.yaml and qwen-image-2.1-turbo.yaml serve the fp8 containers on
  two cards. Two R9700s make a 2048x2048 picture in 61 s at the base model's 40 steps and in
  13 s with Turbo (56 and 12 s with --tp-wire wht6), a 1024x1024 one in 6.0 and 2.6 s. The
  models are under Qwen's research license, which is non-commercial
- an image generator is a program kind of its own (core/gen): an architecture declares its
  conditioning, denoising and decoding passes, and the driver runs the schedule, the pictures of
  a batch and the conditioning cache. An image model's /v1/models entry is its generator's name
  (qwen-image-2.1, qwen-image-2.1-turbo), and its capabilities and startup banner list only the
  images endpoints
- the tiled prefill GEMMs run their tiles in groups of activation bands, 16 for fp8 and 8 for
  bf16, so an operand larger than the 64 MB cache is read once a group instead of once a band. A
  bf16 GEMM with more than 64 MB of weight runs up to twice as fast
- fixed: a second lane opened in the middle of a step started beside work lane 0 had not
  finished. Gemma 4 26B-A4B opens its lane that way, so its first step after startup could read
  rows not yet written
- startup no longer warns about --checkpoint-slots when it was not passed, nor about an expert
  floor on a model with no experts
- the image's FFmpeg writes png, jpeg and webp (libwebp)
- for out-of-tree plugins: RAD_ABI_VERSION is 16. The op vocabulary gains the image generator's
  ops (conv2d_nhwc, ln_mod, ln_mod_quant_fp8, flow_euler, attn_prefix_self and others; docs/OPS.md,
  "Image generation"), and all_reduce takes an optional `overlap`. Plugins built against 1.5.0
  must be rebuilt
2026-10-14 14:03:59 +02:00

248 lines
14 KiB
C++

/* checkpoint.h -- a safetensors or GGUF checkpoint as a source of logical weights.
*
* A checkpoint is read twice in this engine: by rad-convert, which writes a container from it, and
* by the loader, which serves a checkpoint whose encoding is trivial directly (spec §4.3). Both
* need the same three things, and this is the one copy of each:
*
* - the tensors, as one row-major namespace however many shards and drafters they came in;
* - the model's metadata, from config.json (and its siblings) or the GGUF header;
* - a LOGICAL WEIGHT for a declared name: the tensors the architecture plugin's name map
* resolves it to -- concatenations, alternatives and expert slices included -- with the
* encoding they already are when that encoding is trivial, and the rows of it on demand.
*
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), block-scaled FP8,
* where `X.weight_scale_inv` is the scale plane of `X.weight`, and MXFP4 as AMD Quark ships it
* (`X.weight` U8 codes, `X.weight_scale` U8 exponents), which is `fp4_e2m1*e8m0[1x32]` byte for
* byte. Anything else is a weight whose served form needs quantisation work, which a recipe does
* ahead of time -- or, for a published GPTQ-packed release (AutoRound, GPTQ), an IMPORT: the
* shipped integer codes and group scales re-laid as an encoding the kernels read, at convert time.
*
* AN IMPORTED QUANTISATION IS STATED WEIGHT BY WEIGHT. The checkpoint's quantisation descriptor
* (`auto-round`, `gptq`, `quark`) names the tool that made it, not a served form, so no
* architecture plugin claims it; the plugin is chosen as Checkpoint::imports() describes.
*/
#pragma once
#include "../rad_internal.h"
#include "../rad_core.h"
#include "safetensors.h"
#include "../text/gguf.h"
#include <deque>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace rad {
class Program;
/* ================================================================== tensors */
/* One shape convention from here on: ROW-MAJOR, shape[0] slowest. GGUF stores ne[] fastest-first,
* so it is reversed on the way in. Getting this backwards transposes every matrix in the model
* and produces fluent wrong output, so it is done exactly once, in Checkpoint::open. */
struct SrcTensor {
std::string name;
uint32_t ggml = 0;
uint32_t rad_dtype = RAD_DT_INVALID; /* INVALID: a GGUF block type */
std::vector<int64_t> shape; /* row-major */
const void* data = nullptr;
int64_t bytes = 0;
/* GPTQ-PACKED (auto_gptq's layout, which AutoRound's `auto_round:auto_gptq` export shares):
* `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along
* K from the low bits up, stored unsigned with the zero point 2^(bits-1). The tensor this
* describes is the logical [N, K] code matrix, `rad_dtype` RAD_I4 or RAD_I8; `gptq_group` is
* the K columns one row of its scale tensor covers. 0 for any other tensor. */
int32_t gptq_bits = 0;
int64_t gptq_group = 0;
/* CT-INT4 (compressed-tensors' pack-quantized int4, symmetric): `data` is X.weight_packed's
* int32 words [N, K / 8], eight codes a word along K from the low bits up, stored unsigned with
* the zero point 8. The tensor this describes is the logical [N, K] code matrix, `rad_dtype`
* RAD_I4; `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for
* any other tensor. */
int64_t ct_group = 0;
/* ParoQuant's int5-bitplane (Import::ParoI5): `data` is the AWQ-packed low nibbles qweight
* [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit
* plane qweight_hi [K, N/32], and the zero points qzeros [G, N/8] and qzeros_hi [G, N/32].
* z-lab's int4 (Import::ParoI4) is the same without the fifth-bit planes (aux[0], aux[2] null). */
int pbits = 0; /* 5 for int5-bitplane, 4 for z-lab's plain AWQ-packed int4; 0 otherwise */
const SrcTensor* aux[3] = { nullptr, nullptr, nullptr };
int64_t numel() const {
int64_t n = 1;
for (int64_t d : shape) n *= d;
return shape.empty() ? 0 : n;
}
};
/* ================================================================== metadata */
/* The model's metadata as RadModelMeta, with the strings it points at owned here. */
struct MetaOwn {
std::string arch, name, quant;
std::vector<std::string> keys, vals;
std::vector<const char*> kp, vp;
RadModelMeta m{};
void kv(const std::string& k, const std::string& v) { keys.push_back(k); vals.push_back(v); }
/* A key given LAST that must also WIN: a lookup takes the first row with the key, so
* appending a key the checkpoint already set would write both and read the old one. */
void set(const std::string& k, const std::string& v);
bool has(const std::string& k) const;
const char* get(const std::string& k) const; /* null when absent */
/* Republish the pointers RadModelMeta carries. Every kv()/set() may move the strings, so this
* runs after the last of them and before `m` is read. */
void finish();
};
int meta_from_config_json(const std::string& dir, MetaOwn* out);
/* quantization_config's quant_method and fmt as the plugin descriptor ("fp8_e4m3"), "" without. */
std::string quant_descriptor(const MetaOwn& m);
int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out);
int meta_merge_generation_config(const std::string& dir, MetaOwn* out);
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out);
int meta_from_gguf(GgufFile& g, MetaOwn* out);
/* ================================================================== the checkpoint */
class Checkpoint {
public:
Checkpoint() = default;
Checkpoint(const Checkpoint&) = delete;
Checkpoint& operator=(const Checkpoint&) = delete;
/* A .gguf, a .safetensors, a model.safetensors.index.json, or the directory holding one --
* and the metadata beside it. */
int open(const std::string& path);
/* A SECOND checkpoint, merged into this one's namespace and metadata under `prefix`: a
* drafter that ships as its own repository (DFlash2) borrows the target's embedding and head,
* so it belongs in the target's container, its tensors under `draft.` and its config.json
* under `draft.` keys. */
int add_draft(const std::string& dir, const std::string& prefix);
const SrcTensor* find(const std::string& n) const;
const std::vector<SrcTensor>& tensors() const { return tensors_; }
bool is_gguf() const { return kind_ == Gguf; }
GgufFile& gguf() { return gguf_; }
const std::string& path() const { return path_; }
const std::string& dir() const { return dir_; } /* where config.json and tokenizer.json sit */
/* Where tokenizer.json, tokenizer_config.json and the chat template sit: dir() for a model
* repository, the `processor/` (or `tokenizer/`) folder of a diffusers pipeline. */
const std::string& tok_dir() const { return tok_dir_.empty() ? dir_ : tok_dir_; }
MetaOwn& meta() { return meta_; }
const MetaOwn& meta() const { return meta_; }
/* Sub-tensor `index` of a STACKED tensor -- dim 0 of a rank >= 2 tensor -- as a view, owned
* here so every pointer handed out stays valid for the checkpoint's life. Null, with the
* reason logged, when there is no such slice. */
const SrcTensor* slice(const SrcTensor& st, int index, const char* declared);
/* FP8's block, from quantization_config.weight_block_size; 128x128 when it says nothing. */
int64_t fp8_block_rows() const { return fp8_br_; }
int64_t fp8_block_cols() const { return fp8_bc_; }
/* THE CHECKPOINT'S QUANTISATION, IMPORTED WEIGHT BY WEIGHT, or None. Read from
* quantization_config at open: AutoRound's `auto_round:auto_gptq` export and GPTQ's own (v1,
* the zero point stored less one) are Gptq; Quark's MXFP4 (fp4 weights, per_group 32, e8m0
* scales, no per-layer overrides) is QuarkMx; ParoQuant's MXFP4 (`paroquant_mxfp4`: Quark's
* codes and exponents in a ROTATED basis, with the rotations beside them) is ParoMx. A quantisation of one of those tools in a form
* this does not read stays None, with the reason in import_refusal(). */
/* Its quantization_config keys are then renamed `imported_quantization_config.*`: they
* describe the tool, not a served format, and a plugin reads the latter there. */
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4 };
Import imports() const { return import_; }
const std::string& import_refusal() const { return import_why_; }
/* The pieces an imported weight is read from, as views owned here: for `name` (a `.weight`)
* the GPTQ-packed codes and their scale tensor, or Quark's codes and exponents as their RAD
* dtypes. RAD_E_NOTFOUND when the checkpoint ships `name` as an ordinary tensor or not at
* all; another error, with `why`, when it ships an imported form this cannot read. */
int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
std::string* why);
private:
/* `owner`, when the checkpoint has an index, is its weight_map: a tensor the index places in
* another shard is not read from this one. */
int add_shard(const std::string& p, const std::string& prefix = "",
const std::unordered_map<std::string, std::string>* owner = nullptr);
int open_safetensors(const std::string& path);
int open_diffusers();
int open_gguf(const std::string& path);
void detect_import();
enum Kind { None, Gguf, SafeT } kind_ = None;
std::string path_, dir_, tok_dir_;
GgufFile gguf_;
MetaOwn meta_;
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
std::vector<SrcTensor> tensors_;
std::unordered_map<std::string, size_t> index_;
std::unordered_map<std::string, size_t> index_shard_; /* name -> shards_ position */
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
int64_t fp8_br_ = 128, fp8_bc_ = 128;
Import import_ = Import::None;
std::string import_why_;
int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */
/* import_piece's answers by name, so a weight resolved twice reads one pair of views. */
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
};
/* ================================================================== logical weights */
/* A declared weight's source, as the name map resolves it: pieces joined along `concat_dim`, and
* for block-scaled FP8 each piece's scale plane beside it. */
struct CkptWeight {
std::string name; /* the logical (declared) name */
std::vector<const SrcTensor*> pieces; /* the codes, in concatenation order */
std::vector<const SrcTensor*> scales; /* FP8 only: one a piece */
int concat_dim = 0;
uint32_t rank = 0;
int64_t shape[RAD_MAX_RANK] = {0}; /* the logical shape */
int64_t rows = 0, cols = 0; /* its [rows, cols] view (rad_enc_view) */
/* The encoding the pieces ARE, when it is trivial; `why` says what is not when it is not. */
bool trivial = false;
/* GPTQ-PACKED PIECES, read into `enc` (`i4` or `i8` codes, bf16 scales a 128 of K) by
* ckpt_plane_rows: the codes transposed and offset to signed, the f16 scales rounded to bf16.
* Not trivial -- the rounding means the numbers are not served as shipped -- so the loader
* refuses one and rad-convert keeps it in `enc`, as it keeps a trivial weight. */
bool imported = false;
/* PAROQUANT MXFP4, IMPORTED (Import::ParoMx): `imported` too, so the loader refuses it and
* rad-convert writes it plane by plane through ckpt_plane_rows. Planes 0 and 1 are Quark's
* codes and exponents byte for byte; the rest are the "givens" transform's tables, built here
* from `pq_pairs`/`pq_theta`/`pq_scale`, one set per piece (a piece is a row PART: gate and up,
* or q, k and v, each rotated on its own). */
bool paro = false;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale;
RadEncoding enc{};
std::string why;
};
/* Resolve `name` through `prog`'s name map. RAD_OK; RAD_E_NOTFOUND when the name map has no entry
* for it yet (declare may add one later) or, for an optional weight, none of its tensors is
* there; anything else with the reason in `why`. */
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
CkptWeight* out, std::string* why);
/* The checkpoint tensor a piece or scale reads: its name without the "[index]" a slice of a
* stacked tensor carries, so an expert reads the stack it was cut from. */
std::string ckpt_tensor_of(const SrcTensor& t);
/* Whether `w` reads any tensor named in `names` (checkpoint names, as ckpt_tensor_of gives them),
* through a piece or a scale. Each name it reads is added to `hit` when that is given. */
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
std::unordered_set<std::string>* hit = nullptr);
/* One (part, group) of a ParoQuant rotation as its dense matrix: `S` stages of 64 pairs, the pair's two
* group-local columns `ia`/`ib` and angle `th`, stage-major; out[j * 128 + i] (f16) is output j for the
* unit vector e_i. It is the "givens" encoding's "t.dense" table, row for row. */
void paro_compose_dense(int64_t S, const int32_t* ia, const int32_t* ib, const float* th, uint16_t* out);
/* Logical rows [r0, r0 + nr) of `w` as f32 [nr, cols], whatever the pieces are stored as: a
* plain float widened, FP8 times its block scale, a GGUF block type dequantised. */
int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why);
/* Rows [r0, r0 + nr) of plane `k` of a TRIVIAL or IMPORTED `w`, in the plane's own elements, dense
* into `dst`: the bytes a container entry holds for it. */
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
std::string* why);
} /* namespace rad */