Files
Strata/engine/include/strata/kernels/loop_adapter.hpp
T
Niko1221 781d9ab621 loop: strata_dual_coda_loop_v1 (the owner's Qwen4-35B-A3B-Loop.safetensors) on the looped-core mechanics of #7673
The format is read from the safetensors metadata (core 12..27, coda 28..39) and its math follows the owner's trainer
(03_train_dual_coda_loop.py): attn / mlp LoRAs (hidden -> 128 -> hidden, scale 0.25) added to the block outputs, the
cross-pass mixer R = x + sigmoid(gate) * up(silu(down(rms(m_prev - x) * (1 + norm)))), the entry of every extra pass is
the core's input state, and the coda LoRA delta is scaled by cd_omega[layer] from the first </think> token on.

New: LoopTarget::kAttn / kMlp, loop_lora_add_gated, loop_adapter_set_coda, --loop-coda universal|compact, a sticky
</think> flag (kLoopStickyClose) in the existing per-token flag vector. Without a loop adapter nothing runs.
2026-12-04 07:01:39 +01:00

299 lines
17 KiB
C++

// include/strata/kernels/loop_adapter.hpp - Looped Qwen3.8-Flash-Next (qwen4_exp) recurrent core adapter.
//
// Opt-in (--loop-adapter <ckpt.safetensors> [--loop-passes N]): when unloaded, zero overhead and byte-identical
// to stock Strata. When loaded, executes T passes over core layers [core_start, core_end) with:
// * Anchor-grounded 4-stream HCWorkspaceEntry (FP32 grouped RMSNorm + RMS-matched interpolation + low-rank gate)
// * Per-step 4-stream HCCrossPassMixer (FP32 grouped RMSNorm + low-rank delta + delta_kappa scaling)
// * Pre-folded per-pass core LoRAs (GDN qkv/z/a/b/out, QSA q/k/v/o, MoE router gate, shared expert gate/up/down)
// * Coda LoRAs on layers [core_end, core_end + coda_lora_layers)
// * Distinct GDN and QSA recurrent/KV state slots per pass p = 1..T-1 while sharing 100% of base weights & RAM experts.
#pragma once
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
namespace strata::kernels {
enum class LoopTarget : int {
kGdnQkv = 0,
kGdnZ = 1,
kGdnA = 2,
kGdnB = 3,
kGdnOut = 4,
kQsaQ = 5,
kQsaK = 6,
kQsaV = 7,
kQsaO = 8,
kMoeGate = 9,
kShGate = 10,
kShUp = 11,
kShDown = 12,
kAttn = 13, ///< strata_dual_coda_loop_v1: hidden -> r -> hidden delta on the token-mixer block's output (input: the HC-mixed block input)
kMlp = 14, ///< same, on the MoE block's output (input: the HC-mixed MoE input)
kCount = 15,
};
/// think_start_id value that selects the "sticky close" gate of the dual-coda format: the per-token flag is 1 from the
/// first `</think>` token (inclusive) to the end of the sequence (the trainer's `cumsum(ids == 248069) > 0`).
constexpr int32_t kLoopStickyClose = -2;
struct LoopLoraPair {
const float* a = nullptr; ///< device [rank, in_dim] FP32 row-major
const float* b_eff = nullptr; ///< device [out_dim, rank] FP32 row-major (alpha/rank * pass_gate pre-folded)
int in_dim = 0;
int out_dim = 0;
int rank = 0;
bool valid() const { return a != nullptr && b_eff != nullptr && rank > 0; }
};
struct LoopStep {
int64_t layer = 0; ///< physical layer 0..n_layers-1 (base weights & routed experts)
int pass = 0; ///< 0 = prelude / core pass 0 / coda; 1..T-1 = extra core passes
int core_step = -1; ///< 0..(core_end-core_start-1) on pass >= 1, else -1
int64_t gdn_slot = -1; ///< GDN state ordinal (allocated in SessionState::gdn_state)
int64_t qsa_slot = -1; ///< QSA state ordinal (allocated in SessionState::qsa_states)
bool save_anchor_before = false; ///< true before core_start on pass 0 when stage starts at core_start
bool save_anchor_after = false; ///< true after prelude end (layer == core_start - 1)
bool save_mprev_after = false; ///< true after core_end - 1 on every pass
bool run_workspace_entry = false; ///< true before core_step == 0 on pass >= 1
bool run_cross_pass_mixer = false; ///< true before every core_step on pass >= 1
bool materialize_after = false; ///< true if R must be materialized at end of this step
bool pending_before = false; ///< true if previous step left a deferred FFN write
};
struct LoopAdapter {
bool is_loaded = false;
int num_passes = 1; ///< T (1 = off, 2+ = looped)
int core_start = 16; ///< inclusive
int core_end = 32; ///< exclusive
int coda_lora_layers = 8; ///< layers [core_end, core_end + coda_lora_layers)
int t_max = 3; ///< checkpoint trained T_max (for slot clamping)
float lora_alpha = 32.0f;
float cd_omega = 0.0f;
bool cd_thinking = false; ///< --loop-cd-thinking: gate LoopCD-Hidden to active <think>...</think> spans
int32_t think_start_id = 248068; ///< <think> special token ID (default: Qwen3.8-Flash-Next)
int32_t think_end_id = 248069; ///< </think> special token ID (default: Qwen3.8-Flash-Next)
int64_t n_layers = 48;
int64_t n_embd = 2560;
int64_t hc = 4;
int64_t hc_dim = 10240;
int entry_rank = 128;
int mixer_rank = 128;
int total_lora_hooks = 0;
std::string mode = "gated_workspace";
std::string ckpt_path;
// strata_dual_coda_loop_v1 (the owner's Qwen4-35B-A3B-Loop.safetensors), trainer 03_train_dual_coda_loop.py:
bool dual_coda = false; ///< true: mixer = anchor + sigmoid(gate) * up(silu(down(rms(exit - x)))), entry = the anchor,
///< LoRAs on the block outputs (scale 0.25), coda LoRA delta * (after </think> ? cd_omega[l] : 1)
std::string coda_sel = "universal"; ///< "universal" | "compact" (coda_lora.<sel>.*)
std::vector<float> coda_cd; ///< meta.cd_omega, one per coda layer (host copy)
bool loaded() const { return is_loaded && num_passes >= 2; }
int core_len() const { return core_end - core_start; }
int extra_passes() const { return loaded() ? (num_passes - 1) : 0; }
/// Lookup pre-folded LoRA for `(pass, physical_layer, target)`. Returns null if absent.
const LoopLoraPair* lora(int pass, int64_t layer, LoopTarget target) const;
/// True if any LoRA is attached for `(pass, physical_layer)` on the given target.
bool has_lora(int pass, int64_t layer, LoopTarget target) const { return lora(pass, layer, target) != nullptr; }
/// True if any GDN LoRA (qkv/z/a/b/out) is active on `(pass, layer)`.
bool has_gdn_lora(int pass, int64_t layer) const {
return has_lora(pass, layer, LoopTarget::kGdnQkv) || has_lora(pass, layer, LoopTarget::kGdnZ) ||
has_lora(pass, layer, LoopTarget::kGdnA) || has_lora(pass, layer, LoopTarget::kGdnB) ||
has_lora(pass, layer, LoopTarget::kGdnOut);
}
/// True if any shared-expert LoRA (gate/up/down) is active on `(pass, layer)`.
bool has_sh_lora(int pass, int64_t layer) const {
return has_lora(pass, layer, LoopTarget::kShGate) || has_lora(pass, layer, LoopTarget::kShUp) ||
has_lora(pass, layer, LoopTarget::kShDown);
}
};
/// Global loaded loop adapter (unloaded by default).
const LoopAdapter& loop_adapter();
/// Load adapter checkpoint (`.safetensors` + optional sibling `.json`), pre-fold all pass gates for
/// `num_passes`, and upload FP32 weights + tiny fixed scratch buffers to the current CUDA device.
bool loop_adapter_load(const std::string& safetensors_path, int num_passes, float cd_omega, int64_t n_layers,
int64_t n_embd, int64_t hc, std::string& summary, std::string& err, bool cd_thinking = false,
int32_t think_start_id = 248068, int32_t think_end_id = 248069);
/// strata_dual_coda_loop_v1 files only: which coda LoRA set to use ("universal" for Ultra / Balanced / GGUF quants,
/// "compact" for the Compact tier). Call before loop_adapter_load. Default "universal".
void loop_adapter_set_coda(const std::string& sel);
/// loop_lora_add for the dual-coda hooks (kAttn / kMlp): on a coda layer the LoRA delta of row t is scaled by
/// `flag[t] > 0.5 ? cd_omega[layer - core_end] : 1` (flag = the after-</think> per-token vector, device, [n_tok]).
void loop_lora_add_gated(const float* x, int x_ld, float* y, int y_ld, int pass, int64_t layer, LoopTarget target,
int n_tok, void* stream, const float* flag);
/// Replicate the loaded loop adapter onto the current CUDA device (for `--layer-split` multi-GPU stages).
/// No-op if unloaded or already present on the current device.
bool loop_adapter_replicate(std::string& err);
/// Free GPU memory held by the global loop adapter (safe to call on shutdown).
void loop_adapter_free();
/// Advance thinking-span state by one token (vllm_looped_qwen38 `compute_thinking_token_mask` semantics with
/// `default_thinking=False, include_end_token=False`): entering `<think>` turns gating on (inclusive of `<think>`),
/// seeing `</think>` turns gating off immediately (exclusive of `</think>`).
inline bool loop_think_step(bool in_thinking, int64_t token, int32_t think_start_id, int32_t think_end_id) {
if (think_start_id == kLoopStickyClose) return in_thinking || token == (int64_t) think_end_id; // dual-coda: seen </think>
if (token == (int64_t) think_start_id) return true;
if (token == (int64_t) think_end_id) return false;
return in_thinking;
}
/// Thinking-span state after consuming `tokens[0 .. n-1]` from initial state `in_thinking`.
template <class Token>
inline bool loop_think_state_after(const Token* tokens, int64_t n, int32_t think_start_id, int32_t think_end_id,
bool in_thinking = false) {
if (tokens == nullptr || n <= 0 || (think_start_id < 0 && think_start_id != kLoopStickyClose) || think_end_id < 0 ||
think_start_id == think_end_id)
return in_thinking;
bool s = in_thinking;
for (int64_t i = 0; i < n; ++i) s = loop_think_step(s, (int64_t) tokens[i], think_start_id, think_end_id);
return s;
}
/// Fill `omega_out[0 .. n-1]` with per-token effective LoopCD-Hidden weights for `tokens[0 .. n-1]`,
/// returning the updated thinking-span state after `tokens[n-1]`.
/// When `cd_thinking` is false, fills every entry with `omega` (unconditional legacy behavior).
/// When `cd_thinking` is true, sets `omega_out[i] = omega` iff token `i` is inside an active `<think>` span.
template <class Token>
inline bool loop_cd_fill_omega(const Token* tokens, int64_t n, float omega, bool cd_thinking, int32_t think_start_id,
int32_t think_end_id, bool in_thinking, float* omega_out) {
if (n <= 0 || omega_out == nullptr) return in_thinking;
bool s = in_thinking;
if (think_start_id == kLoopStickyClose && think_end_id >= 0) { // dual-coda: flag = 1 from </think> on (omega unused)
for (int64_t i = 0; i < n; ++i) {
s = loop_think_step(s, (int64_t) tokens[i], think_start_id, think_end_id);
omega_out[i] = s ? 1.0f : 0.0f;
}
return s;
}
if (!cd_thinking || think_start_id < 0 || think_end_id < 0 || think_start_id == think_end_id) {
for (int64_t i = 0; i < n; ++i) omega_out[i] = omega;
return s;
}
for (int64_t i = 0; i < n; ++i) {
s = loop_think_step(s, (int64_t) tokens[i], think_start_id, think_end_id);
omega_out[i] = s ? omega : 0.0f;
}
return s;
}
/// Conversation-cache / checkpoint compatibility key for the active loop execution mode.
/// Returns 0 when no loop adapter is loaded, 1 for stock T=1 single-pass bypass (invariant to LoopCD settings),
/// and a non-zero hash >= 2 encoding `(active_passes, cd_omega, cd_thinking, think_ids)` for looped T >= 2 requests.
inline uint64_t loop_cache_key_for(bool loaded, int active_passes, float cd_omega, bool cd_thinking,
int32_t think_start_id, int32_t think_end_id) {
if (!loaded) return 0;
if (active_passes <= 1) return 1;
uint32_t obits = 0;
if (cd_omega != 0.0f) std::memcpy(&obits, &cd_omega, sizeof obits);
const bool th = (obits != 0) && cd_thinking;
uint64_t h = 1469598103934665603ull;
auto mix = [&](uint64_t v) {
for (int i = 0; i < 8; ++i) {
h ^= (v >> (i * 8)) & 0xffu;
h *= 1099511628211ull;
}
};
mix((uint64_t) active_passes);
mix((uint64_t) obits);
mix(th ? 1ull : 0ull);
if (th) {
mix((uint64_t) (uint32_t) think_start_id);
mix((uint64_t) (uint32_t) think_end_id);
}
return h < 2 ? h + 2 : h;
}
inline uint64_t loop_cache_key(int active_passes, float cd_omega, bool cd_thinking) {
const LoopAdapter& la = loop_adapter();
return loop_cache_key_for(la.loaded(), active_passes, cd_omega, cd_thinking, la.think_start_id, la.think_end_id);
}
/// Number of extra GDN / QSA state slots needed for `[layer_lo, layer_hi)` when loop adapter is loaded.
int64_t loop_extra_gdn_slots(int64_t layer_lo, int64_t layer_hi, int64_t qsa_interval);
int64_t loop_extra_qsa_slots(int64_t layer_lo, int64_t layer_hi, int64_t qsa_interval);
/// Build the ordered execution schedule for `[layer_lo, layer_hi)`.
/// When unloaded or `bypass == true` (per-request `loop_passes=1`), returns `[layer_lo, ..., layer_hi - 1]` with
/// `pass = 0` and standard state ordinals.
std::vector<LoopStep> build_loop_schedule(int64_t n_layers, int64_t qsa_interval, int64_t layer_lo, int64_t layer_hi,
bool bypass = false);
/// One visit of a cyclic layer split: a run of consecutive steps of the whole model's looped order that one physical
/// stage executes before the residual moves to another stage. The global order is [0, core_end) on pass 0, then
/// [core_start, core_end) on every pass 1..T-1, then the coda [core_end, n_layers) on pass 0.
struct LoopVisit {
int owner = 0; ///< physical stage index (the owner of every step's layer)
std::vector<LoopStep> steps; ///< state ordinals are the owner's (its session carve: base range, then extras)
bool embed = false; ///< the first visit: embeds the tokens (no hand-in)
bool head = false; ///< the final visit: runs the head (no hand-out)
int mprev_in = 0; ///< 0: none; 1: m_prev is the handed-in residual (the wrap); 2: relayed beside it
bool mprev_out = false; ///< the next visit takes m_prev relayed (mprev_in == 2)
bool owner_first = false; ///< the owner's first visit of a window / chunk
bool owner_last = false; ///< the owner's last visit of a window / chunk
bool ple = false; ///< holds layer 1 on pass 0 (the PLE block)
};
/// True when the adapter is loaded and a stage boundary in `stage_begin` (the first layer of each stage, [0] == 0)
/// lies strictly inside the recurrent core: the stages then run a cyclic itinerary (build_loop_itinerary).
bool loop_split_cyclic(const std::vector<int64_t>& stage_begin);
/// The cyclic itinerary of a layer split (empty when unloaded). Visits are in execution order; each physical stage
/// owns several. Pass-0 steps use the whole-model state ordinals; a pass p >= 1 step on a stage [u, v) uses
/// F(v) + (p - 1) * h + r, where F counts the layers of its type before v, h is the stage's core layers of that type
/// and r the layer's rank among them - the order session_init carves the stage's extra slots in.
std::vector<LoopVisit> build_loop_itinerary(int64_t n_layers, int64_t qsa_interval, const std::vector<int64_t>& stage_begin);
/// Does a step's output feed a DFlash2 tap? Outside the core only pass 0 runs; inside it the last pass is final.
inline bool loop_tap_pass(const LoopStep& s, const LoopAdapter& la, bool bypass = false) {
if (!la.loaded() || bypass) return true;
const bool core = s.layer >= la.core_start && s.layer < la.core_end;
return core ? s.pass == la.num_passes - 1 : s.pass == 0;
}
/// Anchor-grounded 4-stream HCWorkspaceEntry for `pass_idx = pass - 1` (`0 .. T-2`).
/// `anchor`, `m_prev`, `R_out` are `[n_tok, hc_dim]` contiguous FP32 on device (`R_out` may alias `m_prev`).
void loop_workspace_entry(const float* anchor, const float* m_prev, float* R_out, int pass_idx, int n_tok,
void* stream);
/// 4-stream HCCrossPassMixer for `pass_idx = pass - 1`, `core_step = 0 .. core_len - 1`.
/// `x`, `m_prev`, `R_out` are `[n_tok, hc_dim]` contiguous FP32 on device (`R_out` may alias `x`).
void loop_cross_pass_mixer(const float* x, const float* m_prev, float* R_out, int pass_idx, int core_step, int n_tok,
void* stream);
/// Add LoRA delta `y += (x @ A^T) @ B_eff^T` for `n_tok` rows with arbitrary input/output row strides.
/// No-op if no LoRA is registered for `(pass, layer, target)`.
void loop_lora_add(const float* x, int x_ld, float* y, int y_ld, int pass, int64_t layer, LoopTarget target,
int n_tok, void* stream);
/// Same as `loop_lora_add`, reading IEEE FP16 (`uint16_t`) activations `x_f16` (used by prefill GEMM path).
void loop_lora_add_f16(const uint16_t* x_f16, int x_ld, float* y, int y_ld, int pass, int64_t layer,
LoopTarget target, int n_tok, void* stream);
/// Batched GDN alpha/beta epilogue for `n_tok` rows:
/// gate_out[t, h] = softplus(alpha[t, h] + dt[h]) * ssm_a[h]
/// beta_out[t, h] = sigmoid(beta[t, h])
void loop_gdn_ab_epilogue(const float* alpha, const float* beta, const float* dt, const float* ssm_a,
float* gate_out, float* beta_out, int hv, int n_tok, void* stream);
/// Optional ratio-preserving LoopCD-Hidden on `[n_tok, hc_dim]` when `omega != 0.0f`.
void loop_cd_hidden(const float* m_cur, const float* m_ref, float* R_out, float omega, int n_tok, void* stream);
/// CUDA-graph-safe per-token ratio-preserving LoopCD-Hidden on `[n_tok, hc_dim]`.
/// Reads `omega_per_tok[t]` from device memory; tokens with `omega == 0.0f` leave `R_out` bit-identical to `m_cur`.
void loop_cd_hidden_per_tok(const float* m_cur, const float* m_ref, float* R_out, const float* omega_per_tok,
int n_tok, void* stream);
} // namespace strata::kernels