Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

23.1 KB
Raw Blame
#include <Python.h>
#include "gated_delta_net.h"
#include <c10/cuda/CUDAGuard.h>
#include <ATen/cuda/CUDAContext.h>
#include <torch/extension.h>
#include "../util.h"
#include "../hgemm.cuh"
#include "../quant/exl3_gemm.cuh"
#include "../gdn.cuh"
#include "../add.cuh"

using namespace torch::indexing;

at::Tensor BC_GatedDeltaNet::run_bsz1_a
(
    const at::Tensor& x
)
{
    py::gil_scoped_release _;

    qkvz_proj->run(x, qkvz);
    ba_proj->run(x, ba);

    gated_delta_net_fused_op
    (
        qkvz, ba,
        dt_bias, a_log,
        mixed_qkv, z, beta, g,
        num_k_heads,
        num_v_heads,
        k_head_dim,
        v_head_dim,
        beta_scale
    );

    return mixed_qkv;
}

void BC_GatedDeltaNet::run_bsz1_b
(
    at::Tensor& mixed_qkv,
    at::Tensor& y,
    at::Tensor& recurrent_state
)
{
    cuda_recurrent_gated_delta_rule
    (
        mixed_qkv.transpose(1, 2),
        g,
        beta,
        recurrent_state,
        core_attn_out,
        num_k_heads,
        num_v_heads,
        k_head_dim,
        v_head_dim,
        c10::nullopt,
        false,
        c10::nullopt
    );

    norm->run(core_attn_out, core_attn_out_f, z);
    o_proj->run(core_attn_out_f, y);
}

bool BC_GatedDeltaNetSplit::needs_configure(int bsz, int seqlen, bool history)
{
    TORCH_CHECK(1 <= bsz && bsz <= MAX_BSZ && 1 <= seqlen && seqlen <= MAX_QLEN,
                "BC_GatedDeltaNetSplit: shape out of range");
    return !slot(bsz, seqlen, history).configured;
}

void BC_GatedDeltaNetSplit::configure_slot
(
    int bsz,
    int seqlen,
    bool history,
    at::Tensor qkv,
    at::Tensor z,
    at::Tensor ba,
    at::Tensor beta,
    at::Tensor g,
    at::Tensor mixed_qkv,
    at::Tensor conv_out,
    at::Tensor core_attn_out,
    at::Tensor core_attn_out_f,
    at::Tensor qkv_xh,
    at::Tensor z_xh,
    at::Tensor o_xh
)
{
    Slot& s = slot(bsz, seqlen, history);

    s.qkv             = std::move(qkv);
    s.z               = std::move(z);
    s.ba              = std::move(ba);
    s.beta            = std::move(beta);
    s.g               = std::move(g);
    s.mixed_qkv       = std::move(mixed_qkv);
    s.conv_out        = std::move(conv_out);
    s.core_attn_out   = std::move(core_attn_out);
    s.core_attn_out_f = std::move(core_attn_out_f);
    s.qkv_xh          = std::move(qkv_xh);
    s.z_xh            = std::move(z_xh);
    s.o_xh            = std::move(o_xh);
    s.z_flat = s.z.view({bsz, seqlen, -1});

    // Sliced qkv+z bundle: output pointers into this slot's statics, one per slice
    if (qkvz_ptrs_trellis)
    {
        int R = bsz * seqlen;
        const at::Tensor& meta = qkvz_meta.value();
        int slices = (int) meta.size(1);
        auto t = meta.accessor<int, 2>();
        std::vector<int64_t> ptrs(slices);
        for (int j = 0; j < slices; ++j)
        {
            float* base = (float*) (t[0][j] == 0 ? s.qkv.data_ptr() : s.z_flat.data_ptr());
            ptrs[j] = (int64_t) (base + t[1][j]);
        }
        s.qkvz_c_ptrs = at::tensor(ptrs, at::TensorOptions().dtype(at::kLong)).to(s.qkv.device());
        s.qkvz_xh = at::empty({2, R, s.qkv_xh.size(-1)}, s.qkv_xh.options());
    }

    TORCH_CHECK(s.qkv.is_contiguous() && s.z.is_contiguous() && s.ba.is_contiguous() &&
                s.beta.is_contiguous() && s.g.is_contiguous() && s.mixed_qkv.is_contiguous() &&
                s.conv_out.is_contiguous() && s.core_attn_out.is_contiguous() &&
                s.core_attn_out_f.is_contiguous(),
                "BC_GatedDeltaNetSplit: statics must be contiguous");

    s.graph = std::make_unique<Graph>();
    s.configured = true;
}

