diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 892bcf3d..ddac9118 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -3,7 +3,8 @@ # # Sources are globbed per subdirectory with CONFIGURE_DEPENDS. Re-run cmake if a new file does not # appear. -set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen) +set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen + lora) set(RAD_CORE_SRC "") foreach(d ${RAD_CORE_DIRS}) diff --git a/core/lora/lora.cpp b/core/lora/lora.cpp new file mode 100644 index 00000000..e4d824f2 --- /dev/null +++ b/core/lora/lora.cpp @@ -0,0 +1,1198 @@ +/* lora.cpp -- see lora.h. Pure host code: nothing here reaches a device. */ +#include "lora.h" + +#include "../format/safetensors.h" +#include "../format/share.h" +#include "rad_plugin.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace lora { + +namespace { + +using ojson = nlohmann::ordered_json; + +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 starts_with(const std::string& s, const char* p) { + const size_t n = std::strlen(p); + return s.size() >= n && s.compare(0, n, p) == 0; +} +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::vector split_dots(const std::string& s) { + std::vector v; + size_t at = 0; + while (true) { + const size_t d = s.find('.', at); + v.push_back(s.substr(at, d == std::string::npos ? std::string::npos : d - at)); + if (d == std::string::npos) break; + at = d + 1; + } + return v; +} + +/* `.weight` -> module and its leaf; "" when the source is not a `.weight` tensor. */ +std::string module_of(const std::string& src, std::string* leaf) { + if (!ends_with(src, ".weight")) return ""; + std::string m = src.substr(0, src.size() - 7); + if (m.empty()) return ""; + const size_t d = m.rfind('.'); + if (leaf) *leaf = d == std::string::npos ? m : m.substr(d + 1); + return m; +} + +/* ---------------------------------------------------------------- scope rule (lora.h) */ +bool excluded_source(const std::string& src) { + static const char* const kTower[] = { "visual", "vision_tower", "vision_model", "audio_tower", + "audio_model", "embed_vision", "embed_audio", + "multi_modal_projector", "mm_projector" }; + const std::vector c = split_dots(src); + if (c.empty()) return true; + if (c[0] == "mtp" || c[0] == "draft") return true; + for (const std::string& x : c) + for (const char* t : kTower) + if (x == t) return true; + std::string leaf; + if (!module_of(src, &leaf).empty() && (leaf == "embed_tokens" || leaf == "lm_head")) return true; + return false; +} + +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 (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)"; + static const char* const kScopes[] = { "draft.", "vision.", "audio.", "mtp." }; + for (const char* s : kScopes) + if (starts_with(w.name, s)) return "a non-trunk builder scope"; + return nullptr; +} + +/* The name-map entries for a declared logical weight, found walking back from the end. CONCAT + * extension pieces are declared one after another (map_concat_shards), so the run of equal + * entries around the hit is the whole map, in call order. */ +void scan_maps(const Program& prog, const std::string& declared, + std::vector* out) { + out->clear(); + const auto& nm = prog.name_map; + for (size_t i = nm.size(); i-- > 0;) { + if (!nm[i].declared || declared != nm[i].declared) continue; + size_t lo = i, hi = i; + while (lo > 0 && nm[lo - 1].declared && declared == nm[lo - 1].declared) --lo; + while (hi + 1 < nm.size() && nm[hi + 1].declared && declared == nm[hi + 1].declared) ++hi; + for (size_t k = lo; k <= hi; ++k) out->push_back(&nm[k]); + return; + } +} + +/* Whole-program index, for the callers that walk every op. Same answer as scan_maps for every + * map the builder accepts (pieces of one map are all collected, in order). */ +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); + } + const std::vector* find(const std::string& d) const { + auto it = by.find(d); + return it == by.end() ? nullptr : &it->second; + } +}; + +/* THE predicate, 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; + } + return false; +} + +bool targeted_idx(const Program& prog, const MapIndex& mi, rad_weight h, const TargetSet& t) { + if (h == 0 || h >= prog.weights.size()) return false; + const WeightInfo& w = prog.weights[h]; + const auto* maps = mi.find(w.source); + return maps ? targeted_core(prog, w, *maps, t) : false; +} + +/* An op the builder recorded and could not resolve is never issued: the plugin was handed a null + * handle and declared its fallback. A fixture's op with no bands at all counts as live. */ +bool op_live(const OpInfo& op) { + if (op.bands.empty()) return true; + for (const Band& b : op.bands) + for (int d = 0; d < RAD_N_DOMAINS; ++d) + if (b.dom[d]) return true; + return false; +} + +/* The schema's operand position of `name`, or the built-in layout of the four capable ops when + * there is no schema on the OpInfo (a fixture). */ +int operand_pos(const OpInfo& op, const char* name) { + if (op.schema && op.schema->operands) { + for (int i = 0; i < op.schema->n_operands; ++i) + if (op.schema->operands[i].name && !std::strcmp(op.schema->operands[i].name, name)) + return i; + return -1; + } + /* docs/OPS.md GEMM table. */ + if (!std::strcmp(name, "b")) { + if (op.op == "gemm_nt" || op.op == "gemm_nt_bias") return 1; + if (op.op == "gemm_nt_q" || op.op == "gemm_nt_q_bias") return 2; + } + return -1; +} + +rad_weight b_weight(const OpInfo& op) { + const int pos = operand_pos(op, "b"); + if (pos >= 0 && op.weight_opd.size() == op.weights.size()) { + for (size_t i = 0; i < op.weights.size(); ++i) + if (op.weight_opd[i] == pos) return op.weights[i]; + return 0; + } + return op.weights.empty() ? 0 : op.weights[0]; +} + +void fnv(uint64_t* h, const void* p, size_t n) { + const uint8_t* b = static_cast(p); + for (size_t i = 0; i < n; ++i) { *h ^= b[i]; *h *= 1099511628211ull; } +} + +bool read_file(const std::string& path, std::string* out) { + std::ifstream f(path, std::ios::binary); + if (!f) return false; + std::ostringstream ss; + ss << f.rdbuf(); + *out = ss.str(); + return true; +} + +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 + "]"; +} + +float elem_f32(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; } + } +} +/* bf16 RNE of one element; a bf16 source is copied as is. */ +uint16_t elem_bf16(const StTensor& t, int64_t i) { + if (t.dtype == RAD_BF16) { uint16_t v; std::memcpy(&v, t.data + 2 * i, 2); return v; } + return rad_f32_to_bf16(elem_f32(t, i)); +} + +/* ---------------------------------------------------------------- segments */ +/* Runs of whole parts: source s spans parts [g0, g1); its rows on this rank are part g's + * [lo_g, hi_g) shifted by the container rows of its earlier parts in the run. */ +int segments_runs(const Site& s, const std::vector>& runs, + const std::vector& T, std::vector* out, std::string* err) { + out->clear(); + for (size_t si = 0; si < s.sources.size(); ++si) { + const SiteSource& src = s.sources[si]; + if (!src.targeted) continue; + const int g0 = runs[si].first, g1 = runs[si].second; + int64_t cum = 0; + for (int g = g0; g < g1; ++g) { + if (g > g0) { + if (T[(size_t)g - 1] <= 0) + return fail(err, RAD_E_SHAPE, + fmt("weight '%s': module %s spans row parts %d..%d and the rows of " + "part %d in the container are not recorded", + s.weight.c_str(), src.module.c_str(), g0, g1 - 1, g - 1)); + cum += T[(size_t)g - 1]; + } + SitePart p; + p.module = src.module; + p.src_lo = cum + s.part_lo[(size_t)g]; + p.src_hi = cum + s.part_hi[(size_t)g]; + p.y_col = s.part_y[(size_t)g]; + p.t_off = (int64_t)src.slot * s.max_rank; + p.row_part = g; + if (p.src_hi > p.src_lo) out->push_back(p); + } + } + return RAD_OK; +} + +/* Several sources inside ONE part (CONCAT at n_row_parts <= 1): source s is part-local rows + * [off_s, off_s + rows_s); this rank holds [lo, hi) of the part. */ +int segments_within(const Site& s, const std::vector& rows, const std::vector& want, + std::vector* out, std::string* err) { + out->clear(); + const int64_t lo = s.part_lo[0], hi = s.part_hi[0]; + int64_t off = 0; + for (size_t si = 0; si < s.sources.size(); ++si) { + const SiteSource& src = s.sources[si]; + if (src.targeted && want[si]) { + if (off < 0) + return fail(err, RAD_E_SHAPE, + fmt("weight '%s': the rows of a source before %s are not known, so " + "where it starts in the fused weight is not either", + s.weight.c_str(), src.module.c_str())); + if (rows[si] < 0) + return fail(err, RAD_E_SHAPE, fmt("weight '%s': the rows of %s are not known", + s.weight.c_str(), src.module.c_str())); + const int64_t a = std::max(lo, off), b = std::min(hi, off + rows[si]); + if (a < b) { + SitePart p; + p.module = src.module; + p.src_lo = a - off; + p.src_hi = b - off; + p.y_col = s.part_y[0] + (a - lo); + p.t_off = (int64_t)src.slot * s.max_rank; + p.row_part = 0; + out->push_back(p); + } + } + off = (off < 0 || rows[si] < 0) ? -1 : off + rows[si]; + } + return RAD_OK; +} + +/* Every way to cut P parts into n contiguous non-empty runs. */ +void compositions(int P, int n, std::vector>>* out) { + std::vector> cur; + std::function rec = [&](int start, int left) { + if (left == 1) { + cur.push_back({ start, P }); + out->push_back(cur); + cur.pop_back(); + return; + } + for (int end = start + 1; end <= P - (left - 1); ++end) { + cur.push_back({ start, end }); + rec(end, left - 1); + cur.pop_back(); + } + }; + if (n >= 1 && n <= P) rec(0, n); +} + +bool same_layout(const Site& a, const Site& b) { + if (a.weight != b.weight || a.shard != b.shard || a.K_r != b.K_r || a.k_lo != b.k_lo || + a.K_full != b.K_full || a.N_r != b.N_r || a.R != b.R || a.n_modules != b.n_modules || + a.parts_resolved != b.parts_resolved || a.part_total != b.part_total || + a.part_lo != b.part_lo || a.part_hi != b.part_hi || a.part_y != b.part_y || + a.parts.size() != b.parts.size() || a.sources.size() != b.sources.size()) + return false; + for (size_t i = 0; i < a.parts.size(); ++i) { + const SitePart &x = a.parts[i], &y = b.parts[i]; + if (x.module != y.module || x.src_lo != y.src_lo || x.src_hi != y.src_hi || + x.y_col != y.y_col || x.t_off != y.t_off) + return false; + } + for (size_t i = 0; i < a.sources.size(); ++i) + if (a.sources[i].module != b.sources[i].module || a.sources[i].slot != b.sources[i].slot || + a.sources[i].part_lo != b.sources[i].part_lo || + a.sources[i].part_hi != b.sources[i].part_hi) + return false; + return true; +} + +/* One site's geometry from the weight's recorded facts. */ +int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets, int max_rank, + uint32_t op_index, rad_weight wh, Site* out, std::string* err) { + const OpInfo& op = prog.ops[op_index]; + const WeightInfo& W = prog.weights[wh]; + Site s; + s.gemm = op_index; + s.op = op.op; + s.w = wh; + s.weight = W.name; + s.shard = W.decl.shard; + s.max_rank = max_rank; + s.res_unchecked = op.op == "gemm_nt_bias"; + + if (W.decl.rank != 2) + return fail(err, RAD_E_SHAPE, fmt("weight '%s' is rank %u; a LoRA site needs a matrix", + W.name.c_str(), W.decl.rank)); + s.N_r = W.decl.shape[0]; + s.K_r = W.decl.shape[1]; + long long pn = 0, pk = 0; + if ((op.base.get_i("N", &pn) && pn != s.N_r) || (op.base.get_i("K", &pk) && pk != s.K_r)) + return fail(err, RAD_E_SHAPE, + fmt("op %u (%s) over '%s' declares N=%lld K=%lld and the weight is [%lld, %lld]", + op_index, op.op.c_str(), W.name.c_str(), pn, pk, (long long)s.N_r, + (long long)s.K_r)); + + const int world = prog.ctx.world_size > 0 ? prog.ctx.world_size : 1; + const int index = prog.ctx.rank; + const bool whole = world <= 1 || W.decl.shard == RAD_SHARD_NONE; + + /* ---- K: share.cpp's column cut. */ + if (whole || W.decl.shard == RAD_SHARD_ROW) { + s.k_lo = 0; + s.K_full = s.K_r; + } else { /* COL */ + const bool span = W.shard_hi > 0 || W.n_part_spans > 0; + if (span) { + s.k_lo = W.shard_lo; + if (W.shard_hi - W.shard_lo != s.K_r) + return fail(err, RAD_E_SHAPE, fmt("weight '%s': column span [%lld, %lld) is not its " + "%lld declared columns", W.name.c_str(), + (long long)W.shard_lo, (long long)W.shard_hi, + (long long)s.K_r)); + s.K_full = 0; /* not recorded on the weight: lora_A's columns say */ + } else { + s.k_lo = (int64_t)index * s.K_r; + s.K_full = s.K_r * world; + } + } + + /* ---- rows: share.cpp's per-part cut, in each part's own units. */ + const int P = W.decl.n_row_parts > 1 ? W.decl.n_row_parts : 1; + std::vector rp((size_t)P); + int64_t sum = 0; + for (int g = 0; g < P; ++g) { + rp[(size_t)g] = P > 1 ? W.decl.row_parts[g] : s.N_r; + sum += rp[(size_t)g]; + } + if (sum != s.N_r) + return fail(err, RAD_E_SHAPE, fmt("weight '%s': row parts sum to %lld, declared rows %lld", + W.name.c_str(), (long long)sum, (long long)s.N_r)); + s.part_total.assign((size_t)P, 0); + s.part_lo.assign((size_t)P, 0); + s.part_hi.assign((size_t)P, 0); + s.part_y.assign((size_t)P, 0); + int64_t y = 0; + for (int g = 0; g < P; ++g) { + const size_t G = (size_t)g; + s.part_y[G] = y; + y += rp[G]; + if (whole || W.decl.shard == RAD_SHARD_COL) { + s.part_total[G] = rp[G]; s.part_lo[G] = 0; s.part_hi[G] = rp[G]; + } else if (W.n_part_spans > 0) { + if (W.n_part_spans != P) + return fail(err, RAD_E_SHAPE, fmt("weight '%s': %d part spans for %d parts", + W.name.c_str(), W.n_part_spans, P)); + s.part_total[G] = W.part_total[g]; s.part_lo[G] = W.part_lo[g]; s.part_hi[G] = W.part_hi[g]; + } else if (W.shard_hi > 0) { + s.part_total[G] = 0; /* VR / P: the container's rows, not recorded on the weight */ + s.part_lo[G] = W.shard_lo; s.part_hi[G] = W.shard_hi; + } else { + s.part_total[G] = rp[G] * world; + s.part_lo[G] = (int64_t)index * rp[G]; + s.part_hi[G] = s.part_lo[G] + rp[G]; + } + if (s.part_hi[G] - s.part_lo[G] != rp[G]) + return fail(err, RAD_E_SHAPE, fmt("weight '%s': part %d takes rows [%lld, %lld) and " + "declares %lld", W.name.c_str(), g, + (long long)s.part_lo[G], (long long)s.part_hi[G], + (long long)rp[G])); + } + int64_t N_full = 0; + for (int64_t t : s.part_total) N_full = (t > 0 && N_full >= 0) ? N_full + t : -1; + + /* ---- THE LOADER'S OWN FUNCTION AGREES, or this is not a site. weight_share is what puts the + * base weight's bytes on this rank; asked for a plain [N_full, K_full] entry it must name the + * rectangles this geometry names. */ + if (N_full > 0 && s.K_full > 0) { + WeightInfo v = W; + v.n_sel = 1; + v.sel[0] = 0; + v.sel_rows[0] = s.N_r; + v.sel_cols[0] = s.K_r; + const RadEncoding enc = rad_enc_plain(RAD_BF16); + const int64_t shape[RAD_MAX_RANK] = { N_full, s.K_full }; + PlaneShare ps[RAD_ENC_MAX_PLANES]; + std::string why; + if (weight_share(v, enc, 2, shape, world, index, ps, &why) != RAD_OK) + return fail(err, RAD_E_SHAPE, fmt("weight '%s': weight_share refuses the LoRA view: %s", + W.name.c_str(), why.c_str())); + std::vector want; + int64_t base = 0; + for (int g = 0; g < P; ++g) { + PlaneShare::Rect r; + r.row0 = base + s.part_lo[(size_t)g]; + r.rows = s.part_hi[(size_t)g] - s.part_lo[(size_t)g]; + r.byte0 = s.k_lo * 2; + r.bytes = s.K_r * 2; + base += s.part_total[(size_t)g]; + if (whole || W.decl.shard == RAD_SHARD_COL) { /* one rectangle, every row */ + if (g == 0) { r.row0 = 0; r.rows = s.N_r; want.push_back(r); } + continue; + } + want.push_back(r); + } + bool same = ps[0].rects.size() == want.size(); + for (size_t i = 0; same && i < want.size(); ++i) + same = ps[0].rects[i].row0 == want[i].row0 && ps[0].rects[i].rows == want[i].rows && + ps[0].rects[i].byte0 == want[i].byte0 && ps[0].rects[i].bytes == want[i].bytes; + if (!same) + return fail(err, RAD_E_SHAPE, fmt("weight '%s': the LoRA geometry and weight_share " + "disagree about this rank's rows/columns", + W.name.c_str())); + } + + /* ---- sources, in concatenation order. */ + const auto* maps = mi.find(W.source); + 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; + 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) + 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] : ""); + } + 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); + } + 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; + } + int slot = 0; + for (const std::string& x : srcs) { + 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); + if (ss.targeted) ss.slot = slot++; + s.sources.push_back(ss); + } + s.n_modules = slot; + s.R = (int64_t)slot * max_rank; + const int n = (int)s.sources.size(); + + /* ---- which parts each source covers, when the declaration alone decides it. */ + std::vector> runs((size_t)n, { -1, -1 }); + bool decided = false; + if (P == 1 && n == 1) { + runs[0] = { 0, 1 }; + decided = true; + } else if (P >= 2 && n == P) { + for (int i = 0; i < n; ++i) runs[(size_t)i] = { i, i + 1 }; + decided = true; + } else if (P >= 2 && n == 1) { + runs[0] = { 0, P }; + decided = true; + for (int g = 0; g + 1 < P; ++g) if (s.part_total[(size_t)g] <= 0) decided = false; + } else if (P >= 2 && n > P) { + return fail(err, RAD_E_UNSUPPORTED, + fmt("weight '%s' concatenates %d checkpoint tensors over %d row parts; a " + "source cannot be a whole number of parts", W.name.c_str(), n, P)); + } + /* (P == 1 && n > 1) and (1 < n < P) wait for the adapter's B rows. */ + if (decided) { + for (int i = 0; i < n; ++i) { + s.sources[(size_t)i].part_lo = runs[(size_t)i].first; + s.sources[(size_t)i].part_hi = runs[(size_t)i].second; + } + int st = segments_runs(s, runs, s.part_total, &s.parts, err); + if (st < 0) return st; + s.parts_resolved = true; + } else { + s.parts_resolved = false; + } + *out = std::move(s); + return RAD_OK; +} + +} /* namespace */ + +/* ================================================================== predicates */ +bool weight_targeted(const Program& prog, rad_weight w, const TargetSet& targets) { + if (targets.empty() || w == 0 || w >= prog.weights.size()) return false; + const WeightInfo& wi = prog.weights[w]; + if (excluded_weight(prog, wi)) return false; + std::vector maps; + scan_maps(prog, wi.source, &maps); + return targeted_core(prog, wi, maps, targets); +} + +bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::string* why) { + auto no = [&](const std::string& m) { if (why) *why = m; return false; }; + if (b_out) *b_out = 0; + const bool g = op.op == "gemm_nt", gb = op.op == "gemm_nt_bias", gq = op.op == "gemm_nt_q", + gqb = op.op == "gemm_nt_q_bias"; + if (!g && !gb && !gq && !gqb) return no("op '" + op.op + "' is not a LoRA-capable GEMM"); + const rad_weight b = b_weight(op); + if (b == 0 || b >= prog.weights.size()) return no("op '" + op.op + "' names no `b` weight"); + if (b_out) *b_out = b; + if (gb) { + const char* act = op.base.get_s("act"); + if (act && *act && std::strcmp(act, "none") != 0) + return no(fmt("gemm_nt_bias applies act=%s after the product", act)); + } + if (gq) { + long long p1 = 0, p2 = 0; + op.base.get_i("pb1", &p1); + op.base.get_i("pb2", &p2); + if (p1 > 0 || p2 > 0) + return no(fmt("gemm_nt_q over rotated parts (pb1=%lld pb2=%lld): its input is the " + "rotated activation", p1, p2)); + } + const WeightInfo& w = prog.weights[b]; + if (gq || gqb) { + long long k = 0; + if (w.decl.rank == 2 && op.base.get_i("K", &k) && k != w.decl.shape[1]) + return no(fmt("%s reads K=%lld against a weight of %lld columns (a widened, rotated " + "input)", op.op.c_str(), k, (long long)w.decl.shape[1])); + } + if (w.enc_known && w.enc.transform[0]) + return no(fmt("weight '%s' is stored in the '%.*s' transform basis, so its GEMM is fed a " + "transformed activation", w.name.c_str(), (int)RAD_ENC_STR, w.enc.transform)); + return true; +} + +int find_unsupported_uses(const Program& prog, const TargetSet& targets, + std::vector* out) { + if (out) out->clear(); + if (targets.empty()) return 0; + const MapIndex mi(prog); + int n = 0; + 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; + std::string why; + const bool site = op_is_site(prog, op, &b, &why); + for (rad_weight h : op.weights) { + if (!targeted_idx(prog, mi, h, targets)) continue; + /* Every view of a targeted weight read by a site over the SAME logical weight is the + * site's own (codes, scale, ref). Anything else reading it is not a site. */ + if (site && b && prog.weights[b].source == prog.weights[h].source) continue; + UnsupportedUse u; + u.weight = prog.weights[h].name; + u.op = op.op; + u.op_index = (uint32_t)i; + u.why = site ? "the targeted weight is not this GEMM's `b` operand" : why; + if (const auto* maps = mi.find(prog.weights[h].source)) + for (const RadNameMap* m : *maps) + for (int k = 0; k < m->n_src && k < 8; ++k) { + std::string leaf; + const std::string src = m->src[k] ? m->src[k] : ""; + const std::string mod = module_of(src, &leaf); + if (!mod.empty() && targets.count(leaf) && !excluded_source(src)) + u.module += (u.module.empty() ? "" : ",") + mod; + } + if (out) out->push_back(u); + ++n; + break; /* one report per op */ + } + } + return n; +} + +int build_sites(const Program& prog, const TargetSet& targets, int max_rank, + std::vector* out, std::string* err, std::vector* pool_weights) { + if (!out) return fail(err, RAD_E_INVAL, "build_sites: null output"); + out->clear(); + if (pool_weights) pool_weights->clear(); + 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); + 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; + Site s; + const int st = make_site(prog, mi, targets, max_rank, (uint32_t)i, b, &s, err); + if (st < 0) return st; + auto it = pool_of.find(b); + if (it == pool_of.end()) { + s.pool = (int32_t)first_site.size(); + pool_of.emplace(b, s.pool); + first_site.push_back(out->size()); + if (pool_weights) pool_weights->push_back(s.weight); + } else { + s.pool = it->second; + const Site& f = (*out)[first_site[(size_t)s.pool]]; + if (!same_layout(f, s)) + return fail(err, RAD_E_STATE, + fmt("weight '%s': op %u (%s) and op %u (%s) read it with different " + "LoRA geometry; one pool per weight cannot serve both", + s.weight.c_str(), f.gemm, f.op.c_str(), s.gemm, s.op.c_str())); + } + out->push_back(std::move(s)); + } + return RAD_OK; +} + +TargetSet all_capable_targets(const Program& prog) { + std::set leaves; + for (size_t h = 1; h < prog.weights.size(); ++h) { + const WeightInfo& w = prog.weights[h]; + if (excluded_weight(prog, w)) continue; + std::vector maps; + scan_maps(prog, w.source, &maps); + for (const RadNameMap* m : maps) + for (int k = 0; k < m->n_src && k < 8; ++k) { + std::string leaf; + const std::string src = m->src[k] ? m->src[k] : ""; + if (!module_of(src, &leaf).empty() && !excluded_source(src)) leaves.insert(leaf); + } + } + TargetSet ok; + for (const std::string& l : leaves) { + const TargetSet one{ l }; + std::vector s; + std::string e; + if (find_unsupported_uses(prog, one, nullptr) == 0 && build_sites(prog, one, 1, &s, &e) == RAD_OK && + !s.empty()) + ok.insert(l); + } + return ok; +} + +std::string explain_module(const Program& prog, const TargetSet& targets, const std::string& module) { + const std::string want[3] = { + module, + starts_with(module, "model.") && !starts_with(module, "model.language_model.") + ? "model.language_model." + module.substr(6) : "", + starts_with(module, "model.language_model.") ? "model." + module.substr(21) : "" }; + std::string first; + bool any = false; + for (const RadNameMap& m : prog.name_map) { + std::string src; + for (int k = 0; k < m.n_src && k < 8 && src.empty(); ++k) + for (const std::string& c : want) + if (!c.empty() && m.src[k] && c + ".weight" == m.src[k]) src = m.src[k]; + if (src.empty() || !m.declared) continue; + any = true; + std::string why; + std::string leaf; + module_of(src, &leaf); + rad_weight w = 0; + for (size_t h = 1; h < prog.weights.size() && !w; ++h) + if (prog.weights[h].name == m.declared && prog.weights[h].source == m.declared) + w = (rad_weight)h; + if (excluded_source(src)) { + why = src + " is in a non-trunk scope (drafter / MTP / tower / vocab)"; + } else if (!targets.count(leaf)) { + why = "its leaf '" + leaf + "' is not in the target module list"; + } else if (!w) { + why = std::string("its declared weight '") + m.declared + "' is not on this rank"; + } else if (const char* ex = excluded_weight(prog, prog.weights[w])) { + why = std::string("'") + m.declared + "' is " + ex; + } else { + std::string reads; + bool site = false; + for (size_t i = 1; i < prog.ops.size(); ++i) { + const OpInfo& op = prog.ops[i]; + if (!op_live(op)) continue; + bool uses = false; + for (rad_weight x : op.weights) + if (x && x < prog.weights.size() && prog.weights[x].source == m.declared) uses = true; + if (!uses) continue; + rad_weight b = 0; + std::string no; + if (op_is_site(prog, op, &b, &no) && b == w) { site = true; continue; } + reads += fmt("%sop %zu %s (%s)", reads.empty() ? "" : "; ", i, op.op.c_str(), no.c_str()); + } + if (!reads.empty()) why = std::string("'") + m.declared + "' is read by " + reads; + else if (!site) why = std::string("no op reads '") + m.declared + "'"; + } + if (why.empty()) return ""; + if (first.empty()) first = why; + } + if (!any) return "the base has no tensor " + module + ".weight in any name map on this rank"; + return first; +} + +/* ================================================================== 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 */ + +int load_adapter(const std::string& dir, const std::vector& sites, int max_rank, + AdapterInfo* info, std::vector* packed, std::string* err) { + if (!info || !packed) return fail(err, RAD_E_INVAL, "load_adapter: null output"); + *info = AdapterInfo{}; + packed->clear(); + info->dir = dir; + if (max_rank <= 0) return fail(err, RAD_E_INVAL, fmt("max LoRA rank %d", max_rank)); + + /* ---- the config */ + const std::string cfg_path = dir + "/adapter_config.json"; + std::string text; + if (!read_file(cfg_path, &text)) + return fail(err, RAD_E_IO, cfg_path + ": cannot read (a PEFT adapter directory has one)"); + const ojson cfg = ojson::parse(text, nullptr, false); + if (cfg.is_discarded() || !cfg.is_object()) + return fail(err, RAD_E_FORMAT, cfg_path + ": not a JSON object"); + auto truthy = [&](const char* k) { + if (!cfg.contains(k) || cfg[k].is_null()) return false; + const ojson& v = cfg[k]; + if (v.is_boolean()) return v.get(); + if (v.is_number()) return v.get() != 0.0; + if (v.is_string()) return !v.get().empty(); + if (v.is_array() || v.is_object()) return !v.empty(); + return true; + }; + info->peft_type = cfg.contains("peft_type") && cfg["peft_type"].is_string() + ? cfg["peft_type"].get() : "LORA"; + if (info->peft_type != "LORA") + return fail(err, RAD_E_UNSUPPORTED, fmt("%s: peft_type is %s; only LORA adapters are served", + cfg_path.c_str(), info->peft_type.c_str())); + if (truthy("use_dora")) + return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": use_dora -- DoRA adapters are not served " + "(merge with PEFT's merge_and_unload)"); + if (truthy("modules_to_save")) + return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": modules_to_save -- an adapter that " + "replaces whole modules is not served"); + if (cfg.contains("bias") && cfg["bias"].is_string() && cfg["bias"].get() != "none") + return fail(err, RAD_E_UNSUPPORTED, + cfg_path + ": bias = \"" + cfg["bias"].get() + + "\" -- trained biases are not served"); + if (truthy("lora_bias")) + return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": lora_bias -- a bias on lora_B is not served"); + if (truthy("fan_in_fan_out")) + return fail(err, RAD_E_UNSUPPORTED, + cfg_path + ": fan_in_fan_out -- Conv1D-style (transposed) bases are not served"); + if (truthy("target_parameters")) + return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": target_parameters -- parameter (expert) " + "LoRA is not served"); + if (truthy("trainable_token_indices")) + return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": trainable_token_indices -- embedding " + "updates are not served"); + if (!cfg.contains("r") || !cfg["r"].is_number_integer() || cfg["r"].get() <= 0) + return fail(err, RAD_E_FORMAT, cfg_path + ": no positive integer `r`"); + if (!cfg.contains("lora_alpha") || !cfg["lora_alpha"].is_number()) + return fail(err, RAD_E_FORMAT, cfg_path + ": no numeric `lora_alpha`"); + info->r = cfg["r"].get(); + info->alpha = cfg["lora_alpha"].get(); + info->rslora = cfg.contains("use_rslora") && cfg["use_rslora"].is_boolean() && + cfg["use_rslora"].get(); + if (cfg.contains("base_model_name_or_path") && cfg["base_model_name_or_path"].is_string()) + info->base_model = cfg["base_model_name_or_path"].get(); + if (cfg.contains("target_modules")) { + const ojson& t = cfg["target_modules"]; + if (t.is_string()) info->target_modules.push_back(t.get()); + else if (t.is_array()) + for (const ojson& x : t) if (x.is_string()) info->target_modules.push_back(x.get()); + } + struct Pat { std::string key; std::regex re; double v; }; + std::vector rpat, apat; + for (const char* which : { "rank_pattern", "alpha_pattern" }) { + if (!cfg.contains(which) || cfg[which].is_null()) continue; + if (!cfg[which].is_object()) + return fail(err, RAD_E_FORMAT, cfg_path + ": " + which + " is not an object"); + for (auto it = cfg[which].begin(); it != cfg[which].end(); ++it) { + if (!it.value().is_number()) + return fail(err, RAD_E_FORMAT, cfg_path + ": " + which + "[" + it.key() + + "] is not a number"); + Pat p; + p.key = it.key(); + try { + p.re = std::regex(p.key, std::regex::ECMAScript); + } catch (const std::regex_error& e) { + return fail(err, RAD_E_FORMAT, cfg_path + ": " + which + " key '" + p.key + + "' is not a regex this engine reads (" + e.what() + ")"); + } + p.v = it.value().get(); + if (!std::strcmp(which, "rank_pattern")) { + if (!it.value().is_number_integer() || p.v <= 0) + return fail(err, RAD_E_FORMAT, cfg_path + ": rank_pattern[" + p.key + + "] is not a positive integer"); + info->rank_pattern.push_back({ p.key, (int64_t)p.v }); + rpat.push_back(std::move(p)); + } else { + info->alpha_pattern.push_back({ p.key, p.v }); + apat.push_back(std::move(p)); + } + } + } + + /* ---- the tensors */ + const std::string st_path = dir + "/adapter_model.safetensors"; + SafeTensorsFile st; + if (!std::ifstream(st_path).good() && std::ifstream(dir + "/adapter_model.bin").good()) + return fail(err, RAD_E_UNSUPPORTED, dir + ": adapter_model.bin (pickle) -- save the " + "adapter as safetensors"); + if (st.open(st_path) != RAD_OK) return fail(err, RAD_E_IO, st_path + ": cannot open as safetensors"); + + uint64_t hash = 1469598103934665603ull; + fnv(&hash, text.data(), text.size()); + std::vector order; + for (const StTensor& t : st.tensors()) order.push_back(&t); + std::sort(order.begin(), order.end(), + [](const StTensor* a, const StTensor* b) { return a->name < b->name; }); + for (const StTensor* t : order) { + fnv(&hash, t->name.data(), t->name.size() + 1); + fnv(&hash, t->dtype_str.data(), t->dtype_str.size() + 1); + for (int64_t d : t->shape) fnv(&hash, &d, sizeof d); + if (t->data) fnv(&hash, t->data, (size_t)t->bytes); + } + info->content_hash = hash; + + static const std::regex key_re(R"(^(.*)\.lora_([AB])\.(weight|default\.weight)$)"); + std::map mods; + for (const StTensor* t : order) { + const std::string& k = t->name; + std::smatch m; + if (!std::regex_match(k, m, key_re)) { + std::string why = "is not a linear LoRA A/B tensor"; + if (k.find("lora_embedding_") != std::string::npos) why = "is an embedding LoRA tensor"; + else if (ends_with(k, ".bias")) why = "is a trained bias"; + else if (k.find("modules_to_save") != std::string::npos) why = "is a modules_to_save copy"; + else if (k.find("lora_magnitude_vector") != std::string::npos) why = "is a DoRA magnitude"; + return fail(err, RAD_E_UNSUPPORTED, st_path + ": tensor " + k + " " + why + + "; only linear LoRA A/B pairs are served"); + } + std::string mod = m[1].str(); + const size_t at = mod.find("base_model.model."); /* rad-export: first occurrence */ + if (at != std::string::npos) mod.erase(at, 17); + AdModule& am = mods[mod]; + am.name = mod; + const StTensor*& slot = m[2].str() == "A" ? am.A : am.B; + if (slot) + return fail(err, RAD_E_FORMAT, st_path + ": module " + mod + " has two lora_" + + m[2].str() + " tensors"); + slot = t; + } + if (mods.empty()) return fail(err, RAD_E_FORMAT, st_path + ": no LoRA tensors"); + + for (auto& kv : mods) { + AdModule& am = kv.second; + if (!am.A || !am.B) + return fail(err, RAD_E_FORMAT, fmt("%s: module %s has lora_%s and no lora_%s", + st_path.c_str(), am.name.c_str(), am.A ? "A" : "B", + am.A ? "B" : "A")); + for (const StTensor* t : { am.A, am.B }) { + if (t->dtype != RAD_BF16 && t->dtype != RAD_F16 && t->dtype != RAD_F32) + return fail(err, RAD_E_DTYPE, fmt("module %s: %s is %s; expected BF16, F16 or F32", + am.name.c_str(), t->name.c_str(), + t->dtype_str.c_str())); + if (t->shape.size() != 2 || !t->data) + return fail(err, RAD_E_SHAPE, fmt("module %s: %s has shape %s; expected a matrix", + am.name.c_str(), t->name.c_str(), + shape_str(t->shape).c_str())); + } + int64_t rr = info->r; + double aa = info->alpha; + for (const Pat& p : rpat) if (std::regex_search(am.name, p.re)) { rr = (int64_t)p.v; break; } + for (const Pat& p : apat) if (std::regex_search(am.name, p.re)) { aa = p.v; break; } + if (am.A->shape[0] != rr || am.B->shape[1] != rr) + return fail(err, RAD_E_SHAPE, + fmt("module %s: expected rank %lld (r / rank_pattern), found lora_A %s and " + "lora_B %s", am.name.c_str(), (long long)rr, + shape_str(am.A->shape).c_str(), shape_str(am.B->shape).c_str())); + if (rr > max_rank) + return fail(err, RAD_E_FULL, fmt("module %s: rank %lld is above --max-lora-rank %d", + am.name.c_str(), (long long)rr, max_rank)); + am.rank = rr; + am.alpha = aa; + am.scale = (float)(info->rslora ? aa / std::sqrt((double)rr) : aa / (double)rr); + info->max_module_rank = std::max(info->max_module_rank, rr); + const size_t d = am.name.rfind('.'); + info->leaves.insert(d == std::string::npos ? am.name : am.name.substr(d + 1)); + } + + /* ---- the sites, by pool: the representative of each pool and where its modules sit. */ + int32_t n_pools = 0; + for (const Site& s : sites) { + if (s.pool < 0) return fail(err, RAD_E_INVAL, "site '" + s.weight + "' has no pool"); + if (s.max_rank != max_rank) + return fail(err, RAD_E_INVAL, fmt("sites were built at max rank %d, the load asks %d", + s.max_rank, max_rank)); + n_pools = std::max(n_pools, s.pool + 1); + } + std::vector rep((size_t)n_pools, nullptr); + for (const Site& s : sites) { + const Site*& r = rep[(size_t)s.pool]; + if (!r) r = &s; + else if (!same_layout(*r, s)) + return fail(err, RAD_E_STATE, "pool of '" + s.weight + "' holds sites of two layouts"); + } + 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)); + 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 }); + } + + /* ---- module -> base spelling (VLM bases keep the text model under model.language_model.) */ + std::map, const AdModule*> placed; /* (pool, source) -> module */ + for (auto& kv : mods) { + const AdModule& am = kv.second; + std::vector cand{ am.name }; + if (starts_with(am.name, "model.") && !starts_with(am.name, "model.language_model.")) + cand.push_back("model.language_model." + am.name.substr(6)); + if (starts_with(am.name, "model.language_model.")) + cand.push_back("model." + am.name.substr(21)); + std::vector hit; + for (const std::string& c : cand) if (where.count(c)) hit.push_back(c); + AdapterInfo::Module mi; + mi.name = am.name; + mi.rank = am.rank; + mi.alpha = am.alpha; + mi.scale = am.scale; + if (hit.size() > 1) + return fail(err, RAD_E_INVAL, fmt("module %s matches both %s and %s in the base; the " + "spelling is ambiguous", am.name.c_str(), + hit[0].c_str(), hit[1].c_str())); + if (hit.empty()) { + info->absent.push_back(am.name); + } else { + mi.base = hit[0]; + for (const Slot& sl : where[hit[0]]) { + const AdModule*& to = placed[{ sl.pool, sl.source }]; + if (to) + return fail(err, RAD_E_INVAL, fmt("modules %s and %s both name the base's %s", + to->name.c_str(), am.name.c_str(), + hit[0].c_str())); + to = &am; + if (mi.pool < 0) mi.pool = sl.pool; + } + } + info->modules.push_back(mi); + } + + /* ---- 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; + 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); + const size_t n = s.sources.size(); + std::vector am(n, nullptr); + bool any = false; + for (size_t i = 0; i < n; ++i) { + auto it = placed.find({ p, (int32_t)i }); + if (it != placed.end()) { am[i] = it->second; any = true; } + } + if (!any) continue; + out.empty = false; + const int P = (int)s.part_total.size(); + + /* A: [r, K_full] -- the whole of K for a row/whole site, this rank's columns for COL. */ + for (size_t i = 0; i < n; ++i) { + if (!am[i]) continue; + const StTensor& A = *am[i]->A; + const int64_t kc = A.shape[1]; + if (s.K_full > 0 ? kc != s.K_full : kc < s.k_lo + s.K_r) + return fail(err, RAD_E_SHAPE, + fmt("module %s: lora_A is %s; site '%s' expects [%lld, %s%lld]", + am[i]->name.c_str(), shape_str(A.shape).c_str(), s.weight.c_str(), + (long long)am[i]->rank, s.K_full > 0 ? "" : ">= ", + (long long)(s.K_full > 0 ? s.K_full : s.k_lo + s.K_r))); + } + + /* The parts: fixed at build, or decided now by the B rows. */ + std::vector parts; + std::vector T = s.part_total; + std::vector> runs(n, { -1, -1 }); + for (size_t i = 0; i < n; ++i) runs[i] = { s.sources[i].part_lo, s.sources[i].part_hi }; + if (s.parts_resolved) { + parts = s.parts; + } else if (P == 1) { + /* several sources inside one part: each one's rows from its B, the one unknown (if + * any) from the part's total. */ + std::vector rows(n, -1); + int unknown = 0; + int64_t known = 0; + for (size_t i = 0; i < n; ++i) { + if (am[i]) { rows[i] = am[i]->B->shape[0]; known += rows[i]; } + else ++unknown; + } + if (T[0] > 0) { + if (unknown == 0 && known != T[0]) + return fail(err, RAD_E_SHAPE, fmt("weight '%s': its sources' lora_B rows sum to " + "%lld and the weight has %lld rows", + s.weight.c_str(), (long long)known, + (long long)T[0])); + if (unknown == 1) + for (size_t i = 0; i < n; ++i) if (rows[i] < 0) rows[i] = T[0] - known; + } + std::vector want(n); + for (size_t i = 0; i < n; ++i) want[i] = am[i] != nullptr; + const int st = segments_within(s, rows, want, &parts, err); + if (st < 0) return st; + } else { + std::vector>> all; + compositions(P, (int)n, &all); + std::vector>, std::vector>> ok; + for (const auto& c : all) { + std::vector t = T; + bool unknown_t = false; + for (int64_t x : t) if (x <= 0) unknown_t = true; + bool good = true; + if (unknown_t) { /* an equal-part span: one common part height */ + int64_t tc = 0; + for (size_t i = 0; i < n && good; ++i) { + if (!am[i]) continue; + const int64_t m = c[i].second - c[i].first, b = am[i]->B->shape[0]; + if (b % m) { good = false; break; } + if (!tc) tc = b / m; + else if (tc != b / m) good = false; + } + for (int64_t& x : t) x = tc; + } else { + for (size_t i = 0; i < n && good; ++i) { + if (!am[i]) continue; + int64_t sum = 0; + for (int g = c[i].first; g < c[i].second; ++g) sum += t[(size_t)g]; + good = sum == am[i]->B->shape[0]; + } + } + if (good) ok.push_back({ c, t }); + } + if (ok.size() != 1) { + std::string got; + for (size_t i = 0; i < n; ++i) + if (am[i]) got += fmt("%s%s %lld rows", got.empty() ? "" : ", ", + am[i]->name.c_str(), (long long)am[i]->B->shape[0]); + return fail(err, RAD_E_SHAPE, + fmt("weight '%s': %zu ways to lay its %zu sources over its %d row parts " + "fit the adapter (%s); exactly one must", s.weight.c_str(), + ok.size(), n, P, got.c_str())); + } + runs = ok[0].first; + T = ok[0].second; + const int st = segments_runs(s, runs, T, &parts, err); + if (st < 0) return st; + } + + /* B rows against the runs the parts came from. */ + for (size_t i = 0; i < n; ++i) { + if (!am[i] || runs[i].first < 0) continue; + int64_t sum = 0; + bool all_known = true; + for (int g = runs[i].first; g < runs[i].second; ++g) { + if (T[(size_t)g] <= 0) all_known = false; + sum += T[(size_t)g]; + } + const int64_t b = am[i]->B->shape[0]; + if (all_known ? b != sum : false) + return fail(err, RAD_E_SHAPE, fmt("module %s: lora_B is %s; site '%s' expects " + "[%lld, %lld]", am[i]->name.c_str(), + shape_str(am[i]->B->shape).c_str(), + s.weight.c_str(), (long long)sum, + (long long)am[i]->rank)); + } + for (const SitePart& sp : parts) { + size_t i = 0; + while (i < n && s.sources[i].module != sp.module) ++i; + if (i == n || !am[i]) continue; + if (sp.src_hi > am[i]->B->shape[0]) + return fail(err, RAD_E_SHAPE, fmt("module %s: lora_B is %s; this rank reads its rows " + "[%lld, %lld)", am[i]->name.c_str(), + shape_str(am[i]->B->shape).c_str(), + (long long)sp.src_lo, (long long)sp.src_hi)); + } + + /* Pack. A: rows t_off.. of the module's block; B: rows y_col.., columns t_off..; scale on + * the module's rows. */ + 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; + 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); + } + for (const SitePart& sp : parts) { + size_t i = 0; + while (i < n && s.sources[i].module != sp.module) ++i; + if (i == n || !am[i]) continue; + const StTensor& B = *am[i]->B; + const int64_t r = am[i]->rank; + for (int64_t row = sp.src_lo; row < sp.src_hi; ++row) { + const int64_t yr = sp.y_col + (row - sp.src_lo); + 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.scale[(size_t)yr] = am[i]->scale; + } + } + } + return RAD_OK; +} + +int check_placed(const std::vector& per_rank, std::string* err, const Program* prog, + const TargetSet* targets) { + if (per_rank.empty()) return RAD_OK; + for (const AdapterInfo::Module& m : per_rank[0].modules) { + bool anywhere = false; + for (const AdapterInfo& a : per_rank) + for (const AdapterInfo::Module& x : a.modules) + if (x.name == m.name && x.pool >= 0) anywhere = true; + if (anywhere) continue; + std::string why = prog && targets ? explain_module(*prog, *targets, m.name) : ""; + return fail(err, RAD_E_NOTFOUND, + "adapter module " + m.name + " is not a LoRA site on any rank" + + (why.empty() ? std::string() : ": " + why)); + } + return RAD_OK; +} + +} /* namespace lora */ +} /* namespace rad */ diff --git a/core/lora/lora.h b/core/lora/lora.h new file mode 100644 index 00000000..df6103c4 --- /dev/null +++ b/core/lora/lora.h @@ -0,0 +1,188 @@ +/* lora.h -- runtime LoRA: which declared GEMMs an adapter lands in, and the bytes of one adapter for + * one rank (research/radiance/lora/DESIGN.md §2, §5). + * + * TWO PURE STEPS, both host-only and both read nothing but the declared Program: + * + * build_sites() after declare: every LoRA-capable trunk GEMM whose weight a target names becomes + * a Site -- the weight's per-rank geometry (K slice, output width, which rows of + * which PEFT module land where in the GEMM's y) read off the facts the plugin + * recorded on the weight: its shard mode, row parts, shard / part spans and its + * name-map sources. Never a plugin's own split rule. One Site per GEMM op; the + * Sites of one declared weight share one POOL (one slot layout per weight). + * load_adapter() a PEFT directory -> one PackedSite per pool: exactly the bytes of one slot. + * + * Nothing here allocates device memory or touches a device; the caller declares the pools and copies. + * + * TARGETS ARE HF MODULE LEAF NAMES ("q_proj", "gate_proj", "in_proj_qkv", ...). A declared weight is + * targeted when one of its name-map sources is `..weight`, `leaf` in the set, and the + * weight is not in a non-trunk scope (weight_targeted() states the rule; build_sites and + * find_unsupported_uses use exactly that predicate, and the builder may call it mid-declare). + */ +#pragma once +#include "../rad_core.h" + +#include +#include +#include +#include +#include + +namespace rad { +namespace lora { + +/* HF module LEAF names. A std::set so two callers that build it in different orders get the same + * answer. Empty targets nothing. */ +using TargetSet = std::set; + +/* ONE CONTIGUOUS RUN OF ONE PEFT MODULE'S ROWS INSIDE THIS SITE'S y, ON THIS RANK. + * A module may need SEVERAL parts: in_proj_qkv covers three row parts of the delta net's fused + * ssm_inz, and a rank holds a slice of EACH, so its B rows on that rank are three disjoint runs + * landing at three y columns. Every part of one module carries the same t_off. */ +struct SitePart { + std::string module; /* HF module path without ".weight", as the name map spells it */ + int64_t src_lo = 0, src_hi = 0;/* rows [lo,hi) of the module's full output (= rows of lora_B) */ + int64_t y_col = 0; /* column of this site's per-rank y where row src_lo lands */ + int64_t t_off = 0; /* first t column of the module's block = module slot * max_rank */ + /* ADDED: the weight's row part this run lies in (0 for a weight of one part). */ + int32_t row_part = 0; +}; + +/* ADDED: one name-map source of the site's weight, in concatenation order -- targeted or not, + * because an untargeted source still occupies rows of the fused weight. */ +struct SiteSource { + std::string module; /* source without ".weight" */ + bool targeted = false; + int32_t slot = -1; /* module slot in the site (t_off = slot * max_rank); -1 untargeted */ + /* The run of row parts [part_lo, part_hi) the source occupies, or -1/-1 when the declared + * facts do not decide it (two sources over four parts) and the adapter's B rows must. */ + int32_t part_lo = -1, part_hi = -1; +}; + +struct Site { + uint32_t gemm = 0; /* the gemm op handle (anchor) */ + uint32_t lora_shrink = 0, lora_expand = 0; /* appended op handles (stream G) */ + std::string weight; /* declared weight name */ + int shard = 0; /* RAD_SHARD_ROW / COL / NONE of the base weight */ + int64_t K_r = 0, k_lo = 0, K_full = 0; /* x columns on this rank; COL: A columns + * [k_lo, k_lo + K_r). K_full 0 = not recorded on + * the weight (a COL span): taken from lora_A. */ + int64_t N_r = 0; /* per-rank y width the gemm writes */ + int64_t R = 0; /* capacity: n_modules * max_rank (see report: + * DESIGN said parts.size() * max_rank) */ + std::vector parts; /* empty while !parts_resolved */ + uint32_t pool_a = 0, pool_b = 0, pool_scale = 0; /* PERSIST buffers; 0 here, the caller's */ + + /* ---- ADDED */ + int32_t pool = -1; /* index of the weight in build_sites' per-weight pool list */ + uint32_t w = 0; /* the declared weight's handle */ + std::string op; /* the gemm's op name */ + int32_t n_modules = 0; /* targeted sources */ + int32_t max_rank = 0; + bool parts_resolved = true; /* false: the fused layout is decided by B rows at load */ + bool res_unchecked = false; /* gemm_nt_bias: its optional `res` operand is bound at + * issue, not at declare -- stream G checks it there */ + std::vector sources; + /* Per row part g of the weight (P = max(1, n_row_parts) entries): the part's rows in the + * container (0 = not recorded: an equal-part single span), this rank's rows [lo, hi) of it in + * the part's own units, and the y column where row `lo` lands. */ + std::vector part_total, part_lo, part_hi, part_y; +}; + +/* One adapter, one POOL (= one declared weight), one rank -- exactly the bytes of one slot. */ +struct PackedSite { + std::vector a; /* [R, K_r] bf16, zero rows past the module's rank in each block */ + std::vector b; /* [N_r, R] bf16, zero outside the module's rows / rank block */ + std::vector scale; /* [N_r]: the module's alpha/r (alpha/sqrt(r) rsLoRA) on its rows */ + /* ADDED */ + int32_t pool = -1; + bool empty = true; /* no module of this adapter lands in this pool */ +}; + +/* What an adapter is, independent of the name it is served under. */ +struct AdapterInfo { + struct Module { + std::string name; /* adapter's module path (base_model.model. stripped) */ + std::string base; /* the base's spelling it matched on this rank ("" = absent here) */ + int64_t rank = 0; /* from the tensors (== rank_pattern / r) */ + double alpha = 0.0; /* alpha_pattern / lora_alpha */ + float scale = 0.0f; /* alpha / rank, or alpha / sqrt(rank) with rsLoRA */ + int32_t pool = -1; /* pool it was packed into on this rank, -1 = absent here */ + }; + std::string dir; + std::string base_model; /* base_model_name_or_path */ + std::string peft_type; /* "LORA" */ + int64_t r = 0; /* config r */ + double alpha = 0.0; /* config lora_alpha */ + bool rslora = false; + std::vector target_modules; /* config, as written */ + std::vector> rank_pattern; /* config order */ + std::vector> alpha_pattern; + std::vector modules; /* sorted by name */ + std::set leaves; /* leaf names present in the tensors (targets present) */ + std::vector absent; /* modules no site on THIS rank took (see check_placed) */ + int64_t max_module_rank = 0; + uint64_t content_hash = 0; /* FNV-1a 64 over the config bytes and the tensors */ +}; + +/* A targeted weight read by an op that is not a LoRA site. The caller refuses at startup. */ +struct UnsupportedUse { + std::string weight; /* declared weight */ + std::string module; /* the targeted source module(s), comma separated */ + std::string op; /* the op that reads it */ + uint32_t op_index = 0; + std::string why; +}; + +/* ---------------------------------------------------------------- the one predicate + * Is declared weight `w` a LoRA target? Works on a PARTIALLY declared Program (the builder calls + * it from decl_op): it reads only the weight's own declaration and the name-map entry (or CONCAT + * pieces) whose `declared` is the weight's source -- false when that does not exist yet. + * + * SCOPE RULE (never targets): + * - access RAD_ACCESS_VOCAB (embedding, lm_head) or RAD_ACCESS_PER_REQUEST (encoder towers); + * - a layer group at or above meta.n_layers (the drafter's / MTP head's layers, the rule + * KVGroupInfo::drafter uses) when meta.n_layers > 0; + * - a declared name in a non-trunk builder scope: first component draft / vision / audio / mtp; + * - a source whose first component is `mtp` or `draft`, or that passes through a vision/audio + * tower component (visual, vision_tower, vision_model, audio_tower, audio_model, embed_vision, + * embed_audio, multi_modal_projector, mm_projector), or whose leaf is embed_tokens / lm_head. + * A routed expert IS targeted when its leaf is (so its moe op is reported, never skipped). */ +bool weight_targeted(const Program& prog, rad_weight w, const TargetSet& targets); + +/* Is this op a LoRA-capable GEMM over weight handle `w` (as its `b` operand)? `why` says why not. + * gemm_nt; gemm_nt_bias without `act`; gemm_nt_q without `pb1`/`pb2`, with K == the weight's K, + * over a weight whose known encoding has no `transform`; gemm_nt_q_bias (same encoding rule). */ +bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::string* why); + +/* Every op that reads a targeted weight (any view of it) and is not a capable site over it. */ +int find_unsupported_uses(const Program& prog, const TargetSet& targets, + std::vector* out); + +/* The Sites of one rank's Program. `pool_weights` (optional) receives the per-weight pool list: + * Site::pool indexes it, and its order is the order the pools' first sites appear in. RAD_OK or a + * negative code with `err` naming the weight. Pool handles are left 0. */ +int build_sites(const Program& prog, const TargetSet& targets, int max_rank, + std::vector* out, std::string* err, + std::vector* pool_weights = nullptr); + +/* Every leaf whose every targeted weight in `prog` would be a site: what "all LoRA-capable trunk + * linears" means when no adapter names the targets. */ +TargetSet all_capable_targets(const Program& prog); + +/* One adapter for one rank: `packed` gets one PackedSite per pool (index = Site::pool), in the + * slot layout of the pool's sites. Refusals return a negative code and name module, expected and + * found. A module with no site on THIS rank is not refused here -- an attention-zero rank holds no + * q/k/v/o -- it is listed in info->absent; check_placed() refuses one no rank took. */ +int load_adapter(const std::string& dir, const std::vector& sites, int max_rank, + AdapterInfo* info, std::vector* packed, std::string* err); + +/* 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, + const Program* prog = nullptr, const TargetSet* targets = nullptr); + +/* Why a module path is not a site on this Program, in one sentence ("" when it is one). */ +std::string explain_module(const Program& prog, const TargetSet& targets, const std::string& module); + +} /* namespace lora */ +} /* namespace rad */ diff --git a/tests/lora_test.cpp b/tests/lora_test.cpp new file mode 100644 index 00000000..45cf5a76 --- /dev/null +++ b/tests/lora_test.cpp @@ -0,0 +1,1231 @@ +/* lora_test.cpp -- core/lora: sites from the declared Program, and a PEFT adapter packed per rank. + * + * HOST ONLY, AND IT NEVER REACHES THE DEVICE LAYER. No kernel plugin is loaded: a Registry that + * loads one brackets the dlopen with the device backend's code mark, which in a HIP build starts the + * AQL backend. The Programs here are made by the REAL core Builder, over an empty Registry, driven + * by the REAL arch/common code that declares the weights -- LinearFP8::declare (rad_fp8.h) with the + * arguments the blocks pass (rad_block_attn_fp8.h, rad_block_mlp_fp8.h, rad_block_attn_gated_fp8.h, + * rad_block_gdn_fp8.h), over a Geom from the real geom_from(), and the delta net's uneven head split + * as qwen4exp_fp8.cpp computes it (remainder_place). With no schema in the Registry the GEMM ops + * themselves do not resolve, so each is appended to the Program as decl_op would record it (op name, + * parameters, weights, schema operand positions). Everything a LoRA site is read from -- the + * WeightInfo, its row parts and spans, the name map -- is exactly what the builder records. + * + * The dense reference is the test's own: the full delta scale * B @ A of every module, placed by + * MODEL SEMANTICS (which heads / which ff columns a rank owns), not by anything lora.cpp computes. + */ +#include "rad_test.h" + +#include "build/rad_build.h" +#include "lora/lora.h" +#include "plugin/registry.h" +#include "rad_plugin.h" + +#include +#include + +#include + +#include +#include +#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; /* no plugin is ever loaded into it */ + return r; +} + +/* ------------------------------------------------------------------ temp dirs */ +std::string g_tmp; +std::string tmp_root() { + if (g_tmp.empty()) { + const char* t = std::getenv("TMPDIR"); + std::string tpl = std::string(t && *t ? t : "/tmp") + "/lora_test.XXXXXX"; + std::vector buf(tpl.begin(), tpl.end()); + buf.push_back(0); + if (mkdtemp(buf.data())) g_tmp = buf.data(); + } + return g_tmp; +} +std::string new_dir(const std::string& name) { + const std::string d = tmp_root() + "/" + name; + mkdir(d.c_str(), 0755); + return d; +} + +/* ------------------------------------------------------------------ deterministic values */ +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; +} + +/* What the stored element is, read back the way any reader would, and rounded to bf16 RNE -- the + * value a packed slot can hold. */ +float stored_then_bf16(const std::string& dt, float f) { + float v = f; + if (dt == "F16") v = rad_f16_to_f32(rad_f32_to_f16(f)); + else if (dt == "BF16") v = rad_bf16_to_f32(rad_f32_to_bf16(f)); + return rad_bf16_to_f32(rad_f32_to_bf16(v)); +} + +void put(std::vector* b, const std::string& dt, float f) { + if (dt == "F32") { + uint8_t x[4]; std::memcpy(x, &f, 4); b->insert(b->end(), x, x + 4); + } else { + const uint16_t h = dt == "F16" ? rad_f32_to_f16(f) : rad_f32_to_bf16(f); + uint8_t x[2]; std::memcpy(x, &h, 2); b->insert(b->end(), x, x + 2); + } +} + +/* ------------------------------------------------------------------ a safetensors writer */ +struct TW { + std::string name, dtype; + std::vector shape; + std::vector bytes; +}; +void write_st(const std::string& path, const std::vector& ts) { + ojson h = ojson::object(); + uint64_t off = 0; + for (const TW& t : ts) { + h[t.name] = { { "dtype", t.dtype }, { "shape", t.shape }, + { "data_offsets", { off, off + t.bytes.size() } } }; + off += t.bytes.size(); + } + 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 TW& t : ts) f.write((const char*)t.bytes.data(), (std::streamsize)t.bytes.size()); +} + +/* ------------------------------------------------------------------ an adapter */ +struct ModSpec { + std::string module; /* as the adapter spells it, without base_model.model. */ + int64_t r = 8, rows = 0, cols = 0; + std::string dtA = "BF16", dtB = "BF16"; + uint32_t seed = 1; + bool default_spelling = false; /* .lora_A.default.weight */ + float scale = 0.f; /* what the config says it is (checked) */ +}; + +struct Adapter { + std::string dir; + std::vector mods; +}; + +void write_adapter(Adapter* ad, const std::string& name, const ojson& cfg) { + ad->dir = new_dir(name); + std::ofstream(ad->dir + "/adapter_config.json") << cfg.dump(1); + std::vector ts; + for (const ModSpec& m : ad->mods) { + const std::string sfx = m.default_spelling ? ".default.weight" : ".weight"; + TW a{ "base_model.model." + m.module + ".lora_A" + sfx, m.dtA, { m.r, m.cols }, {} }; + TW b{ "base_model.model." + m.module + ".lora_B" + sfx, m.dtB, { m.rows, m.r }, {} }; + for (int64_t i = 0; i < m.r * m.cols; ++i) put(&a.bytes, m.dtA, val(m.seed, (uint64_t)i)); + for (int64_t i = 0; i < m.rows * m.r; ++i) put(&b.bytes, m.dtB, val(m.seed + 7777, (uint64_t)i)); + ts.push_back(std::move(a)); + ts.push_back(std::move(b)); + } + write_st(ad->dir + "/adapter_model.safetensors", ts); +} + +ojson base_cfg(int64_t r, double alpha, std::vector targets) { + ojson c = ojson::object(); + c["peft_type"] = "LORA"; + c["base_model_name_or_path"] = "test/base-model"; + c["r"] = r; + c["lora_alpha"] = alpha; + c["target_modules"] = targets; + c["bias"] = "none"; + c["use_rslora"] = false; + c["use_dora"] = false; + c["fan_in_fan_out"] = false; + c["modules_to_save"] = nullptr; + return c; +} + +/* The full dense delta of one module, from the values as a slot holds them. [rows, cols] */ +std::vector module_delta(const ModSpec& m) { + std::vector d((size_t)(m.rows * m.cols), 0.0); + for (int64_t i = 0; i < m.rows; ++i) + for (int64_t j = 0; j < m.r; ++j) { + const double b = stored_then_bf16(m.dtB, val(m.seed + 7777, (uint64_t)(i * m.r + j))); + for (int64_t k = 0; k < m.cols; ++k) + d[(size_t)(i * m.cols + k)] += + b * stored_then_bf16(m.dtA, val(m.seed, (uint64_t)(j * m.cols + k))); + } + for (double& x : d) x *= (double)m.scale; + return d; +} + +/* ------------------------------------------------------------------ the declared programs */ +/* Model semantics of one declared weight on one rank: the full weight's rows this rank's y holds, + * in y order, and the full K columns its x holds. `sources` are the checkpoint modules in concat + * order with their full row counts. Absent on this rank: `present` false. */ +struct Truth { + bool present = false; + int shard = RAD_SHARD_ROW; + int64_t N_full = 0, K_full = 0; + std::vector> sources; + std::vector rows, cols; +}; +void add_range(std::vector* v, int64_t lo, int64_t hi) { + for (int64_t i = lo; i < hi; ++i) v->push_back(i); +} + +struct RankProg { + Program prog; + std::map truth; /* by declared weight name */ +}; + +OpInfo gemm_op(const char* name, int64_t N, int64_t K, const char* dtype, int64_t lo, int64_t hi, + std::vector w, std::vector opd, bool grouped) { + OpInfo o; + o.op = name; + o.base.set_i("N", N); + o.base.set_i("K", K); + if (grouped) o.base.set_i("group", AR::RAD_FP8_BLOCK); + o.base.set_s("dtype", dtype); + o.ranged_key = "M"; + o.range_lo = lo; + o.range_hi = hi; + o.weights = std::move(w); + o.weight_opd = std::move(opd); + return o; +} +uint32_t push_op(Builder& b, OpInfo o) { + o.index = (int32_t)b.program().ops.size(); + b.program().ops.push_back(std::move(o)); + return (uint32_t)b.program().ops.size() - 1; +} + +/* LinearFP8::declare as a block calls it, then the GEMM it would have declared over the two + * views: gemm_nt_q fp8a8 (`b`, `b_scale` at schema positions 2, 3). `m1` adds the decode matvec + * LinearFP8 declares beside it when fp8_matvec_rows() > 0 (the same two views, a lower band). */ +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 = {}, int64_t span_lo = 0, int64_t span_hi = 0, + std::initializer_list rot = {}, AR::LinearFP8* keep = nullptr, bool m1 = false) { + AR::LinearFP8 lin{}; + AR::ActFP8 act{}; + const int st = lin.declare(&b, nm, g, base, N, K, shard, AR::grp_layer(layer), src, act, 0, 0, + parts, span_lo, span_hi, rot); + if (st < 0 || !lin.w || !lin.ws) return st < 0 ? st : RAD_E_INVAL; + if (m1) + push_op(b, gemm_op("gemm_nt_q", N, K, "fp8a16", 1, 16, { lin.w, lin.ws }, { 2, 3 }, true)); + push_op(b, gemm_op("gemm_nt_q", N, K, "fp8a8", m1 ? 17 : 1, g.max_tok, { lin.w, lin.ws }, + { 2, 3 }, true)); + if (keep) *keep = lin; + 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 = 4096; + c.scope = ""; + return c; +} + +/* ---- LLaMA fp8 (MiniCPM5's family; arch/llama_fp8): fused [q|k|v], o, fused [gate|up], down. */ +RadModelMeta llama_meta() { + RadModelMeta m{}; + m.arch_id = "llama"; m.name = "lora-test-llama"; m.quant = "fp8_e4m3"; + m.n_layers = 2; m.n_embd = 256; m.n_head = 12; m.n_head_kv = 12; m.head_dim = 128; + m.n_ff = 1536; m.n_vocab = 4096; m.n_ctx_train = 4096; + m.rms_eps = 1e-5f; m.rope_theta = 5e5f; m.rope_scale = 1.0f; + return m; +} + +int build_llama(int rank, int world, RankProg* out) { + const RadModelMeta meta = llama_meta(); + const RadBuildCtx ctx = ctx_for(rank, world); + AR::Geom g{}; + RAD_ARCH_TRY(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16)); /* llama_fp8.cpp:414 */ + Builder b(empty_registry(), meta, ctx); + AR::Names nm(""); + const char* pre = "model.layers"; /* llama_fp8.cpp:567 */ + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const int64_t q_all = g.n_head_all * g.head_dim, kv_all = g.n_head_kv_all * g.head_dim; + for (int l = 0; l < (int)meta.n_layers; ++l) { + auto ck = [&](const char* leaf) { return nm.ckpt("%s.%d.%s.weight", pre, l, leaf); }; + /* rad_block_attn_fp8.h:120-122 */ + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd, + RAD_SHARD_ROW, l, { ck("self_attn.q_proj"), ck("self_attn.k_proj"), + ck("self_attn.v_proj") }, + { q_dim, kv_dim, kv_dim })); + /* rad_block_attn_fp8.h:175-176 */ + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim, + RAD_SHARD_COL, l, { ck("self_attn.o_proj") })); + /* rad_block_mlp_fp8.h:115-117 */ + AR::LinearFP8 gu{}; + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), 2 * g.n_ff, g.n_embd, + RAD_SHARD_ROW, l, { ck("mlp.gate_proj"), ck("mlp.up_proj") }, + { g.n_ff, g.n_ff }, 0, 0, {}, &gu)); + /* rad_block_mlp_fp8.h:144-146 */ + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.ffn_down", l), g.n_embd, g.n_ff, RAD_SHARD_COL, + l, { ck("mlp.down_proj") })); + + const std::string L = std::to_string(l), P = std::string(pre) + "." + L + "."; + Truth t; + t.present = true; t.shard = RAD_SHARD_ROW; t.N_full = q_all + 2 * kv_all; t.K_full = g.n_embd; + t.sources = { { P + "self_attn.q_proj", q_all }, { P + "self_attn.k_proj", kv_all }, + { P + "self_attn.v_proj", kv_all } }; + add_range(&t.rows, rank * q_dim, (rank + 1) * q_dim); + add_range(&t.rows, q_all + rank * kv_dim, q_all + (rank + 1) * kv_dim); + add_range(&t.rows, q_all + kv_all + rank * kv_dim, q_all + kv_all + (rank + 1) * kv_dim); + add_range(&t.cols, 0, g.n_embd); + out->truth["blk." + L + ".attn_qkv.weight"] = t; + + Truth o; + o.present = true; o.shard = RAD_SHARD_COL; o.N_full = g.n_embd; o.K_full = q_all; + o.sources = { { P + "self_attn.o_proj", g.n_embd } }; + add_range(&o.rows, 0, g.n_embd); + add_range(&o.cols, rank * q_dim, (rank + 1) * q_dim); + out->truth["blk." + L + ".attn_output.weight"] = o; + + Truth f; + f.present = true; f.shard = RAD_SHARD_ROW; f.N_full = 2 * g.n_ff_all; f.K_full = g.n_embd; + f.sources = { { P + "mlp.gate_proj", g.n_ff_all }, { P + "mlp.up_proj", g.n_ff_all } }; + add_range(&f.rows, rank * g.n_ff, (rank + 1) * g.n_ff); + add_range(&f.rows, g.n_ff_all + rank * g.n_ff, g.n_ff_all + (rank + 1) * g.n_ff); + add_range(&f.cols, 0, g.n_embd); + out->truth["blk." + L + ".ffn_gate_up.weight"] = f; + + Truth d; + d.present = true; d.shard = RAD_SHARD_COL; d.N_full = g.n_embd; d.K_full = g.n_ff_all; + d.sources = { { P + "mlp.down_proj", g.n_embd } }; + add_range(&d.rows, 0, g.n_embd); + add_range(&d.cols, rank * g.n_ff, (rank + 1) * g.n_ff); + out->truth["blk." + L + ".ffn_down.weight"] = d; + } + out->prog = std::move(b.program()); + return RAD_OK; +} + +/* ---- The hybrid trunk (Qwen3.5 / Qwen4-Exp family, VLM-spelled checkpoint): layer 0 gated delta + * net, layer 1 gated full attention, a dense MLP in both. Two KV heads, five K heads: at three ranks + * attention runs on two and rank 2 is attention-zero, and the delta net splits 2/2/1 with the extra + * head on rank 2 first (remainder_place); at four ranks the KV heads replicate. */ +const int64_t kNK = 5, kNV = 10, kHK = 128, kHV = 128; +RadModelMeta hybrid_meta() { + RadModelMeta m{}; + m.arch_id = "qwen4exp"; m.name = "lora-test-hybrid"; m.quant = "fp8_e4m3"; + m.n_layers = 2; m.n_embd = 256; m.n_head = 8; m.n_head_kv = 2; m.head_dim = 128; + m.n_ff = 1536; m.n_vocab = 4096; m.n_ctx_train = 4096; + m.rms_eps = 1e-6f; m.rope_theta = 1e7f; m.rope_scale = 1.0f; + return m; +} + +struct GdnSplit { int64_t nk, kf, nv, vf; bool uneven; }; +/* qwen4exp_fp8.cpp:419-444, verbatim in substance. */ +GdnSplit gdn_split(const AR::Geom& g) { + GdnSplit s{ kNK, 0, kNV, 0, false }; + if (g.world > 1 && (kNK % g.world != 0 || kNV % g.world != 0)) { + const int64_t ratio = kNV / kNK, base = kNK / g.world, rem = kNK % g.world; + const int64_t pl = AR::remainder_place(g, g.rank, 0); + s.nk = base + (pl < rem ? 1 : 0); + s.kf = pl * base + (pl < rem ? pl : rem); + s.nv = ratio * s.nk; + s.vf = ratio * s.kf; + s.uneven = true; + } else { + s.nk = kNK / g.world; s.nv = kNV / g.world; + s.kf = g.rank * s.nk; s.vf = g.rank * s.nv; + } + return s; +} + +int build_hybrid(int rank, int world, RankProg* out, bool m1_on_inz = true) { + const RadModelMeta meta = hybrid_meta(); + const RadBuildCtx ctx = ctx_for(rank, world); + AR::Geom g{}; + /* qwen4exp_fp8.cpp:326 */ + RAD_ARCH_TRY(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16, true, true)); + Builder b(empty_registry(), meta, ctx); + AR::Names nm(""); + const char* pre = "model.language_model.layers"; + const std::string VP = std::string(pre); + const GdnSplit sp = gdn_split(g); + const int64_t k_dim = sp.nk * kHK, v_dim = sp.nv * kHV, k_all = kNK * kHK, v_all = kNV * kHV; + + /* ---- layer 0: the gated delta net (rad_block_gdn_fp8.h:231-242, 276-299, 318-321, 405-408) */ + { + const int l = 0; + auto ck = [&](const char* leaf) { return nm.ckpt("%s.%d.%s.weight", pre, l, leaf); }; + RAD_ARCH_TRY(AR::map_concat(&b, nm.f("blk.%d.ssm_ab.weight", l), + { ck("linear_attn.in_proj_a"), ck("linear_attn.in_proj_b") }, 0)); + const rad_weight w_ab = AR::decl_w(&b, nm.f("blk.%d.ssm_ab.weight", l), RAD_BF16, + { 2 * sp.nv, g.n_embd }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_ROW, AR::grp_layer(l), 0, { sp.nv, sp.nv }); + if (!w_ab) return RAD_E_INVAL; + AR::LinearFP8 in{}; + AR::ActFP8 act{}; + RAD_ARCH_TRY(in.declare(&b, nm, g, nm.f("blk.%d.ssm_inz", l), 2 * k_dim + 2 * v_dim, + g.n_embd, RAD_SHARD_ROW, AR::grp_layer(l), + { ck("linear_attn.in_proj_qkv"), ck("linear_attn.in_proj_z") }, act, + 0, 0, { k_dim, k_dim, v_dim, v_dim }, 0, 0, + { 2 * k_dim + v_dim, v_dim })); + if (sp.uneven) { + const int64_t kl = sp.kf * kHK, vl = sp.vf * kHV; + const int64_t lo[4] = { kl, kl, vl, vl }; + const int64_t hi[4] = { kl + k_dim, kl + k_dim, vl + v_dim, vl + v_dim }; + const int64_t tot[4] = { k_all, k_all, v_all, v_all }; + RAD_ARCH_TRY(in.span_parts(&b, lo, hi, tot, 4)); + const int64_t alo[2] = { sp.vf, sp.vf }, ahi[2] = { sp.vf + sp.nv, sp.vf + sp.nv }; + const int64_t atot[2] = { kNV, kNV }; + RAD_ARCH_TRY(rad_weight_shard_span_parts(&b, w_ab, alo, ahi, atot, 2)); + } + if (m1_on_inz) + push_op(b, gemm_op("gemm_nt_q", in.N, in.K, "fp8a16", 1, 16, { in.w, in.ws }, { 2, 3 }, true)); + push_op(b, gemm_op("gemm_nt_q", in.N, in.K, "fp8a8", m1_on_inz ? 17 : 1, g.max_tok, + { in.w, in.ws }, { 2, 3 }, true)); + push_op(b, gemm_op("gemm_nt", 2 * sp.nv, g.n_embd, "bf16", 1, g.max_tok, { w_ab }, { 1 }, false)); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.ssm_out", l), g.n_embd, v_dim, RAD_SHARD_COL, l, + { ck("linear_attn.out_proj") }, {}, sp.uneven ? sp.vf * kHV : 0, + sp.uneven ? sp.vf * kHV + v_dim : 0)); + + const std::string P = VP + ".0."; + Truth t; + t.present = true; t.shard = RAD_SHARD_ROW; t.N_full = 2 * k_all + 2 * v_all; t.K_full = g.n_embd; + t.sources = { { P + "linear_attn.in_proj_qkv", 2 * k_all + v_all }, + { P + "linear_attn.in_proj_z", v_all } }; + add_range(&t.rows, sp.kf * kHK, sp.kf * kHK + k_dim); + add_range(&t.rows, k_all + sp.kf * kHK, k_all + sp.kf * kHK + k_dim); + add_range(&t.rows, 2 * k_all + sp.vf * kHV, 2 * k_all + sp.vf * kHV + v_dim); + add_range(&t.rows, 2 * k_all + v_all + sp.vf * kHV, 2 * k_all + v_all + sp.vf * kHV + v_dim); + add_range(&t.cols, 0, g.n_embd); + out->truth["blk.0.ssm_inz.weight"] = t; + Truth ab; + ab.present = true; ab.shard = RAD_SHARD_ROW; ab.N_full = 2 * kNV; ab.K_full = g.n_embd; + ab.sources = { { P + "linear_attn.in_proj_a", kNV }, { P + "linear_attn.in_proj_b", kNV } }; + add_range(&ab.rows, sp.vf, sp.vf + sp.nv); + add_range(&ab.rows, kNV + sp.vf, kNV + sp.vf + sp.nv); + add_range(&ab.cols, 0, g.n_embd); + out->truth["blk.0.ssm_ab.weight"] = ab; + Truth so; + so.present = true; so.shard = RAD_SHARD_COL; so.N_full = g.n_embd; so.K_full = v_all; + so.sources = { { P + "linear_attn.out_proj", g.n_embd } }; + add_range(&so.rows, 0, g.n_embd); + add_range(&so.cols, sp.vf * kHV, sp.vf * kHV + v_dim); + out->truth["blk.0.ssm_out.weight"] = so; + } + + /* ---- layer 1: gated attention (rad_block_attn_gated_fp8.h:189-213, 270-278, 453-455) */ + { + const int l = 1; + auto ck = [&](const char* leaf) { return nm.ckpt("%s.%d.%s.weight", pre, l, leaf); }; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(), qg_dim = 2 * q_dim; + const bool a_spanned = g.attn_world != g.world; + const bool kv_spanned = g.world > g.n_head_kv_all || a_spanned; + const int64_t kv_lo = kv_spanned ? g.kv_off : 0, kv_hi = kv_spanned ? g.kv_off + kv_dim : 0; + const int64_t qg_lo = a_spanned ? g.attn_rank * qg_dim : 0; + const int64_t qg_hi = a_spanned ? (g.attn_rank + 1) * qg_dim : 0; + const int64_t o_lo = a_spanned ? g.attn_rank * q_dim : 0; + const int64_t o_hi = a_spanned ? (g.attn_rank + 1) * q_dim : 0; + const std::string P = VP + ".1."; + const int64_t q_all = g.n_head_all * g.head_dim, kv_all = g.n_head_kv_all * g.head_dim; + if (!g.attn_zero) { + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.attn_qg", l), qg_dim, g.n_embd, RAD_SHARD_ROW, + l, { ck("self_attn.q_proj") }, {}, qg_lo, qg_hi)); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd, RAD_SHARD_ROW, + l, { ck("self_attn.k_proj") }, {}, kv_lo, kv_hi)); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd, RAD_SHARD_ROW, + l, { ck("self_attn.v_proj") }, {}, kv_lo, kv_hi)); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim, + RAD_SHARD_COL, l, { ck("self_attn.o_proj") }, {}, o_lo, o_hi)); + } + /* MODEL SEMANTICS: this rank's query heads, and the KV head(s) those heads read. */ + const int ar = g.attn_rank; + const int64_t qh0 = ar * g.n_head, group = g.n_head_all / g.n_head_kv_all; + const int64_t kvh0 = qh0 / group; + Truth qg; + qg.present = !g.attn_zero; qg.N_full = 2 * q_all; qg.K_full = g.n_embd; + qg.sources = { { P + "self_attn.q_proj", 2 * q_all } }; + add_range(&qg.rows, qh0 * 2 * g.head_dim, (qh0 + g.n_head) * 2 * g.head_dim); + add_range(&qg.cols, 0, g.n_embd); + out->truth["blk.1.attn_qg.weight"] = qg; + for (const char* kv : { "k", "v" }) { + Truth t; + t.present = !g.attn_zero; t.N_full = kv_all; t.K_full = g.n_embd; + t.sources = { { P + "self_attn." + kv + "_proj", kv_all } }; + add_range(&t.rows, kvh0 * g.head_dim, (kvh0 + g.n_head_kv) * g.head_dim); + add_range(&t.cols, 0, g.n_embd); + out->truth[std::string("blk.1.attn_") + kv + ".weight"] = t; + } + Truth o; + o.present = !g.attn_zero; o.shard = RAD_SHARD_COL; o.N_full = g.n_embd; o.K_full = q_all; + o.sources = { { P + "self_attn.o_proj", g.n_embd } }; + add_range(&o.rows, 0, g.n_embd); + add_range(&o.cols, qh0 * g.head_dim, (qh0 + g.n_head) * g.head_dim); + out->truth["blk.1.attn_output.weight"] = o; + } + + /* ---- the dense MLP of both layers (rad_block_mlp_fp8.h:115-146) */ + for (int l = 0; l < 2; ++l) { + auto ck = [&](const char* leaf) { return nm.ckpt("%s.%d.%s.weight", pre, l, leaf); }; + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), 2 * g.n_ff, g.n_embd, + RAD_SHARD_ROW, l, { ck("mlp.gate_proj"), ck("mlp.up_proj") }, + { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("blk.%d.ffn_down", l), g.n_embd, g.n_ff, RAD_SHARD_COL, + l, { ck("mlp.down_proj") })); + const std::string L = std::to_string(l), P = VP + "." + L + "."; + Truth f; + f.present = true; f.N_full = 2 * g.n_ff_all; f.K_full = g.n_embd; + f.sources = { { P + "mlp.gate_proj", g.n_ff_all }, { P + "mlp.up_proj", g.n_ff_all } }; + add_range(&f.rows, rank * g.n_ff, (rank + 1) * g.n_ff); + add_range(&f.rows, g.n_ff_all + rank * g.n_ff, g.n_ff_all + (rank + 1) * g.n_ff); + add_range(&f.cols, 0, g.n_embd); + out->truth["blk." + L + ".ffn_gate_up.weight"] = f; + Truth d; + d.present = true; d.shard = RAD_SHARD_COL; d.N_full = g.n_embd; d.K_full = g.n_ff_all; + d.sources = { { P + "mlp.down_proj", g.n_embd } }; + add_range(&d.rows, 0, g.n_embd); + add_range(&d.cols, rank * g.n_ff, (rank + 1) * g.n_ff); + out->truth["blk." + L + ".ffn_down.weight"] = d; + } + out->prog = std::move(b.program()); + return RAD_OK; +} + +/* ------------------------------------------------------------------ the dense comparison */ +struct Full { int64_t N = 0, K = 0; std::vector d; int shard = RAD_SHARD_ROW; }; + +/* The full delta of every declared weight the adapter touches, keyed by weight name, placing each + * module at its source's rows in concat order. `alias` maps the adapter's spelling to the base's. */ +std::map full_deltas(const std::map& truth, + const Adapter& ad, const std::string& from, + const std::string& to) { + std::map out; + for (const auto& kv : truth) { + const Truth& t = kv.second; + Full f; + f.N = t.N_full; f.K = t.K_full; f.shard = t.shard; + f.d.assign((size_t)(f.N * f.K), 0.0); + int64_t off = 0; + bool any = false; + for (const auto& s : t.sources) { + for (const ModSpec& m : ad.mods) { + std::string base = m.module; + if (!from.empty() && base.compare(0, from.size(), from) == 0) + base = to + base.substr(from.size()); + if (base != s.first) continue; + CHECK_EQ(m.rows, s.second); + CHECK_EQ(m.cols, f.K); + if (m.rows != s.second || m.cols != f.K) continue; + const std::vector md = module_delta(m); + for (int64_t i = 0; i < m.rows; ++i) + for (int64_t k = 0; k < f.K; ++k) + f.d[(size_t)((off + i) * f.K + k)] = md[(size_t)(i * f.K + k)]; + any = true; + } + off += s.second; + } + if (any) out[kv.first] = std::move(f); + } + return out; +} + +/* The rank's slot product scale ⊙ (B @ A), [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) { + if (p.scale[(size_t)y] == 0.0f) continue; + 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; +} + +/* Every rank of one world: sites, the adapter packed, each pool's product against the reference + * slice, the COL ranks summing to the whole delta, and the ROW ranks covering every row. */ +void check_world(const char* label, int world, + const std::function& build, const Adapter& ad, + const lora::TargetSet& targets, int max_rank, const std::string& from, + const std::string& to, int* n_pools_checked) { + std::vector rp((size_t)world); + std::vector infos((size_t)world); + std::map want; + std::map> col_sum; + std::map> row_seen; + for (int r = 0; r < world; ++r) { + REQUIRE_EQ(build(r, world, &rp[(size_t)r]), RAD_OK); + if (r == 0) want = full_deltas(rp[0].truth, ad, from, to); + std::vector sites; + std::vector pools; + std::string err; + const int st = lora::build_sites(rp[(size_t)r].prog, targets, max_rank, &sites, &err, &pools); + if (st != RAD_OK) fprintf(stderr, " %s world %d rank %d: %s\n", label, world, r, err.c_str()); + REQUIRE_EQ(st, RAD_OK); + std::vector un; + CHECK_EQ(lora::find_unsupported_uses(rp[(size_t)r].prog, targets, &un), 0); + std::vector packed; + const int ls = lora::load_adapter(ad.dir, sites, max_rank, &infos[(size_t)r], &packed, &err); + if (ls != RAD_OK) fprintf(stderr, " %s world %d rank %d: %s\n", label, world, r, err.c_str()); + REQUIRE_EQ(ls, RAD_OK); + REQUIRE_EQ(packed.size(), pools.size()); + /* one representative site per pool; every site of a pool names it */ + std::vector rep(pools.size(), nullptr); + for (const lora::Site& s : sites) { + REQUIRE(s.pool >= 0 && (size_t)s.pool < pools.size()); + CHECK_EQ(pools[(size_t)s.pool], s.weight); + if (!rep[(size_t)s.pool]) rep[(size_t)s.pool] = &s; + } + /* every truth weight present on this rank whose sources are targeted has a pool */ + for (const auto& kv : rp[(size_t)r].truth) { + bool targeted = false; + for (const auto& src : kv.second.sources) { + const size_t d = src.first.rfind('.'); + if (targets.count(src.first.substr(d + 1))) targeted = true; + } + bool pooled = false; + for (const std::string& p : pools) if (p == kv.first) pooled = true; + CHECK_EQ(pooled, kv.second.present && targeted); + } + for (size_t p = 0; p < pools.size(); ++p) { + const lora::Site& s = *rep[p]; + const Truth& t = rp[(size_t)r].truth.at(s.weight); + REQUIRE(t.present); + REQUIRE_EQ((int64_t)t.rows.size(), s.N_r); + REQUIRE_EQ((int64_t)t.cols.size(), s.K_r); + const lora::PackedSite& pk = packed[p]; + REQUIRE_EQ((int64_t)pk.a.size(), s.R * s.K_r); + REQUIRE_EQ((int64_t)pk.b.size(), s.N_r * s.R); + REQUIRE_EQ((int64_t)pk.scale.size(), s.N_r); + auto it = want.find(s.weight); + if (it == want.end()) { /* targeted, but this adapter has none of its modules */ + CHECK(pk.empty); + for (float x : pk.scale) CHECK_EQ(x, 0.0f); + continue; + } + const Full& f = it->second; + const std::vector d = slot_delta(s, pk); + int bad = 0; + for (int64_t y = 0; y < s.N_r; ++y) + for (int64_t k = 0; k < s.K_r; ++k) { + const double ref = f.d[(size_t)(t.rows[(size_t)y] * f.K + t.cols[(size_t)k])]; + if (std::fabs(d[(size_t)(y * s.K_r + k)] - ref) > 1e-6 * (1.0 + std::fabs(ref))) + ++bad; + } + if (bad) fprintf(stderr, " %s world %d rank %d: %s has %d wrong elements\n", label, + world, r, s.weight.c_str(), bad); + CHECK_EQ(bad, 0); + ++*n_pools_checked; + if (s.shard == RAD_SHARD_COL && world > 1) { + std::vector& cs = col_sum[s.weight]; + if (cs.empty()) cs.assign(f.d.size(), 0.0); + for (int64_t y = 0; y < s.N_r; ++y) + for (int64_t k = 0; k < s.K_r; ++k) + cs[(size_t)(t.rows[(size_t)y] * f.K + t.cols[(size_t)k])] += d[(size_t)(y * s.K_r + k)]; + } else { + std::vector& rs = row_seen[s.weight]; + if (rs.empty()) rs.assign((size_t)f.N, 0); + for (int64_t y = 0; y < s.N_r; ++y) rs[(size_t)t.rows[(size_t)y]] = 1; + } + /* zero padding: rows of A past a module's rank, columns of B outside its block */ + for (const lora::SiteSource& src : s.sources) { + if (!src.targeted) continue; + int64_t rk = 0; + for (const auto& m : infos[(size_t)r].modules) + if (m.base == src.module) rk = m.rank; + for (int64_t j = rk; j < max_rank; ++j) + for (int64_t k = 0; k < s.K_r; ++k) + CHECK_EQ(pk.a[(size_t)((src.slot * max_rank + j) * s.K_r + k)], (uint16_t)0); + } + } + } + for (const auto& kv : col_sum) { + const Full& f = want.at(kv.first); + int bad = 0; + for (size_t i = 0; i < f.d.size(); ++i) + if (std::fabs(kv.second[i] - f.d[i]) > 1e-6 * (1.0 + std::fabs(f.d[i]))) ++bad; + if (bad) fprintf(stderr, " %s world %d: the COL ranks of %s do not sum to its delta (%d)\n", + label, world, kv.first.c_str(), bad); + CHECK_EQ(bad, 0); + } + for (const auto& kv : row_seen) { + int missing = 0; + for (int x : kv.second) missing += x ? 0 : 1; + if (missing) fprintf(stderr, " %s world %d: %d rows of %s on no rank\n", label, world, + missing, kv.first.c_str()); + CHECK_EQ(missing, 0); + } + std::string err; + CHECK_OK(lora::check_placed(infos, &err, &rp[0].prog, &targets)); + if (!err.empty()) fprintf(stderr, " %s world %d: %s\n", label, world, err.c_str()); +} + +/* ------------------------------------------------------------------ the adapters */ +Adapter llama_adapter() { + Adapter ad; + uint32_t seed = 10; + /* k_proj is NOT targeted: the fused qkv's middle source stays base-only. */ + for (int l = 0; l < 2; ++l) { + const std::string P = "model.layers." + std::to_string(l) + "."; + ModSpec q{ P + "self_attn.q_proj", 16, 1536, 256, "F32", "BF16", seed++, false, 1.0f }; + ModSpec v{ P + "self_attn.v_proj", 8, 1536, 256, "BF16", "F16", seed++, false, 2.0f }; + ModSpec o{ P + "self_attn.o_proj", 8, 256, 1536, "F16", "F32", seed++, false, 2.0f }; + ModSpec g{ P + "mlp.gate_proj", 8, 1536, 256, "BF16", "BF16", seed++, true, 2.0f }; + ModSpec u{ P + "mlp.up_proj", 16, 1536, 256, "BF16", "F32", seed++, false, 1.0f }; + ModSpec d{ P + "mlp.down_proj", 8, 256, 1536, "F32", "F16", seed++, false, 4.0f }; + ad.mods.insert(ad.mods.end(), { q, v, o, g, u, d }); + } + ojson c = base_cfg(8, 16.0, { "q_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" }); + c["rank_pattern"] = { { "self_attn\\.q_proj", 16 }, { "up_proj", 16 } }; + c["alpha_pattern"] = { { "down_proj$", 32 } }; + write_adapter(&ad, "llama", c); + return ad; +} + +/* Spelled the text-model way (`model.layers.`) against a VLM base (`model.language_model.layers.`). */ +Adapter hybrid_adapter() { + Adapter ad; + uint32_t seed = 100; + const std::string P0 = "model.layers.0.", P1 = "model.layers.1."; + ad.mods = { + { P0 + "linear_attn.in_proj_qkv", 16, 2 * kNK * kHK + kNV * kHV, 256, "BF16", "F32", seed++, false, 1.0f }, + { P0 + "linear_attn.in_proj_z", 8, kNV * kHV, 256, "F16", "BF16", seed++, false, 0.5f }, + { P0 + "linear_attn.in_proj_a", 8, kNV, 256, "F32", "F32", seed++, false, 2.0f }, + { P0 + "linear_attn.in_proj_b", 8, kNV, 256, "BF16", "BF16", seed++, false, 2.0f }, + { P0 + "linear_attn.out_proj", 8, 256, kNV * kHV, "BF16", "F16", seed++, false, 2.0f }, + { P1 + "self_attn.q_proj", 16, 2 * 8 * 128, 256, "BF16", "BF16", seed++, false, 1.0f }, + { P1 + "self_attn.k_proj", 8, 2 * 128, 256, "F32", "BF16", seed++, false, 2.0f }, + { P1 + "self_attn.v_proj", 8, 2 * 128, 256, "BF16", "F32", seed++, false, 2.0f }, + { P1 + "self_attn.o_proj", 8, 256, 8 * 128, "F16", "F16", seed++, false, 2.0f }, + { P0 + "mlp.gate_proj", 8, 1536, 256, "BF16", "BF16", seed++, false, 2.0f }, + { P0 + "mlp.up_proj", 8, 1536, 256, "BF16", "BF16", seed++, false, 2.0f }, + { P0 + "mlp.down_proj", 8, 256, 1536, "BF16", "BF16", seed++, false, 4.0f }, + { P1 + "mlp.down_proj", 8, 256, 1536, "F32", "BF16", seed++, false, 4.0f }, + }; + ojson c = base_cfg(8, 16.0, { "in_proj_qkv", "in_proj_z", "in_proj_a", "in_proj_b", "out_proj", + "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", + "down_proj" }); + c["rank_pattern"] = { { "in_proj_qkv", 16 }, { "q_proj", 16 } }; + c["alpha_pattern"] = { { "in_proj_z", 4 }, { "down_proj$", 32 } }; + write_adapter(&ad, "hybrid", c); + return ad; +} + +/* Only in_proj_z and k_proj, spelled the base's own way: the fused ssm_inz is laid out from z's + * rows alone. */ +Adapter hybrid_adapter2() { + Adapter ad; + ad.mods = { + { "model.language_model.layers.0.linear_attn.in_proj_z", 4, kNV * kHV, 256, "F32", "F32", 500, false, 8.0f }, + { "model.language_model.layers.1.self_attn.k_proj", 4, 2 * 128, 256, "BF16", "BF16", 501, false, 8.0f }, + }; + ojson c = base_cfg(4, 32.0, { "in_proj_z", "k_proj" }); + write_adapter(&ad, "hybrid2", c); + return ad; +} + +const lora::TargetSet kLlamaTargets{ "q_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" }; +const lora::TargetSet kHybridTargets{ "in_proj_qkv", "in_proj_z", "in_proj_a", "in_proj_b", "out_proj", + "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", + "down_proj" }; + +/* A load that must refuse, with `needle` in the message. */ +void expect_refusal(const std::string& dir, const std::vector& sites, int max_rank, + const char* needle) { + lora::AdapterInfo info; + std::vector packed; + std::string err; + const int st = lora::load_adapter(dir, sites, max_rank, &info, &packed, &err); + CHECK(st < 0); + if (!has(err, needle)) + fprintf(stderr, " expected a refusal naming '%s', got (%d) '%s'\n", needle, st, err.c_str()); + CHECK(has(err, needle)); +} + +std::vector llama_sites(int rank, int world, const lora::TargetSet& t, RankProg* rp) { + std::vector s; + std::string err; + build_llama(rank, world, rp); + lora::build_sites(rp->prog, t, 16, &s, &err); + return s; +} + +} /* namespace */ + +/* ================================================================== the dense reference */ +TEST(llama_fused_qkv_and_gate_up_every_world) { + const Adapter ad = llama_adapter(); + int n = 0; + for (int world : { 1, 2, 3, 4 }) + check_world("llama", world, build_llama, ad, kLlamaTargets, 16, "", "", &n); + CHECK(n > 0); + fprintf(stderr, " llama: %d pool slots checked against the dense delta\n", n); +} + +TEST(hybrid_gated_attention_and_uneven_delta_net_every_world) { + const Adapter ad = hybrid_adapter(); + int n = 0; + auto b = [](int r, int w, RankProg* p) { return build_hybrid(r, w, p); }; + for (int world : { 1, 2, 3, 4 }) + check_world("hybrid", world, b, ad, kHybridTargets, 16, "model.", "model.language_model.", &n); + CHECK(n > 0); + fprintf(stderr, " hybrid: %d pool slots checked against the dense delta\n", n); +} + +TEST(hybrid_partial_adapter_lays_out_the_fused_inz_from_z_alone) { + const Adapter ad = hybrid_adapter2(); + int n = 0; + auto b = [](int r, int w, RankProg* p) { return build_hybrid(r, w, p); }; + for (int world : { 1, 2, 3, 4 }) + check_world("hybrid2", world, b, ad, kHybridTargets, 16, "", "", &n); + CHECK(n > 0); +} + +/* ================================================================== the geometry itself */ +TEST(sites_record_the_uneven_split_and_attention_zero_rank) { + /* world 3: rank 2 is attention-zero and holds delta-net K heads [0, 2) of 5 (remainder first). */ + RankProg r2; + REQUIRE_EQ(build_hybrid(2, 3, &r2), RAD_OK); + std::vector s; + std::vector pools; + std::string err; + REQUIRE_EQ(lora::build_sites(r2.prog, kHybridTargets, 16, &s, &err, &pools), RAD_OK); + for (const lora::Site& x : s) CHECK(!has(x.weight, "attn_")); + const lora::Site* inz = nullptr; + int inz_sites = 0; + for (const lora::Site& x : s) if (x.weight == "blk.0.ssm_inz.weight") { inz = inz ? inz : &x; ++inz_sites; } + REQUIRE(inz != nullptr); + CHECK_EQ(inz_sites, 2); /* the decode matvec and the GEMM: one pool */ + CHECK_EQ(inz->n_modules, 2); + CHECK_EQ(inz->R, 32); + CHECK(!inz->parts_resolved); /* two sources over four parts: B rows decide */ + REQUIRE_EQ(inz->part_lo.size(), (size_t)4); + CHECK_EQ(inz->part_lo[0], 0); + CHECK_EQ(inz->part_hi[0], 256); + CHECK_EQ(inz->part_lo[2], 0); + CHECK_EQ(inz->part_hi[2], 512); + CHECK_EQ(inz->part_total[0], 640); + CHECK_EQ(inz->part_total[3], 1280); + int n_inz_pools = 0; + for (const std::string& p : pools) n_inz_pools += p == "blk.0.ssm_inz.weight"; + CHECK_EQ(n_inz_pools, 1); + /* rank 1 holds K heads [4, 5) */ + RankProg r1; + REQUIRE_EQ(build_hybrid(1, 3, &r1), RAD_OK); + REQUIRE_EQ(lora::build_sites(r1.prog, kHybridTargets, 16, &s, &err), RAD_OK); + for (const lora::Site& x : s) + if (x.weight == "blk.0.ssm_out.weight") { + CHECK_EQ(x.shard, (int)RAD_SHARD_COL); + CHECK_EQ(x.k_lo, 8 * 128); + CHECK_EQ(x.K_r, 2 * 128); + CHECK_EQ(x.K_full, 0); /* a COL span: the container width is lora_A's */ + } + /* llama even split, world 4 rank 3: the fused qkv's targeted q and v land at y 0 and y 768 */ + RankProg l3; + REQUIRE_EQ(build_llama(3, 4, &l3), RAD_OK); + REQUIRE_EQ(lora::build_sites(l3.prog, kLlamaTargets, 16, &s, &err), RAD_OK); + bool seen = false; + for (const lora::Site& x : s) + if (x.weight == "blk.0.attn_qkv.weight") { + seen = true; + CHECK(x.parts_resolved); + CHECK_EQ(x.n_modules, 2); + REQUIRE_EQ(x.parts.size(), (size_t)2); + CHECK_EQ(x.parts[0].module, std::string("model.layers.0.self_attn.q_proj")); + CHECK_EQ(x.parts[0].src_lo, 3 * 384); + CHECK_EQ(x.parts[0].src_hi, 4 * 384); + CHECK_EQ(x.parts[0].y_col, 0); + CHECK_EQ(x.parts[0].t_off, 0); + CHECK_EQ(x.parts[1].module, std::string("model.layers.0.self_attn.v_proj")); + CHECK_EQ(x.parts[1].src_lo, 3 * 384); + CHECK_EQ(x.parts[1].y_col, 2 * 384); + CHECK_EQ(x.parts[1].t_off, 16); + } + CHECK(seen); +} + +/* ================================================================== the predicate, mid-declare */ +TEST(weight_targeted_reads_only_what_exists_at_the_moment) { + const RadModelMeta meta = llama_meta(); + const RadBuildCtx ctx = ctx_for(0, 1); + Builder b(empty_registry(), meta, ctx); + const lora::TargetSet t{ "q_proj" }; + RadWeightDecl d{}; + d.dtype = RAD_BF16; d.rank = 2; d.shape[0] = 128; d.shape[1] = 256; + d.access = RAD_ACCESS_PER_TOKEN; d.shard = RAD_SHARD_ROW; d.group = AR::grp_layer(0); + const rad_weight w = rad_decl_weight(&b, "blk.0.attn_q.weight", &d); + REQUIRE(w != 0); + CHECK(!lora::weight_targeted(b.program(), w, t)); /* no name map yet */ + REQUIRE_EQ(AR::map_copy(&b, "blk.0.attn_q.weight", "model.layers.0.self_attn.q_proj.weight"), RAD_OK); + CHECK(lora::weight_targeted(b.program(), w, t)); + CHECK(!lora::weight_targeted(b.program(), w, { "k_proj" })); + CHECK(!lora::weight_targeted(b.program(), w, {})); + CHECK(!lora::weight_targeted(b.program(), 0, t)); + CHECK(!lora::weight_targeted(b.program(), 999, t)); +} + +TEST(scopes_that_are_never_targets) { + const RadModelMeta meta = llama_meta(); /* n_layers 2 */ + const RadBuildCtx ctx = ctx_for(0, 1); + Builder b(empty_registry(), meta, ctx); + auto decl = [&](const char* name, const char* src, int access, int layer) { + AR::map_copy(&b, name, src); + RadWeightDecl d{}; + d.dtype = RAD_BF16; d.rank = 2; d.shape[0] = 128; d.shape[1] = 256; + d.access = access; d.shard = RAD_SHARD_NONE; d.group = AR::grp_layer(layer); + const rad_weight w = rad_decl_weight(&b, name, &d); + push_op(b, gemm_op("gemm_nt", 128, 256, "bf16", 1, 64, { w }, { 1 }, false)); + return w; + }; + const lora::TargetSet t{ "q_proj", "qkv", "lm_head", "embed_tokens" }; + /* the MTP head: declared at layer n_layers, sourced from mtp.* */ + const rad_weight mtp = decl("blk.2.attn_qg.weight", "mtp.layers.0.self_attn.q_proj.weight", + RAD_ACCESS_PER_TOKEN, 2); + const rad_weight mtp2 = decl("blk.1.attn_mtp.weight", "mtp.layers.0.self_attn.q_proj.weight", + RAD_ACCESS_PER_TOKEN, 1); + const rad_weight vis = decl("v.blk.0.qkv.weight", "model.visual.blocks.0.attn.qkv.weight", + RAD_ACCESS_PER_REQUEST, 0); + const rad_weight vis2 = decl("blk.0.vt.weight", "model.vision_tower.layers.0.self_attn.q_proj.weight", + RAD_ACCESS_PER_TOKEN, 0); + const rad_weight head = decl("output.weight", "lm_head.weight", RAD_ACCESS_VOCAB, -1); + const rad_weight emb = decl("token_embd.weight", "model.embed_tokens.weight", RAD_ACCESS_PER_TOKEN, -1); + const rad_weight drf = decl("draft.blk.0.attn_q.weight", "model.layers.0.self_attn.q_proj.weight", + RAD_ACCESS_PER_TOKEN, 0); + const rad_weight trunk = decl("blk.0.attn_q.weight", "model.layers.0.self_attn.q_proj.weight", + RAD_ACCESS_PER_TOKEN, 0); + for (rad_weight w : { mtp, mtp2, vis, vis2, head, emb, drf }) + CHECK(!lora::weight_targeted(b.program(), w, t)); + CHECK(lora::weight_targeted(b.program(), trunk, t)); + std::vector s; + std::string err; + REQUIRE_EQ(lora::build_sites(b.program(), t, 16, &s, &err), RAD_OK); + REQUIRE_EQ(s.size(), (size_t)1); + CHECK_EQ(s[0].weight, std::string("blk.0.attn_q.weight")); + CHECK_EQ(lora::find_unsupported_uses(b.program(), t, nullptr), 0); + CHECK(has(lora::explain_module(b.program(), t, "lm_head"), "non-trunk")); + CHECK(has(lora::explain_module(b.program(), t, "mtp.layers.0.self_attn.q_proj"), "non-trunk")); + CHECK_EQ(lora::explain_module(b.program(), t, "model.layers.0.self_attn.q_proj"), std::string()); +} + +/* ================================================================== startup refusals */ +TEST(non_capable_consumers_are_reported_never_skipped) { + const RadModelMeta meta = llama_meta(); + const RadBuildCtx ctx = ctx_for(0, 1); + Builder b(empty_registry(), meta, ctx); + AR::Geom g{}; + REQUIRE_EQ(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16), RAD_OK); + AR::Names nm(""); + AR::LinearFP8 gu{}; + REQUIRE_EQ(linear(b, nm, g, "blk.0.ffn_gate_up", 2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, 0, + { "model.layers.0.mlp.gate_proj.weight", "model.layers.0.mlp.up_proj.weight" }, + { g.n_ff, g.n_ff }, 0, 0, {}, &gu), RAD_OK); + /* the fused gated fold over the same views (rad_block_mlp_fp8.h:132-140): live -> reported */ + OpInfo gated; + gated.op = "gemm_nt_q_gated"; + gated.base.set_i("N", gu.N); gated.base.set_i("K", gu.K); gated.base.set_s("act", "silu"); + gated.weights = { gu.w, gu.ws }; gated.weight_opd = { 2, 3 }; + const uint32_t gi = push_op(b, gated); + std::vector un; + const lora::TargetSet t{ "gate_proj" }; + REQUIRE_EQ(lora::find_unsupported_uses(b.program(), t, &un), 1); + CHECK_EQ(un[0].op, std::string("gemm_nt_q_gated")); + CHECK_EQ(un[0].op_index, gi); + CHECK_EQ(un[0].weight, std::string("blk.0.ffn_gate_up.weight")); + CHECK(has(un[0].module, "model.layers.0.mlp.gate_proj")); + CHECK_EQ(lora::find_unsupported_uses(b.program(), { "down_proj" }, nullptr), 0); + /* ...and the same op left UNRESOLVED (the builder's fallback: it is recorded, never issued) */ + Band dead; + b.program().ops[gi].bands.push_back(dead); + CHECK_EQ(lora::find_unsupported_uses(b.program(), t, nullptr), 0); + std::vector s; + std::string err; + REQUIRE_EQ(lora::build_sites(b.program(), t, 16, &s, &err), RAD_OK); + CHECK_EQ(s.size(), (size_t)1); + CHECK(lora::all_capable_targets(b.program()).count("gate_proj") == 1); + + /* a routed expert (moe_gemm_q over a stacked slice): targeted, so reported */ + RadNameMap ex = AR::map_base("blk.0.ffn_gate_up_exps.3.weight", RAD_MAP_CONCAT); + ex.n_src = 2; + ex.src[0] = "model.layers.0.mlp.experts.gate_proj.weight"; ex.src_index[0] = 3; + ex.src[1] = "model.layers.0.mlp.experts.up_proj.weight"; ex.src_index[1] = 3; + REQUIRE_EQ(rad_decl_name_map(&b, &ex), RAD_OK); + RadWeightDecl d{}; + d.dtype = RAD_F8E4M3; d.rank = 2; d.shape[0] = 256; d.shape[1] = 256; + d.access = RAD_ACCESS_CONDITIONAL; d.shard = RAD_SHARD_NONE; d.group = AR::grp_expert(0, 3); + const rad_weight xw = rad_decl_weight(&b, "blk.0.ffn_gate_up_exps.3.weight", &d); + REQUIRE(xw != 0); + OpInfo moe; + moe.op = "moe_gemm_q"; + moe.weights = { xw }; + push_op(b, moe); + un.clear(); + REQUIRE_EQ(lora::find_unsupported_uses(b.program(), t, &un), 1); + CHECK_EQ(un[0].op, std::string("moe_gemm_q")); + CHECK(lora::all_capable_targets(b.program()).count("gate_proj") == 0); +} + +TEST(a_transformed_or_rotated_weight_is_not_a_site) { + const RadModelMeta meta = llama_meta(); + const RadBuildCtx ctx = ctx_for(0, 1); + Builder b(empty_registry(), meta, ctx); + /* The weight's encoding as the model holds it, through the builder's own source lookup: plain + * bf16 in the "perm" basis. */ + b.set_sources([](const std::string& name, const Program&, WeightSource* out) { + if (name != "blk.0.attn_q.weight") return (int)RAD_E_NOTFOUND; + out->enc = rad_enc_plain(RAD_BF16); + rad_enc_copy_str(out->enc.transform, "perm"); + out->rank = 2; out->shape[0] = 128; out->shape[1] = 256; + return (int)RAD_OK; + }); + auto decl = [&](const char* name, const char* src) { + AR::map_copy(&b, name, src); + RadWeightDecl d{}; + d.dtype = RAD_BF16; d.rank = 2; d.shape[0] = 128; d.shape[1] = 256; + d.access = RAD_ACCESS_PER_TOKEN; d.shard = RAD_SHARD_NONE; d.group = AR::grp_layer(0); + return rad_decl_weight(&b, name, &d); + }; + const rad_weight wq = decl("blk.0.attn_q.weight", "model.layers.0.self_attn.q_proj.weight"); + const rad_weight wk = decl("blk.0.attn_k.weight", "model.layers.0.self_attn.k_proj.weight"); + const rad_weight wv = decl("blk.0.attn_v.weight", "model.layers.0.self_attn.v_proj.weight"); + const rad_weight wo = decl("blk.0.attn_o.weight", "model.layers.0.self_attn.o_proj.weight"); + REQUIRE(wq && wk && wv && wo); + REQUIRE(b.program().weights[wq].enc_known); + push_op(b, gemm_op("gemm_nt", 128, 256, "bf16", 1, 64, { wq }, { 1 }, false)); + OpInfo parts = gemm_op("gemm_nt_q", 128, 256, "mxfp4a8", 1, 64, { wk, wk }, { 2, 3 }, true); + parts.base.set_i("pb1", 64); + push_op(b, parts); + push_op(b, gemm_op("gemm_nt_q", 128, 512, "mxfp4a8", 1, 64, { wv, wv }, { 2, 3 }, true)); + OpInfo act = gemm_op("gemm_nt_bias", 128, 256, "bf16", 1, 64, { wo, wo }, { 1, 2 }, false); + act.base.set_s("act", "gelu"); + push_op(b, act); + const lora::TargetSet t{ "q_proj", "k_proj", "v_proj", "o_proj" }; + std::vector un; + REQUIRE_EQ(lora::find_unsupported_uses(b.program(), t, &un), 4); + CHECK(has(un[0].why, "perm")); + CHECK_EQ(un[0].weight, std::string("blk.0.attn_q.weight")); + CHECK(has(un[0].module, "q_proj")); + CHECK(has(un[1].why, "pb1")); + CHECK(has(un[2].why, "K=512")); + CHECK(has(un[3].why, "act=gelu")); + std::vector s; + std::string err; + REQUIRE_EQ(lora::build_sites(b.program(), t, 16, &s, &err), RAD_OK); + CHECK_EQ(s.size(), (size_t)0); + CHECK(has(lora::explain_module(b.program(), t, "model.layers.0.self_attn.q_proj"), "perm")); +} + +/* ================================================================== load refusals */ +TEST(load_refusals_name_module_expected_and_found) { + RankProg rp; + const std::vector sites = llama_sites(0, 1, kLlamaTargets, &rp); + REQUIRE(!sites.empty()); + const std::string q = "model.layers.0.self_attn.q_proj"; + auto one = [&](const char* name, ojson cfg, std::vector mods) { + Adapter ad; + ad.mods = std::move(mods); + write_adapter(&ad, name, cfg); + return ad.dir; + }; + const ModSpec good{ q, 8, 1536, 256, "BF16", "BF16", 1, false, 2.f }; + const ojson ok = base_cfg(8, 16, { "q_proj" }); + + { ojson c = ok; c["use_dora"] = true; + expect_refusal(one("dora", c, { good }), sites, 16, "DoRA"); } + { ojson c = ok; c["peft_type"] = "LOHA"; + expect_refusal(one("loha", c, { good }), sites, 16, "peft_type is LOHA"); } + { ojson c = ok; c["modules_to_save"] = { "lm_head" }; + expect_refusal(one("mts", c, { good }), sites, 16, "modules_to_save"); } + { ojson c = ok; c["bias"] = "all"; + expect_refusal(one("bias", c, { good }), sites, 16, "trained biases"); } + { ojson c = ok; c["fan_in_fan_out"] = true; + expect_refusal(one("fifo", c, { good }), sites, 16, "fan_in_fan_out"); } + { ojson c = ok; c["alpha_pattern"] = { { "(?Pq_proj)", 4 } }; + expect_refusal(one("regex", c, { good }), sites, 16, "(?Pq_proj)"); } + /* tensors that are not linear LoRA pairs */ + { + Adapter ad; + ad.mods = { good }; + write_adapter(&ad, "emb", ok); + std::vector ts; + TW e{ "base_model.model.model.embed_tokens.lora_embedding_A", "BF16", { 8, 4 }, std::vector(64, 0) }; + ts.push_back(e); + write_st(ad.dir + "/adapter_model.safetensors", ts); + expect_refusal(ad.dir, sites, 16, "embedding LoRA"); + TW bias{ "base_model.model." + q + ".lora_B.bias", "BF16", { 1536 }, std::vector(3072, 0) }; + write_st(ad.dir + "/adapter_model.safetensors", { bias }); + expect_refusal(ad.dir, sites, 16, "trained bias"); + TW mts{ "base_model.model.lm_head.modules_to_save.default.weight", "BF16", { 4, 4 }, std::vector(32, 0) }; + write_st(ad.dir + "/adapter_model.safetensors", { mts }); + expect_refusal(ad.dir, sites, 16, "modules_to_save"); + TW lone{ "base_model.model." + q + ".lora_A.weight", "BF16", { 8, 256 }, std::vector(8 * 256 * 2, 0) }; + write_st(ad.dir + "/adapter_model.safetensors", { lone }); + expect_refusal(ad.dir, sites, 16, "has lora_A and no lora_B"); + TW i8{ "base_model.model." + q + ".lora_A.weight", "I8", { 8, 256 }, std::vector(8 * 256, 0) }; + TW i8b{ "base_model.model." + q + ".lora_B.weight", "BF16", { 1536, 8 }, std::vector(1536 * 16, 0) }; + write_st(ad.dir + "/adapter_model.safetensors", { i8, i8b }); + expect_refusal(ad.dir, sites, 16, "expected BF16, F16 or F32"); + } + /* shapes */ + { ModSpec m = good; m.cols = 255; + expect_refusal(one("acols", ok, { m }), sites, 16, "lora_A is [8, 255]; site 'blk.0.attn_qkv.weight' expects [8, 256]"); } + { ModSpec m = good; m.rows = 1535; + expect_refusal(one("brows", ok, { m }), sites, 16, "lora_B is [1535, 8]; site 'blk.0.attn_qkv.weight' expects [1536, 8]"); } + { ModSpec m = good; m.r = 4; + expect_refusal(one("rank", ok, { m }), sites, 16, "expected rank 8 (r / rank_pattern), found lora_A [4, 256]"); } + { ModSpec m = good; m.r = 32; ojson c = base_cfg(32, 32, { "q_proj" }); + expect_refusal(one("toobig", c, { m }), sites, 16, "rank 32 is above --max-lora-rank 16"); } + { ojson c = ok; c["rank_pattern"] = { { "q_proj", 16 } }; + expect_refusal(one("pattern", c, { good }), sites, 16, "expected rank 16"); } + /* a module the base lacks / a module that is not a site: not placed on any rank */ + { + ModSpec m = good; + m.module = "model.layers.0.self_attn.nope_proj"; + Adapter ad; + ad.mods = { good, m }; + write_adapter(&ad, "lacks", ok); + lora::AdapterInfo info; + std::vector packed; + std::string err; + REQUIRE_EQ(lora::load_adapter(ad.dir, sites, 16, &info, &packed, &err), RAD_OK); + REQUIRE_EQ(info.absent.size(), (size_t)1); + CHECK(lora::check_placed({ info }, &err, &rp.prog, &kLlamaTargets) < 0); + CHECK(has(err, "nope_proj")); + CHECK(has(err, "the base has no tensor model.layers.0.self_attn.nope_proj.weight")); + } + { + RankProg rq; + const std::vector qonly = llama_sites(0, 1, { "q_proj" }, &rq); + ModSpec g{ "model.layers.0.mlp.gate_proj", 8, 1536, 256, "BF16", "BF16", 3, false, 2.f }; + Adapter ad; + ad.mods = { good, g }; + write_adapter(&ad, "notsite", ok); + lora::AdapterInfo info; + std::vector packed; + std::string err; + REQUIRE_EQ(lora::load_adapter(ad.dir, qonly, 16, &info, &packed, &err), RAD_OK); + const lora::TargetSet qt{ "q_proj" }; + CHECK(lora::check_placed({ info }, &err, &rq.prog, &qt) < 0); + CHECK(has(err, "model.layers.0.mlp.gate_proj")); + CHECK(has(err, "not in the target module list")); + } + /* the sites were built for another max rank */ + expect_refusal(one("maxrank", ok, { good }), sites, 8, "max rank 16, the load asks 8"); +} + +TEST(an_ambiguous_vlm_spelling_is_refused) { + const RadModelMeta meta = llama_meta(); + const RadBuildCtx ctx = ctx_for(0, 1); + Builder b(empty_registry(), meta, ctx); + auto decl = [&](const char* name, const char* src) { + AR::map_copy(&b, name, src); + RadWeightDecl d{}; + d.dtype = RAD_BF16; d.rank = 2; d.shape[0] = 128; d.shape[1] = 256; + d.access = RAD_ACCESS_PER_TOKEN; d.shard = RAD_SHARD_NONE; d.group = AR::grp_layer(0); + const rad_weight w = rad_decl_weight(&b, name, &d); + push_op(b, gemm_op("gemm_nt", 128, 256, "bf16", 1, 64, { w }, { 1 }, false)); + }; + decl("blk.0.a.weight", "model.layers.0.mlp.down_proj.weight"); + decl("blk.0.b.weight", "model.language_model.layers.0.mlp.down_proj.weight"); + std::vector s; + std::string err; + REQUIRE_EQ(lora::build_sites(b.program(), { "down_proj" }, 16, &s, &err), RAD_OK); + REQUIRE_EQ(s.size(), (size_t)2); + Adapter ad; + ad.mods = { { "model.layers.0.mlp.down_proj", 8, 128, 256, "BF16", "BF16", 9, false, 2.f } }; + write_adapter(&ad, "ambig", base_cfg(8, 16, { "down_proj" })); + expect_refusal(ad.dir, s, 16, "ambiguous"); + /* one base module named twice by the adapter, once in each spelling */ + std::vector one; + REQUIRE_EQ(lora::build_sites(b.program(), { "down_proj" }, 16, &one, &err), RAD_OK); + one.resize(1); /* only blk.0.a.weight: model.layers.0.mlp.down_proj */ + Adapter twice; + twice.mods = { { "model.layers.0.mlp.down_proj", 8, 128, 256, "BF16", "BF16", 9, false, 2.f }, + { "model.language_model.layers.0.mlp.down_proj", 8, 128, 256, "BF16", "BF16", 10, + false, 2.f } }; + write_adapter(&twice, "twice", base_cfg(8, 16, { "down_proj" })); + expect_refusal(twice.dir, one, 16, "both name the base's model.layers.0.mlp.down_proj"); +} + +/* ================================================================== the adapter's facts */ +TEST(adapter_info_and_scales) { + RankProg rp; + const std::vector sites = llama_sites(0, 1, kLlamaTargets, &rp); + const Adapter ad = llama_adapter(); + lora::AdapterInfo info; + std::vector packed; + std::string err; + REQUIRE_EQ(lora::load_adapter(ad.dir, sites, 16, &info, &packed, &err), RAD_OK); + CHECK_EQ(info.base_model, std::string("test/base-model")); + CHECK_EQ(info.r, 8); + CHECK_EQ(info.alpha, 16.0); + CHECK_EQ(info.max_module_rank, 16); + CHECK_EQ(info.modules.size(), ad.mods.size()); + CHECK(info.absent.empty()); + CHECK(info.leaves.count("q_proj") && info.leaves.count("down_proj") && !info.leaves.count("k_proj")); + for (const lora::AdapterInfo::Module& m : info.modules) + for (const ModSpec& s : ad.mods) + if (s.module == m.name) { + CHECK_EQ(m.rank, s.r); + CHECK_EQ(m.scale, s.scale); + CHECK(m.pool >= 0); + } + /* the hash is the content's: same bytes in another directory, same hash */ + lora::AdapterInfo again; + const std::string copy = new_dir("llama_copy"); + for (const char* f : { "/adapter_config.json", "/adapter_model.safetensors" }) { + std::ifstream i(ad.dir + f, std::ios::binary); + std::ofstream o(copy + f, std::ios::binary); + o << i.rdbuf(); + } + REQUIRE_EQ(lora::load_adapter(copy, sites, 16, &again, &packed, &err), RAD_OK); + CHECK_EQ(again.content_hash, info.content_hash); + /* rsLoRA: alpha / sqrt(r) */ + Adapter rs; + rs.mods = { { "model.layers.0.self_attn.q_proj", 16, 1536, 256, "BF16", "BF16", 4, false, 4.f } }; + ojson c = base_cfg(16, 16, { "q_proj" }); + c["use_rslora"] = true; + write_adapter(&rs, "rslora", c); + lora::AdapterInfo ri; + REQUIRE_EQ(lora::load_adapter(rs.dir, sites, 16, &ri, &packed, &err), RAD_OK); + REQUIRE_EQ(ri.modules.size(), (size_t)1); + CHECK_EQ(ri.modules[0].scale, 4.0f); + CHECK(ri.content_hash != info.content_hash); +} + +TEST(zz_remove_the_temporary_adapters) { + if (!g_tmp.empty()) { + std::error_code ec; + std::filesystem::remove_all(g_tmp, ec); + CHECK(!ec); + } +} + +TEST(nothing_here_touches_a_device) { + /* A guard on the guard: the Registry these programs were declared against has no plugin. */ + CHECK_EQ(empty_registry().plugins().size(), (size_t)0); +} + +RAD_TEST_MAIN()