diff --git a/abi/rad_abi.h b/abi/rad_abi.h index fe7d8223..b7f4816a 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -18,7 +18,7 @@ extern "C" { * kind of plugin reports it, and a plugin that does not report exactly this version is refused at * load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a * change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 27u +#define RAD_ABI_VERSION 28u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 02b57052..4f35d92d 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -1311,17 +1311,20 @@ typedef struct RadVideoGenDecl { * denoiser reads `ref_tab`, so this flag is what makes staging and consumption flip together. */ int32_t ref_rows; - /* The largest MODULATION-GROUP count this generator's modulation table holds -- its denoiser's - * `kMaxSegs`. A modulation cell is a pure function of a segment's KIND (its modality and its - * timestep-embedding block), so runs of consecutive segments that share a cell collapse into one - * group and the table is sized by the GROUP count, not the reference count: nine reference photos - * pack into four groups (prompt, all-photos, soundtrack, video). The attention still takes the - * FINE per-segment table (which may hold far more segments than this), so this is not a limit on - * how many references ride -- only on how many DISTINCT cells the sequence changes through. The - * driver refuses a request whose merged group count exceeds it at submit (it lays the pack out and - * merges it itself, via `rad_arch_video_mod_segs`, so it knows before dispatch) rather than letting - * the arch abort mid-generation. 0 = no reference consumption, so no such limit. Trailing since - * ABI 23: an older plugin declares none and keeps the 0 default. */ + /* The largest number of DISTINCT MODULATION CELLS this generator's modulation table holds -- + * its denoiser's `kMaxSegs`. A modulation cell is a pure function of a segment's KIND (its + * modality and its timestep-embedding block) and, since ABI 28, of a prompt vision-pad run's + * tag: runs of consecutive same-cell rows collapse into one GROUP, and groups that share a cell + * read it through the column map staged with the group boundaries (`rad_arch_video_mod_segs`), + * so the table is sized by the DISTINCT-CELL count -- not the group count and not the reference + * count. The attention still takes the FINE per-segment table (which may hold far more segments + * than this), so this is not a limit on how many references ride -- only on how many DISTINCT + * cells the sequence and its prompt pads change through. The driver refuses a request whose + * merged cells exceed it at submit (it lays the pack out and merges it itself, via + * `rad_arch_video_mod_segs`, so it knows before dispatch) rather than letting the arch abort + * mid-generation. 0 = no reference consumption, so no such limit. Trailing since ABI 23: an + * older plugin declares none and keeps the 0 default; its meaning was the merged GROUP count + * until ABI 28 made the cells and the groups separate. */ int32_t max_ref_segs; /* Debug introspection of the encoder outputs (diagnostics only, not part of the serving @@ -1851,7 +1854,9 @@ int64_t rad_arch_encode_geom(int32_t kind, const int64_t* in, int32_t* out, int6 * of rad_arch_video_segs. `g` is the target's geometry and `ref_tab` the request's keyframes * and VAE references -- RadVideoGenBatch::ref_tab, its int32 table verbatim -- or null when the * request conditions on no VAE media, which lays out the plain [text | soundtrack | video] - * sequence. Returns the packed sequence's total rows -- the rows RAD_VPOS_STEP positions -- or + * sequence. Since ABI 28 the table may carry a trailing list of prompt vision-pad tag runs; the + * PAD LAYOUT is untouched by them (they ride inside the prompt's rows), so this export reads only + * the counts, references and keyframes and answers identically with or without the tail. Returns the packed sequence's total rows -- the rows RAD_VPOS_STEP positions -- or * a negative status for counts the model cannot present or caps too small to write into. With * `seg` non-null it writes the segment boundaries (seg[k] the first row of segment k, of the n * it needs) when `cap_seg` int32s hold them; with `pos` non-null the rotary positions (f32 diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index afe5317c..e30ede65 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -623,20 +623,30 @@ typedef struct RadVideoGenBatch { * reference's `kind` is 0 a picture, 1 a standalone audio, 2 a video, 3 a video's * soundtrack; `slot` is its 1-based number within its kind -- the slot its encode pass * wrote. The counts are latent units: a reference's own latent grid (height, width), its - * latent frames and its audio latents, 0 where the kind carries neither. A batch without - * the field laid out is one an older engine built: no references. Trailing since ABI 23. */ + * latent frames and its audio latents, 0 where the kind carries neither. Since ABI 28 the + * table then carries the prompt's VISION-PAD TAG RUNS, which lay out nothing but DO change + * the modulation cells the pad rows read: one int32 count, then 2 words per run {start, + * length} — token spans inside the prompt where the image pads (the vision_start, tiles and + * vision_end of one visual reference) carry the video tag instead of the text tag. A table + * written by an ABI 28 driver always has the word count (0 when the prompt has no pads); a + * batch without the field laid out is one an older engine built: no references. Trailing + * since ABI 23. */ const int32_t* ref_tab; - /* ---- The modulated-norm's segment boundaries, device i32. The denoiser's attention reads the - * FINE `seg_cu` -- one segment per reference block, which the block-sparse attention needs to - * give each reference its own prefix sink -- but the modulated norm reads a COARSER table: - * consecutive segments that share a modulation cell (the same modality and the same - * timestep-embedding block) merge into one, because a cell is a pure function of a segment's - * kind. This is that merged table's boundaries, a subset of `seg_cu`'s -- every fine boundary - * that is also a cell change. Sizing the modulation table by the GROUP count, not the reference - * count, is what lets a wide reference request (up to nine photos, which pack into four groups) - * ride a fixed table. On a plain request (or one that merges nothing) it is exactly `seg_cu`; a - * driver stages the same bytes into both. Trailing since ABI 23. */ + /* ---- The modulated-norm's group boundaries -- and, since ABI 28, its group->column MAP -- + * device i32. The denoiser's attention reads the FINE `seg_cu` -- one segment per reference + * block, which the block-sparse attention needs to give each reference its own prefix sink -- + * but the modulated norm reads a COARSER table: runs of consecutive rows that share a + * modulation cell merge into one GROUP, a cell being a pure function of a segment's kind and + * (since ABI 28) of a prompt vision-pad's tag, so pad runs cut the text group. This operand is + * the merged table's boundaries -- every boundary that is also a cell change, a superset of + * `seg_cu`'s subset once pads cut -- followed, since ABI 28, by one i32 per group: the + * modulation-table COLUMN that group reads. Groups that share a cell share a column, so the + * table is sized by the DISTINCT-CELL count however many groups the pads and kinds cut: that + * is what lets a wide reference request ride a fixed table. On a plain request it is exactly + * `seg_cu` -- boundaries alone, no map -- and the arch reads no map either: a driver stages a + * map only for the merged (reference-conditioned) table, and the plain path keeps the + * byte-identical pre-ABI-28 bytes. Trailing since ABI 23. */ const int32_t* mod_cu; /* ---- The sampler that advances the latents: RAD_SAMPLER_* above. Trailing since ABI 24. */ diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index 2de406bc..4e8d53e2 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -3359,13 +3359,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * consumption all move together behind this one constant; a request with no reference * table stays on the byte-identical plain path (step_dit's refc gate is `V->ref_tab`). */ d.ref_rows = kRefConsume; - /* The denoiser's modulation table is one cell per modulation GROUP, `kMaxSegs` columns. - * A cell is a pure function of a segment's kind, so a run of consecutive same-cell - * segments -- nine reference photos, say -- shares one cell and the table is pitched by - * the group count, not the reference count; a pack that MERGES to more groups than this - * aborts the step. The driver builds and merges the pack itself (rad_arch_video_mod_segs) - * and reads this cap, refusing an over-wide request at submit -- the model's ceilings - * (max_ref_images & co.) stay the model's, this is the build's table. */ + /* The denoiser's modulation table is one column per DISTINCT modulation cell, + * `kMaxSegs` columns. A cell is a pure function of a segment's kind and of a prompt + * vision-pad's tag, so the groups the norm walks -- prompt pieces, pad runs, reference + * blocks, targets -- map onto a handful of columns; the table is pitched by that + * DISTINCT-CELL count, not the group or reference count, and a request whose cells + * exceed it aborts the step. The driver builds and merges the pack itself + * (rad_arch_video_mod_segs) and reads this cap, refusing an over-wide request at submit + * -- the model's ceilings (max_ref_images & co.) stay the model's, this is the build's + * table. */ d.max_ref_segs = kRefConsume ? kMaxSegs : 0; /* Debug naming of the encoder outputs (R4D_ENC_DEBUG): the driver reads these back and * logs a digest so the encoder's numbers can be inspected without a step-side d2h the @@ -3489,6 +3491,24 @@ static minimaxh3::Ref2VAPack ref_pack_of(const RadVideoGeom* g, const int32_t* r return p; } +/* The vision-pad tag runs the table's tail carries, after the keyframes: [n, (start, len) x n], + * each run the `vision_start` / tiles / `vision_end` span of one reference photo inside the prompt. + * The reference implementation tags those rows with the VIDEO modality, not text -- the pad run + * keeps the prompt's timestep row but swaps its ada projection -- so the merged modulation groups + * must cut the text segment at these edges. A table without the tail (the counts word absent or + * zero) is the pre-tag-run layout: no runs, groups equal segment kinds. */ +static std::vector ref_pads_of(const int32_t* ref_tab) { + std::vector runs; + if (!ref_tab) return runs; + const int32_t nr = ref_tab[0], nk = ref_tab[1]; + const int32_t* w = ref_tab + 2 + (int64_t)nr * 6 + (int64_t)nk * 3; + const int32_t np = *w++; + if (np < 0 || np > 4096) return runs; /* a table from before the tail, or corrupt */ + for (int32_t i = 0; i < np; ++i, w += 2) + if (w[1] > 0) runs.push_back({ w[0], (int64_t)w[0] + w[1], 0 }); + return runs; +} + /* A segment's modulation cell -- its modality's ada projection (0 video, 1 text, 2 audio) and the * timestep-embedding block it reads over [0,S) video, [S,2S) audio, [2S,3S) video-pinned, * [3S,4S) audio-pinned -- is a pure function of the segment's kind. That rule lives in one place, @@ -3658,14 +3678,16 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { const bool refc = kRefConsume && V->ref_tab; std::vector> cell; if (refc) { - /* One cell per modulation GROUP, not per fine segment. A cell is fixed by a segment's kind - * (its modality's ada projection and its timestep-embedding block), so consecutive - * same-cell segments -- every reference photo, say, all video-pinned -- collapse into one. - * The table is written at the group's column and the norm is handed the group boundaries - * (V->mod_cu), so a wide reference request rides a table pitched by its GROUP count. */ + /* One cell per DISTINCT modulation cell -- not per group, and not per fine segment. A cell + * is fixed by a segment's kind (its modality's ada projection and its timestep-embedding + * block), and by the tag of a vision-pad run inside the prompt, so the groups the norm + * walks (prompt, pad, photos, soundtrack, video, ...) address a handful of columns through + * the map staged with the group boundaries. The table is written once per column and the + * norm maps group -> column itself, so a wide reference request rides a table pitched by + * its DISTINCT-CELL count however many groups its pads cut. */ const minimaxh3::Ref2VAPack p = ref_pack_of(&V->geom, V->ref_tab); minimaxh3::Ref2VAModGroups grp; - minimaxh3::ref2va_mod_groups(p, S, &grp); + minimaxh3::ref2va_mod_groups(p, S, ref_pads_of(V->ref_tab), &grp); for (size_t i = 0; i < grp.md.size(); ++i) cell.emplace_back(grp.md[i], grp.r0[i]); } else { for (int e = 0; e < kSegs; ++e) @@ -3673,8 +3695,8 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { } const int64_t ncell = (int64_t)cell.size(); if (ncell > kMaxSegs) { - rad_step_fail(c, "minimaxh3: the reference conditioning lays out more sequence segments than " - "this plugin's modulation table holds"); + rad_step_fail(c, "minimaxh3: the reference conditioning reads more distinct modulation cells " + "than this plugin's modulation table holds"); return; } for (int64_t l = 0; l < L; ++l) { @@ -3721,23 +3743,28 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { * segments and lands every offset exactly as before. */ const bool refc = kRefConsume && V->ref_tab; minimaxh3::Ref2VAPack pk; + minimaxh3::Ref2VAModGroups grp; int64_t ng = kSegs; /* modulation groups: the norm table's width */ + int64_t vcol = ng - 1; /* the video target's table COLUMN */ int64_t vrows, aseg, vseg; if (refc) { pk = ref_pack_of(&V->geom, V->ref_tab); - /* The table is pitched by the merged GROUP count (a cell is fixed by a segment's kind, so - * consecutive same-cell segments collapse), while the attention keeps the fine per-segment - * layout. Checked against the table width is the merged count, not the reference count. */ - minimaxh3::Ref2VAModGroups grp; - minimaxh3::ref2va_mod_groups(pk, m.S, &grp); - ng = (int64_t)grp.md.size(); - if (ng > kMaxSegs || pk.segs.size() < 2 || + /* The groups the norm walks (segment kinds merged, the prompt cut at its vision-pad runs) + * address the table through a column map, so the table is pitched by its DISTINCT-CELL + * count while the groups may outnumber it -- and the attention keeps the fine per-segment + * layout. Checked against the table width is the distinct-cell count, not the group or + * reference count. */ + minimaxh3::ref2va_mod_groups(pk, m.S, ref_pads_of(V->ref_tab), &grp); + ng = (int64_t)grp.bound.size() - 1; + if (ng < 1 || grp.col.size() != (size_t)ng || (int64_t)grp.md.size() > kMaxSegs || + pk.segs.size() < 2 || pk.segs.back().kind != minimaxh3::kR2VVideo || pk.segs[pk.segs.size() - 2].kind != minimaxh3::kR2VAudio) { rad_step_fail(c, "minimaxh3: the reference conditioning did not merge to a video/audio " "target pair within the modulation table"); return; } + vcol = grp.col[(size_t)ng - 1]; /* the video target's own column */ const minimaxh3::Ref2VASeg& vid = pk.segs.back(); vrows = vid.end - vid.start; aseg = pk.segs[pk.segs.size() - 2].start; /* the audio target, just before the video */ @@ -3840,6 +3867,12 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { * selects its per-reference prefix sinks from the fine `segs`, the norm selects its per-cell * modulation from `mod_segs`. On the plain path the driver stages identical bytes to both. */ const RadOperand mod_segs = praw(V->mod_cu, RAD_I32, ng + 1); + /* The group->column map: the merged table stages the mod-seg export's combined answer, the + * ng+1 boundaries above followed by the ng columns. The norm maps its group index through it, + * so groups that share a cell read one table column. Half 1 and every plain path need none: + * half 1's slice already starts AT the video target's column, and its two-boundary cu maps to + * the slice's single row. */ + const RadOperand mod_col = refc ? praw(V->mod_cu + ng + 1, RAD_I32, ng) : RAD_NONE; const RadOperand geom = praw(V->geom_d, RAD_I32, RAD_VGEOM_N); const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); const RadOperand pos = praw2(V->pos, RAD_F32, 3, R); @@ -3855,7 +3888,8 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { * run on lane 1 while lane 0 computes the other half; the attention stays whole. The second * half starts at the video target's middle row -- the video target is the pack's last segment, * so the half is video alone: the batch's one-sequence cu_seqlens and the video target's - * modulation row (the last cell) stand for the segment table. Lane 0 waits for a half's + * modulation row (its own table column, sliced to one row) stand for the segment table. Lane 0 + * waits for a half's * all-reduce before its first reader, issued before the next all-reduce goes to lane 1 (a join * orders a lane behind everything issued on the other). */ const bool split = g.world > 1; @@ -3863,10 +3897,11 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { const int64_t hr0[2] = { 0, cut }, hn[2] = { cut, R - cut }; const int nh = split ? 2 : 1; const RadOperand segh[2] = { mod_segs, cu }; + const RadOperand colh[2] = { mod_col, RAD_NONE }; auto modh = [&](int h, int64_t l, int k, int chunks) { if (h == 0) return mod(l, k, chunks); const int64_t r = k / per; - return bcol_at(m.b_modg, r * L * kMaxSegs + l * kMaxSegs + (ng - 1), m.Ws, (k % per) * D, + return bcol_at(m.b_modg, r * L * kMaxSegs + l * kMaxSegs + vcol, m.Ws, (k % per) * D, chunks * D, 1); }; /* A half's partial sums across the ranks, kArRows rows a message, on lane 1 when split. */ @@ -3894,7 +3929,7 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { l > 0 ? modh(h, l - 1, 5, 1) : RAD_NONE, modh(h, l, 0, 2), RAD_W(B.w_n1), segh[h], brow_slice(m.b_h, r0, n, D), brow_slice(m.a_hm.cq(), r0, n, D), brow_slice(m.a_hm.cs(), r0, n, nD), - RAD_NONE); + RAD_NONE, colh[h]); /* The dump's per-block window (R4D_DIT_SEL): block l-1's residual STREAM rows * [0, kDbgL). b_ao is not the stream -- it holds block l-1's raw MLP delta until this * block's norm folds it -- but op_mq1 writes the folded stream back to b_h, so right @@ -3937,7 +3972,7 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { RAD_ISSUE_N(c, B.op_mq2, n, brow_slice(m.b_ao, r0, n, D), modh(h, l, 2, 1), modh(h, l, 3, 2), RAD_W(B.w_n2), segh[h], brow_slice(m.b_h, r0, n, D), brow_slice(m.a_hm.cq(), r0, n, D), brow_slice(m.a_hm.cs(), r0, n, nD), - RAD_NONE); + RAD_NONE, colh[h]); B.gate_up.step(c, m.a_hm, m.b_gu, R, r0, n); B.gq.step(c, m.b_gu, R, r0, n); B.down.step(c, m.a_ffn, m.b_ao, R, r0, n); @@ -3952,7 +3987,7 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { (lane * m.S + V->step) * (int64_t)kMaxSegs * 2 * D * (int64_t)sizeof(uint16_t); RAD_ISSUE_N(c, m.op_nout, R, brows(m.b_ao, R), mod(L - 1, 5, 1), RAD_P_T2(nout, RAD_BF16, ng, 2 * D), RAD_W(m.w_no_n), mod_segs, brows(m.b_h, R), - brows(m.b_hn, R)); + brows(m.b_hn, R), mod_col); /* Block 49's stream, slot L-1: only op_nout folds the last MLP delta into b_h (the reference * FinalLayer norms the same post-fold stream), so this follows it. Nothing between here and * the pass' end writes b_h. */ @@ -4628,17 +4663,22 @@ extern "C" int64_t rad_arch_video_pack(const RadVideoGeom* g, const int32_t* ref return p.rows; } -/* The merged modulation-group boundaries: a SUBSET of rad_arch_video_pack's segment boundaries, - * with the boundaries that fall inside a run of consecutive same-cell segments dropped. The - * denoiser's attention reads the fine pack boundaries (each reference needs its own prefix sink), - * but the modulated norm reads these coarser ones -- a modulation cell is fixed by a segment's kind, - * so a run of reference photos shares one cell and one table column, letting nine photos ride the - * fixed `kMaxSegs`-wide table that the twelve fine segments would overrun. The merge is independent - * of the sampler's step count (whether two neighbours share a cell depends only on their kinds), so - * S is passed as 1 here purely to keep the timestep-embedding blocks distinct; the boundaries it - * yields are the ones step_cond/step_dit derive at the real S. A plain geometry collapses to the - * fine table: it is the same pack, and the driver then stages identical bytes to both operands. Call - * with mod = nullptr for the number of int32s needed. */ +/* The merged modulation groups, in the combined form the step stages as one operand: the group + * BOUNDARIES followed by the group->table-column MAP. The boundaries are a SUBSET of + * rad_arch_video_pack's segment boundaries, with those falling inside a run of consecutive + * same-cell segments dropped -- and once the reference table carries vision-pad runs, also cut + * inside the prompt wherever the pad tag changes the cell. The denoiser's attention reads the fine + * pack boundaries (each reference needs its own prefix sink), but the modulated norm reads these + * coarser ones. A modulation cell is fixed by a segment's kind (and a pad run's tag), so groups + * REPEAT cells: nine photos share one cell, and the pad groups share the video cell with the target + * -- the map sends every group to one of the handful of distinct cells, letting any group count + * ride the fixed `kMaxSegs`-wide table. The merge is independent of the sampler's step count + * (whether two neighbours share a cell depends only on their kinds and tags), so S is passed as 1 + * here purely to keep the timestep-embedding blocks distinct; the boundaries and columns it yields + * are the ones step_cond/step_dit derive at the real S. A plain geometry collapses to the fine + * table with an identity map: it is the same pack, and the norm then reads exactly the pre-map + * bytes. `mod` gets `nb` boundaries then `nb - 1` columns, `2 * nb - 1` int32s total. Call with + * mod = nullptr for the number of int32s needed. */ extern "C" int64_t rad_arch_video_mod_segs(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* mod, int64_t cap) { if (!g || g->n_text < 1 || g->n_text > minimaxh3::kMaxText) return RAD_E_INVAL; @@ -4647,11 +4687,13 @@ extern "C" int64_t rad_arch_video_mod_segs(const RadVideoGeom* g, const int32_t* return RAD_E_INVAL; const minimaxh3::Ref2VAPack p = minimaxh3::ref_pack_of(g, ref_tab); minimaxh3::Ref2VAModGroups grp; - minimaxh3::ref2va_mod_groups(p, 1, &grp); - const int64_t n = (int64_t)grp.bound.size(); + minimaxh3::ref2va_mod_groups(p, 1, minimaxh3::ref_pads_of(ref_tab), &grp); + const int64_t nb = (int64_t)grp.bound.size(); + const int64_t n = nb + nb - 1; if (!mod) return n; if (cap < n) return RAD_E_INVAL; for (size_t k = 0; k < grp.bound.size(); ++k) mod[k] = (int32_t)grp.bound[k]; + for (size_t k = 0; k < grp.col.size(); ++k) mod[nb + k] = (int32_t)grp.col[k]; return n; } #endif diff --git a/arch/minimaxh3/rad_ref2va_pack.cpp b/arch/minimaxh3/rad_ref2va_pack.cpp index d1bbcf68..2973aecb 100644 --- a/arch/minimaxh3/rad_ref2va_pack.cpp +++ b/arch/minimaxh3/rad_ref2va_pack.cpp @@ -287,24 +287,73 @@ static void cell_of_kind(int kind, int64_t S, int* md, int64_t* r0) { } } -void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, Ref2VAModGroups* out) { - out->bound.clear(); out->md.clear(); out->r0.clear(); - /* Walk the segments in sequence order, opening a new group whenever the cell changes or a gap - * would otherwise appear. Empty segments carry no rows: they neither extend nor split a group, - * so a run of photos with an empty cond between them still rides one cell. */ - int cur_md = 0; int64_t cur_r0 = 0; bool open = false; - int64_t prev_end = 0; +void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, const std::vector& runs, + Ref2VAModGroups* out) { + out->bound.clear(); out->col.clear(); out->md.clear(); out->r0.clear(); + /* Normalise the tag runs: keep the part of each that falls inside the text segment, drop the + * rest, order by start, and trim a run that would overlap its predecessor -- runs describe + * disjoint token spans, but the driver's view and this one must never disagree by accident. */ + std::vector norm; + for (const Ref2VATagRun& r : runs) { + Ref2VATagRun c = r; + if (c.end <= c.start) continue; + norm.push_back(c); + } + std::sort(norm.begin(), norm.end(), + [](const Ref2VATagRun& a, const Ref2VATagRun& b) { return a.start < b.start; }); + norm.erase(std::unique(norm.begin(), norm.end(), + [](const Ref2VATagRun& a, const Ref2VATagRun& b) { + return a.start == b.start && a.end == b.end && a.tag == b.tag; + }), + norm.end()); + + /* Lay the row pieces: each non-empty segment contributes its cell, except the text segment, + * which is cut at the (clamped) run edges into prompt pieces (text tag on the text block) and + * pad pieces (the run's tag, still on the video-schedule block -- the reference keeps the pad + * rows on the prompt's timestep row and changes only the ada projection). */ + struct Piece { int64_t start, end; int md; int64_t r0; }; + std::vector pieces; for (const Ref2VASeg& s : p.segs) { if (s.end <= s.start) continue; - int md; int64_t r0; - cell_of_kind(s.kind, S, &md, &r0); - if (!open || md != cur_md || r0 != cur_r0 || s.start != prev_end) { - if (open) out->bound.push_back(s.start); /* close the previous group at this start */ - else out->bound.push_back(0); - cur_md = md; cur_r0 = r0; open = true; - out->md.push_back(md); out->r0.push_back(r0); + if (s.kind == kR2VText) { + int64_t at = s.start; + for (const Ref2VATagRun& r : norm) { + const int64_t a = std::max(r.start, s.start), b = std::min(r.end, s.end); + if (b <= at) continue; /* fully covered already */ + if (a >= s.end) break; /* the rest lies past the prompt */ + if (a > at) pieces.push_back({ at, a, 1, 0 }); + if (b > at) pieces.push_back({ std::max(a, at), b, r.tag, 0 }); + at = std::max(at, b); + } + if (at < s.end) pieces.push_back({ at, s.end, 1, 0 }); + continue; } - prev_end = s.end; + Piece pc; pc.start = s.start; pc.end = s.end; + cell_of_kind(s.kind, S, &pc.md, &pc.r0); + pieces.push_back(pc); + } + + /* Merge adjacent pieces that share a cell -- every merge the old segment walk made still + * happens (a photo run is one repeated cell), and the new pad pieces merge back into a + * prompt/neighbour piece exactly when their cells agree. Cells deduplicate into table + * COLUMNS: `md`/`r0` describe the distinct cells, `col` maps each group to its cell. */ + int cur_col = -1; bool open = false; + int64_t prev_end = 0; + auto column_of = [&](int md, int64_t r0) { + for (size_t c = 0; c < out->md.size(); ++c) + if (out->md[c] == md && out->r0[c] == r0) return (int)c; + out->md.push_back(md); out->r0.push_back(r0); + return (int)out->md.size() - 1; + }; + for (const Piece& pc : pieces) { + const int col = column_of(pc.md, pc.r0); + if (!open || col != cur_col || pc.start != prev_end) { + if (open) out->bound.push_back(pc.start); /* close the previous group at this start */ + else out->bound.push_back(0); + cur_col = col; open = true; + out->col.push_back(col); + } + prev_end = pc.end; } if (open) out->bound.push_back(p.rows); /* the last group runs to the end of the sequence */ } diff --git a/arch/minimaxh3/rad_ref2va_pack.h b/arch/minimaxh3/rad_ref2va_pack.h index 531affb5..5bf56e6a 100644 --- a/arch/minimaxh3/rad_ref2va_pack.h +++ b/arch/minimaxh3/rad_ref2va_pack.h @@ -119,15 +119,33 @@ void ref2va_ada_cell(const Ref2VAPack& p, double t_v, double t_a, std::vector bound; /* [count + 1]: cumulative row boundaries, [0 .. rows] */ - std::vector md; /* [count]: the group's ada projection (0 video, 1 text, 2 audio) */ - std::vector r0; /* [count]: the timestep-embedding block the group's cell reads */ + std::vector col; /* [count]: which cell (index into md/r0) the group reads */ + std::vector md; /* [cells]: the cell's ada projection (0 video, 1 text, 2 audio) */ + std::vector r0; /* [cells]: the timestep-embedding block the cell reads */ }; /* `S` is the sampler's step count (the embedding's per-schedule row span); it fixes the pinned - * blocks at [2S,3S) video / [3S,4S) audio, exactly as the arch's ref_cell_of does. */ -void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, Ref2VAModGroups* out); + * blocks at [2S,3S) video / [3S,4S) audio, exactly as the arch's ref_cell_of does. `runs` are the + * tag runs inside the text segment -- sorted is not required (they are normalised here), anything + * outside the text span is dropped. An empty `runs` gives exactly the segment-kind merge: cells + * then never repeat, so `col` is the identity and the output matches the pre-tag-run tables. */ +void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, const std::vector& runs, + Ref2VAModGroups* out); /* Lay the sequence out. Returns 0, or -1 on a negative dimension (the driver has already bounded * media against the arch's ceilings; this only refuses nonsense). */ diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 1ec67519..692102c3 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -627,6 +627,28 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_ j.ref_tab.insert(j.ref_tab.end(), {first ? 0 : s.frames - 1, 1 /*one latent frame*/, 0 /*no soundtrack*/}); } + /* The vision-pad tag runs, appended after the keyframes: [n, (start, len) x n] token spans + * inside the prompt. The reference implementation tags every image reference's vision block + * -- its `vision_start`, tiles and `vision_end` -- with the VIDEO modality, not text, so the + * denoiser must modulate those rows with the video ada projection. The spans are the placed + * media items' expansions; audio items keep the text tag (the reference tags images only) + * and an item placed past the prompt's end belongs to no step. A table without media still + * writes the count word, so the plugin's reader never runs past the table. */ + if (!j.ref_tab.empty()) { + std::vector> pads; + if (r.media) + for (const mm::Placed& pl : r.media->items) { + if (!pl.item || pl.item->kind == mm::Kind::Audio) continue; + const int64_t a = pl.tok, b = a + (int64_t)pl.item->expand.size(); + if (a < 0 || b <= a || b > j.geom.n_text) continue; + pads.push_back({ a, b }); + } + j.ref_tab.push_back((int32_t)pads.size()); + for (const std::pair& p : pads) { + j.ref_tab.push_back((int32_t)p.first); + j.ref_tab.push_back((int32_t)(p.second - p.first)); + } + } } /* The step's packed sequence. When the denoiser consumes the reference table the pack is the * only source of its rows, segment boundaries and positions -- the reference rows sit between @@ -674,18 +696,20 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_ return no("the reference conditioning layout has no closing segment boundary"); j.seg.resize((size_t)nseg); j.nseg = nseg; - /* The modulation groups. A modulation cell is fixed by a segment's kind, so the denoiser - * merges runs of consecutive same-cell segments and pitches its fixed-width table by the - * GROUP count, not the reference count -- which is how nine reference photos (four groups: - * prompt, all-photos, soundtrack, video) ride a table the fine layout (twelve segments) - * would overrun. The plugin merges for us (rad_arch_video_mod_segs); one that exports none - * merges nothing, so the group table is the fine one and the older per-segment ceiling - * applies. Refuse over-wide merges here, at submit, where a clean answer is still possible. */ + /* The modulation groups. A modulation cell is fixed by a segment's kind and by the tag of a + * vision-pad run, so the denoiser merges runs of consecutive same-cell segments AND + * deduplicates the cells: the merged table is the group BOUNDARIES followed by the + * group->column MAP, and its width is the DISTINCT-CELL count, not the group or reference + * count -- which is how nine reference photos interleaved with prompt text (and their pad + * runs, which split it) ride a table the fine layout would overrun. The plugin merges for us + * (rad_arch_video_mod_segs); one that exports none merges nothing, so the group table is the + * fine one, the map is empty and the older per-segment ceiling applies. Refuse over-wide + * merges here, at submit, where a clean answer is still possible. */ int nmod = -1; if (mod_segs_) { - j.mod_seg.assign((size_t)kSegCap, 0); - nmod = (int)mod_segs_(&j.geom, j.ref_tab.data(), j.mod_seg.data(), kSegCap); - if (nmod < 0 || nmod > kSegCap) + j.mod_seg.assign((size_t)(2 * kSegCap), 0); + nmod = (int)mod_segs_(&j.geom, j.ref_tab.data(), j.mod_seg.data(), 2 * kSegCap); + if (nmod < 1 || nmod > 2 * kSegCap) return no("the model could not merge the reference conditioning into its " "modulation groups"); j.mod_seg.resize((size_t)nmod); @@ -694,12 +718,23 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_ j.mod_seg = j.seg; } j.nmod = nmod; - const int ngroups = nmod - 1; /* `mod_seg` is boundaries: one more than the groups */ - if (d.max_ref_segs > 0 && ngroups > d.max_ref_segs) - return no("these references change the conditioning's modulation cell " + - std::to_string(ngroups) + " times, but this deployment's modulation table holds " + - std::to_string(d.max_ref_segs) + " cells -- ask for references that share their " - "modalities and target, or fewer of them"); + if (d.max_ref_segs > 0) { + /* With the map staged the table width is the highest column + 1; without it every + * group is its own cell, so the group count is the width. */ + int ncells = nmod - 1; /* boundaries: one more than the groups */ + if (mod_segs_) { + const int nb = (nmod + 1) / 2; + ncells = 0; + for (int k = nb; k < nmod; ++k) + if (j.mod_seg[(size_t)k] + 1 > ncells) ncells = j.mod_seg[(size_t)k] + 1; + } + if (ncells > d.max_ref_segs) + return no("these references and their prompt markers switch the conditioning's " + "modulation cell " + std::to_string(ncells) + + " ways, but this deployment's modulation table holds " + + std::to_string(d.max_ref_segs) + " cells -- ask for references that share " + "their modalities and target, or fewer of them"); + } /* `rows` stays the plain text+audio+video count: every non-step pass (encode, decode, * audio, upscale) stages its own segment table and target counts from it and must see the * bytes it sees today. Only build_step runs at the widened `step_rows`. */ @@ -746,9 +781,10 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_ j.seg_s.assign(segs.begin(), segs.begin() + nseg_s); j.nseg_s = nseg_s; if (mod_segs_) { - j.mod_seg_s.assign((size_t)kSegCap, 0); - const int n = (int)mod_segs_(&gs, j.ref_tab.data(), j.mod_seg_s.data(), kSegCap); - if (n < 1 || n > kSegCap) + j.mod_seg_s.assign((size_t)(2 * kSegCap), 0); + const int n = (int)mod_segs_(&gs, j.ref_tab.data(), j.mod_seg_s.data(), + 2 * kSegCap); + if (n < 1 || n > 2 * kSegCap) return no("the model could not merge the draft-size reference conditioning " "into its modulation groups"); j.mod_seg_s.resize((size_t)n); @@ -1154,10 +1190,10 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, } reg_[R_SEG].used = 4 * 4; } - /* The norm's merged boundaries. On a widened step that is the plugin's merged group table (a - * subset of the fine one just staged into R_SEG); on the plain path and every non-step pass it - * is the fine table verbatim -- nothing merges there, so the norm reads the same bytes as the - * attention and the generated output is exactly what it was before this operand split. */ + /* The norm's merged groups: boundaries then, since ABI 28, the group->column map (the plugin's + * rad_arch_video_mod_segs combined output). On the plain path and every non-step pass it is the + * fine table alone -- nothing merges there and the arch reads no map, so the norm reads the + * same bytes as the attention and the output is what it was before this operand split. */ int32_t* mod = hptr(R_MOD); if (wide && (wsmall ? j.nmod_s : j.nmod) > 0) { const std::vector& tab = wsmall ? j.mod_seg_s : j.mod_seg; diff --git a/core/plugin/registry.h b/core/plugin/registry.h index eda15e4a..59c7f285 100644 --- a/core/plugin/registry.h +++ b/core/plugin/registry.h @@ -104,10 +104,11 @@ struct Plugin { * out and refuses requests that carry VAE references. */ int64_t (*arch_video_pack)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, float*, int64_t) = nullptr; - /* Optional (rad_builder.h); the merged modulation-group boundaries a conditioned pack collapses - * to (rad_arch_video_mod_segs). Null with arch_video_pack present means the driver stages the - * fine table into the norm operand too -- correct whenever nothing merges (a plain or a - * single-reference sequence), and refused at submit only when a wide pack would need it. */ + /* Optional (rad_arch_video_mod_segs, documented at the plugin's definition); the merged + * modulation groups a conditioned pack collapses to, as boundaries then the group->column map. + * Null with arch_video_pack present means the driver stages the fine table into the norm operand + * too, boundaries only -- correct whenever nothing merges (a plain or a single-reference + * sequence), and refused at submit only when a wide pack would need it. */ int64_t (*arch_video_mod_segs)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t) = nullptr; /* Optional (rad_builder.h); null means the driver runs no encode pass. */ diff --git a/libr4d/r4d_video.hip b/libr4d/r4d_video.hip index e0286431..e5091b39 100644 --- a/libr4d/r4d_video.hip +++ b/libr4d/r4d_video.hip @@ -85,10 +85,14 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel( const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ qs, uint16_t* __restrict__ z, int n, int n_seq, float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld, float wadd, - int once, int layer, int none) { + int once, int layer, int none, const int* __restrict__ colmap) { __shared__ float sh[kT / 32]; const int r = blockIdx.x; - const int e = seq_of(cu, n_seq, r); + int e = seq_of(cu, n_seq, r); + // Optional column indirection: `cu` may bound MORE groups than the modulation table has + // columns (groups that share a cell map to one column), so a group index is translated to its + // table column here -- null leaves the segment index itself, exactly as before. + if (colmap) e = colmap[e]; uint16_t* xr = x + (size_t)r * x_ld; float v[kRmChunks][8]; float ss = 0.0f; @@ -489,6 +493,10 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) { const RadTensor* q = qmode ? r4d_opt(a, 6) : nullptr; const RadTensor* qs = qmode ? r4d_opt(a, 7) : nullptr; const RadTensor* z = r4d_opt(a, qmode ? 8 : 6); + // Optional group->column map, issued after the last operand of either mode (slot 9 with the + // quantising chain, slot 7 with the plain one). Absent for every other issuer: the segment + // index remains the column. + const RadTensor* cm = r4d_opt(a, qmode ? 9 : 7); if (!sc || !cu || !x || (qmode ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL); const bool gated = r4d_geti_or(a, "gated", 0) != 0; if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL); @@ -513,8 +521,12 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) { if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE); } const long long n_seq = r4d_numel(cu) - 1, rows = qmode ? rq : rz; - if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || (w && r4d_numel(w) < n) || - (qmode && rqs < rows) || (gated && (ry < rows || rg < n_seq)) || (z && rz < rows)) + if (cm && (!is_i32(cm) || !r4d_contig(cm) || r4d_numel(cm) < n_seq)) + return R4D_NO(RAD_E_SHAPE); + // With the map the table rows index the COLUMNS, not the groups, so its row count need not + // reach n_seq; the issuer (the only one who passes a map) guarantees mapped columns < rows. + if (rows <= 0 || n_seq <= 0 || rx < rows || (!cm && rs < n_seq) || (w && r4d_numel(w) < n) || + (qmode && rqs < rows) || (gated && (ry < rows || (!cm && rg < n_seq))) || (z && rz < rows)) return R4D_NO(RAD_E_SHAPE); const float eps = (float)r4d_getf(a, "eps", 1e-6); const float wadd = (float)r4d_getf(a, "wadd", 0.0); @@ -532,7 +544,7 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) { Q ? (uint8_t*)q->data : nullptr, Q ? (float*)qs->data : nullptr, \ z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, eps, (int)yl, \ (int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl, wadd, once, layer, \ - none) + none, cm ? (const int*)cm->data : nullptr) if (qmode == 2) { if (gated) R4D_RMQ(true, 2); else R4D_RMQ(false, 2); diff --git a/libref/ref_gen.cpp b/libref/ref_gen.cpp index df781c71..1d6f1235 100644 --- a/libref/ref_gen.cpp +++ b/libref/ref_gen.cpp @@ -164,14 +164,16 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ rms_mod / rms_mod_quant_fp8 */ /* The checks both forms share: `s` holds [shift | scale] in each of its n_seq rows, `g` a gate - * row per sequence when `gated`, and every row operand at least `rows` rows. */ + * row per sequence when `gated`, and every row operand at least `rows` rows. With `mapped` the + * column map is bound -- sequences address TABLE COLUMNS through it, so `s` (and `g`) may hold + * fewer rows than there are sequences, and the map's own bound is the caller's. */ static int rms_mod_check(const RadTensor* y, const RadTensor* g, const RadTensor* s, const RadTensor* w, const RadTensor* x, int64_t n, int64_t n_seq, - int64_t rows, bool gated) { + int64_t rows, bool gated, bool mapped) { if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || (w && numel(w) < n) || - numel(s) < n_seq * 2 * n) + (!mapped && numel(s) < n_seq * 2 * n)) return RAD_E_SHAPE; - if (gated && (rows_of(y, n) < rows || numel(g) < n_seq * n)) return RAD_E_SHAPE; + if (gated && (rows_of(y, n) < rows || (!mapped && numel(g) < n_seq * n))) return RAD_E_SHAPE; return RAD_OK; } @@ -230,11 +232,15 @@ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor* /* A diffusion transformer's adaptive RMS norm with a shift (MiniMax-H3's * `norm(h) * (1 + scale) + shift`), the gated residual of the branch before it optionally first; - * the norm chain rounds to z's dtype. */ + * the norm chain rounds to z's dtype. + * + * The optional trailing `colmap` (slot 7 bf16, slot 9 quant -- see rad_runtime.h) maps each + * sequence to a TABLE COLUMN, so sequences that share a modulation cell can address one table row + * through non-contiguous boundaries; the map indexes sequences, one i32 each. */ int ref_rms_mod(const RadArgs* a, RadStream) { if (a->n_t < 7) return RAD_E_INVAL; const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = t_in(a, 3); - const RadTensor *cu = &a->t[4], *x = &a->t[5], *z = &a->t[6]; + const RadTensor *cu = &a->t[4], *x = &a->t[5], *z = &a->t[6], *cm = t_in(a, 7); const int64_t n = p_int(a, "n", 0); const bool gated = p_int(a, "gated", 0) != 0; const float eps = p_f32(a, "eps", 1e-6f); @@ -246,11 +252,14 @@ int ref_rms_mod(const RadArgs* a, RadStream) { if (none && t_in(a, 3)) return RAD_E_INVAL; if (n <= 0 || (gated && (!y || !g))) return RAD_E_SHAPE; const int64_t rows = rows_of(z, n), n_seq = numel(cu) - 1; - RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated)); + if (cm && (cm->dtype != RAD_I32 || numel(cm) < n_seq)) return RAD_E_SHAPE; + RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated, cm != nullptr)); REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { std::vector o((size_t)n); - rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, z->dtype, o.data(), wadd, once, layer, none); + int64_t e = seq_of(cu, n_seq, r); + if (cm) e = (int64_t)ldt(cm, e); + rms_mod_row(y, g, s, w, x, r, e, n, eps, gated, z->dtype, o.data(), wadd, once, layer, none); const int64_t zb = rowoff(z, r, n), zs = laststride(z); for (int64_t i = 0; i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]); } @@ -264,6 +273,7 @@ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) { if (a->n_t < 9) return RAD_E_INVAL; const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = t_in(a, 3); const RadTensor *cu = &a->t[4], *x = &a->t[5], *q = &a->t[6], *sc = &a->t[7], *z = t_in(a, 8); + const RadTensor *cm = t_in(a, 9); const int64_t n = p_int(a, "n", 0), grp = p_int(a, "group", 0); const bool gated = p_int(a, "gated", 0) != 0; const float eps = p_f32(a, "eps", 1e-6f); @@ -275,12 +285,15 @@ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) { if (none && t_in(a, 3)) return RAD_E_INVAL; if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE; const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp; - RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated)); + if (cm && (cm->dtype != RAD_I32 || numel(cm) < n_seq)) return RAD_E_SHAPE; + RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated, cm != nullptr)); if (numel(sc) < rows * ngrp || (z && rows_of(z, n) < rows)) return RAD_E_SHAPE; REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { std::vector o((size_t)n); - rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, RAD_BF16, o.data(), wadd, once, layer, none); + int64_t e = seq_of(cu, n_seq, r); + if (cm) e = (int64_t)ldt(cm, e); + rms_mod_row(y, g, s, w, x, r, e, n, eps, gated, RAD_BF16, o.data(), wadd, once, layer, none); const int64_t zb = z ? rowoff(z, r, n) : 0, zs = z ? laststride(z) : 0; for (int64_t i = 0; z && i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]); const int64_t qb = rowoff(q, r, n), qs = laststride(q); diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 4c6d0658..eb658385 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -1,4 +1,4 @@ -/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 27 and +/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 28 and * RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot * of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it * from the test's printout only together with a version bump. */ diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index 62061d0c..bd44b5a5 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -8,7 +8,7 @@ * * Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every * struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and - * the layout agrees with the table below, taken at RAD_ABI_VERSION 27 and RAD_FORMAT_VER 2. Under + * the layout agrees with the table below, taken at RAD_ABI_VERSION 28 and RAD_FORMAT_VER 2. Under * those versions a listed field may not move or change size, an ABI struct may only grow by fields * past its old end, and an on-disk struct may not change at all. The table is a snapshot of the * headers: nothing else states the layout. When it disagrees the test prints the live table. @@ -58,8 +58,10 @@ std::vector cpp_rows() { }; } -/* The layout at RAD_ABI_VERSION 27 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 27, kTableFormat = 2; +/* The layout at RAD_ABI_VERSION 28 / RAD_FORMAT_VER 2 (see the file header). ABI 28 changed table + * semantics (the reference table's tag-run tail, the mod-cu column map) and the rms_mod operand + * slots, not any struct's shape -- the snapshot is unchanged from 27, only re-stamped. */ +constexpr uint32_t kTableAbi = 28, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/ref2va_pack_test.cpp b/tests/ref2va_pack_test.cpp index 16d30599..943c421f 100644 --- a/tests/ref2va_pack_test.cpp +++ b/tests/ref2va_pack_test.cpp @@ -276,7 +276,7 @@ TEST(pack_mod_groups_images_collapse_to_four) { const int64_t S = 24; Ref2VAModGroups grp; - ref2va_mod_groups(p, S, &grp); + ref2va_mod_groups(p, S, {}, &grp); CHECK_EQ(grp.md.size(), 4u); CHECK(grp.md == std::vector({ 1, 0, 2, 0 })); /* text, photos, audio, video */ /* Cells: text and the video target read the video schedule (r0 = 0); the photos read the @@ -302,8 +302,8 @@ TEST(pack_mod_groups_invariants_over_the_goldens) { for (const char* name : { "t2va", "fl2va", "ref2va_all", "chain", "no_text" }) { const Ref2VAPack p = build_case(golden()[name]); Ref2VAModGroups a, b; - ref2va_mod_groups(p, 1, &a); - ref2va_mod_groups(p, 64, &b); + ref2va_mod_groups(p, 1, {}, &a); + ref2va_mod_groups(p, 64, {}, &b); CHECK(a.bound == b.bound); CHECK(!a.bound.empty()); CHECK_EQ(a.bound.front(), 0); @@ -322,11 +322,42 @@ TEST(pack_mod_groups_invariants_over_the_goldens) { size_t g = 0; while (g + 1 < a.bound.size() && a.bound[g + 1] <= s.start) ++g; CHECK(a.bound[g] <= s.start && s.end <= a.bound[g + 1]); - CHECK_EQ(a.md[g], ref2va_seg_tag(s.kind)); + CHECK_EQ(a.md[a.col[g]], ref2va_seg_tag(s.kind)); } - /* adjacent groups differ in (md, r0) -- merging left no mergeable neighbours */ - for (size_t i = 0; i + 1 < a.md.size(); ++i) - CHECK(a.md[i] != a.md[i + 1] || a.r0[i] != a.r0[i + 1]); + /* adjacent groups differ in cell -- merging left no mergeable neighbours -- and two groups + * share a column EXACTLY when they read the same cell: a cond photo and a ref photo carry + * one cell, and separated by a soundtrack they stay two groups on one column, so the map + * is not the identity. Mirrors the pack's cell_of_kind at a's S. */ + const int64_t S = 1; + auto cell = [S](int kind) -> std::pair { + switch (kind) { + case kR2VAudio: return { 2, S }; break; /* audio schedule */ + case kR2VCondAudio: + case kR2VRefAudio: return { 2, 2 * S }; break; /* audio-pinned block */ + case kR2VText: return { 1, 0 }; break; /* video schedule */ + case kR2VCond: + case kR2VRefImg: return { 0, 2 * S }; break; /* video-pinned block */ + default: return { 0, 0 }; break; /* video target */ + } + }; + auto kind_at = [&p](int64_t row) { + for (const Ref2VASeg& s : p.segs) + if (s.start <= row && row < s.end) return s.kind; + return -1; + }; + for (size_t i = 0; i + 1 < a.col.size(); ++i) CHECK(a.col[i] != a.col[i + 1]); + std::vector used(a.md.size(), 0); + for (size_t i = 0; i < a.col.size(); ++i) { + CHECK(a.col[i] >= 0 && (size_t)a.col[i] < a.md.size()); + used[a.col[i]] = 1; + const std::pair c = cell(kind_at(a.bound[i])); + CHECK_EQ(a.md[a.col[i]], c.first); + CHECK_EQ(a.r0[a.col[i]], c.second); + for (size_t j = 0; j < i; ++j) + CHECK_EQ((int)(a.col[i] == a.col[j]), + (int)(cell(kind_at(a.bound[i])) == cell(kind_at(a.bound[j])))); + } + for (char u : used) CHECK(u); /* every column is addressed */ } } @@ -339,7 +370,7 @@ TEST(pack_mod_groups_plain_equals_the_fine_table) { Ref2VAGeom g{ 3, 8, 10, 4 }; CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0); Ref2VAModGroups grp; - ref2va_mod_groups(p, 32, &grp); + ref2va_mod_groups(p, 32, {}, &grp); CHECK_EQ(grp.md.size(), 3u); CHECK(grp.md == std::vector({ 1, 2, 0 })); /* text, audio, video */ CHECK(grp.r0 == std::vector({ 0, 32, 0 })); /* video sched, audio sched, video */ @@ -347,4 +378,91 @@ TEST(pack_mod_groups_plain_equals_the_fine_table) { CHECK(grp.bound == std::vector({ 0, 5, 13, 5 + 8 + 60 })); } +TEST(pack_mod_groups_pad_run_cuts_the_prompt) { + /* One vision-pad run inside the prompt: the reference tags those rows VIDEO, so they get a + * group of their own reading the video ada projection on the VIDEO-SCHEDULE block (the prompt + * keeps its own timestep row -- only the projection changes). The cell deduplication is the + * whole point: the text pieces before and after the pad share ONE column, and the pad shares + * its column with the video target -- three distinct cells for five groups. */ + Ref2VAPack p; + Ref2VAGeom g{ 3, 8, 10, 4 }; + CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0); + const int64_t S = 32; + Ref2VAModGroups grp; + ref2va_mod_groups(p, S, { Ref2VATagRun{ 1, 3, 0 } }, &grp); + CHECK(grp.bound == std::vector({ 0, 1, 3, 5, 13, 5 + 8 + 60 })); + CHECK(grp.col == std::vector({ 0, 1, 0, 2, 1 })); /* text, pad, text, audio, video */ + CHECK(grp.md == std::vector({ 1, 0, 2 })); + CHECK(grp.r0 == std::vector({ 0, 0, S })); /* pad on the video schedule */ +} + +TEST(pack_mod_groups_many_pads_stay_few_cells) { + /* Nine reference photos, each with its pad run and prompt text between: the groups multiply + * (text and pad alternate), the DISTINCT CELLS do not -- four: text, pad/video, the photos' + * pinned video cell, the soundtrack. This is the merge the fixed modulation table rides. */ + Ref2VAGeom g{ 2, 8, 8, 3 }; + std::vector refs(9, Ref2VARef{ kR2VRefImage, 6, 6, 1, 0 }); + Ref2VAPack p; + CHECK_EQ(ref2va_build(100, g, {}, refs, &p), 0); + std::vector runs; + for (int i = 0; i < 9; ++i) runs.push_back({ (int64_t)i * 10 + 1, (int64_t)i * 10 + 3, 0 }); + const int64_t S = 24; + Ref2VAModGroups grp; + ref2va_mod_groups(p, S, runs, &grp); + CHECK_EQ(grp.col.size(), 22u); /* 19 prompt pieces + photos + soundtrack + video */ + CHECK_EQ(grp.md.size(), 4u); /* ... over four cells */ + CHECK(grp.md == std::vector({ 1, 0, 0, 2 })); /* text, pad, photo-pinned, audio */ + CHECK(grp.r0 == std::vector({ 0, 0, 2 * S, S })); + /* The video target shares the pad's cell and column; the photo group shares the pad's + * projection but not its block. */ + CHECK_EQ(grp.col.front(), 0); + CHECK_EQ(grp.col[1], 1); + CHECK_EQ(grp.col.back(), 1); + CHECK_EQ(grp.bound.front(), 0); + CHECK_EQ(grp.bound.back(), p.rows); +} + +TEST(pack_mod_groups_runs_are_normalised) { + /* Runs arrive as the driver staged them: unsorted, partly outside the prompt, even empty. The + * merge clamps each to the text segment, drops what falls outside, and the result is the same + * cut as hand-placed in-range runs. A run covering the whole prompt leaves one pad group and + * NO text group; an out-of-range run cuts nothing at all. */ + Ref2VAPack p; + Ref2VAGeom g{ 3, 8, 10, 4 }; + CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0); + const int64_t S = 32; + Ref2VAModGroups one, a, b; + ref2va_mod_groups(p, S, { Ref2VATagRun{ 1, 5, 0 } }, &one); + /* Same cut: out-of-range tails, an empty run, a run starting before the prompt and one ending + * at its start, in scrambled order. The two in-range fragments meet and merge into one pad + * group [1,5), exactly the single-run table. */ + ref2va_mod_groups(p, S, + { Ref2VATagRun{ 4, 9, 0 }, Ref2VATagRun{ 3, 6, 0 }, Ref2VATagRun{ 1, 3, 0 }, + Ref2VATagRun{ 2, 2, 0 }, Ref2VATagRun{ -4, 0, 0 } }, + &a); + CHECK(a.bound == one.bound); + CHECK(a.col == one.col); + ref2va_mod_groups(p, S, { Ref2VATagRun{ 5, 9, 0 } }, &b); /* starts at the segment end */ + CHECK_EQ(b.col.size(), 3u); /* untouched: the plain three groups */ + CHECK(b.col == std::vector({ 0, 1, 2 })); +} + +TEST(pack_mod_groups_pad_tag_audio_reads_the_audio_projection) { + /* The run struct carries its tag, so a tag-2 run (the audio modality) on the prompt's rows + * would open the (2, 0) cell -- a distinct column from both the text piece and the audio + * TARGET's (2, S). The reference tags only image pads (tag 0), so nothing emits this today; + * the plumbing is tag-generic on purpose. */ + Ref2VAPack p; + Ref2VAGeom g{ 3, 8, 10, 4 }; + CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0); + Ref2VAModGroups grp; + ref2va_mod_groups(p, 16, { Ref2VATagRun{ 0, 5, 2 } }, &grp); + /* The run covers the whole prompt, so the text group is entirely pad: three groups over three + * distinct cells -- (2,0) pad, (2,16) audio target, (0,0) video target. */ + CHECK(grp.bound == std::vector({ 0, 5, 13, 73 })); + CHECK(grp.md == std::vector({ 2, 2, 0 })); + CHECK(grp.r0 == std::vector({ 0, 16, 0 })); + CHECK(grp.col == std::vector({ 0, 1, 2 })); +} + RAD_TEST_MAIN() diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 912617db..e8d19839 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -6544,6 +6544,72 @@ TEST(rms_mod_rounds_each_step_and_reads_shift_then_scale) { CHECK_EQ(run("rms_mod", c), RAD_E_SHAPE); } +/* The optional column map (rad_runtime.h, ABI 28): sequences address TABLE COLUMNS through it, + * so sequences that share a modulation cell read one table row through boundaries that do not + * merge -- and the gate and table may hold fewer rows than there are sequences. A mapped run + * must equal the same computation with the columns shuffled into sequence order and no map. */ +TEST(rms_mod_column_map_redirects_sequences_to_table_columns) { + const std::vector yv = { 2, -4, 2, -4, 2, -4 }; + T w(RAD_BF16, {2}); w.f({1.5f, 0.75f}); + T cu(RAD_I32, {3}); cu.n({0, 1, 3}); /* row 0 is sequence 0, rows 1-2 sequence 1 */ + /* Mapped: columns {B, A} read by sequences {1, 0} -- A's shift/scale/gate land on sequence 0, + * B's on the rest, exactly the identity run's pairing with the table rows swapped. */ + T sA(RAD_BF16, {2, 4}); sA.f({0, 0.5f, 0.00390625f, 0, 0.125f, 1, 0.5f, 0.25f}); + T gA(RAD_BF16, {2, 2}); gA.f({0, 0, 0.5f, 0.25f}); + T cm(RAD_I32, {2}); cm.n({1, 0}); + T y(RAD_BF16, {3, 2}); y.f(yv); + T x1(RAD_BF16, {3, 2}); x1.f({1, -1, 1, -1, 1, -1}); + T z1(RAD_BF16, {3, 2}); + A a; a.t(y).t(gA).t(sA).t(w).t(cu).t(x1).t(z1).t(cm).i("M", 3).i("n", 2).d("eps", 0) + .i("gated", 1).s("dtype", "bf16"); + CHECK_OK(run("rms_mod", a)); + CHECK_EQ(x1.at(0), 2.0f); CHECK_EQ(x1.at(1), -2.0f); /* sequence 0: A's gate */ + CHECK_EQ(z1.at(0), 2.375f); CHECK_EQ(z1.at(1), 0.0625f); /* sequence 0: A's row */ + CHECK_EQ(z1.at(2), 1.5f); CHECK_EQ(z1.at(3), -0.25f); /* rows 1-2: B, ungated */ + CHECK_EQ(z1.at(4), 1.5f); CHECK_EQ(z1.at(5), -0.25f); + + /* The same output with no map, columns in sequence order. */ + T sB(RAD_BF16, {2, 4}); sB.f({0.125f, 1, 0.5f, 0.25f, 0, 0.5f, 0.00390625f, 0}); + T gB(RAD_BF16, {2, 2}); gB.f({0.5f, 0.25f, 0, 0}); + T x2(RAD_BF16, {3, 2}); x2.f({1, -1, 1, -1, 1, -1}); + T z2(RAD_BF16, {3, 2}); + A b; b.t(y).t(gB).t(sB).t(w).t(cu).t(x2).t(z2).i("M", 3).i("n", 2).d("eps", 0) + .i("gated", 1).s("dtype", "bf16"); + CHECK_OK(run("rms_mod", b)); + CHECK(x1.mem == x2.mem); + CHECK(z1.mem == z2.mem); + + /* One column for two sequences: the map makes a smaller-than-sequences gate and table legal, + * and without the map the same call is refused. */ + T s1(RAD_BF16, {1, 4}); s1.f({0.125f, 1, 0.5f, 0.25f}); + T g1(RAD_BF16, {1, 2}); g1.f({0.5f, 0.25f}); + T cm1(RAD_I32, {2}); cm1.n({0, 0}); + T x3(RAD_BF16, {3, 2}); x3.f({1, -1, 1, -1, 1, -1}); + T z3(RAD_BF16, {3, 2}); + A d; d.t(y).t(g1).t(s1).t(w).t(cu).t(x3).t(z3).t(cm1).i("M", 3).i("n", 2).d("eps", 0) + .i("gated", 1).s("dtype", "bf16"); + CHECK_OK(run("rms_mod", d)); + for (int64_t r = 0; r < 3; ++r) { + CHECK_EQ(z3.at(2 * r), 2.375f); + CHECK_EQ(z3.at(2 * r + 1), 0.0625f); + } + A e; e.t(y).t(g1).t(s1).t(w).t(cu).t(x3).t(z3).i("M", 3).i("n", 2).d("eps", 0) + .i("gated", 1).s("dtype", "bf16"); + CHECK_EQ(run("rms_mod", e), RAD_E_SHAPE); + + /* A map that is not i32, or shorter than the sequence count, is refused. */ + T cmf(RAD_F32, {2}); cmf.f({1, 0}); + T x4(RAD_BF16, {3, 2}); x4.f({1, -1, 1, -1, 1, -1}); + T z4(RAD_BF16, {3, 2}); + A f; f.t(y).t(gA).t(sA).t(w).t(cu).t(x4).t(z4).t(cmf).i("M", 3).i("n", 2).d("eps", 0) + .i("gated", 1).s("dtype", "bf16"); + CHECK_EQ(run("rms_mod", f), RAD_E_SHAPE); + T cms(RAD_I32, {1}); cms.n({1}); + A g; g.t(y).t(gA).t(sA).t(w).t(cu).t(x4).t(z4).t(cms).i("M", 3).i("n", 2).d("eps", 0) + .i("gated", 1).s("dtype", "bf16"); + CHECK_EQ(run("rms_mod", g), RAD_E_SHAPE); +} + /* rms_mod_quant_fp8 is rms_mod with its chain in bf16 and quant_act_fp8 over that row: the same * bytes in x, z, the codes and the scales as the pair. */ TEST(rms_mod_quant_fp8_is_rms_mod_then_quant_act_fp8) { @@ -6578,6 +6644,43 @@ TEST(rms_mod_quant_fp8_is_rms_mod_then_quant_act_fp8) { CHECK(sc1.mem == sc2.mem); } +/* The quant form takes the column map at its own trailing slot (9): the same run, both per-column + * operands' rows swapped, the sequences redirected to each other's column, matches byte for byte. */ +TEST(rms_mod_quant_fp8_takes_the_column_map_too) { + const std::vector yv = { 5, 6, 7, 8, 0.3f, -0.7f, 0.1f, 1.9f }; + const std::vector gv = { 0, 0.5f, 2, -1, 0.5f, 1, -1, 2 }; + const std::vector xv = { 1, 2, 3, 4, -0.25f, 0.5f, 3, -2 }; + const std::vector sv = { 0.5f, -0.5f, 1, 0, 0.25f, 0.125f, -0.75f, 2, + 0, 1, -1, 0.5f, 0.125f, 0.25f, 0.5f, 1 }; + const int64_t n = 4; + T cu(RAD_I32, {3}); cu.n({0, 1, 2}); + T y(RAD_BF16, {2, n}); y.f(yv); + T g(RAD_BF16, {2, n}); g.f(gv); + T s(RAD_BF16, {2, 2 * n}); s.f(sv); + T w(RAD_BF16, {n}); w.f({1, 0.5f, 2, 0.75f}); + T x1(RAD_BF16, {2, n}); x1.f(xv); + T q1(RAD_F8E4M3, {2, n}), sc1(RAD_F32, {2, 2}), z1(RAD_BF16, {2, n}); + A a; a.t(y).t(g).t(s).t(w).t(cu).t(x1).t(q1).t(sc1).t(z1) + .i("M", 2).i("n", n).d("eps", 1e-5).i("group", 2).i("gated", 1).s("dtype", "bf16"); + CHECK_OK(run("rms_mod_quant_fp8", a)); + + T gs(RAD_BF16, {2, n}); + gs.f({ gv[4], gv[5], gv[6], gv[7], gv[0], gv[1], gv[2], gv[3] }); + T ss(RAD_BF16, {2, 2 * n}); + ss.f({ sv[8], sv[9], sv[10], sv[11], sv[12], sv[13], sv[14], sv[15], + sv[0], sv[1], sv[2], sv[3], sv[4], sv[5], sv[6], sv[7] }); + T cm(RAD_I32, {2}); cm.n({1, 0}); + T x2(RAD_BF16, {2, n}); x2.f(xv); + T q2(RAD_F8E4M3, {2, n}), sc2(RAD_F32, {2, 2}), z2(RAD_BF16, {2, n}); + A b; b.t(y).t(gs).t(ss).t(w).t(cu).t(x2).t(q2).t(sc2).t(z2).t(cm) + .i("M", 2).i("n", n).d("eps", 1e-5).i("group", 2).i("gated", 1).s("dtype", "bf16"); + CHECK_OK(run("rms_mod_quant_fp8", b)); + CHECK(x1.mem == x2.mem); + CHECK(z1.mem == z2.mem); + CHECK(q1.mem == q2.mem); + CHECK(sc1.mem == sc2.mem); +} + /* flow_x0_step in f32 steps: st = 1 - 0.3f, r = 0.4f / 0.7f, d = x + st v, x' = r x + (1 - r) d. * From x 1, v 3 that is 1.8999999f (0x3ff33333), where the algebraically equal x + (1 - r) st v * gives 1.9f; from x -2.5, v 0.75 it is -2.275f. */