void BC_GatedDeltaNetSplit::configure_slot_kda
(
    int bsz,
    int seqlen,
    bool history,
    at::Tensor qkv,
    at::Tensor z,
    at::Tensor b_out,
    at::Tensor fa_out,
    at::Tensor fb_out,
    at::Tensor ga_out,
    at::Tensor beta,
    at::Tensor g,
    at::Tensor mixed_qkv,
    at::Tensor conv_out,
    at::Tensor core_attn_out,
    at::Tensor core_attn_out_f,
    at::Tensor qkv_xh,
    at::Tensor o_xh
)
{
    Slot& s = slot(bsz, seqlen, history);

    s.qkv             = std::move(qkv);
    s.z               = std::move(z);
    s.b_out           = std::move(b_out);
    s.fa_out          = std::move(fa_out);
    s.fb_out          = std::move(fb_out);
    s.ga_out          = std::move(ga_out);
    s.beta            = std::move(beta);
    s.g               = std::move(g);
    s.mixed_qkv       = std::move(mixed_qkv);
    s.conv_out        = std::move(conv_out);
    s.core_attn_out   = std::move(core_attn_out);
    s.core_attn_out_f = std::move(core_attn_out_f);
    s.qkv_xh          = std::move(qkv_xh);
    s.o_xh            = std::move(o_xh);
    s.z_flat = s.z.view({bsz, seqlen, -1});

    TORCH_CHECK(s.qkv.is_contiguous() && s.z.is_contiguous() && s.b_out.is_contiguous() &&
                s.fa_out.is_contiguous() && s.fb_out.is_contiguous() && s.ga_out.is_contiguous() &&
                s.beta.is_contiguous() && s.g.is_contiguous() && s.mixed_qkv.is_contiguous() &&
                s.conv_out.is_contiguous() && s.core_attn_out.is_contiguous() &&
                s.core_attn_out_f.is_contiguous(),
                "BC_GatedDeltaNetSplit (KDA): statics must be contiguous");

    s.graph = std::make_unique<Graph>();
    s.configured = true;
}

void BC_GatedDeltaNetSplit::set_qkvz_bundle
(
    at::Tensor ptrs_trellis,
    at::Tensor ptrs_suh,
    at::Tensor ptrs_svh,
    at::Tensor meta,
    int K,
    bool mcg,
    bool mul1
)
{
    TORCH_CHECK(!kda, "BC_GatedDeltaNetSplit: qkvz bundle is for the split (non-KDA) projections");
    TORCH_CHECK(meta.device().is_cpu() && meta.dtype() == at::kInt && meta.dim() == 2 && meta.size(0) == 5,
                "BC_GatedDeltaNetSplit: qkvz_meta must be a CPU int32 (5, slices) tensor");
    int slices = (int) meta.size(1);
    TORCH_CHECK(ptrs_trellis.size(0) == slices && ptrs_svh.size(0) == slices && ptrs_suh.size(0) == 2,
                "BC_GatedDeltaNetSplit: qkvz pointer tables must cover every slice / both sources");
    auto dev = ptrs_trellis.device();
    qkvz_size_n = meta.select(0, 2).contiguous().to(dev);
    qkvz_n_stride = meta.select(0, 3).contiguous().to(dev);
    qkvz_had_src = meta.select(0, 4).contiguous().to(dev);
    int width = meta[2][0].item<int>();
    qkvz_carrier = at::empty({slices, MAX_BSZ * MAX_QLEN, width}, at::TensorOptions().dtype(at::kFloat).device(dev));
    qkvz_ptrs_trellis = std::move(ptrs_trellis);
    qkvz_ptrs_suh = std::move(ptrs_suh);
    qkvz_ptrs_svh = std::move(ptrs_svh);
    qkvz_meta = std::move(meta);
    qkvz_K = K;
    qkvz_mcg = mcg;
    qkvz_mul1 = mul1;
}

