okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
1// src/kernels/iq_nibble_parity.cpp - STRATA_EXPERT_NIBBLE (strata/core/expert_nibble.hpp): the 4-bit gate/up expert 2// slots against the production kernels and the GGUF blobs, bit for bit. 3// 4// build/iq_nibble_parity --header the host half of expert_nibble.hpp (no GPU) 5// build/iq_nibble_parity <shard.gguf> [<shard.gguf> ...] [--layers-per-fmt 2] [--layers 1,17] [--ne 512] 6// [--plans 8] [--synthetic 64] [--no-ggml] [--negative] 7// build/iq_nibble_parity --synthetic-only [--synthetic 64] [--plans 8] [--no-ggml] no model, no shard 8// 9// Each model (any shard of it; its other shards are opened beside it) gives `--layers-per-fmt` layers of each 10// converted format (IQ2_S, IQ3_XXS, IQ3_S; or `--layers`), `--ne` experts each, read from the GGUF tensors into the 11// blob the pack holds (gate rows, up rows, down rows). Per layer: 12// (1) nibble::transcode, 64 blobs a batch as the startup fill runs it: 0 items that do not round-trip; 13// (2) every gate/up byte of a slot is written (8 slots transcoded again into another pre-fill byte); 14// (3) nibble::hash_slots against nibble::hash_host on every slot read back (and a flipped byte must change it); 15// (4) the host codec on every item: decode_item then encode_item gives the code back; 16// (5) ggml's reference dequantizer (to_float) on every GGUF row against the weight the 4-bit slot gives through 17// dequantize_row_iq2_s / _iq3_xxs / _iq3_s's own expression (code, scale byte, fp16 d): every weight, bit for bit; 18// (6) nibble::check_gguf (the start-up check: the GGUF blocks rebuilt from every slot against the blob): 0 words 19// differ; nibble::gather_gguf (the prompt path's MMQ gather) in groups of 16 and of 1..15 from a later first 20// position: the rebuilt [gate | up] and the down rows byte for byte the blob's, the MMQ tail after the group zero; 21// (7) native_expert_grouped on the converted slots (native_expert_layout_nib) against the same call on the GGUF 22// blobs (native_expert_layout): hq and out byte for byte for every entry, and gate / up where the reference 23// layout writes them - in the card's default layout (a GP100: mode 8, whose gate/up kernel writes hq) and in the 24// CUDA layout (native_expert_set_mode(0)), each with native_grouped_set_v1 off and on (h too, in mode 0 + v1); 25// top-10 routing T = 1..6 at 0% and 50% sharing (`--plans` each), one group of T entries (G = 1) per T, plans of 26// groups with 0..11 entries (more than one GRP_NC pass, empty groups); grid_groups 0 (cap) and 4 (the PCIe 27// call's stride); the default kernel per format and each skeleton forced (S, P); q8_1 activations random, all 28// +127, all -127 and alternating +-127 (the sum of x at its extremes, +-4064). 29// `--synthetic N`: per format, N experts whose gate/up blocks are random bytes (every grid index, sign byte and scale 30// nibble the format has; the coverage is counted and must be complete) and whose fp16 d cycle through +-the smallest 31// subnormal, +-65504, +-1, the smallest normal and two ordinary values; checks (1)-(7) on them. 32// `--synthetic-only`: the synthetic experts alone, for every gate/up format x both down types (IQ4_NL, Q2_0), the down rows 33// random bytes with ordinary fp16 scales: checks (1)-(7) with no model file (a GP100 is still needed). 34// `--negative`: the control - one code byte per slot changed after the transcode; (6) and (7) must then report differences. 35// Exit 0 when every check is equal; 1 otherwise; 2 on a usage or setup error. A build without STRATA_EXPERT_NIBBLE_BUILT 36// (the CUDA build with STRATA_EXPERIMENTAL_SM60) has no 4-bit kernels: --header only. 37#include "strata/artifact/gguf_reader.hpp" 38#include "strata/core/expert_nibble.hpp" 39#include "strata/kernels/cpu/native_expert.hpp" 40#include "strata/kernels/iq_kernels.hpp" 41 42#include "ggml.h" 43 44#include <cuda_runtime.h> 45 46#include <algorithm> 47#include <atomic> 48#include <cstdio> 49#include <cstdlib> 50#include <cstring> 51#include <memory> 52#include <random> 53#include <set> 54#include <string> 55#include <thread> 56#include <vector> 57 58namespace { 59 60namespace nib= strata::core::nibble; 61namespace K = strata::kernels; 62namespace cpu= strata::kernels::cpu; 63 64int fails = 0 ; 65void expect (bool ok ,const char * what ) { 66if (!ok ) { 67 std::printf ("FAIL %s\n" ,what ); 68++ fails ; 69 } 70} 71 72// Every value the format holds at every one of an item's 32 positions (the other positions cycle through the set), 73// encoded, decoded and compared; and one value outside the set must be refused. 74void round_trip (int fmt ,const std::vector < int8_t >& set ,int8_t outside ) { 75int8_t g [32 ],back [32 ]; 76uint32_t q [4 ]; 77for (size_t shift = 0 ;shift < set .size ();++ shift ) { 78for (int i = 0 ;i < 32 ;++ i )g [i ]= set [(shift + (size_t )i ) %set .size ()]; 79const bool ok = nib::encode_item (fmt ,g ,q ); 80 nib::decode_item (fmt ,q ,back ); 81expect (ok && std::memcmp (g ,back ,32 )== 0 , (std::string (nib::fmt_name (fmt ))+ " round trip" ).c_str ()); 82 } 83for (int i = 0 ;i < 32 ;++ i )g [i ]= set [0 ]; 84g [17 ]= outside ; 85expect (!nib::encode_item (fmt ,g ,q ), (std::string (nib::fmt_name (fmt ))+ " refuses a value outside the set" ).c_str ()); 86} 87 88int header_check () { 89expect (nib::kGuBytes == 1766400 && nib::kScOff == 1638400 && nib::kDOff == 1740800 ,"layout sizes" ); 90expect (nib::code_off (nib::kNFf ,0 )== nib::kUpCodesOff ,"up rows' codes" ); 91expect (nib::slot_bytes_for (921600 ) % nib::kSlotAlign == 0 ,"slot alignment" ); 92round_trip (nib::kIQ2_S , {8 ,25 ,43 ,-8 ,-25 ,-43 },9 ); 93round_trip (nib::kIQ3_XXS , {4 ,12 ,20 ,28 ,36 ,44 ,52 ,62 ,-4 ,-12 ,-20 ,-28 ,-36 ,-44 ,-52 ,-62 },5 ); 94 std::vector < int8_t > s3 ; 95for (int v = -15 ;v <=15 ;v += 2 )s3 .push_back ((int8_t )v ); 96round_trip (nib::kIQ3_S ,s3 ,2 ); 97// IQ2_S's nibble is the decode kernel's PRMT selector into {8,25,43,0} {-8,-25,-43,0} 98 { 99int8_t g [32 ]= {},back [32 ]; 100uint32_t q [4 ]; 101for (int i = 0 ;i < 32 ;++ i )g [i ]= (int8_t ) (i %2 ?-25 :43 ); 102 nib::encode_item (nib::kIQ2_S ,g ,q ); 103expect ((q [0 ]& 0xFu )== 2u && (q [0 ] >>4 & 0xFu )== 5u ,"IQ2_S selector nibbles" ); 104 nib::decode_item (nib::kIQ2_S ,q ,back ); 105expect (std::memcmp (g ,back ,32 )== 0 ,"IQ2_S selector decode" ); 106 } 107expect (nib::gu_skeleton (nib::kIQ2_S )== nib::kSkelP && nib::gu_skeleton (nib::kIQ3_XXS )== nib::kSkelS && 108 nib::gu_skeleton (nib::kIQ3_S )== nib::kSkelS , 109"kernel table" ); 110 { 111const uint8_t b [6 ]= {1 ,2 ,3 ,4 ,5 ,6 }; 112const uint64_t h = nib::hash_host (b ,6 ); 113const uint64_t want = (uint64_t ) (0x04030201u ^0u )* nib::kHashMul + (uint64_t ) (0x00000605u ^1u )* nib::kHashMul ; 114expect (h == want ,"hash_host" ); 115 } 116 std::printf ("%s (%d failures)\n" ,fails == 0 ?"header OK" :"header FAILED" ,fails ); 117return fails == 0 ?0 :1 ; 118} 119 120// ------------------------------------------------------------------------------------------------ the GPU parity 121 122#define CK (x ) \ 123 do { \ 124 cudaError_t e_ = (x); \ 125 if (e_ != cudaSuccess) { \ 126 std::fprintf(stderr, "%s:%d %s: %s\n", __FILE__, __LINE__, #x, cudaGetErrorString(e_)); \ 127 std::exit(2); \ 128 } \ 129 } while (0) 130 131struct Q81 {// block_q8_1: fp16 d, fp16 s (= d * sum), 32 int8 132uint16_t d ,s ; 133int8_t qs [32 ]; 134}; 135static_assert(sizeof (Q81 )== 36 ,"block_q8_1" ); 136 137constexpr int64_t kEmbd = nib::kNEmbd ,kFf = nib::kNFf ; 138constexpr int kTok = 12 ;// activation rows: T <= 6 for routing plans, 12 for the 0..11-entry plans 139 140// One layer: `ne` GGUF blobs (gate rows | up rows | down rows, as the pack and the host arena hold them) on the host 141// and the device, and their converted slots. 142struct Layer { 143 std::string tag ; 144int layer = -1 ; 145 cpu::NativeFmt f ; 146 nib::LayerVram V ; 147K ::NativeExpertLayout Lr ,Ln ; 148int ne = 0 ; 149 std::vector < uint8_t > host ;// ne x f.bytes 150uint8_t * raw = nullptr ;// device copy of `host` 151uint8_t * slots = nullptr ;// ne x V.slot_bytes (the last one only `hashed` long: nothing past it is readable) 152}; 153 154bool layer_fmt (const strata::GgufModel & m ,int l ,int & gt ,int & dt ) { 155const auto * g = m .find ("blk." + std::to_string (l )+ ".ffn_gate_exps.weight" ); 156const auto * d = m .find ("blk." + std::to_string (l )+ ".ffn_down_exps.weight" ); 157if (g == nullptr || d == nullptr )return false; 158gt = (int )g -> type ; 159dt = (int )d -> type ; 160return true; 161} 162 163// The blobs of experts [0, ne) of layer l. 164bool read_layer (const strata::GgufModel & m ,int l ,int ne ,Layer & Y ) { 165const char * roles [3 ]= {"gate" ,"up" ,"down" }; 166const strata::TensorInfo * t [3 ]= {}; 167size_t sh [3 ]= {}; 168for (int r = 0 ;r < 3 ;++ r )t [r ]= m .find ("blk." + std::to_string (l )+ ".ffn_" + roles [r ]+ "_exps.weight" ,& sh [r ]); 169if (!t [0 ]|| !t [1 ]|| !t [2 ])return false; 170 std::string err ; 171if (!cpu::native_fmt ((int )t [0 ]-> type , (int )t [2 ]-> type ,kEmbd ,kFf ,Y .f ,err )) { 172 std::printf ("layer %d: %s\n" ,l ,err .c_str ()); 173return false; 174 } 175const size_t gu_role = Y .f .up_off ,dn_role = Y .f .bytes - Y .f .down_off ; 176Y .layer = l ; 177Y .ne = ne ; 178Y .host .resize ((size_t )ne * Y .f .bytes ); 179const uint8_t * G = m .shard (sh [0 ]).tensor_data (* t [0 ]); 180const uint8_t * U = m .shard (sh [1 ]).tensor_data (* t [1 ]); 181const uint8_t * D = m .shard (sh [2 ]).tensor_data (* t [2 ]); 182for (int e = 0 ;e < ne ;++ e ) { 183uint8_t * b = Y .host .data ()+ (size_t )e * Y .f .bytes ; 184 std::memcpy (b ,G + (size_t )e * gu_role ,gu_role ); 185 std::memcpy (b + Y .f .up_off ,U + (size_t )e * gu_role ,gu_role ); 186 std::memcpy (b + Y .f .down_off ,D + (size_t )e * dn_role ,dn_role ); 187 } 188return true; 189} 190 191// check (6): nibble::check_gguf over every slot (the start-up check), and nibble::gather_gguf (the prompt path's gather) 192// in groups of 16 and from later first positions, against the blobs byte for byte (and the MMQ tail zeroed). 193// `expect_diff`: the negative control (only the report says so: the counts must then be > 0). 194long long gguf_parity (const Layer & Y ,const unsigned long long * dp ,bool expect_diff ) { 195long long bad_total = 0 ; 196const int ne = Y .ne ; 197unsigned long long * dbad = nullptr ; 198CK (cudaMalloc (& dbad ,8 )); 199CK (cudaMemset (dbad ,0 ,8 )); 200for (int e0 = 0 ;e0 < ne ;e0 += 64 ) { 201const int rc = nib::check_gguf (Y .V ,Y .raw + (size_t )e0 * Y .V .raw_bytes , std::min (64 ,ne - e0 ),dp + e0 ,dbad ,nullptr ); 202if (rc != 0 ) { 203 std::printf ("check_gguf: %s\n" ,cudaGetErrorString ((cudaError_t )rc )); 204 std::exit (2 ); 205 } 206 } 207CK (cudaDeviceSynchronize ()); 208unsigned long long cbad = 0 ; 209CK (cudaMemcpy (& cbad ,dbad ,8 ,cudaMemcpyDeviceToHost )); 210CK (cudaFree (dbad )); 211// the gathers: MMQ's group buffers (16 experts of [gate | up] and of down, each followed by the 4096-byte tail) 212const uint64_t gub = (uint64_t ) nib::kRows * Y .f .gu_row ,db = Y .V .down_bytes ,zero = 4096 ; 213uint8_t * ggu = nullptr ,* gd = nullptr ; 214CK (cudaMalloc (& ggu ,16 * gub + zero )); 215CK (cudaMalloc (& gd ,16 * db + zero )); 216 std::vector < uint8_t > hgu (16 * gub + zero ),hd (16 * db + zero ); 217 std::vector < unsigned long long > hp (ne ); 218CK (cudaMemcpy (hp .data (),dp , (size_t )ne * 8 ,cudaMemcpyDeviceToHost )); 219long long gbad = 0 ,groups = 0 ; 220for (int e0 = 0 ;e0 < ne ;e0 += 16 ) { 221const int first = (e0 /16 ) %4 == 3 ?1 + (e0 /64 ) %15 :0 ;// every 4th group from a later position 222const int n = std::min (16 ,ne - e0 ); 223if (first >=n )continue ; 224const uint8_t * sl [16 ]= {}; 225for (int q = first ;q < n ;++ q )sl [q ]= (const uint8_t * ) (uintptr_t )hp [(size_t ) (e0 + q )]; 226CK (cudaMemset (ggu ,0xA5 ,16 * gub + zero )); 227CK (cudaMemset (gd ,0xA5 ,16 * db + zero )); 228const int rc = nib::gather_gguf (Y .V ,sl ,first ,n ,ggu ,gub ,gd ,db ,zero ,nullptr ); 229if (rc != 0 ) { 230 std::printf ("gather_gguf: %s\n" ,cudaGetErrorString ((cudaError_t )rc )); 231 std::exit (2 ); 232 } 233CK (cudaDeviceSynchronize ()); 234CK (cudaMemcpy (hgu .data (),ggu ,hgu .size (),cudaMemcpyDeviceToHost )); 235CK (cudaMemcpy (hd .data (),gd ,hd .size (),cudaMemcpyDeviceToHost )); 236for (int q = first ;q < n ;++ q ) { 237const uint8_t * raw = Y .host .data ()+ (size_t ) (e0 + q )* Y .f .bytes ; 238gbad += std::memcmp (hgu .data ()+ (size_t )q * gub ,raw ,gub )!= 0 ; 239gbad += std::memcmp (hd .data ()+ (size_t )q * db ,raw + Y .f .down_off ,db )!= 0 ; 240 } 241for (uint64_t i = 0 ;i < zero ;++ i )gbad += hgu [(size_t )n * gub + i ]!= 0 || hd [(size_t )n * db + i ]!= 0 ?1 :0 ; 242++ groups ; 243 } 244CK (cudaFree (ggu )); 245CK (cudaFree (gd )); 246 std::printf (" check_gguf: %llu words differ; gather_gguf (%lld groups, the tail zeroed): %lld matrices or tail bytes differ%s\n" , 247cbad ,groups ,gbad ,expect_diff ?" (NEGATIVE CONTROL: both must be > 0)" :"" ); 248bad_total += (long long )cbad + gbad ;// the negative control fails the run, as (7) does: it must 249return bad_total ; 250} 251 252// Plans the layer, uploads the blobs, transcodes them into slots (checks 1-6). 253long long convert (Layer & Y ,bool ggml_check ) { 254long long bad_total = 0 ; 255 nib::Config c ; 256c .on = true; 257Y .V = nib::plan_layer (Y .layer ,Y .f ,c ); 258Y .Lr = K ::native_expert_layout (Y .f .gu_type ,Y .f .d_type ,kEmbd ,kFf ); 259Y .Ln = K ::native_expert_layout_nib (Y .f .gu_type ,Y .f .d_type ,kEmbd ,kFf ); 260if (!Y .V .on || Y .V .slot_bytes != Y .Ln .bytes || Y .V .down_off != Y .Ln .down_off || Y .Lr .bytes != Y .f .bytes ) { 261 std::printf ("layer %d: plan_layer / native_expert_layout_nib disagree (on %d, slot %llu vs %zu)\n" ,Y .layer , 262 (int )Y .V .on , (unsigned long long )Y .V .slot_bytes ,Y .Ln .bytes ); 263return 1 ; 264 } 265const int ne = Y .ne ; 266const size_t slots_bytes = (size_t ) (ne - 1 )* Y .V .slot_bytes + Y .V .hashed ; 267CK (cudaMalloc (& Y .raw ,Y .host .size ())); 268CK (cudaMemcpy (Y .raw ,Y .host .data (),Y .host .size (),cudaMemcpyHostToDevice )); 269CK (cudaMalloc (& Y .slots ,slots_bytes )); 270CK (cudaMemset (Y .slots ,0xA5 ,slots_bytes )); 271 std::vector < unsigned long long > hp (ne ); 272for (int e = 0 ;e < ne ;++ e )hp [e ]= (unsigned long long ) (Y .slots + (size_t )e * Y .V .slot_bytes ); 273unsigned long long * dp = nullptr ,* dbad = nullptr ,* dhash = nullptr ; 274CK (cudaMalloc (& dp , (size_t )ne * 8 )); 275CK (cudaMalloc (& dbad ,8 )); 276CK (cudaMalloc (& dhash , (size_t )ne * 8 )); 277CK (cudaMemcpy (dp ,hp .data (), (size_t )ne * 8 ,cudaMemcpyHostToDevice )); 278CK (cudaMemset (dbad ,0 ,8 )); 279// (1) the startup fill's batches: 64 blobs at a time, then the down rows behind the codes 280for (int e0 = 0 ;e0 < ne ;e0 += 64 ) { 281const int n = std::min (64 ,ne - e0 ); 282const int rc = nib::transcode (Y .V ,Y .raw + (size_t )e0 * Y .V .raw_bytes ,n ,dp + e0 ,dbad ,nullptr ); 283if (rc != 0 ) { 284 std::printf ("transcode: %s\n" ,cudaGetErrorString ((cudaError_t )rc )); 285 std::exit (2 ); 286 } 287 } 288for (int e = 0 ;e < ne ;++ e ) 289CK (cudaMemcpyAsync (Y .slots + (size_t )e * Y .V .slot_bytes + nib::kDownOff , 290Y .raw + (size_t )e * Y .V .raw_bytes + Y .V .raw_down_off ,Y .V .down_bytes ,cudaMemcpyDeviceToDevice )); 291CK (cudaDeviceSynchronize ()); 292unsigned long long bad = 0 ; 293CK (cudaMemcpy (& bad ,dbad ,8 ,cudaMemcpyDeviceToHost )); 294 std::printf ("%s layer %2d %-7s / down %-6s: %d experts, blob %zu B, slot %llu B (x%.3f); transcode: %llu of %lld items do not round-trip\n" , 295Y .tag .c_str (),Y .layer , nib::fmt_name (Y .f .gu_type ),ggml_type_name ((ggml_type )Y .f .d_type ),ne ,Y .f .bytes , 296 (unsigned long long )Y .V .slot_bytes , (double )Y .V .slot_bytes / (double )Y .f .bytes ,bad , 297 (long long )ne * nib::kRows * nib::kItems ); 298bad_total += (long long )bad ; 299bad_total += gguf_parity (Y ,dp , false); 300// (2) every gate/up byte written: the first 8 blobs again into slots pre-filled with 0x5A 301 { 302const int n8 = std::min (8 ,ne ); 303uint8_t * alt = nullptr ; 304unsigned long long * ap = nullptr ; 305CK (cudaMalloc (& alt , (size_t )n8 * Y .V .slot_bytes )); 306CK (cudaMemset (alt ,0x5A , (size_t )n8 * Y .V .slot_bytes )); 307 std::vector < unsigned long long > ah (n8 ); 308for (int e = 0 ;e < n8 ;++ e )ah [e ]= (unsigned long long ) (alt + (size_t )e * Y .V .slot_bytes ); 309CK (cudaMalloc (& ap , (size_t )n8 * 8 )); 310CK (cudaMemcpy (ap ,ah .data (), (size_t )n8 * 8 ,cudaMemcpyHostToDevice )); 311CK (cudaMemset (dbad ,0 ,8 )); 312if (nib::transcode (Y .V ,Y .raw ,n8 ,ap ,dbad ,nullptr )!= 0 ) std::exit (2 ); 313CK (cudaDeviceSynchronize ()); 314 std::vector < uint8_t > a (nib::kGuBytes ),b (nib::kGuBytes ); 315long long wbad = 0 ; 316for (int e = 0 ;e < n8 ;++ e ) { 317CK (cudaMemcpy (a .data (),Y .slots + (size_t )e * Y .V .slot_bytes , nib::kGuBytes ,cudaMemcpyDeviceToHost )); 318CK (cudaMemcpy (b .data (),alt + (size_t )e * Y .V .slot_bytes , nib::kGuBytes ,cudaMemcpyDeviceToHost )); 319wbad += std::memcmp (a .data (),b .data (), nib::kGuBytes )!= 0 ; 320 } 321 std::printf (" every gate/up byte written (0xA5 vs 0x5A pre-fill, %d slots): %lld differ\n" ,n8 ,wbad ); 322bad_total += wbad ; 323CK (cudaFree (alt )); 324CK (cudaFree (ap )); 325 } 326// (3) the device hash of every slot against the host reference over the slot read back 327const int rc = nib::hash_slots (Y .V ,dp ,ne ,dhash ,nullptr ); 328if (rc != 0 ) { 329 std::printf ("hash_slots: %s\n" ,cudaGetErrorString ((cudaError_t )rc )); 330 std::exit (2 ); 331 } 332 std::vector < unsigned long long > hh (ne ); 333CK (cudaMemcpy (hh .data (),dhash , (size_t )ne * 8 ,cudaMemcpyDeviceToHost )); 334 std::vector < uint8_t > sl (slots_bytes ); 335CK (cudaMemcpy (sl .data (),Y .slots ,slots_bytes ,cudaMemcpyDeviceToHost )); 336 std::atomic < long long > hbad {0 },cbad {0 },dnbad {0 },gbad {0 }; 337 std::atomic < long long > grows {0 }; 338 std::string first_ggml ; 339 std::atomic < int > first_set {0 }; 340const ggml_type_traits * tr = ggml_get_type_traits ((ggml_type )Y .f .gu_type ); 341const unsigned nth = std::max (1u , std::min (16u , std::thread::hardware_concurrency ())); 342 std::vector < std::thread > th ; 343for (unsigned ti = 0 ;ti < nth ;++ ti ) 344th .emplace_back ([& ,ti ]() { 345 std::vector < float > ref ((size_t )kEmbd ),got ((size_t )kEmbd ); 346for (int e = (int )ti ;e < ne ;e += (int )nth ) { 347const uint8_t * s = sl .data ()+ (size_t )e * Y .V .slot_bytes ; 348const uint8_t * raw = Y .host .data ()+ (size_t )e * Y .f .bytes ; 349hbad += nib::hash_host (s ,Y .V .hashed )!= hh [e ]; 350if (e == 0 ) {// the hash sees every byte: one flipped must change it 351 std::vector < uint8_t > t2 (s ,s + Y .V .hashed ); 352t2 [Y .V .hashed - 1 ] ^=1 ; 353hbad += nib::hash_host (t2 .data (),Y .V .hashed )== hh [e ]; 354 } 355dnbad += std::memcmp (s + nib::kDownOff ,raw + Y .V .raw_down_off ,Y .V .down_bytes )!= 0 ; 356for (int64_t r = 0 ;r < nib::kRows ;++ r ) { 357// (4) the host codec 358for (int64_t k = 0 ;k < nib::kItems ;++ k ) { 359uint32_t q [4 ],q2 [4 ]; 360int8_t g [32 ]; 361 std::memcpy (q ,s + nib::code_off (r ,k ),16 ); 362 nib::decode_item (Y .f .gu_type ,q ,g ); 363const bool ok = nib::encode_item (Y .f .gu_type ,g ,q2 ); 364cbad += !ok || std::memcmp (q ,q2 ,16 )!= 0 ; 365 } 366if (!ggml_check )continue ; 367// (5) ggml's dequantizer of the GGUF row against the slot's weights through its expression 368const uint8_t * row = raw + (r < kFf ? (size_t )r * Y .f .gu_row :Y .f .up_off + (size_t ) (r - kFf )* Y .f .gu_row ); 369tr -> to_float (row ,ref .data (),kEmbd ); 370for (int64_t k = 0 ;k < nib::kItems ;++ k ) { 371uint32_t q [4 ]; 372 std::memcpy (q ,s + nib::code_off (r ,k ),16 ); 373int8_t gv [32 ]; 374 nib::decode_item (Y .f .gu_type ,q ,gv ); 375const int sc = s [nib::scale_off (r ,k )]; 376ggml_fp16_t dh ; 377 std::memcpy (& dh ,s + nib::d_off (r ,k /8 ),sizeof dh ); 378const float d = ggml_fp16_to_fp32 (dh ); 379for (int j = 0 ;j < 32 ;++ j ) { 380const float db = Y .f .gu_type == nib::kIQ2_S ?d * (0.5f + ((j < 16 ?sc :sc >> 4 )& 0xf ))* 0.25f 381 :Y .f .gu_type == nib::kIQ3_XXS ?d * (0.5f + sc )* 0.5f 382 :d * sc ; 383const int a = gv [j ]< 0 ?- (int )gv [j ] : (int )gv [j ]; 384float v = db * a ; 385if (gv [j ]< 0 )v = - v ; 386got [(size_t ) (k * 32 + j )]= v ; 387 } 388 } 389++ grows ; 390if (std::memcmp (ref .data (),got .data (),ref .size ()* sizeof (float ))!= 0 ) { 391++ gbad ; 392if (first_set .exchange (1 )== 0 ) { 393size_t cc = 0 ; 394while (cc < ref .size ()&& std::memcmp (& ref [cc ],& got [cc ],4 )== 0 )++ cc ; 395char buf [200 ]; 396 std::snprintf (buf ,sizeof buf ,"expert %d row %lld column %zu: slot %.9g, GGUF %.9g" ,e , 397 (long long )r ,cc , (double )got [cc ], (double )ref [cc ]); 398first_ggml = buf ; 399 } 400 } 401 } 402 } 403 }); 404for (auto & t :th )t .join (); 405 std::printf (" hash_slots vs hash_host: %lld of %d slots differ (+1 flipped-byte check); down rows: %lld of %d slots differ;" 406" host codec: %lld of %lld items differ\n" , 407hbad .load (),ne ,dnbad .load (),ne ,cbad .load (), (long long )ne * nib::kRows * nib::kItems ); 408if (ggml_check ) 409 std::printf (" ggml to_float of the GGUF rows vs the slot's weights: %lld of %lld rows differ%s%s\n" ,gbad .load (), 410grows .load (),first_ggml .empty () ?"" :"; first: " ,first_ggml .c_str ()); 411bad_total += hbad + dnbad + cbad + gbad ; 412CK (cudaFree (dp )); 413CK (cudaFree (dbad )); 414CK (cudaFree (dhash )); 415return bad_total ; 416} 417 418// ---- plans: synthetic top-10 routing and resident_plan_kernel's grouping (groups by first appearance) 419struct Plan { 420int ng = 0 ,ne = 0 ,ntok = 0 ,maxn = 0 ; 421 std::vector < int > gid ,start ,tok ,dst ; 422}; 423 424void make_routing (std::mt19937 & rng ,int NE ,int T ,int share_pct , std::vector < int >& ids ) { 425ids .clear (); 426 std::vector < int > prev ,cur ; 427for (int t = 0 ;t < T ;++ t ) { 428cur .clear (); 429const bool sh = t > 0 && share_pct > 0 ; 430if (sh ) { 431 std::vector < int > p = prev ; 432 std::shuffle (p .begin (),p .end (),rng ); 433cur .assign (p .begin (),p .begin ()+ 10 * share_pct /100 ); 434 } 435while ((int )cur .size ()< 10 ) { 436const int e = (int ) (rng () % (unsigned )NE ); 437if (std::find (cur .begin (),cur .end (),e )!= cur .end ())continue ; 438if (sh && std::find (prev .begin (),prev .end (),e )!= prev .end ())continue ; 439cur .push_back (e ); 440 } 441 std::shuffle (cur .begin (),cur .end (),rng ); 442ids .insert (ids .end (),cur .begin (),cur .end ()); 443prev = cur ; 444 } 445} 446 447Plan build_plan (const std::vector < int >& ids ) { 448const int n = (int )ids .size (); 449Plan p ; 450 std::vector < int > first (n ),cnt ,grp_of (n ,-1 ); 451for (int j = 0 ;j < n ;++ j ) { 452int f = j ; 453for (int i = 0 ;i < j ;++ i ) 454if (ids [i ]== ids [j ]) {f = i ;break ; } 455first [j ]= f ; 456 } 457for (int j = 0 ;j < n ;++ j ) 458if (first [j ]== j ) { 459grp_of [j ]= p .ng ++ ; 460p .gid .push_back (ids [j ]); 461cnt .push_back (0 ); 462 } 463for (int j = 0 ;j < n ;++ j )cnt [grp_of [first [j ]]]++ ; 464p .start .assign (p .ng + 1 ,0 ); 465int acc = 0 ; 466for (int g = 0 ;g < p .ng ;++ g ) { 467p .start [g ]= acc ; 468acc += cnt [g ]; 469p .maxn = std::max (p .maxn ,cnt [g ]); 470 } 471p .start [p .ng ]= acc ; 472p .tok .assign (n ,0 ); 473p .dst .assign (n ,0 ); 474 std::vector < int > fill (p .ng ,0 ); 475for (int j = 0 ;j < n ;++ j ) { 476const int g = grp_of [first [j ]]; 477const int at = p .start [g ]+ fill [g ]++ ; 478p .tok [at ]= j /10 ; 479p .dst [at ]= j ; 480 } 481p .ne = n ; 482p .ntok = n /10 ; 483return p ; 484} 485 486// one group of T entries (G = 1): an expert every token of the window routes to 487Plan single_group (std::mt19937 & rng ,int NE ,int T ) { 488Plan p ; 489p .ntok = T ; 490p .ng = 1 ; 491p .gid .push_back ((int ) (rng () % (unsigned )NE )); 492p .start = {0 ,T }; 493for (int t = 0 ;t < T ;++ t ) { 494p .tok .push_back (t ); 495p .dst .push_back (T - 1 - t ); 496 } 497p .ne = T ; 498p .maxn = T ; 499return p ; 500} 501 502// groups of 0..11 entries (more than one GRP_NC pass, empty groups), 12 tokens, distinct tokens within a group, 503// destination rows in any order 504Plan synthetic_plan (std::mt19937 & rng ,int NE ) { 505Plan p ; 506p .ntok = kTok ; 507 std::vector < int > ids (NE ); 508for (int i = 0 ;i < NE ;++ i )ids [i ]= i ; 509 std::shuffle (ids .begin (),ids .end (),rng ); 510const int sizes []= {3 ,0 ,11 ,1 ,5 ,8 ,0 ,2 ,4 ,9 ,6 ,7 ,10 ,1 }; 511int acc = 0 ; 512for (int g = 0 ;g < (int ) (sizeof sizes /sizeof sizes [0 ]);++ g ) { 513p .gid .push_back (ids [(size_t )g %ids .size ()]); 514p .start .push_back (acc ); 515 std::vector < int > toks (kTok ); 516for (int i = 0 ;i < kTok ;++ i )toks [i ]= i ; 517 std::shuffle (toks .begin (),toks .end (),rng ); 518 std::sort (toks .begin (),toks .begin ()+ sizes [g ]); 519for (int i = 0 ;i < sizes [g ];++ i ) { 520p .tok .push_back (toks [i ]); 521p .dst .push_back (acc + i ); 522 } 523acc += sizes [g ]; 524p .maxn = std::max (p .maxn ,sizes [g ]); 525 } 526p .start .push_back (acc ); 527p .ng = (int )p .gid .size (); 528p .ne = acc ; 529 std::vector < int > perm (acc ); 530for (int i = 0 ;i < acc ;++ i )perm [i ]= i ; 531 std::shuffle (perm .begin (),perm .end (),rng ); 532for (int i = 0 ;i < acc ;++ i )p .dst [i ]= perm [i ]; 533return p ; 534} 535 536std::vector < Q81 > make_x (std::mt19937 & rng ) { 537 std::vector < Q81 > x ((size_t )kTok * (kEmbd /32 )); 538for (size_t i = 0 ;i < x .size ();++ i ) { 539Q81 & b = x [i ]; 540const int tok = (int ) (i / (kEmbd /32 )); 541const float d = 0.002f + 0.03f * (float ) (rng () %1000 ) /1000.0f ; 542int sum = 0 ; 543for (int j = 0 ;j < 32 ;++ j ) { 544int q = (int ) (rng () %255 )- 127 ; 545if (tok == 1 )q = 127 ;// the sum of x at its extremes (+-4064) 546if (tok == 2 )q = -127 ; 547if (tok == 3 && (i % (kEmbd /32 ))< 8 )q = (j & 1 ) ?127 :-127 ; 548b .qs [j ]= (int8_t )q ; 549sum += q ; 550 } 551b .d = ggml_fp32_to_fp16 (d ); 552b .s = ggml_fp32_to_fp16 (d * (float )sum ); 553 } 554return x ; 555} 556 557struct Dev { 558unsigned long long * ptr = nullptr ; 559int32_t * start = nullptr ,* ng = nullptr ,* tok = nullptr ,* dst = nullptr ; 560}; 561Dev upload (const Plan & p ,const Layer & Y ,bool conv ) { 562Dev d ; 563 std::vector < unsigned long long > hp (std::max (1 ,p .ng )); 564for (int g = 0 ;g < p .ng ;++ g ) 565hp [g ]= conv ? (unsigned long long ) (Y .slots + (size_t )p .gid [g ]* Y .V .slot_bytes ) 566 : (unsigned long long ) (Y .raw + (size_t )p .gid [g ]* Y .f .bytes ); 567CK (cudaMalloc (& d .ptr , (size_t ) std::max (1 ,p .ng )* 8 )); 568CK (cudaMalloc (& d .start , (size_t ) (p .ng + 1 )* 4 )); 569CK (cudaMalloc (& d .ng ,4 )); 570CK (cudaMalloc (& d .tok , (size_t ) std::max (1 ,p .ne )* 4 )); 571CK (cudaMalloc (& d .dst , (size_t ) std::max (1 ,p .ne )* 4 )); 572CK (cudaMemcpy (d .ptr ,hp .data (),hp .size ()* 8 ,cudaMemcpyHostToDevice )); 573CK (cudaMemcpy (d .start ,p .start .data (), (size_t ) (p .ng + 1 )* 4 ,cudaMemcpyHostToDevice )); 574CK (cudaMemcpy (d .ng ,& p .ng ,4 ,cudaMemcpyHostToDevice )); 575if (p .ne ) { 576CK (cudaMemcpy (d .tok ,p .tok .data (), (size_t )p .ne * 4 ,cudaMemcpyHostToDevice )); 577CK (cudaMemcpy (d .dst ,p .dst .data (), (size_t )p .ne * 4 ,cudaMemcpyHostToDevice )); 578 } 579return d ; 580} 581void release (Dev & d ) { 582CK (cudaFree (d .ptr )); 583CK (cudaFree (d .start )); 584CK (cudaFree (d .ng )); 585CK (cudaFree (d .tok )); 586CK (cudaFree (d .dst )); 587} 588 589struct Outs { 590 std::vector < uint8_t > gate ,up ,h ,hq ,out ; 591}; 592// one native_expert_grouped call; scratch and out pre-filled with `fill` so an unwritten value shows 593Outs run (const Layer & Y ,const Plan & p ,bool conv ,const void * dx ,void * scr ,float * dout ,int64_t gy ,int mode , 594uint8_t fill ) { 595// the window's capacity, as verify sizes it: T x 10 groups and entries (the blocks past the plan's groups idle) 596const int64_t cap_e = std::max < int64_t > ((int64_t )p .ntok * 10 , std::max (p .ne ,p .ng )),cap_g = cap_e ; 597Dev d = upload (p ,Y ,conv ); 598CK (cudaMemset (scr ,fill ,K ::native_expert_scratch_bytes (cap_e ,kFf ))); 599CK (cudaMemset (dout ,fill , (size_t )cap_e * kEmbd * 4 )); 600K ::native_expert_set_mode (mode ,0 ); 601K ::native_expert_grouped (conv ?Y .Ln :Y .Lr ,d .ptr ,d .start ,d .ng ,d .dst ,d .tok ,cap_g ,cap_e ,dx ,scr ,dout ,nullptr ,gy ); 602K ::native_expert_set_mode (-1 ,0 ); 603CK (cudaGetLastError ()); 604CK (cudaDeviceSynchronize ()); 605const size_t f = (size_t )cap_e * kFf * 4 ,fa = (f + 255 )& ~(size_t )255 ; 606Outs o ; 607o .gate .resize ((size_t )p .ne * kFf * 4 ); 608o .up .resize (o .gate .size ()); 609o .h .resize (o .gate .size ()); 610o .hq .resize ((size_t )p .ne * (kFf /32 )* 36 ); 611o .out .resize ((size_t )p .ne * kEmbd * 4 ); 612const uint8_t * s = (const uint8_t * )scr ; 613if (p .ne ) { 614CK (cudaMemcpy (o .gate .data (),s ,o .gate .size (),cudaMemcpyDeviceToHost )); 615CK (cudaMemcpy (o .up .data (),s + fa ,o .up .size (),cudaMemcpyDeviceToHost )); 616CK (cudaMemcpy (o .h .data (),s + 2 * fa ,o .h .size (),cudaMemcpyDeviceToHost )); 617CK (cudaMemcpy (o .hq .data (),s + 3 * fa ,o .hq .size (),cudaMemcpyDeviceToHost )); 618 std::vector < uint8_t > all ((size_t )cap_e * kEmbd * 4 ); 619CK (cudaMemcpy (all .data (),dout ,all .size (),cudaMemcpyDeviceToHost )); 620for (int e = 0 ;e < p .ne ;++ e ) 621 std::memcpy (o .out .data ()+ (size_t )e * kEmbd * 4 ,all .data ()+ (size_t )p .dst [e ]* kEmbd * 4 ,kEmbd * 4 ); 622 } 623release (d ); 624return o ; 625} 626 627long long diff_rows (const std::vector < uint8_t >& a ,const std::vector < uint8_t >& b ,size_t row ) { 628long long n = 0 ; 629for (size_t i = 0 ;i + row <=a .size ();i += row )n += std::memcmp (a .data ()+ i ,b .data ()+ i ,row )!= 0 ; 630return n ; 631} 632 633// check (7): every plan, both grid strides, every kernel choice, both layouts, v1 off / on, against the GGUF blobs 634// through the production kernels 635long long grouped_parity (const Layer & Y , std::mt19937 & rng ,int plans ,const void * dx ,void * scr ,float * dout ) { 636struct Case { 637Plan p ; 638int T ; 639 }; 640 std::vector < Case > cases ; 641for (int T = 1 ;T <=6 ;++ T ) { 642for (int share : {0 ,50 }) 643for (int i = 0 ;i < plans ;++ i ) { 644 std::vector < int > ids ; 645make_routing (rng ,Y .ne ,T ,share ,ids ); 646cases .push_back ({build_plan (ids ),T }); 647 } 648cases .push_back ({single_group (rng ,Y .ne ,T ),T }); 649 } 650for (int i = 0 ;i < 4 ;++ i )cases .push_back ({synthetic_plan (rng ,Y .ne ),kTok }); 651int hist [13 ]= {}; 652for (const Case & cs :cases ) 653for (int g = 0 ;g < cs .p .ng ;++ g )hist [std::min (12 ,cs .p .start [g + 1 ]- cs .p .start [g ])]++ ; 654struct Var { 655int v ,mode ; 656bool v1 ; 657const char * name ; 658 }; 659// mode -1: the card's default layout (a GP100: mode 8 - its reference gate/up kernel writes hq, not gate / up); 660// mode 0: the CUDA layout 661const Var vars []= { {-1 ,-1 , false,"default, card" }, {0 ,-1 , false,"S, card" }, {1 ,-1 , false,"P, card" }, 662 {-1 ,-1 , true,"default, card, V1" }, {-1 ,0 , false,"default, mode 0" }, 663 {0 ,0 , false,"S, mode 0" }, {1 ,0 , false,"P, mode 0" }, {-1 ,0 , true,"default, mode 0, V1" }, 664// STRATA_NIB_GU_PROTO (nib_gu_proto.cuh): the staged-once kernel, id 31 665 {31 ,-1 , false,"gu-proto 31, card" }, {31 ,0 , false,"gu-proto 31, mode 0" }, 666 {31 ,0 , true,"gu-proto 31, mode 0, V1" } }; 667constexpr int NV = (int ) (sizeof vars /sizeof vars [0 ]); 668long long rows [NV ]= {},bad [NV ][5 ]= {},total = 0 ; 669for (const Case & cs :cases ) 670for (int64_t gy : { (int64_t )0 , (int64_t )4 }) { 671Outs ref [2 ][2 ];// [mode 0][v1] 672bool have [2 ][2 ]= {}; 673for (int vi = 0 ;vi < NV ;++ vi ) { 674const int m0 = vars [vi ].mode == 0 ?1 :0 ,r1 = vars [vi ].v1 ?1 :0 ; 675K ::native_grouped_set_v1 (vars [vi ].v1 ); 676if (!have [m0 ][r1 ]) { 677K ::native_expert_nib_set_variant (-1 ); 678ref [m0 ][r1 ]= run (Y ,cs .p , false,dx ,scr ,dout ,gy ,vars [vi ].mode ,0xFF ); 679have [m0 ][r1 ]= true; 680 } 681K ::native_expert_nib_set_variant (vars [vi ].v ); 682const Outs o = run (Y ,cs .p , true,dx ,scr ,dout ,gy ,vars [vi ].mode ,0x00 ); 683rows [vi ]+= cs .p .ne ; 684// gate / up: written by both arms in the CUDA layout, and by every arm of a striding call (gy 4: mode 0) 685const bool gu = vars [vi ].mode == 0 || gy == 4 ; 686if (gu ) { 687bad [vi ][0 ]+= diff_rows (ref [m0 ][r1 ].gate ,o .gate ,kFf * 4 ); 688bad [vi ][1 ]+= diff_rows (ref [m0 ][r1 ].up ,o .up ,kFf * 4 ); 689 } 690if (vars [vi ].v1 && gu )bad [vi ][2 ]+= diff_rows (ref [m0 ][r1 ].h ,o .h ,kFf * 4 ); 691bad [vi ][3 ]+= diff_rows (ref [m0 ][r1 ].hq ,o .hq , (kFf /32 )* 36 ); 692bad [vi ][4 ]+= diff_rows (ref [m0 ][r1 ].out ,o .out ,kEmbd * 4 ); 693 } 694 } 695K ::native_expert_nib_set_variant (-1 ); 696K ::native_grouped_set_v1 (false); 697 std::printf (" plans: %zu (T 1..6 x sharing 0/50%% x %d, G=1 per T, 4 of 0..11 entries); groups by entries:" ,cases .size (), 698plans ); 699for (int n = 0 ;n <=12 ;++ n ) std::printf (" %d:%d" ,n ,hist [n ]); 700 std::printf ("\n" ); 701for (int vi = 0 ;vi < NV ;++ vi ) { 702const long long b = bad [vi ][0 ]+ bad [vi ][1 ]+ bad [vi ][2 ]+ bad [vi ][3 ]+ bad [vi ][4 ]; 703 std::printf (" native_expert_grouped %-20s: %6lld entries x 2 strides, rows differing: gate %lld, up %lld, h %s, hq %lld, out %lld\n" , 704vars [vi ].name ,rows [vi ],bad [vi ][0 ],bad [vi ][1 ], 705vars [vi ].v1 ? std::to_string (bad [vi ][2 ]).c_str () :"-" ,bad [vi ][3 ],bad [vi ][4 ]); 706total += b ; 707 } 708return total ; 709} 710 711// --synthetic: random gate/up blocks, d cycling through the fp16 extremes; the coverage of each field is counted 712long long synthesize (Layer & Y , std::mt19937 & rng ) { 713static const uint16_t kD []= {0x0001 ,0x8001 ,0x7BFF ,0xFBFF ,0x3C00 ,0xBC00 ,0x0400 ,0x1A00 ,0x2400 }; 714const int gt = Y .f .gu_type ; 715const size_t bb = gt == nib::kIQ2_S ?82 :gt == nib::kIQ3_XXS ?98 :110 ;// block_iq2_s / iq3_xxs / iq3_s 716const size_t nblk = (size_t ) nib::kRows * nib::kSuper ; 717 std::set < int > grid ,sign ,scale ,dset ; 718for (int e = 0 ;e < Y .ne ;++ e ) { 719uint8_t * b = Y .host .data ()+ (size_t )e * Y .f .bytes ; 720for (size_t i = 0 ;i < 2 * Y .f .up_off ;++ i )b [i ]= (uint8_t )rng (); 721for (size_t k = 0 ;k < nblk ;++ k ) { 722uint8_t * blk = b + k * bb ; 723const uint16_t d = kD [((size_t )e * nblk + k ) % (sizeof kD /sizeof kD [0 ])]; 724 std::memcpy (blk ,& d ,2 ); 725dset .insert (d ); 726const uint8_t * qs = blk + 2 ; 727for (int ib = 0 ;ib < 8 ;++ ib ) { 728if (gt == nib::kIQ2_S ) { 729const uint8_t * qh = blk + 66 ; 730const uint8_t * sc = blk + 74 ; 731for (int l = 0 ;l < 4 ;++ l ) { 732grid .insert (qs [4 * ib + l ] | ((qh [ib ] << (8 - 2 * l ))& 0x300 )); 733sign .insert (qs [32 + 4 * ib + l ]); 734 } 735scale .insert (sc [ib ]& 15 ); 736scale .insert (sc [ib ] >>4 ); 737 }else if (gt == nib::kIQ3_XXS ) { 738uint32_t aux ; 739 std::memcpy (& aux ,blk + 66 + 4 * ib ,4 ); 740for (int l = 0 ;l < 8 ;++ l )grid .insert (qs [8 * ib + l ]); 741for (int l = 0 ;l < 4 ;++ l )sign .insert ((int ) ((aux >> (7 * l ))& 127 )); 742scale .insert ((int ) (aux >>28 )); 743 }else { 744const uint8_t qh = blk [66 + ib ]; 745const uint8_t * sg = blk + 74 ; 746const uint8_t * sc = blk + 106 ; 747for (int l = 0 ;l < 4 ;++ l ) { 748grid .insert (qs [8 * ib + 2 * l ] | ((qh << (8 - 2 * l ))& 256 )); 749grid .insert (qs [8 * ib + 2 * l + 1 ] | ((qh << (7 - 2 * l ))& 256 )); 750sign .insert (sg [4 * ib + l ]); 751 } 752scale .insert ((sc [ib /2 ] >> (4 * (ib & 1 )))& 15 ); 753 } 754 } 755 } 756 } 757const size_t want_grid = gt == nib::kIQ2_S ?1024 :gt == nib::kIQ3_XXS ?256 :512 ; 758const size_t want_sign = gt == nib::kIQ3_XXS ?128 :256 ; 759const bool ok = grid .size ()== want_grid && sign .size ()== want_sign && scale .size ()== 16 && 760dset .size ()== sizeof kD /sizeof kD [0 ]; 761 std::printf ("synthetic %-7s: %d experts, coverage: grid indices %zu/%zu, sign %s %zu/%zu, scale nibbles %zu/16, d values %zu/%zu" 762" (+-min subnormal, +-65504, +-1, min normal, 2 ordinary) %s\n" , 763 nib::fmt_name (gt ),Y .ne ,grid .size (),want_grid ,gt == nib::kIQ3_XXS ?"indices" :"bytes" ,sign .size (), 764want_sign ,scale .size (),dset .size (),sizeof kD /sizeof kD [0 ],ok ?"complete" :"INCOMPLETE" ); 765return ok ?0 :1 ; 766} 767 768std::vector < int > split_ints (const std::string & s ) { 769 std::vector < int > v ; 770size_t p = 0 ; 771while (p < s .size ()) { 772v .push_back (std::atoi (s .c_str ()+ p )); 773p = s .find (',' ,p ); 774if (p == std::string::npos )break ; 775++ p ; 776 } 777return v ; 778} 779 780}// namespace 781 782int main (int argc ,char ** argv ) { 783setvbuf (stdout ,nullptr ,_IONBF ,0 ); 784if (argc == 2 && std::strcmp (argv [1 ],"--header" )== 0 )return header_check (); 785 std::vector < std::string > shards ; 786int per_fmt = 2 ,NE = 512 ,plans = 8 ,syn = 64 ; 787bool ggml_check = true,negative = false,syn_only = false; 788 std::vector < int > only ; 789for (int i = 1 ;i < argc ;++ i ) { 790const std::string a = argv [i ]; 791auto next = [& ]()-> const char * { 792if (i + 1 >=argc ) { 793 std::fprintf (stderr ,"%s needs a value\n" ,a .c_str ()); 794 std::exit (2 ); 795 } 796return argv [++ i ]; 797 }; 798if (a == "--layers-per-fmt" )per_fmt = std::atoi (next ()); 799else if (a == "--layers" )only = split_ints (next ()); 800else if (a == "--ne" )NE = std::atoi (next ()); 801else if (a == "--plans" )plans = std::atoi (next ()); 802else if (a == "--synthetic" )syn = std::atoi (next ()); 803else if (a == "--no-ggml" )ggml_check = false; 804else if (a == "--negative" )negative = true; 805else if (a == "--synthetic-only" )syn_only = true; 806else if (a .size ()> 5 && a .substr (a .size ()- 5 )== ".gguf" )shards .push_back (a ); 807else { 808 std::fprintf (stderr , 809"usage: iq_nibble_parity --header\n" 810" iq_nibble_parity <shard.gguf> [<shard.gguf> ...] [--layers-per-fmt 2] [--layers 1,17] [--ne 512]\n" 811" [--plans 8] [--synthetic 64] [--no-ggml] [--negative]\n" 812" iq_nibble_parity --synthetic-only [--synthetic 64] [--plans 8] [--no-ggml]\n" ); 813return 2 ; 814 } 815 } 816if ((shards .empty ()&& !syn_only )|| NE < 16 || NE > 512 ) { 817 std::fprintf (stderr ,"iq_nibble_parity: give at least one model shard (.gguf); --ne 16..512\n" ); 818return 2 ; 819 } 820CK (cudaSetDevice (0 )); 821cudaDeviceProp prop {}; 822CK (cudaGetDeviceProperties (& prop ,0 )); 823char bus [64 ]= {}; 824CK (cudaDeviceGetPCIBusId (bus ,sizeof bus ,0 )); 825 std::printf ("device 0: %s, bus %s, cc %d.%d, %d SMs\n" ,prop .name ,bus ,prop .major ,prop .minor ,prop .multiProcessorCount ); 826if (prop .major != 6 || prop .minor != 0 ) { 827 std::fprintf (stderr ,"iq_nibble_parity: the 4-bit kernels are the sm_60 build's; this GPU is cc %d.%d (skipped)\n" , 828prop .major ,prop .minor ); 829return 77 ; 830 } 831if (!STRATA_EXPERT_NIBBLE_BUILT || nib::prepare (nullptr )!= 0 ) { 832 std::fprintf (stderr ,"iq_nibble_parity: no 4-bit kernels in this build, or the GGUF codebooks are not unique\n" ); 833return 2 ; 834 } 835 std::mt19937 rng (20261019 ); 836void * scr = nullptr ; 837float * dout = nullptr ; 838void * dx = nullptr ; 839const int64_t capmax = (int64_t )kTok * 10 ; 840CK (cudaMalloc (& scr ,K ::native_expert_scratch_bytes (capmax ,kFf ))); 841CK (cudaMalloc ((void ** )& dout , (size_t )capmax * kEmbd * 4 )); 842const std::vector < Q81 > hx = make_x (rng ); 843CK (cudaMalloc (& dx ,hx .size ()* sizeof (Q81 ))); 844CK (cudaMemcpy (dx ,hx .data (),hx .size ()* sizeof (Q81 ),cudaMemcpyHostToDevice )); 845 846if (syn_only ) {// no model: every gate/up format with each down type, random experts 847long long total_s = 0 ; 848int done = 0 ; 849for (const int gt : {nib::kIQ2_S , nib::kIQ3_XXS , nib::kIQ3_S }) 850for (const int dt : {20 ,42 }) {// the packs' down types: IQ4_NL, Q2_0 851Layer S ; 852 std::string err ; 853if (!cpu::native_fmt (gt ,dt ,kEmbd ,kFf ,S .f ,err )) { 854 std::printf ("%s / down type %d: %s\n" , nib::fmt_name (gt ),dt ,err .c_str ()); 855++ total_s ; 856continue ; 857 } 858S .tag = "syn" ; 859S .layer = 0 ; 860S .ne = std::max (16 , std::min (syn ,NE )); 861S .host .resize ((size_t )S .ne * S .f .bytes ); 862for (auto & b :S .host )b = (uint8_t )rng (); 863// block_iq4_nl and block_q2_0 are 18 bytes, the fp16 scale first: an ordinary scale in every block of the down rows 864for (int e = 0 ;e < S .ne ;++ e ) 865for (size_t o = S .f .down_off ;o + 18 <=S .f .bytes ;o += 18 ) { 866const uint16_t sc = (uint16_t ) ((9u <<10 ) | (rng ()& 0x3FFu )); 867 std::memcpy (S .host .data ()+ (size_t )e * S .f .bytes + o ,& sc ,2 ); 868 } 869long long sb = synthesize (S ,rng ); 870sb += convert (S ,ggml_check ); 871sb += grouped_parity (S ,rng ,plans ,dx ,scr ,dout ); 872total_s += sb ; 873++ done ; 874CK (cudaFree (S .raw )); 875CK (cudaFree (S .slots )); 876 } 877 std::printf ("\n%s: %d synthetic format pairs, %lld differences\n" ,total_s == 0 && done == 6 ?"PASS" :"FAIL" ,done ,total_s ); 878return total_s == 0 && done == 6 ?0 :1 ; 879 } 880long long total = 0 ; 881int layers_done = 0 ; 882 std::vector < int > syn_done ; 883for (size_t si = 0 ;si < shards .size ();++ si ) { 884 std::unique_ptr < strata::GgufModel > model ; 885try { 886model = std::make_unique < strata::GgufModel > (strata::GgufModel ::open (shards [si ])); 887 }catch (const std::exception & ex ) { 888 std::fprintf (stderr ,"iq_nibble_parity: %s\n" ,ex .what ()); 889return 2 ; 890 } 891const std::string tag (1 , (char ) ('A' + si )); 892 std::printf ("\n#### model %s: %s (%zu shards)\n" ,tag .c_str (),shards [si ].c_str (),model -> size ()); 893 std::vector < int > pick ; 894int count [64 ]= {}; 895for (int l = 0 ;l < 256 ;++ l ) { 896int gt = -1 ,dt = -1 ; 897if (!layer_fmt (* model ,l ,gt ,dt ))break ; 898if (!nib::fmt_built (gt ))continue ; 899const bool want = only .empty () ?count [gt ]++ < per_fmt : std::find (only .begin (),only .end (),l )!= only .end (); 900if (want )pick .push_back (l ); 901 } 902for (int l :pick ) { 903Layer Y ; 904Y .tag = tag ; 905if (!read_layer (* model ,l ,NE ,Y )) { 906 std::printf ("layer %d: cannot read its experts\n" ,l ); 907++ total ; 908continue ; 909 } 910long long b = convert (Y ,ggml_check ); 911if (negative ) {// the control: one code byte changed per slot (item 3 of row 5), which (6) must see 912for (int e = 0 ;e < Y .ne ;++ e ) { 913uint8_t * at = Y .slots + (size_t )e * Y .V .slot_bytes + nib::code_off (5 ,3 ); 914uint8_t v = 0 ; 915CK (cudaMemcpy (& v ,at ,1 ,cudaMemcpyDeviceToHost )); 916v ^=0x11 ; 917CK (cudaMemcpy (at ,& v ,1 ,cudaMemcpyHostToDevice )); 918 } 919 std::printf (" NEGATIVE CONTROL: one code byte changed per slot - the rows below must differ\n" ); 920 std::vector < unsigned long long > hp (Y .ne ); 921for (int e = 0 ;e < Y .ne ;++ e )hp [e ]= (unsigned long long ) (Y .slots + (size_t )e * Y .V .slot_bytes ); 922unsigned long long * dp = nullptr ; 923CK (cudaMalloc (& dp , (size_t )Y .ne * 8 )); 924CK (cudaMemcpy (dp ,hp .data (), (size_t )Y .ne * 8 ,cudaMemcpyHostToDevice )); 925b += gguf_parity (Y ,dp , true); 926CK (cudaFree (dp )); 927 } 928b += grouped_parity (Y ,rng ,plans ,dx ,scr ,dout ); 929total += b ; 930++ layers_done ; 931// the synthetic experts of this format, once: this layer's blobs with random gate/up blocks 932if (syn > 0 && std::find (syn_done .begin (),syn_done .end (),Y .f .gu_type )== syn_done .end ()&& !negative ) { 933syn_done .push_back (Y .f .gu_type ); 934Layer S ; 935S .tag = "syn" ; 936S .layer = Y .layer ; 937S .f = Y .f ; 938S .ne = std::min (syn ,Y .ne ); 939S .host .assign (Y .host .begin (),Y .host .begin ()+ (ptrdiff_t ) ((size_t )S .ne * Y .f .bytes )); 940long long sb = synthesize (S ,rng ); 941sb += convert (S ,ggml_check ); 942sb += grouped_parity (S ,rng , std::max (1 ,plans /2 ),dx ,scr ,dout ); 943total += sb ; 944CK (cudaFree (S .raw )); 945CK (cudaFree (S .slots )); 946 } 947CK (cudaFree (Y .raw )); 948CK (cudaFree (Y .slots )); 949 } 950 } 951 std::printf ("\n%s: %d layers (+ %zu synthetic formats), %lld differences\n" ,total == 0 ?"PASS" :"FAIL" ,layers_done , 952syn_done .size (),total ); 953return total == 0 ?0 :1 ; 954}