okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a8a51b280
main
1// src/core/gguf_expert_source.cpp - see the header. Plain C++, no device code. 2#include "strata/core/gguf_expert_source.hpp" 3#include "strata/kernels/cpu/expert_layout.hpp" 4#include "b60_layout_state.hpp" 5 6#include <algorithm> 7#include <atomic> 8#include <cstring> 9#include <utility> 10#include <fcntl.h> 11#include <unistd.h> 12#include <dpct/dpct.hpp> 13#include <sycl/sycl.hpp> 14#include <thread> 15#include <atomic> 16#include <algorithm> 17#include <utility> 18#include <stdexcept> 19 20namespace strata::core { 21 22namespace { 23constexpr size_t kRing = 512 ;// blobs alive at once: the prompt path holds a layer's worth of streamed experts 24} 25 26GgufExpertSource ::~GgufExpertSource () {close (); } 27 28void GgufExpertSource ::close () { 29for (uint8_t * c :mirror_chunks_ )if (c ) sycl::free (c , dpct::get_in_order_queue ()); 30mirror_chunks_ .clear (); 31mirror_bytes_ = 0 ;mirror_ptr_ .clear ();layer_first_ .clear (); 32for (int fd :fds_ )if (fd >=0 ) ::close (fd ); 33fds_ .clear ();names_ .clear ();layer_fd_ .clear ();ring_ .clear ();ring_key_ .clear ();where_ .clear (); 34ring_next_ = 0 ; 35} 36 37bool GgufExpertSource ::open (const std::string & shard1 ,int64_t n_layers ,int64_t n_expert , std::string & err ) { 38close (); 39const auto & lay = strata::kernels::cpu::expert_layout (); 40if (!lay .native || lay .gguf_off .size ()< (size_t ) (3 * n_layers )) { 41err = "--stream-experts needs a native (IQ) pack whose native_experts.txt carries the GGUF tensor offsets" ; 42return false; 43 } 44for (int64_t l = 0 ;l < n_layers ;++ l ) 45for (int r = 0 ;r < 3 ;++ r ) 46if (lay .gguf_off [(size_t ) (3 * l + r )]== 0 ) { 47err = "--stream-experts: layer " + std::to_string (l )+ " has no GGUF offset for its experts" ; 48return false; 49 } 50shard_ = shard1 ; 51const size_t cut = shard1 .find_last_of ("/\\" ); 52dir_ = cut == std::string::npos ? std::string () :shard1 .substr (0 ,cut + 1 ); 53n_layers_ = n_layers ; 54n_expert_ = n_expert ; 55layer_fd_ .assign ((size_t ) (3 * n_layers ),-1 ); 56for (int64_t l = 0 ;l < n_layers ;++ l ) 57for (int r = 0 ;r < 3 ;++ r ) 58if (fd_of (l ,r ,err )< 0 ) {close ();return false; } 59ring_ .resize (kRing ); 60for (auto & b :ring_ )b .resize ((size_t )lay .max_blob ); 61ring_key_ .assign (kRing ,-1 ); 62return true; 63} 64 65// The file of role `role` (0 gate, 1 up, 2 down) of `layer`. ExpertLayout::gguf_file is per layer AND role 66// (`3 * layer + role`) since upstream 0.1.31; indexing it by layer alone read a shard-2 layer from shard 1 (Swift 1.5, 67// whose layers 13-47 are in shard 2: garbage IQ1_M scales, NaN logits - 2026-10-01). 68int GgufExpertSource ::fd_of (int64_t layer ,int role , std::string & err ) { 69const size_t i = (size_t ) (3 * layer + role ); 70if (layer_fd_ [i ] >=0 )return fds_ [(size_t )layer_fd_ [i ]]; 71const auto & lay = strata::kernels::cpu::expert_layout (); 72 std::string name = shard_ ; 73if (lay .gguf_file .size ()> i && !lay .gguf_file [i ].empty ())name = dir_ + lay .gguf_file [i ]; 74for (size_t k = 0 ;k < names_ .size ();++ k ) 75if (names_ [k ]== name ) {layer_fd_ [i ]= (int )k ;return fds_ [k ]; } 76const int fd = ::open (name .c_str (),O_RDONLY |O_CLOEXEC ); 77if (fd < 0 ) {err = "--stream-experts: cannot open " + name ;return -1 ; } 78names_ .push_back (name ); 79fds_ .push_back (fd ); 80layer_fd_ [i ]= (int )fds_ .size ()- 1 ; 81return fd ; 82} 83 84const uint8_t * GgufExpertSource ::blob (int64_t layer ,int64_t expert ) { 85if (layer < 0 || layer >=n_layers_ || expert < 0 || expert >=n_expert_ || ring_ .empty ())return nullptr ; 86if (!mirror_ptr_ .empty ()) { 87const uint8_t * p = mirror_ptr_ [(size_t ) (layer * n_expert_ + expert )]; 88if (p != nullptr )return p ; 89 } 90const auto & lay = strata::kernels::cpu::expert_layout (); 91const auto & fm = lay .fmt [(size_t )layer ]; 92const uint64_t blob = lay .bytes [(size_t )layer ]; 93// the arena loader's gather, for one expert: [gate | up | down] from the three tensors 94const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,blob - fm .down_off }; 95const uint64_t at [3 ]= {0 ,fm .up_off ,fm .down_off }; 96const int64_t key = ((int64_t )layer <<20 ) |expert ; 97size_t slot ; 98 { 99 std::lock_guard < std::mutex > lk (mu_ ); 100auto it = where_ .find (key ); 101if (it != where_ .end ()) {++ reads_ ;return ring_ [it -> second ].data (); }// still resident 102slot = ring_next_ ; 103ring_next_ = (ring_next_ + 1 ) %ring_ .size (); 104if (ring_key_ [slot ] >=0 )where_ .erase (ring_key_ [slot ]); 105ring_key_ [slot ]= key ; 106where_ [key ]= slot ; 107 } 108 std::vector < uint8_t >& buf = ring_ [slot ]; 109for (int r = 0 ;r < 3 ;++ r ) { 110const int fd = fds_ [(size_t )layer_fd_ [(size_t ) (3 * layer + r )]]; 111const uint64_t src = lay .gguf_off [(size_t ) (3 * layer + r )]+ per [r ]* (uint64_t )expert ; 112uint64_t done = 0 ; 113while (done < per [r ]) { 114const ssize_t n = ::pread (fd ,buf .data ()+ at [r ]+ done , (size_t ) (per [r ]- done ), (off_t ) (src + done )); 115if (n <=0 ) { std::lock_guard < std::mutex > lk (mu_ );where_ .erase (key );ring_key_ [slot ]= -1 ;return nullptr ; } 116done += (uint64_t )n ; 117 } 118 } 119++ reads_ ; 120return buf .data (); 121} 122 123int64_t GgufExpertSource ::mirror (const std::vector < std::pair < int64_t ,int64_t >>& pairs ,uint64_t cap ,int threads , 124 std::string & err ) { 125err .clear (); 126const auto & lay = strata::kernels::cpu::expert_layout (); 127 std::vector < std::pair < int64_t ,int64_t >> take ; 128uint64_t total = 0 ; 129for (const auto & [l ,e ] :pairs ) { 130if (l < 0 || l >=n_layers_ || e < 0 || e >=n_expert_ )continue ; 131const uint64_t b = (lay .bytes [(size_t )l ]+ 255 ) /256 * 256 ; 132if (b > cap - total )break ; 133take .push_back ({l ,e }); 134total += b ; 135 } 136if (take .empty ())return 0 ; 137// Alchemist (Arc A-series) refuses a single USM host allocation past ~3 GiB (docs/INTEL.md, A750), so the mirror 138// is built from chunks under that. Battlemage and the CUDA/HIP builds never hit the limit, but chunking is neutral 139// for them. One chunk per (up to) 2 GiB of experts. 140constexpr uint64_t kChunk = 2ull <<30 ; 141 std::vector < uint8_t *> chunks ; 142// Free every chunk unless the mirror is handed over to the object: covers an allocation failure, a failed read and 143// any exception (a container allocation, a std::thread that cannot be created) on the way out. 144struct ChunkCleanup { 145 std::vector < uint8_t *>& v ; 146bool armed = true; 147 ~ChunkCleanup () {if (armed )for (uint8_t * c :v )if (c ) sycl::free (c , dpct::get_in_order_queue ()); } 148 }cleanup {chunks }; 149 std::vector < uint8_t *> ptrs (take .size (),nullptr ); 150uint64_t placed = 0 ; 151uint8_t * cur = nullptr ; 152uint64_t cur_off = 0 ,cur_size = 0 ; 153for (size_t j = 0 ;j < take .size ();++ j ) { 154const uint64_t b = (lay .bytes [(size_t )take [j ].first ]+ 255 ) /256 * 256 ; 155if (cur == nullptr || cur_off + b > cur_size ) { 156// never smaller than one blob, so a single blob past kChunk still fits its chunk 157const uint64_t want = std::max (b , std::min < uint64_t > (kChunk ,total - placed )); 158uint8_t * nc = nullptr ; 159try { 160nc = (uint8_t * ) sycl::malloc_host ((size_t )want , dpct::get_in_order_queue ()); 161 }catch (const sycl::exception & ex ) { 162err = std::string ("mirror: " )+ ex .what (); 163 } 164if (nc == nullptr ) { 165if (err .empty ()) 166err = "mirror: no pinned host memory for " + std::to_string (want >>20 )+ " MiB" ; 167return -1 ; 168 } 169chunks .push_back (nc ); 170cur = nc ;cur_off = 0 ;cur_size = want ; 171 } 172ptrs [j ]= cur + cur_off ; 173cur_off += b ; 174placed += b ; 175 } 176 std::atomic < size_t > next {0 }; 177 std::atomic < bool > bad {false}; 178 std::vector < std::thread > ts ; 179try { 180for (int i = 0 ;i < std::max (1 ,threads );++ i ) 181ts .emplace_back ([& ] { 182for (size_t j ; (j = next .fetch_add (1 ))< take .size ()&& !bad .load ();) { 183const auto [l ,e ]= take [j ]; 184if (!read_into (l ,e ,ptrs [j ], (size_t )lay .bytes [(size_t )l ]))bad .store (true); 185 } 186 }); 187 }catch (...) { 188for (auto & th :ts )if (th .joinable ())th .join ();// join before the cleanup frees, and before unwinding 189throw ; 190 } 191for (auto & th :ts )th .join (); 192if (bad .load ()) { 193err = "mirror: reading an expert from the GGUF failed" ; 194return -1 ; 195 } 196for (uint8_t * c :mirror_chunks_ )if (c ) sycl::free (c , dpct::get_in_order_queue ()); 197mirror_chunks_ = std::move (chunks ); 198cleanup .armed = false;// the chunks now belong to the object 199mirror_bytes_ = total ; 200mirror_ptr_ .assign ((size_t ) (n_layers_ * n_expert_ ),nullptr ); 201layer_first_ .assign ((size_t )n_layers_ ,nullptr ); 202for (size_t j = 0 ;j < take .size ();++ j ) { 203const auto [l ,e ]= take [j ]; 204mirror_ptr_ [(size_t ) (l * n_expert_ + e )]= ptrs [j ]; 205if (layer_first_ [(size_t )l ]== nullptr )layer_first_ [(size_t )l ]= ptrs [j ]; 206 } 207return (int64_t )take .size (); 208} 209 210bool GgufExpertSource ::pinned (int64_t layer ,int64_t expert )const { 211if (mirror_ptr_ .empty ()|| layer < 0 || layer >=n_layers_ || expert < 0 || expert >=n_expert_ )return false; 212return mirror_ptr_ [(size_t ) (layer * n_expert_ + expert )]!= nullptr ; 213} 214 215const uint8_t * GgufExpertSource ::device_alias (int64_t layer ,int64_t expert )const { 216if (mirror_ptr_ .empty ()|| layer < 0 || layer >=n_layers_ )return nullptr ; 217if (expert >=0 && expert < n_expert_ ) { 218const uint8_t * p = mirror_ptr_ [(size_t ) (layer * n_expert_ + expert )]; 219if (p != nullptr )return p ; 220 } 221return layer_first_ [(size_t )layer ]; 222} 223 224bool GgufExpertSource ::read_into (int64_t layer ,int64_t expert ,uint8_t * dst ,size_t bytes )const { 225if (layer < 0 || layer >=n_layers_ || expert < 0 || expert >=n_expert_ || dst == nullptr )return false; 226const auto & lay = strata::kernels::cpu::expert_layout (); 227const auto & fm = lay .fmt [(size_t )layer ]; 228const uint64_t blob = lay .bytes [(size_t )layer ]; 229if (bytes < blob )return false; 230const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,blob - fm .down_off }; 231const uint64_t at [3 ]= {0 ,fm .up_off ,fm .down_off }; 232for (int r = 0 ;r < 3 ;++ r ) { 233const int fd = fds_ [(size_t )layer_fd_ [(size_t ) (3 * layer + r )]]; 234const uint64_t src = lay .gguf_off [(size_t ) (3 * layer + r )]+ per [r ]* (uint64_t )expert ; 235uint64_t done = 0 ; 236while (done < per [r ]) { 237const ssize_t n = ::pread (fd ,dst + at [r ]+ done , (size_t ) (per [r ]- done ), (off_t ) (src + done )); 238if (n <=0 )return false; 239done += (uint64_t )n ; 240 } 241 } 242return true; 243} 244 245// Exchange existing host/device bytes without an additional expert blob. 246namespace { 247class MirrorCacheExchange ; 248void exchange_mirror_bytes (uint8_t * device ,uint8_t * mirror ,size_t bytes , sycl::queue & q ) { 249if (!device || !mirror || !bytes || bytes %16 || 250 (reinterpret_cast < uintptr_t > (device )& 15 )|| (reinterpret_cast < uintptr_t > (mirror )& 15 )|| 251 sycl::get_pointer_type (device ,q .get_context ())!= sycl::usm::alloc::device || 252 sycl::get_pointer_type (mirror ,q .get_context ())!= sycl::usm::alloc::host ) 253throw std::invalid_argument ("mirror cache exchange requires aligned device/host whole blobs" ); 254const size_t vectors = bytes /16 ; 255auto * dp = reinterpret_cast < uint32_t *> (device ); 256auto * hp = reinterpret_cast < uint32_t *> (mirror ); 257q .parallel_for < MirrorCacheExchange > ( 258 sycl::nd_range < 1 > ((vectors + 255 ) /256 * 256 ,256 ), 259 [= ](sycl::nd_item < 1 > item ) [[sycl ::reqd_sub_group_size (32 )]] { 260const size_t i = item .get_global_id (0 ); 261if (i >=vectors )return ; 262 sycl::uint4 old_device ,old_host ; 263old_device .load (0 ,dp + 4 * i ); 264old_host .load (0 ,hp + 4 * i ); 265old_host .store (0 ,dp + 4 * i ); 266old_device .store (0 ,hp + 4 * i ); 267 }); 268q .wait_and_throw (); 269} 270}// namespace 271 272bool GgufExpertSource ::exchange_cached_expert (int64_t layer ,int32_t incoming ,int32_t outgoing , 273void * device_slot ,void * stream , std::string & err ) { 274if (layer < 0 || layer >=n_layers_ || incoming < 0 || outgoing < 0 || 275incoming >=n_expert_ || outgoing >=n_expert_ || incoming == outgoing || 276mirror_ptr_ .empty ()|| !stream ) { 277err = "mirror cache exchange invalid identity" ;return false; 278 } 279const size_t in = (size_t )(layer * n_expert_ + incoming ); 280const size_t out = (size_t )(layer * n_expert_ + outgoing ); 281 std::lock_guard < std::mutex > lock (mu_ ); 282if (!mirror_ptr_ [in ]|| mirror_ptr_ [out ]) { 283err = "mirror cache exchange requires incoming mirror and unmirrored outgoing" ;return false; 284 } 285try { 286auto * memory = const_cast < uint8_t *> (mirror_ptr_ [in ]); 287const auto & layout = strata::kernels::cpu::expert_layout (); 288if (strata::kernels::b60_weights_packed ()) { 289const auto & f = layout .fmt .at ((size_t )layer ); 290 strata::kernels::b60_exchange_single_expert (static_cast < uint8_t *> (device_slot ),memory , 291f .gu_type , (size_t )f .up_off , (size_t )f .down_off , (size_t )layout .blob_bytes (layer ),stream ); 292 }else { 293exchange_mirror_bytes (static_cast < uint8_t *> (device_slot ),memory , 294 (size_t )layout .blob_bytes (layer ),* static_cast < sycl::queue *> (stream )); 295 } 296mirror_ptr_ [out ]= memory ; 297mirror_ptr_ [in ]= nullptr ; 298return true; 299 }catch (const std::exception & e ) {err = e .what ();return false; } 300} 301}// namespace strata::core