#if !defined(USE_ROCM)
#define SIDE_CHECK(call) TORCH_CHECK((call) == cudaSuccess, "side branch: " #call " failed")

// Side branch for a launch-bound kernel inside an outer (whole-forward) graph capture: fork from the capturing
// stream, run on a per-device side stream, join back before the result is read. The graph executes the branch
// concurrently with whatever the main stream runs meanwhile.
struct SideBranch
{
    cudaStream_t stream = nullptr;
    cudaEvent_t fork_ev = nullptr, join_ev = nullptr;
};

static SideBranch& side_branch(int device)
{
    static SideBranch branches[16];
    SideBranch& b = branches[device];
    if (!b.stream)
    {
        SIDE_CHECK(cudaStreamCreateWithFlags(&b.stream, cudaStreamNonBlocking));
        SIDE_CHECK(cudaEventCreateWithFlags(&b.fork_ev, cudaEventDisableTiming));
        SIDE_CHECK(cudaEventCreateWithFlags(&b.join_ev, cudaEventDisableTiming));
    }
    return b;
}
#endif

void BC_GatedDeltaNetSplit::run_bszN_gr
(
    const at::Tensor& x,
    at::Tensor& y,
    at::Tensor& conv_state,
    at::Tensor& recurrent_state,
    at::Tensor& recurrent_base,
    const at::Tensor& slots,
    bool history,
    Slot& s,
    Graph* graph
)
{
    int R = (int) (x.size(0) * x.size(1));

    // The b/a gate GEMV is tiny and launch-bound (~6 us for microseconds of work): under an outer capture it runs
    // on a forked branch next to the qkv/z projection instead of after it. Same kernel, same inputs: bit-identical.
    // EXL3_GDN_BA_FORK=0 keeps it in line.
    bool ba_forked = false;
    cudaStream_t ba_main_stream = nullptr;
    cudaEvent_t ba_join_ev = nullptr;
#if !defined(USE_ROCM)
    static const bool ba_fork_on = [] { const char* e = getenv("EXL3_GDN_BA_FORK"); return !e || atoi(e) != 0; }();
    if (ba_fork_on && !kda && !graph)
    {
        cudaStream_t main_stream = at::cuda::getCurrentCUDAStream().stream();
        if (graph_outer_capture(main_stream))
        {
            int device;
            cudaGetDevice(&device);
            SideBranch& sb = side_branch(device);
            SIDE_CHECK(cudaEventRecord(sb.fork_ev, main_stream));
            SIDE_CHECK(cudaStreamWaitEvent(sb.stream, sb.fork_ev, 0));
            gdn_ba_gemv_gr(x, ba_weight_t, ba_bias, s.ba, nullptr, sb.stream);
            SIDE_CHECK(cudaEventRecord(sb.join_ev, sb.stream));
            ba_forked = true;
            ba_main_stream = main_stream;
            ba_join_ev = sb.join_ev;
        }
    }
#endif
    bool use_qkvz = qkvz_ptrs_trellis.has_value() && !kda && R <= 32;

    // qkv/z projections: bypass BC_LinearEXL3::run_gr, which hard-refuses graph capture above 1
    // row -- call exl3_gemm_gr directly with this slot's own xh scratch instead, exactly like
    // BC_GatedMLP::run_bszN_gr does for shared-expert projections
    if (use_qkvz)
    {
        // Both projections as one sliced mgemm into the qkv / z statics (no biases by construction)
        TORCH_CHECK(x.is_contiguous(), "BC_GatedDeltaNetSplit: input must be contiguous");
        at::Tensor x3 = x.view({1, R, x.size(2)});
        at::Tensor carrier = qkvz_carrier.narrow(1, 0, R);
        exl3_mgemm_gr(x3, qkvz_ptrs_trellis.value(), carrier, qkvz_ptrs_suh.value(), s.qkvz_xh, qkvz_ptrs_svh.value(),
                      c10::nullopt, c10::nullopt, qkvz_K, -1, qkvz_mcg, qkvz_mul1, -1, -1, 0, graph,
                      1, qkvz_size_n, s.qkvz_c_ptrs, qkvz_n_stride, qkvz_had_src, 2);
    }
    else
    {
        exl3_gemm_gr(x, qkv_proj->trellis, s.qkv, qkv_proj->suh, s.qkv_xh, qkv_proj->svh, -1, qkv_proj->mcg, qkv_proj->mul1, 0, graph);
        if (qkv_proj->bias)
            add_gr(s.qkv, qkv_proj->bias.value(), s.qkv, graph);
    }

    if (kda)
    {
        // KDA: three fp16 GEMVs off x (patched inputs), low-rank second stages and the gate op
        // run entirely on graph statics. z (the sigmoid norm gate) is the g_b output
        gdn_ba_gemv_gr(x, b_weight_t, {}, s.b_out, graph);
        gdn_ba_gemv_gr(x, f_a_weight_t, {}, s.fa_out, graph);
        gdn_ba_gemv_gr(x, g_a_weight_t, {}, s.ga_out, graph);
        gdn_lowrank_gemv_f_gr(s.fa_out, f_b_weight_t, s.fb_out, graph);
        gdn_lowrank_gemv_f_gr(s.ga_out, g_b_weight_t, s.z_flat, graph);
        kda_gate_op_gr
        (
            s.qkv, s.b_out, s.fb_out,
            dt_bias, a_log,
            s.mixed_qkv, s.beta, s.g,
            lower_bound, beta_scale,
            graph
        );
    }
    else
    {
        if (!use_qkvz)
        {
            exl3_gemm_gr(x, z_proj->trellis, s.z_flat, z_proj->suh, s.z_xh, z_proj->svh, -1, z_proj->mcg, z_proj->mul1, 0, graph);
            if (z_proj->bias)
                add_gr(s.z_flat, z_proj->bias.value(), s.z_flat, graph);
        }

        if (!ba_forked)
            gdn_ba_gemv_gr(x, ba_weight_t, ba_bias, s.ba, graph);
#if !defined(USE_ROCM)
        else
            SIDE_CHECK(cudaStreamWaitEvent(ba_main_stream, ba_join_ev, 0));      // join: s.ba is read below
#endif

        gated_delta_net_fused_op_3_gr
        (
            s.qkv, s.ba,
            dt_bias, a_log,
            s.mixed_qkv, s.beta, s.g,
            beta_scale,
            graph
        );
    }

    cuda_causal_conv1d_update_gr
    (
        s.mixed_qkv,
        conv_state,
        slots,
        conv1d_weight,
        conv1d_bias,
        s.conv_out,
        true,
        history,
        graph
    );

    cuda_recurrent_gated_delta_rule_gr
    (
        s.conv_out,
        s.g,
        s.beta,
        recurrent_state,
        s.core_attn_out,
        num_k_heads,
        num_v_heads,
        k_head_dim,
        v_head_dim,
        slots,
        history,
        recurrent_base,
        graph
    );

    norm->run_gr(s.core_attn_out, s.core_attn_out_f, s.z, graph);

    exl3_gemm_gr(s.core_attn_out_f, o_proj->trellis, y, o_proj->suh, s.o_xh, o_proj->svh, -1, o_proj->mcg, o_proj->mul1, 0, graph);
    if (o_proj->bias)
        add_gr(y, o_proj->bias.value(), y, graph);
}

