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.

25.8 KB
Raw Blame
#pragma once
// core9: always-inline copies of the phases that the compiler outlines in the mf7 kernel (router, top-k, gate/up, down). Generated by gen_inl.py from the core7 sources,
// bodies unchanged (only the names and __forceinline__): in the mf7 kernel they were real calls (s_swappc_b64), which cap the caller's register budget (callees ignore it)
// and force the caller to spill across the call.
#include "exl3_moe_fused7.cuh"
#if defined(USE_ROCM) || defined(__HIPCC__)
namespace mf9 {
using namespace mf;
using namespace mf7;
template <class S>
__device__ __forceinline__ void ph_router9(const Params& p, Smem<S>& s)
{
    MF_DIMS
    constexpr int NIT = D / 64, NE = 2;
    static_assert(D % 64 == 0, "router7 shape");
    const int R = p.R, wave = threadIdx.x >> 5, lane = threadIdx.x & 31;
    half* mx = s.u.g.A;
    for (int i = threadIdx.x; i < R * D / 8; i += THREADS) ((uint4*) mx)[i] = ((const uint4*) p.mixed)[i];
    __syncthreads();
    for (int eb = wave * p.G + blockIdx.x; eb < NEXP; eb += NE * 16 * p.G)
    {
        uint32_t g[NE][NIT];
        #pragma unroll
        for (int k = 0; k < NE; ++k)
        {
            const int e = eb + k * 16 * p.G;
            const uint32_t* g2 = (const uint32_t*) (p.router + router_row<S>(e < NEXP ? e : eb));
            #pragma unroll
            for (int i = 0; i < NIT; ++i) g[k][i] = g2[lane + 32 * i];
        }
        #pragma unroll
        for (int k = 0; k < NE; ++k)
        {
            const int e = eb + k * 16 * p.G;
            if (e < NEXP)
            {
                float sum[MAXR];
                #pragma unroll
                for (int r = 0; r < MAXR; ++r) sum[r] = 0.0f;
                #pragma unroll
                for (int i = 0; i < NIT; ++i)
                {
                    const half2 gg = __builtin_bit_cast(half2, g[k][i]);
                    #pragma unroll
                    for (int r = 0; r < MAXR; ++r)
                        if (r < R)
                        {
                            const half2 hh = ((const half2*) (mx + (size_t) r * D))[lane + 32 * i];
                            sum[r] = fmaf(__half2float(__low2half(hh)), __half2float(__low2half(gg)), sum[r]);
                            sum[r] = fmaf(__half2float(__high2half(hh)), __half2float(__high2half(gg)), sum[r]);
                        }
                }
                #pragma unroll
                for (int r = 0; r < MAXR; ++r)
                {
                    float v = wave_sum_down(sum[r]);
                    if (lane == 0 && r < R) p.scores[scores_idx<S>(r, e)] = __float2half_rn(v);
                }
            }
        }
    }
    if (blockIdx.x == p.G - 1 && wave == 15)
    {
        // replay of the engine's add_sigmoid_gate_proj reduction (virtual thread t = lane + 32 j, strided fma chain, tree strides 512..32 as register folds, then 16..1 by shuffles);
        // all sgate loads are issued first, the fma chain order per (row, j) is unchanged
        constexpr int NT3 = (D + 1023) / 1024;
        float sgf[32][NT3];
        #pragma unroll
        for (int j = 0; j < 32; ++j)
            #pragma unroll
            for (int t = 0; t < NT3; ++t)
            {
                const int i = lane + 32 * j + 1024 * t;
                sgf[j][t] = i < D ? __half2float(p.sgate_w[i]) : 0.0f;
            }
        for (int r = 0; r < R; ++r)
        {
            float pt[32];
            #pragma unroll
            for (int j = 0; j < 32; ++j)
            {
                float a = 0.0f;
                #pragma unroll
                for (int t = 0; t < NT3; ++t)
                {
                    const int i = lane + 32 * j + 1024 * t;
                    if (i < D) a = fmaf(sgf[j][t], __half2float(mx[(size_t) r * D + i]), a);
                }
                pt[j] = a;
            }
            #pragma unroll
            for (int w = 16; w >= 1; w >>= 1)
            {
                #pragma unroll
                for (int j = 0; j < w; ++j) pt[j] += pt[j + w];
            }
            const float v = wave_sum_down(pt[0]);
            if (lane == 0) p.sgl[r] = v;
        }
    }
}

template <class S, bool TM>
__device__ __forceinline__ void ph_finalize9(const Params& p, Smem<S>& s)
{
    MF_DIMS
    const int R = p.R, team = threadIdx.x >> 8, tid = threadIdx.x & 255, lane = tid & 31, warp = tid >> 5;
    const int D4 = D / 4;
    constexpr int CH = 32, NI = LR / 32, NTS = (LR * MAXR + 255) / 256;
    static_assert(LR % 32 == 0 && D % CH == 0, "finalize7 shape");
    const int total = DM::FIN_CHUNKS;
    const int rounds = (total + p.G * 2 - 1) / (p.G * 2);
    float* t_s = s.u.h.t[team];
    float* rmr_s = s.u.h.rmr[team];
    const float inv_h = 1.0f / (float) H;
    for (int k = 0; k < rounds; ++k)
    {
        const int cidx = blockIdx.x * 2 + team + k * p.G * 2;
        const bool valid = cidx < total;
        const int c = cidx * (CH / 4) + warp;                  // the warp's single column quad
        // loads in this order (the wait counter is in order): dots of the scalar prologue (L2), then the int8 up words (DRAM)
        static_assert(H == 4, "float4 dots rows");
        float dsum[4];
        float4 dd[NTS];
        #pragma unroll
        for (int h = 0; h < 4; ++h) dsum[h] = 0.0f;
        if (valid && tid < H * R) { const int r = tid / H, h = tid % H; dsum[0] = p.dots[dots_idx<S>(r, MR, h)]; }
        #pragma unroll
        for (int q = 0; q < NTS; ++q)
        {
            const int idx = tid + 256 * q;
            dd[q] = make_float4(0.f, 0.f, 0.f, 0.f);
            if (valid && idx < LR * R) { const int r = idx / LR, ii = idx % LR; dd[q] = *(const float4*) (p.dots + dots_idx<S>(r, 0, 0) + (size_t) ii * H); }
        }
        uint32_t up[H][NI];
        #pragma unroll
        for (int h = 0; h < H; ++h)
            #pragma unroll
            for (int i = 0; i < NI; ++i)
                up[h][i] = valid ? *(const uint32_t*) (p.upt + upt_u32<S>(h, c, lane + 32 * i) * 4) : 0u;
        if (k == 0) st7<TM>(p, 12);
        if (valid && tid < H * R)
        {
            const int r = tid / H, h = tid % H;
            rmr_s[r * 4 + h] = rsqrtf(dsum[0] / (float) D + p.rms_eps);
        }
        __syncthreads();
        if (k == 0) st7<TM>(p, 13);
        if (valid)
        {
            #pragma unroll
            for (int q = 0; q < NTS; ++q)
            {
                const int idx = tid + 256 * q;
                if (idx < LR * R)
                {
                    const int r = idx / LR, ii = idx % LR;
                    float v = 0.0f;
                    v = fmaf(rmr_s[r * 4 + 0], dd[q].x, v); v = fmaf(rmr_s[r * 4 + 1], dd[q].y, v); v = fmaf(rmr_s[r * 4 + 2], dd[q].z, v); v = fmaf(rmr_s[r * 4 + 3], dd[q].w, v);
                    v *= inv_h;
                    t_s[r * LR + ii] = v * sigmoidf_(v);
                }
            }
            if (cidx == 0 && tid < H)
            {
                for (int r = 0; r < R; ++r)
                {
                    const float* dr = p.dots + dots_idx<S>(r, 0, 0);
                    float v = 0.0f;
                    #pragma unroll
                    for (int h = 0; h < H; ++h) v = fmaf(rmr_s[r * 4 + h], dr[(size_t) (LR + tid) * H + h], v);
                    p.post[(size_t) r * H + tid] = 2.0f * sigmoidf_(v * inv_h);
                }
            }
        }
        __syncthreads();
        if (k == 0) st7<TM>(p, 14);
        if (valid)
        {
            float4 g[MAXR][H];
            #pragma unroll
            for (int r = 0; r < MAXR; ++r)
                #pragma unroll
                for (int h = 0; h < H; ++h) g[r][h] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
            float4 gsc[H];
            #pragma unroll
            for (int i = 0; i < NI; ++i)
            {
                const int ii = lane + 32 * i;
                float ti[MAXR];
                #pragma unroll
                for (int r = 0; r < MAXR; ++r) ti[r] = r < R ? t_s[r * LR + ii] : 0.0f;
                if (p.gs && (i & 1) == 0)                           // first 32-rank step of a 64-rank group
                {
                    #pragma unroll
                    for (int h = 0; h < H; ++h) gsc[h] = *(const float4*) (p.up_scale + upgs_idx<S>(h, c, ii));
                }
                #pragma unroll
                for (int h = 0; h < H; ++h)
                {
                    float u0, u1, u2, u3;
                    unpack_s8x4(up[h][i], u0, u1, u2, u3);
                    if (p.gs) { u0 = gs_dq(u0, gsc[h].x); u1 = gs_dq(u1, gsc[h].y); u2 = gs_dq(u2, gsc[h].z); u3 = gs_dq(u3, gsc[h].w); }
                    #pragma unroll
                    for (int r = 0; r < MAXR; ++r)
                        if (r < R)
                        {
                            g[r][h].x = fmaf(ti[r], u0, g[r][h].x); g[r][h].y = fmaf(ti[r], u1, g[r][h].y);
                            g[r][h].z = fmaf(ti[r], u2, g[r][h].z); g[r][h].w = fmaf(ti[r], u3, g[r][h].w);
                        }
                }
            }
            #pragma unroll
            for (int r = 0; r < MAXR; ++r)
                if (r < R)
                    #pragma unroll
                    for (int h = 0; h < H; ++h)
                        for (int o = 16; o > 0; o >>= 1)
                        {
                            g[r][h].x += __shfl_xor(g[r][h].x, o, 32); g[r][h].y += __shfl_xor(g[r][h].y, o, 32);
                            g[r][h].z += __shfl_xor(g[r][h].z, o, 32); g[r][h].w += __shfl_xor(g[r][h].w, o, 32);
                        }
            if (lane == 0)
            {
                #pragma unroll
                for (int r = 0; r < MAXR; ++r)
                    if (r < R)
                    {
                        const float4* s4 = (const float4*) (p.xin + xin_row<S>(r, 0));
                        float4 o = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
                        #pragma unroll
                        for (int h = 0; h < H; ++h)
                        {
                            const float4 sc = p.gs ? make_float4(1.0f, 1.0f, 1.0f, 1.0f) : *(const float4*) (p.up_scale + upsc_idx<S>(h, c));
                            float4 sv = s4[(size_t) h * D4 + c];
                            half4 wq = *(const half4*) (p.w + upsc_idx<S>(h, c));
                            float coef = rmr_s[r * 4 + h] * inv_h;
                            o.x = fmaf(sigmoidf_(g[r][h].x * sc.x) * coef * __low2float(wq.x),  sv.x, o.x);
                            o.y = fmaf(sigmoidf_(g[r][h].y * sc.y) * coef * __high2float(wq.x), sv.y, o.y);
                            o.z = fmaf(sigmoidf_(g[r][h].z * sc.z) * coef * __low2float(wq.y),  sv.z, o.z);
                            o.w = fmaf(sigmoidf_(g[r][h].w * sc.w) * coef * __high2float(wq.y), sv.w, o.w);
                        }
                        half2* out2 = (half2*) (p.mixed + mixed_row<S>(r));
                        out2[c * 2] = __floats2half2_rn(o.x, o.y);
                        out2[c * 2 + 1] = __floats2half2_rn(o.z, o.w);
                    }
            }
        }
        __syncthreads();
        if (k == 0) st7<TM>(p, 15);
    }
}

template <class S>
__device__ __forceinline__ void ph_combine9(const Params& p, Smem<S>& s)
{
    MF_DIMS
    const int R = p.R, NA = R * TOPK;
    const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;
    const int items = DM::CMB_BLOCKS * R;
    for (int i = blockIdx.x; i < items; i += p.G)
    {
        const int cb = i / R, r = i % R;
        if (wave <= TOPK)
        {
            const int a = r * TOPK + (wave < TOPK ? wave : 0);
            int pp = 0, e = 0;
            const half* const* sv;
            if (wave < TOPK)
            {
                for (int q = 0; q < NA; ++q) if (s.sorted_a[q] == a) { pp = q; break; }
                e = s.sorted_e[pp]; sv = p.svt + 6 * e;
            }
            else { pp = NA + r; sv = p.svt + 6 * NEXP; }
            float4 v = ((const float4*) (p.dn + dn_row<S>(pp) + cb * 128))[lane];
            v = had_regs_f_post(v, sv[5] + cb * 128, lane);
            ((float4*) (s.u.c.rows + wave * 128))[lane] = v;
        }
        __syncthreads();
        if (threadIdx.x < 128)
        {
            const int col = cb * 128 + threadIdx.x, c = threadIdx.x;
            float sum = 0.0f;
            for (int q = 0; q < NA; ++q)
            {
                const int a = s.sorted_a[q];
                if (a / TOPK != r) continue;
                const int slot = a % TOPK;
                const float weighted = __fmul_rn(s.u.c.rows[slot * 128 + c], __half2float(s.wt[a]));
                sum = __fadd_rn(sum, weighted);
            }
            const float syw = 1.0f / (1.0f + __expf(-p.sgl[r]));
            if (!(syw < 1e-8f)) sum += s.u.c.rows[TOPK * 128 + c] * syw;
            p.ydbg[(size_t) r * D + col] = sum;
            #pragma unroll
            for (int h = 0; h < H; ++h)
            {
                const float po = p.post[r * H + h];
                const float xv = p.xin[xout_idx<S>(r, h, col)];
                float o = po * sum;
                o += xv;
                p.xout[xout_idx<S>(r, h, col)] = o;
            }
        }
        __syncthreads();
    }
}

// ballot top-k (variant bit V_TK2). The 10 serial argmax ranks of the plain selection (10 x 5 cross-lane butterfly steps) become one
// bit descent over a unique 25-bit key (ordered fp16 score << 9 | 511 - expert): the 10th largest key needs 25 rounds of 16 ballot popcounts and
// no cross-lane data movement; the 10 selected keys are then ranked through the wave's own scratch. Same total order as the plain loop (score
// descending, expert ascending; NaN and -inf the lowest class, -0 == +0), same rank order, same float values for gmax / ek.
constexpr int V_TK2 = 0x1000;
__device__ __forceinline__ uint32_t tk2_key(const half h, const int idx)
{
    uint32_t u = __half_as_ushort(h);
    uint32_t k;
    if ((u & 0x7fffu) > 0x7c00u || u == 0xfc00u) k = 0u;             // NaN or -inf: lowest class
    else { if ((u & 0x7fffu) == 0u) u = 0u; k = (u & 0x8000u) ? ((~u) & 0xffffu) : (u | 0x8000u); }
    return (k << 9) | (uint32_t) (511 - idx);
}
__device__ __forceinline__ float tk2_value(const uint32_t ukey)
{
    const uint32_t k = ukey >> 9;
    if (k == 0u) return -__FLT_MAX__;
    const uint32_t u = (k & 0x8000u) ? (k & 0x7fffu) : ((~k) & 0xffffu);
    return __half2float(__ushort_as_half((unsigned short) u));
}

template <class S>
__device__ __forceinline__ void ph_topk_tail9(const Params& p, Smem<S>& s)
{
    MF_DIMS
    const int R = p.R;
    const int NA = R * TOPK;
    if (threadIdx.x < NA)
    {
        const int a = threadIdx.x, e = s.sel[a];
        int pp = 0;
        for (int b = 0; b < NA; ++b) { const int eb = s.sel[b]; pp += (eb < e) || (eb == e && b < a); }
        s.sorted_e[pp] = e; s.sorted_a[pp] = a; s.tok[pp] = a / TOPK;
    }
    __syncthreads();
    if (threadIdx.x < NA) s.head[threadIdx.x] = (threadIdx.x == 0 || s.sorted_e[threadIdx.x - 1] != s.sorted_e[threadIdx.x]) ? 1 : 0;
    __syncthreads();
    if (threadIdx.x == 0)
    {
        if constexpr (TRows<S>::v > MAXR) { s.ngroups = build_units_wide(s.head, NA, R, s.gstart, s.urows); }   // moe8: units of <= MAXR rows, shared expert = ceil(R / MAXR) units
        else {
        int g = 0;
        for (int q = 0; q < NA; ++q) if (s.head[q]) s.gstart[g++] = q;
        s.gstart[g] = NA; s.ngroups = g;
        for (int u = 0; u < g; ++u) s.urows[u] = min(s.gstart[u + 1] - s.gstart[u], MAXR);
        s.urows[g] = R;                       // the shared expert: R rows
        }
    }
    __syncthreads();
}

template <class S>
__device__ __forceinline__ void ph_topk9(const Params& p, Smem<S>& s, int vm = 0)
{
    MF_DIMS
    constexpr int KEYS = DM::KEYS;
    const int R = p.R, wave = threadIdx.x >> 5, lane = threadIdx.x & 31;
    constexpr bool TK2_OK = NEXP == 512 && KEYS == 16 && TOPK <= 16;   // other shapes (test shapes) keep the plain selection
    if (TK2_OK && (vm & V_TK2) && wave < R)
    {
        uint32_t uk[KEYS];
        #pragma unroll
        for (int i = 0; i < KEYS; ++i) uk[i] = tk2_key(p.scores[scores_idx<S>(wave, i * 32 + lane)], i * 32 + lane);
        uint32_t thr = 0;
        #pragma unroll 1
        for (int b = 24; b >= 0; --b)
        {
            const uint32_t cand = thr | (1u << b);
            int cnt = 0;
            #pragma unroll
            for (int i = 0; i < KEYS; ++i) cnt += __builtin_popcount(__builtin_amdgcn_ballot_w32(uk[i] >= cand));
            if (cnt >= TOPK) thr = cand;
        }
        volatile int* cmp = (volatile int*) &s.sorted_a[wave * TOPK];      // compacted selected keys (scratch, rewritten by the tail below)
        volatile int* ord = (volatile int*) &s.tok[wave * TOPK];           // keys in rank order
        int base = 0;
        #pragma unroll
        for (int i = 0; i < KEYS; ++i)
        {
            const bool sel = uk[i] >= thr;
            const unsigned m = __builtin_amdgcn_ballot_w32(sel);
            if (sel) cmp[base + __builtin_popcount(m & ((1u << lane) - 1u))] = (int) uk[i];
            base += __builtin_popcount(m);
        }
        __builtin_amdgcn_wave_barrier();
        int myk = 0, rk = 0;
        if (lane < TOPK)
        {
            myk = cmp[lane];
            #pragma unroll
            for (int j = 0; j < TOPK; ++j) rk += (cmp[j] > myk);
            ord[rk] = myk;
        }
        __builtin_amdgcn_wave_barrier();
        const uint32_t k0 = (uint32_t) ord[0];
        const uint32_t kr = lane < TOPK ? (uint32_t) ord[lane] : 0u;
        const float gmax = tk2_value(k0);
        const float bk = tk2_value(kr);
        const float ek = (bk == gmax) ? 1.0f : expf(bk - gmax);
        const int myidx = clamp_expert(511 - (int) (kr & 511u), NEXP);
        const float e = lane < TOPK ? ek : 0.0f;
        const float sum = wave_sum_down(e) + 1.0e-20f;
        if (lane < TOPK)
        {
            s.sel[wave * TOPK + lane] = myidx;
            s.wt[wave * TOPK + lane] = __float2half_rn(e / sum);
        }
    }
    else if (wave < R)
    {
        float key[KEYS];
        #pragma unroll
        for (int i = 0; i < KEYS; ++i)
        {
            // NaN and -inf scores become the lowest finite key: they stay selectable (lowest index first), so a row always picks TOPK distinct
            // experts and a group never holds more than R rows (the A staging buffers hold MAXR rows)
            const float kv = __half2float(p.scores[scores_idx<S>(wave, i * 32 + lane)]);
            key[i] = (kv > -__FLT_MAX__) ? kv : -__FLT_MAX__;
        }
        float gmax = 0.0f, ek = 0.0f;
        int myidx = 0;
        #pragma unroll
        for (int rank = 0; rank < TOPK; ++rank)
        {
            float bk = -INFINITY; int bi = 0x7fffffff;
            #pragma unroll
            for (int i = 0; i < KEYS; ++i)
                if (key[i] > bk) { bk = key[i]; bi = i * 32 + lane; }
            #pragma unroll
            for (int o = 16; o > 0; o >>= 1)
            {
                float ok = __shfl_xor(bk, o, 32); int oi = __shfl_xor(bi, o, 32);
                if (ok > bk || (ok == bk && oi < bi)) { bk = ok; bi = oi; }
            }
            if (rank == 0) gmax = bk;
            if (lane == rank) { ek = (bk == gmax) ? 1.0f : expf(bk - gmax); myidx = clamp_expert(bi, NEXP); }
            #pragma unroll
            for (int i = 0; i < KEYS; ++i)
                if (i * 32 + lane == bi) key[i] = -INFINITY;
        }
        const float e = lane < TOPK ? ek : 0.0f;
        const float sum = wave_sum_down(e) + 1.0e-20f;
        if (lane < TOPK)
        {
            s.sel[wave * TOPK + lane] = myidx;
            s.wt[wave * TOPK + lane] = __float2half_rn(e / sum);
        }
    }
    __syncthreads();
    ph_topk_tail9<S>(p, s);
}

// Split launches: the stages after the router re-enter here with s.sel / s.wt reloaded from seldbg (block 0 of the top-k stage wrote them)
template <class S>
__device__ __forceinline__ void topk_restore9(const Params& p, Smem<S>& s)
{
    if (threadIdx.x < p.R * S::TOPK)
    {
        s.sel[threadIdx.x] = p.seldbg[threadIdx.x];
        s.wt[threadIdx.x] = __ushort_as_half((unsigned short) p.seldbg[sel_wt_base(TRows<S>::v) + threadIdx.x]);
    }
    __syncthreads();
    ph_topk_tail9<S>(p, s);
}

template <class S, int ABL>
__device__ __forceinline__ void ph_gateup9(const Params& p, Smem<S>& s)
{
    MF_DIMS
    const int R = p.R, NA = R * TOPK, NAR = NA + R;
    const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;
    const int NU = s.ngroups + (TRows<S>::v > MAXR ? units_shared(R) : 1);
    constexpr int TPP = DM::TPP;
    const bool nat = p.native != 0;
    const long long W = split_total(s.urows, NU, 2, TPP);
    const int lo = split_tile(s.urows, NU, 2, TPP, (long long) blockIdx.x * W / p.G), hi = split_tile(s.urows, NU, 2, TPP, (long long) (blockIdx.x + 1) * W / p.G);
    int i = lo;
    while (i < hi)
    {
        const int segA = i / TPP, endA = min(hi, (segA + 1) * TPP);
        const int iB = endA, segB = iB / TPP;
        const bool hasB = iB < hi;
        const int endB = hasB ? min(hi, (segB + 1) * TPP) : iB;
        const int nA = endA - i, nB = endB - iB;
        __syncthreads();
        for (int w2 = 0; w2 < (hasB ? 2 : 1); ++w2)
        {
            const int seg = w2 ? segB : segA;
            const Seg g = seginfo<S>(p, s, seg, true);
            half* Abuf = w2 ? s.u.g.A2 : s.u.g.A;
            const half* suh = g.sv[g.proj == 0 ? 0 : 2];
            for (int task = wave; task < g.rows * DM::CMB_BLOCKS; task += 16)
            {
                const int row = task / DM::CMB_BLOCKS, blk = task % DM::CMB_BLOCKS;
                const int token = g.shared ? (TRows<S>::v > MAXR ? g.p0 - NA + row : row) : s.tok[g.p0 + row];
                half4 v = ((const half4*) (p.mixed + mixed_row<S>(token) + blk * 128))[lane];
                v = had_regs_h<true, false>(v, suh + blk * 128, lane);
                ((half4*) (Abuf + a_row_gu<S>(row, blk)))[lane] = v;
            }
        }
        __syncthreads();
        for (int n = wave; n < nA + nB; n += 16)
        {
            const bool inB = n >= nA;
            const int seg = inB ? segB : segA;
            const int tile = (inB ? iB + (n - nA) : i + n) - seg * TPP;
            const Seg g = seginfo<S>(p, s, seg, true);
            const uint32_t* Ab = (const uint32_t*) (inB ? s.u.g.A2 : s.u.g.A);
            half* C = p.gu + gu_out<S>(g.proj, NAR, g.p0);
            const uint32_t* Wm = p.wt[3 * (g.shared ? DM::NEXP : g.e) + g.proj];
            if (g.shared)
                mf7_tile_rows<DM::SB, false, DM::KSG, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::SB, DM::KSG, TPP, tile), tile_ss(nat, DM::SB, TPP), C, INTER, tile, s.u.g.red, wave, lane);
            else
                mf7_tile_rows<DM::RB, false, DM::KSG, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::RB, DM::KSG, TPP, tile), tile_ss(nat, DM::RB, TPP), C, INTER, tile, s.u.g.red, wave, lane);
        }
        i = endB;
    }
}

