okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6a74320ca
main
1// metal/tests/sample_parity.cpp - greedy argmax (sample.metal) vs the CPU over 248,320 logits with planted ties, 2// and its time. 3#include "mtl_rt.h" 4#include "ref_quant.h" 5 6#include <algorithm> 7#include <cmath> 8#include <cstdio> 9#include <vector> 10 11int main () { 12constexpr uint32_t V = 248320 ,PARTS = 120 ; 13 mtl::Context cx ; 14const int lib = cx .compile ({"sample.metal" },"#define NO_GGML_COMMON 1\n" ); 15 mtl::Pipeline pp = cx .pipeline (lib ,"argmax_part" ),pf = cx .pipeline (lib ,"argmax_final" ); 16const int MAXT = 8 ; 17 mtl::Buffer lg = cx .alloc (4 * (size_t )V * MAXT ),pv = cx .alloc (4 * PARTS * MAXT ),pi = cx .alloc (4 * PARTS * MAXT ), 18out = cx .alloc (4 * MAXT ); 19 ref::Rng r (5 ); 20int fails = 0 ; 21struct A {uint32_t n_vocab ,parts ; }a {V ,PARTS }; 22for (int trial = 0 ;trial < 20 ;++ trial ) { 23const int nt = 1 + trial %MAXT ; 24for (size_t i = 0 ;i < (size_t )V * nt ;++ i )lg .as < float > ()[i ]= std::round (r .sym ()* 1000.0f ) /100.0f ; 25for (int t = 0 ;t < nt ;++ t ) { 26// plant a tie at the maximum 27const size_t i1 = r .next () %V ,i2 = r .next () %V ; 28lg .as < float > ()[t * V + i1 ]= 20.0f ; 29lg .as < float > ()[t * V + i2 ]= 20.0f ; 30 } 31 mtl::Dispatch d1 ,d2 ; 32d1 .p = & pp ; 33d1 .args = {mtl::Arg ::B (lg ), mtl::Arg ::B (pv ), mtl::Arg ::B (pi ), mtl::Arg ::V (a )}; 34d1 .grid [0 ]= PARTS ; 35d1 .grid [1 ]= nt ; 36d1 .tg [0 ]= 256 ; 37d2 .p = & pf ; 38d2 .args = {mtl::Arg ::B (pv ), mtl::Arg ::B (pi ), mtl::Arg ::B (out ), mtl::Arg ::V (a )}; 39d2 .grid [0 ]= nt ; 40d2 .tg [0 ]= 256 ; 41cx .run ({d1 ,d2 }); 42for (int t = 0 ;t < nt ;++ t ) { 43const float * l = lg .as < float > ()+ (size_t )t * V ; 44int best = 0 ; 45for (uint32_t i = 1 ;i < V ;++ i ) 46if (l [i ]> l [best ])best = (int )i ; 47fails += out .as < int > ()[t ]!= best ; 48 } 49if (trial == 19 ) { 50 std::vector < mtl::Dispatch > ds ; 51for (int k = 0 ;k < 64 ;++ k ) {ds .push_back (d1 );ds .push_back (d2 ); } 52cx .warm (ds ,0.05 ); 53 std::vector < double > ts ; 54for (int k = 0 ;k < 7 ;++ k )ts .push_back (cx .run (ds ) /64 ); 55 std::sort (ts .begin (),ts .end ()); 56 std::printf ("argmax %d token(s) over %u logits: %.2f us (2 dispatches)\n" ,nt ,V ,ts [3 ]* 1e6 ); 57 } 58 } 59 std::printf ("argmax parity, 20 windows with planted ties: %d wrong %s\n" ,fails ,fails ?"FAIL" :"PASS" ); 60return fails ?1 :0 ; 61}