void BC_GatedDeltaNetSplit::run_bszN
(
    const at::Tensor& x,
    at::Tensor& y,
    at::Tensor& conv_state,
    at::Tensor& recurrent_state,
    at::Tensor& recurrent_base,
    const at::Tensor& slots,
    bool history
)
{
    py::gil_scoped_release release;
    c10::cuda::CUDAGuard device_guard(x.device());
    cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();

    int bsz = (int) x.size(0);
    int seqlen = (int) x.size(1);
    TORCH_CHECK(bsz >= 1 && bsz <= MAX_BSZ && seqlen >= 1 && seqlen <= MAX_QLEN,
                "BC_GatedDeltaNetSplit::run_bszN: shape out of range");
    Slot& s = slot(bsz, seqlen, history);
    TORCH_CHECK(s.configured, "BC_GatedDeltaNetSplit::run_bszN: slot not configured");

    if (s.graph->disabled || graph_outer_capture(stream) || (!s.graph->ready && !s.graph->ready_to_record))
    {
        run_bszN_gr(x, y, conv_state, recurrent_state, recurrent_base, slots, history, s, nullptr);
        s.graph->ready_to_record = true;
        s.graph_state_size = (int) conv_state.size(2);
        s.graph_hist_stride = (int) recurrent_state.size(1);
        return;
    }

    // The captured graph bakes in the state-buffer geometry (scalar kernel args can't be patched),
    // so a cache with different dimensions falls back to the eager path. The snapshot is per slot:
    // another slot's eager run against a second cache must not re-arm this slot's replay
    if ((int) conv_state.size(2) != s.graph_state_size ||
        (int) recurrent_state.size(1) != s.graph_hist_stride)
    {
        run_bszN_gr(x, y, conv_state, recurrent_state, recurrent_base, slots, history, s, nullptr);
        return;
    }

    if (!s.graph->ready)
    {
        s.graph->capture_begin();
        run_bszN_gr(x, y, conv_state, recurrent_state, recurrent_base, slots, history, s, s.graph.get());
        s.graph->capture_end();
    }

    std::vector<PPTR> args;
    if (kda)
        args = std::vector<PPTR>
        {
            PPTR(GP_gemm_A,         (void*) x.data_ptr()),          // qkv_proj input
            PPTR(GP_gdn_ba_x,       (void*) x.data_ptr()),          // b_proj input
            PPTR(GP_gdn_ba_x,       (void*) x.data_ptr()),          // f_a input
            PPTR(GP_gdn_ba_x,       (void*) x.data_ptr()),          // g_a input
            PPTR(GP_conv1d_state,   (void*) conv_state.data_ptr()),
            PPTR(GP_conv1d_slots,   (void*) slots.data_ptr()),
            PPTR(GP_gdn_rule_state, (void*) recurrent_state.data_ptr()),
            PPTR(GP_gdn_rule_slots, (void*) slots.data_ptr()),
            PPTR(GP_gdn_rule_base,  (void*) recurrent_base.data_ptr()),
            PPTR(GP_gemm_C,         (void*) y.data_ptr())           // o_proj output
        };
    else if (qkvz_ptrs_trellis.has_value() && (int) (x.size(0) * x.size(1)) <= 32)
        args = std::vector<PPTR>
        {
            PPTR(GP_mgemm_A,        (void*) x.data_ptr()),          // sliced qkv+z bundle input
            PPTR(GP_gdn_ba_x,       (void*) x.data_ptr()),
            PPTR(GP_conv1d_state,   (void*) conv_state.data_ptr()),
            PPTR(GP_conv1d_slots,   (void*) slots.data_ptr()),
            PPTR(GP_gdn_rule_state, (void*) recurrent_state.data_ptr()),
            PPTR(GP_gdn_rule_slots, (void*) slots.data_ptr()),
            PPTR(GP_gdn_rule_base,  (void*) recurrent_base.data_ptr()),
            PPTR(GP_gemm_C,         (void*) y.data_ptr())           // o_proj output
        };
    else
        args = std::vector<PPTR>
        {
            PPTR(GP_gemm_A,         (void*) x.data_ptr()),          // qkv_proj input
            PPTR(GP_gemm_A,         (void*) x.data_ptr()),          // z_proj input
            PPTR(GP_gdn_ba_x,       (void*) x.data_ptr()),
            PPTR(GP_conv1d_state,   (void*) conv_state.data_ptr()),
            PPTR(GP_conv1d_slots,   (void*) slots.data_ptr()),
            PPTR(GP_gdn_rule_state, (void*) recurrent_state.data_ptr()),
            PPTR(GP_gdn_rule_slots, (void*) slots.data_ptr()),
            PPTR(GP_gdn_rule_base,  (void*) recurrent_base.data_ptr()),
            PPTR(GP_gemm_C,         (void*) y.data_ptr())           // o_proj output
        };
    s.graph->launch(args, stream);
}

