okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Shawn Jacksoncore: the model's geometry is read from its GGUF metadata and checked against the shape the kernels are compiled forf812e9a16

main
9.7 KiB216 linesraw
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// ggml/src/ggml-cuda/{mmf.cuh,mma.cuh,unary.cu,binbcast.cu}.
3// MIT License
4// Copyright (c) 2023-2026 The ggml authors
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11// The above copyright notice and this permission notice shall be included in all
12// copies or substantial portions of the Software.
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21#include "strata/kernels/native_qsa_score.hpp"
22#include "strata/core/geometry.hpp"
23#include <cuda_runtime.h>
24#include <atomic>
25#include <cstddef>
26#include <cstdint>
27#include <stdexcept>
28
29namespace strata::kernels {
30namespace {
31std::atomic<bool> enabled{false};
32constexpr int D=128, HEADS=4, R=4, ROWS=32, WARPS=2, STRIDE=36, COMBINE=68;
33static_assert(D == strata::core::kCompiledGeometry.idx_key_dim && HEADS == strata::core::kCompiledGeometry.idx_q_heads && R == strata::core::kCompiledGeometry.idx_block,
34              "native_qsa_score is compiled for core/geometry.hpp");
35struct TileA { uint32_t x[4]; };
36struct TileB { uint32_t x[2]; };
37struct TileC { float x[4]={0.0f,0.0f,0.0f,0.0f}; };
38#if !defined(__HIPCC__)
39#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800
40__device__ __forceinline__ void load_a(TileA& a,const float* p) {
41    const float* src=p+(threadIdx.x%16)*STRIDE+(threadIdx.x/16)*4;
42    asm volatile("ldmatrix.sync.aligned.m8n8.x4.b16 {%0,%1,%2,%3}, [%4];"
43        : "=r"(a.x[0]),"=r"(a.x[1]),"=r"(a.x[2]),"=r"(a.x[3]):"l"(src));
44}
45__device__ __forceinline__ void load_b(TileB& b,const float* p) {
46    const float* src=p+(threadIdx.x%8)*STRIDE+((threadIdx.x/8)*4)%8;
47    asm volatile("ldmatrix.sync.aligned.m8n8.x2.b16 {%0,%1}, [%2];"
48        : "=r"(b.x[0]),"=r"(b.x[1]):"l"(src));
49}
50__device__ __forceinline__ void mma(TileC& c,const TileA& a,const TileB& b) {
51    // Deliberately no cvt.rn.tf32: pinned mma.cuh passes raw F32 bits directly.
52    asm("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};"
53        : "+f"(c.x[0]),"+f"(c.x[1]),"+f"(c.x[2]),"+f"(c.x[3])
54        : "r"(a.x[0]),"r"(a.x[1]),"r"(a.x[2]),"r"(a.x[3]),"r"(b.x[0]),"r"(b.x[1]));
55}
56#endif
57__global__ __launch_bounds__(64,1) void score_kernel(
58        const float* __restrict__ pooled,const float* __restrict__ query,
59        const float* __restrict__ bias,const int32_t* __restrict__ step,
60        int max_cells,float* __restrict__ cells) {
61    const int n=step[kStepNKv],full=step[kStepNBid];
62    if(n<1||n>max_cells||step[kStepPos]!=n-1||full!=n/R||
63       step[kStepWidth]!=(n<2051?n:2051))return;
64    const int row0=blockIdx.x*ROWS;
65    if(row0>full)return;
66    const int lane=threadIdx.x,warp=threadIdx.y;
67#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
68    // Turing (STRATA_EXPERIMENTAL_SM75, a layer-split stage): no tf32 mma.  The same scores with FP32 FMAs, one row
69    // per thread of the first warp - rounded differently from the tensor-core path (FP32 instead of TF32 inputs).
70    if(warp!=0)return;
71    const int row=row0+lane;
72    if(row>full)return;
73    float h[HEADS];
74    for(int j=0;j<HEADS;++j){
75        float acc=0.0f;
76        for(int d=0;d<D;++d)acc=fmaf(pooled[size_t(row)*D+d],query[j*D+d],acc);
77        h[j]=fmaxf(acc,0.0f);
78    }
79    float sum=__fadd_rn(__fadd_rn(__fadd_rn(h[0],h[1]),h[2]),h[3]);
80    if(bias)sum=__fadd_rn(sum,bias[row]);
81    sum=__fadd_rn(sum,row==full&&n%R?1e9f:0.0f);
82    for(int i=row*R;i<n&&i<(row+1)*R;++i)cells[i]=sum;
83#else
84    __shared__ __align__(16) float shared[WARPS*16*STRIDE];
85    float* tile=shared+warp*16*STRIDE;
86    TileC c[2];
87    // mmf's launch heuristic picks2warps for K128. Each warp accumulates
88    // K[warp*32,warp*32+32), then K[warp*32+64,warp*32+96).
89    for(int col=warp*32+lane;col<D;col+=WARPS*32){
90        TileA a[2][4];
91#pragma unroll
92        for(int ia=0;ia<2;++ia){
93            __syncwarp();
94#pragma unroll
95            for(int i=0;i<16;++i){
96                const int row=row0+ia*16+i;
97                tile[i*STRIDE+lane]=row<=full?pooled[size_t(row)*D+col]:0.0f;
98            }
99            __syncwarp();
100#pragma unroll
101            for(int k=0;k<4;++k)load_a(a[ia][k],tile+k*8);
102        }
103        __syncwarp();
104#pragma unroll
105        for(int h=0;h<8;++h)tile[h*STRIDE+lane]=h<HEADS?query[h*D+col]:0.0f;
106        __syncwarp();
107#pragma unroll
108        for(int k=0;k<4;++k){
109            TileB b;load_b(b,tile+k*8);
110#pragma unroll
111            for(int ia=0;ia<2;++ia)mma(c[ia],a[ia][k],b);
112        }
113    }
114    __syncthreads();
115#pragma unroll
116    for(int ia=0;ia<2;++ia){
117#pragma unroll
118        for(int l=0;l<4;++l){
119            const int i=warp*ROWS+ia*16+(l/2)*8+lane/4;
120            const int h=(lane%4)*2+l%2;
121            shared[h*COMBINE+i]=c[ia].x[l];
122        }
123    }
124    __syncthreads();
125    // In the reference: +0 then warp0 partial then warp1 partial, followed
126    // by materialized ReLU, CONT(head0), ADD(head1), ADD(head2), ADD(head3).
127    if(warp==0){
128        const int row=row0+lane;
129        if(row>full)return;
130        float h[HEADS];
131#pragma unroll
132        for(int j=0;j<HEADS;++j){
133            float v=__fadd_rn(0.0f,shared[j*COMBINE+lane]);
134            v=__fadd_rn(v,shared[j*COMBINE+ROWS+lane]);
135            h[j]=fmaxf(v,0.0f);
136        }
137        float sum=__fadd_rn(__fadd_rn(__fadd_rn(h[0],h[1]),h[2]),h[3]);
138        if(bias)sum=__fadd_rn(sum,bias[row]);
139        sum=__fadd_rn(sum,row==full&&n%R?1e9f:0.0f);
140        // The live causal mask is +0. Invalid/padded cells are never exported.
141        sum=__fadd_rn(sum,0.0f);
142        for(int i=row*R;i<n&&i<(row+1)*R;++i)cells[i]=sum;
143    }
144#endif
145}
146#else
147// gfx1100 has no CUDA ldmatrix/mma instruction sequence. Keep the same entry point and
148// score contract with an ordered scalar F32 dot for each indexer head. The four heads
149// run independently; their ReLU'd scores are then added in the documented head order.
150// This path favors a well-defined fallback over pretending the CUDA PTX is portable.
151__global__ void scalar_score_kernel(
152        const float* __restrict__ pooled,const float* __restrict__ query,
153        const float* __restrict__ bias,const int32_t* __restrict__ step,
154        int max_cells,float* __restrict__ cells) {
155    const int n=step[kStepNKv],full=step[kStepNBid];
156    if(n<1||n>max_cells||step[kStepPos]!=n-1||full!=n/R||
157       step[kStepWidth]!=(n<2051?n:2051))return;
158    const int row=blockIdx.x;
159    if(row>full)return;
160    __shared__ float head_score[HEADS];
161    const int head=threadIdx.x;
162    if(head<HEADS){
163        float dot=0.0f;
164#pragma unroll
165        for(int d=0;d<D;++d)
166            dot=__fmaf_rn(pooled[size_t(row)*D+d],query[size_t(head)*D+d],dot);
167        head_score[head]=dot>0.0f?dot:0.0f;
168    }
169    __syncthreads();
170    if(head==0){
171        float sum=__fadd_rn(0.0f,head_score[0]);
172        sum=__fadd_rn(sum,head_score[1]);
173        sum=__fadd_rn(sum,head_score[2]);
174        sum=__fadd_rn(sum,head_score[3]);
175        if(bias)sum=__fadd_rn(sum,bias[row]);
176        sum=__fadd_rn(sum,row==full&&n%R?1e9f:0.0f);
177        sum=__fadd_rn(sum,0.0f);
178        for(int i=row*R;i<n&&i<(row+1)*R;++i)cells[i]=sum;
179    }
180}
181#endif
182struct Span{const void* p;size_t n;};
183void validate(Span s){
184    const auto p=reinterpret_cast<uintptr_t>(s.p);
185    if(!p||p%4||s.n>UINTPTR_MAX-p)throw std::invalid_argument("native QSA score requires aligned bounded spans");
186}
187bool overlaps(Span a,Span b){
188    const auto x=reinterpret_cast<uintptr_t>(a.p),y=reinterpret_cast<uintptr_t>(b.p);
189    return x<y+b.n&&y<x+a.n;
190}
191} // namespace
192void native_qsa_score_set_enabled(bool value){enabled.store(value,std::memory_order_relaxed);}
193bool native_qsa_score_enabled(){return enabled.load(std::memory_order_relaxed);}
194void native_qsa_score(const float* pooled,const float* query,const float* bias,
195                      const QsaShapes& s,const int32_t* step,int64_t max_blocks,int64_t max_cells,
196                      float* cells,void* stream){
197    if(!stream||s.idx_dim!=D||s.idx_n_head!=HEADS||s.idx_block!=R||s.idx_top_k!=2048||
198       max_cells<1||max_cells>INT32_MAX-3||max_blocks!=max_cells/R+1)
199        throw std::invalid_argument("native QSA score requires128dim/4heads/4cells/2048budget, exact capacities and explicit stream");
200    const Span spans[]={{pooled,size_t(max_blocks)*D*4},{query,HEADS*D*4},
201        {step,kStepCount*4},{cells,size_t(max_cells)*4},{bias,bias?size_t(max_blocks)*4:0}};
202    const int count=bias?5:4;
203    for(int i=0;i<count;++i)validate(spans[i]);
204    for(int i=0;i<count;++i)for(int j=i+1;j<count;++j)
205        if(overlaps(spans[i],spans[j]))throw std::invalid_argument("native QSA score spans overlap");
206#if defined(__HIPCC__)
207    scalar_score_kernel<<<unsigned(max_blocks),128,0,static_cast<cudaStream_t>(stream)>>>(
208        pooled,query,bias,step,int(max_cells),cells);
209#else
210    score_kernel<<<unsigned((max_blocks+ROWS-1)/ROWS),dim3(32,WARPS),0,static_cast<cudaStream_t>(stream)>>>(
211        pooled,query,bias,step,int(max_cells),cells);
212#endif
213    const auto error=cudaGetLastError();
214    if(error!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(error));
215}
216} // namespace strata::kernels