template <class S, int ABL>
__device__ __forceinline__ void ph_down9(const Params& p, Smem<S>& s)
{
    MF_DIMS
    const int R = p.R, NA = R * TOPK, NAR = NA + R;
    const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;
    const int NU = s.ngroups + (TRows<S>::v > MAXR ? units_shared(R) : 1);
    constexpr int TPU = DM::TPU;
    const bool nat = p.native != 0;
    const long long W = split_total(s.urows, NU, 1, TPU);
    const int lo = split_tile(s.urows, NU, 1, TPU, (long long) blockIdx.x * W / p.G), hi = split_tile(s.urows, NU, 1, TPU, (long long) (blockIdx.x + 1) * W / p.G);
    int i = lo;
    while (i < hi)
    {
        const int segA = i / TPU, endA = min(hi, (segA + 1) * TPU);
        const int iB = endA, segB = iB / TPU;
        const bool hasB = iB < hi;
        const int endB = hasB ? min(hi, (segB + 1) * TPU) : iB;
        const int nA = endA - i, nB = endB - iB;
        __syncthreads();
        for (int w2 = 0; w2 < (hasB ? 2 : 1); ++w2)
        {
            const Seg g = seginfo<S>(p, s, w2 ? segB : segA, false);
            half* Abuf = w2 ? s.u.g.A2 : s.u.g.A;
            const half* const* sv = g.sv;
            for (int task = wave; task < g.rows * DM::INT_BLOCKS; task += 16)
            {
                const int row = task / DM::INT_BLOCKS, blk = task % DM::INT_BLOCKS;
                half4 gg = ((const half4*) (p.gu + gu_read<S>(NAR, g.p0 + row, blk, 0)))[lane];
                half4 uu = ((const half4*) (p.gu + gu_read<S>(NAR, g.p0 + row, blk, 1)))[lane];
                gg = had_regs_h<false, true>(gg, sv[1] + blk * 128, lane);
                uu = had_regs_h<false, true>(uu, sv[3] + blk * 128, lane);
                half4 a;
                {
                    float f0 = __half2float(__low2half(gg.x)), f1 = __half2float(__high2half(gg.x));
                    float f2 = __half2float(__low2half(gg.y)), f3 = __half2float(__high2half(gg.y));
                    half h0 = __float2half_rn(f0 / (1.0f + expf(-f0))), h1 = __float2half_rn(f1 / (1.0f + expf(-f1)));
                    half h2 = __float2half_rn(f2 / (1.0f + expf(-f2))), h3 = __float2half_rn(f3 / (1.0f + expf(-f3)));
                    a.x = __halves2half2(__hmul(h0, __low2half(uu.x)), __hmul(h1, __high2half(uu.x)));
                    a.y = __halves2half2(__hmul(h2, __low2half(uu.y)), __hmul(h3, __high2half(uu.y)));
                }
                a = had_regs_h<true, false>(a, sv[4] + blk * 128, lane);
                ((half4*) (Abuf + a_row_dn<S>(row, blk)))[lane] = a;
            }
        }
        __syncthreads();
        for (int n = wave; n < nA + nB; n += 16)
        {
            const bool inB = n >= nA;
            const int seg = inB ? segB : segA;
            const int tile = (inB ? iB + (n - nA) : i + n) - seg * TPU;
            const Seg g = seginfo<S>(p, s, seg, false);
            const uint32_t* Ab = (const uint32_t*) (inB ? s.u.g.A2 : s.u.g.A);
            float* C = p.dn + dn_row<S>(g.p0);
            const uint32_t* Wm = p.wt[3 * (g.shared ? DM::NEXP : g.e) + 2];
            if (g.shared)
                mf7_tile_rows<DM::SB, true, DM::KSD, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::SB, DM::KSD, TPU, tile), tile_ss(nat, DM::SB, TPU), C, D, tile, s.u.g.red, wave, lane);
            else
                mf7_tile_rows<DM::RB, true, DM::KSD, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::RB, DM::KSD, TPU, tile), tile_ss(nat, DM::RB, TPU), C, D, tile, s.u.g.red, wave, lane);
        }
        i = endB;
    }
}

}  // namespace mf9
#endif