bool BC_Mamba2::needs_configure(int bsz, int seqlen, bool history)
{
    TORCH_CHECK(1 <= bsz && bsz <= MAX_BSZ && 1 <= seqlen && seqlen <= MAX_QLEN,
                "BC_Mamba2: shape out of range");
    return !slot(bsz, seqlen, history).configured;
}

void BC_Mamba2::configure_slot
(
    int bsz,
    int seqlen,
    bool history,
    c10::optional<at::Tensor> xp,
    at::Tensor proj,
    at::Tensor mixed_xbc,
    at::Tensor dt,
    at::Tensor g,
    at::Tensor z_gate,
    at::Tensor conv_out,
    at::Tensor core_attn_out,
    at::Tensor core_attn_out_f,
    c10::optional<at::Tensor> yp,
    at::Tensor in_xh,
    at::Tensor o_xh
)
{
    Slot& s = slot(bsz, seqlen, history);

    s.xp              = std::move(xp);
    s.proj            = std::move(proj);
    s.mixed_xbc       = std::move(mixed_xbc);
    s.dt              = std::move(dt);
    s.g               = std::move(g);
    s.conv_out        = std::move(conv_out);
    s.core_attn_out   = std::move(core_attn_out);
    s.core_attn_out_f = std::move(core_attn_out_f);
    s.yp              = std::move(yp);
    s.in_xh           = std::move(in_xh);
    s.o_xh            = std::move(o_xh);

    TORCH_CHECK(padded_in == s.xp.has_value(), "BC_Mamba2: xp presence must match padded_in");
    TORCH_CHECK(padded_out == s.yp.has_value(), "BC_Mamba2: yp presence must match padded_out");

    TORCH_CHECK(s.proj.is_contiguous() && s.mixed_xbc.is_contiguous() && s.dt.is_contiguous() &&
                s.g.is_contiguous() && s.conv_out.is_contiguous() && s.core_attn_out.is_contiguous() &&
                s.core_attn_out_f.is_contiguous() && z_gate.is_contiguous(),
                "BC_Mamba2: statics must be contiguous");

    int gs = v_dim / num_k_heads;
    s.z_gate = z_gate.view({bsz, seqlen, num_k_heads, gs});
    s.core_g = s.core_attn_out.view({bsz, seqlen, num_k_heads, gs});
    s.core_f_g = s.core_attn_out_f.view({bsz, seqlen, num_k_heads, gs});

    s.graph = std::make_unique<Graph>();
    s.configured = true;
}

void BC_Mamba2::run_bszN_gr
(
    const at::Tensor& x,
    at::Tensor& y,
    at::Tensor& conv_state,
    at::Tensor& recurrent_state,
    const at::Tensor& slots,
    bool history,
    Slot& s,
    Graph* graph
)
{
    int bsz = (int) x.size(0);
    int seqlen = (int) x.size(1);
    int R = bsz * seqlen;

    // Padded in_proj K: stage x through the zero-padded static (pad columns are zeroed at
    // configure time and only the exact width is ever copied in)
    at::Tensor x_in = x;
    if (s.xp)
    {
        at::Tensor x2 = x.reshape({R, hidden_size});
        at::Tensor xp2 = s.xp.value();
        copy2d_gr(x2, xp2, graph);
        x_in = xp2.view({bsz, seqlen, -1});
    }

    // in_proj: bypass BC_LinearEXL3::run_gr for the same reason as BC_GatedDeltaNetSplit above
    exl3_gemm_gr(x_in, in_proj->trellis, s.proj, in_proj->suh, s.in_xh, in_proj->svh, -1, in_proj->mcg, in_proj->mul1, 0, graph);
    if (in_proj->bias)
        add_gr(s.proj, in_proj->bias.value(), s.proj, graph);

    mamba2_fused_op_gr(s.proj, s.mixed_xbc, s.dt, s.g, s.z_gate, dt_bias, a_log, v_dim, dt_first, dt_min, dt_max, graph);

    cuda_causal_conv1d_update_gr
    (
        s.mixed_xbc,
        conv_state,
        slots,
        conv1d_weight,
        conv1d_bias,
        s.conv_out,
        true,
        history,
        graph
    );

    cuda_recurrent_mamba2_gr
    (
        s.conv_out,
        s.g,
        s.dt,
        d_skip,
        recurrent_state,
        s.core_attn_out,
        num_k_heads,
        num_v_heads,
        k_head_dim,
        v_head_dim,
        slots,
        history,
        graph
    );

    norm->run_gr(s.core_g, s.core_f_g, s.z_gate, graph);

    // Padded o_proj N: the GEMM writes the padded static, then the exact width copies out to y
    if (s.yp)
    {
        at::Tensor yp3 = s.yp.value().view({bsz, seqlen, -1});
        exl3_gemm_gr(s.core_attn_out_f, o_proj->trellis, yp3, o_proj->suh, s.o_xh, o_proj->svh, -1, o_proj->mcg, o_proj->mul1, 0, graph);
        if (o_proj->bias)
            add_gr(yp3, o_proj->bias.value(), yp3, graph);
        at::Tensor y2 = y.reshape({R, hidden_size});
        at::Tensor yp2 = s.yp.value();
        copy2d_gr(yp2, y2, graph);
    }
    else
    {
        exl3_gemm_gr(s.core_attn_out_f, o_proj->trellis, y, o_proj->suh, s.o_xh, o_proj->svh, -1, o_proj->mcg, o_proj->mul1, 0, graph);
        if (o_proj->bias)
            add_gr(y, o_proj->bias.value(), y, graph);
    }
}

void BC_Mamba2::run_bszN
(
    const at::Tensor& x,
    at::Tensor& y,
    at::Tensor& conv_state,
    at::Tensor& recurrent_state,
    const at::Tensor& slots,
    bool history
)
{
    py::gil_scoped_release release;
    c10::cuda::CUDAGuard device_guard(x.device());
    cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();

    int bsz = (int) x.size(0);
    int seqlen = (int) x.size(1);
    TORCH_CHECK(bsz >= 1 && bsz <= MAX_BSZ && seqlen >= 1 && seqlen <= MAX_QLEN,
                "BC_Mamba2::run_bszN: shape out of range");
    Slot& s = slot(bsz, seqlen, history);
    TORCH_CHECK(s.configured, "BC_Mamba2::run_bszN: slot not configured");

    if (s.graph->disabled || graph_outer_capture(stream) || (!s.graph->ready && !s.graph->ready_to_record))
    {
        run_bszN_gr(x, y, conv_state, recurrent_state, slots, history, s, nullptr);
        s.graph->ready_to_record = true;
        s.graph_state_size = (int) conv_state.size(2);
        s.graph_hist_stride = (int) recurrent_state.size(1);
        return;
    }

    // The captured graph bakes in the state-buffer geometry (scalar kernel args can't be patched),
    // so a cache with different dimensions falls back to the eager path. The snapshot is per slot:
    // another slot's eager run against a second cache must not re-arm this slot's replay
    if ((int) conv_state.size(2) != s.graph_state_size ||
        (int) recurrent_state.size(1) != s.graph_hist_stride)
    {
        run_bszN_gr(x, y, conv_state, recurrent_state, slots, history, s, nullptr);
        return;
    }

    if (!s.graph->ready)
    {
        s.graph->capture_begin();
        run_bszN_gr(x, y, conv_state, recurrent_state, slots, history, s, s.graph.get());
        s.graph->capture_end();
    }

    std::vector<PPTR> args;
    args.reserve(8);
    if (s.xp)
        args.emplace_back(GP_copy2d_src, (void*) x.data_ptr());
    else
        args.emplace_back(GP_gemm_A, (void*) x.data_ptr());     // in_proj input
    args.emplace_back(GP_conv1d_state,   (void*) conv_state.data_ptr());
    args.emplace_back(GP_conv1d_slots,   (void*) slots.data_ptr());
    args.emplace_back(GP_gdn_rule_state, (void*) recurrent_state.data_ptr());
    args.emplace_back(GP_gdn_rule_slots, (void*) slots.data_ptr());
    if (s.yp)
        args.emplace_back(GP_copy2d_dst, (void*) y.data_ptr());
    else
        args.emplace_back(GP_gemm_C, (void*) y.data_ptr());     // o_proj output
    s.graph->launch(args, stream);
}