spark_runtime/weights.rs
1// SPDX-License-Identifier: AGPL-3.0-only
2
3//! Weight loading from safetensors files (SBIO IORouter for filesystem I/O).
4
5use crate::gpu::{DevicePtr, GpuBackend};
6use anyhow::{Result, bail};
7use std::collections::HashMap;
8use std::path::Path;
9
10/// Advise the OS to evict a file's pages from the page cache.
11///
12/// On GB10 (unified memory), mmap'd safetensors share the GPU memory pool.
13/// After copying tensors to GPU, the mmap pages linger in the page cache,
14/// consuming memory that should be available for KV cache and inference buffers.
15/// This function tells the kernel those pages are no longer needed.
16#[cfg(target_os = "linux")]
17pub(crate) fn evict_page_cache(file: &std::fs::File) {
18 use std::os::unix::io::AsRawFd;
19 // POSIX_FADV_DONTNEED = 4 on Linux (POSIX standard).
20 // macOS lacks posix_fadvise — see the non-linux branch below.
21 const POSIX_FADV_DONTNEED: libc::c_int = 4;
22 unsafe {
23 libc::posix_fadvise(file.as_raw_fd(), 0, 0, POSIX_FADV_DONTNEED);
24 }
25}
26
27#[cfg(not(target_os = "linux"))]
28pub(crate) fn evict_page_cache(_file: &std::fs::File) {
29 // No-op: macOS/BSD have no posix_fadvise. Apple Silicon UMA already
30 // shares page cache with the GPU pool, so eviction is unnecessary.
31}
32
33/// Data type of a weight tensor.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum WeightDtype {
36 BF16,
37 FP32,
38 FP8E4M3,
39 FP8E8M0,
40 UInt8,
41 Int64,
42 /// Keep-packed PrismML ternary Q2_0 (ggml id 42): raw on-disk blocks stay
43 /// 2-bit in VRAM (fp16 scale + 2-bit codes per group of `group` elements),
44 /// dequantized in-kernel by the native `q2_0_gemv` decode path. Only
45 /// produced by the GGUF loader under `ATLAS_GGUF_NATIVE_Q2=1`. Its byte
46 /// footprint is NOT a per-element size (2-bit codes + an inline scale per
47 /// group), so [`WeightDtype::byte_size`] returns 0 for this variant and the
48 /// real size is computed in [`WeightTensor::byte_size`] (shape + group).
49 PackedQ2_0 {
50 group: u16,
51 },
52}
53
54impl WeightDtype {
55 /// Bytes per element for the fixed-width dtypes. Returns 0 for the
56 /// block-based [`WeightDtype::PackedQ2_0`] — [`WeightTensor::byte_size`]
57 /// handles that variant directly, and no caller multiplies its numel by this.
58 pub fn byte_size(self) -> usize {
59 match self {
60 Self::BF16 => 2,
61 Self::FP32 => 4,
62 Self::FP8E4M3 => 1,
63 Self::FP8E8M0 => 1,
64 Self::UInt8 => 1,
65 Self::Int64 => 8,
66 Self::PackedQ2_0 { .. } => 0,
67 }
68 }
69
70 fn from_safetensors(dtype: safetensors::Dtype) -> Result<Self> {
71 match dtype {
72 safetensors::Dtype::BF16 => Ok(Self::BF16),
73 safetensors::Dtype::F32 => Ok(Self::FP32),
74 safetensors::Dtype::U8 => Ok(Self::UInt8),
75 // I8: raw 1-byte container for 4-bit-packed NVFP4 (DeepSeek-V4 MTP
76 // experts). Treat as UInt8 — signedness is irrelevant for packed FP4.
77 safetensors::Dtype::I8 => Ok(Self::UInt8),
78 safetensors::Dtype::F8_E4M3 => Ok(Self::FP8E4M3),
79 safetensors::Dtype::F8_E8M0 => Ok(Self::FP8E8M0),
80 safetensors::Dtype::I64 => Ok(Self::Int64),
81 other => bail!("Unsupported safetensors dtype: {other:?}"),
82 }
83 }
84
85 /// Map a raw safetensors header dtype STRING (as it appears in the JSON
86 /// header, e.g. `"BF16"`, `"F8_E4M3"`) to a [`WeightDtype`], factored out
87 /// so the RDMA weight loader (which receives dtype as a wire string in the
88 /// peer manifest, not a `safetensors::Dtype`) resolves it identically to
89 /// the disk loaders — byte-identity depends on the two ends agreeing.
90 pub fn from_safetensors_str(s: &str) -> Result<Self> {
91 Ok(match s {
92 "F32" => Self::FP32,
93 "BF16" => Self::BF16,
94 "U8" => Self::UInt8,
95 // I8 is a 1-byte raw container (packed NVFP4); signedness is
96 // irrelevant, treat as raw bytes exactly like the disk path.
97 "I8" => Self::UInt8,
98 "F8_E4M3" => Self::FP8E4M3,
99 "F8_E8M0" => Self::FP8E8M0,
100 "I64" => Self::Int64,
101 other => bail!("Unsupported safetensors dtype '{other}'"),
102 })
103 }
104}
105
106/// Convert a little-endian IEEE-754 half-precision (F16) tensor byte buffer
107/// to BF16 bytes. F16 and BF16 are both 2 bytes/element but have different
108/// bit layouts (5-bit vs 8-bit exponent), so the bytes cannot be
109/// reinterpreted — each value goes f16 → f32 (exact) → bf16
110/// (round-to-nearest-even). Shared by both disk loaders so F16 checkpoints
111/// (e.g. centml modelopt W4A4 exports, which ship all unquantized tensors as
112/// F16) land in the store as BF16; [`WeightDtype`] itself stays closed to
113/// store-legal dtypes and F16 can never appear on the RDMA wire.
114pub(crate) fn f16_to_bf16_bytes(src: &[u8]) -> Vec<u8> {
115 use half::{bf16, f16};
116 debug_assert_eq!(src.len() % 2, 0, "F16 tensor byte length must be even");
117 let mut out = Vec::with_capacity(src.len());
118 for pair in src.chunks_exact(2) {
119 let h = f16::from_le_bytes([pair[0], pair[1]]);
120 out.extend_from_slice(&bf16::from_f32(h.to_f32()).to_le_bytes());
121 }
122 out
123}
124
125/// A weight tensor on the GPU.
126pub struct WeightTensor {
127 pub ptr: DevicePtr,
128 pub shape: Vec<usize>,
129 pub dtype: WeightDtype,
130}
131
132impl WeightTensor {
133 pub fn num_elements(&self) -> usize {
134 self.shape.iter().product()
135 }
136
137 pub fn byte_size(&self) -> usize {
138 match self.dtype {
139 // Packed Q2_0: `n_blocks = numel / group` blocks of
140 // `2 + group/4` bytes (34 @ g128, 18 @ g64) — the on-disk footprint.
141 WeightDtype::PackedQ2_0 { group } => {
142 let g = group as usize;
143 debug_assert!(g == 128 || g == 64, "unexpected Q2_0 group {g}");
144 let n_blocks = self.num_elements() / g.max(1);
145 n_blocks * (2 + g / 4)
146 }
147 d => self.num_elements() * d.byte_size(),
148 }
149 }
150
151 /// The Q2_0 group size if this tensor is keep-packed ternary, else `None`.
152 pub fn q2_group(&self) -> Option<u16> {
153 match self.dtype {
154 WeightDtype::PackedQ2_0 { group } => Some(group),
155 _ => None,
156 }
157 }
158
159 /// True if this tensor holds keep-packed ternary Q2_0 blocks (id 42).
160 pub fn is_packed_q2(&self) -> bool {
161 matches!(self.dtype, WeightDtype::PackedQ2_0 { .. })
162 }
163}
164
165/// All model weights loaded onto the GPU, keyed by HuggingFace name.
166pub struct WeightStore {
167 weights: HashMap<String, WeightTensor>,
168 /// Tensors deliberately NOT uploaded, with where they live on disk.
169 ///
170 /// The n-gram embedding tables of the LongCat / Qwen3.8-Flash-Next family
171 /// are 63 GB (LongCat-Lite) to ~102 GB (Flash-Next) of BF16. Uploading
172 /// them through the generic path would exhaust a 121 GB unified box
173 /// before any quantization could run — and on GB10 the fallback is
174 /// `alloc_managed`, i.e. Linux swap, i.e. the documented kernel freeze.
175 /// They are skipped at load and served either by streaming per-table
176 /// quantize-on-load or straight off NVMe by `NgramRowCache`, both of
177 /// which need only this (path, offset) locator.
178 deferred: HashMap<String, DeferredTensor>,
179}
180
181/// Where a skipped tensor lives, so a consumer can read it in place.
182#[derive(Clone, Debug)]
183pub struct DeferredTensor {
184 /// Shard file containing the tensor.
185 pub path: std::path::PathBuf,
186 /// ABSOLUTE byte offset of the tensor's first element in that file
187 /// (safetensors header length + the tensor's `data_offsets[0]`).
188 pub offset: u64,
189 pub shape: Vec<usize>,
190 pub dtype: WeightDtype,
191}
192
193impl WeightStore {
194 /// Create an empty weight store (for testing).
195 pub fn empty() -> Self {
196 Self {
197 weights: HashMap::new(),
198 deferred: HashMap::new(),
199 }
200 }
201
202 /// Record a tensor that was skipped at load, with its on-disk location.
203 pub fn defer(&mut self, name: String, t: DeferredTensor) {
204 self.deferred.insert(name, t);
205 }
206
207 /// Look up a deferred (not-uploaded) tensor's on-disk location.
208 pub fn deferred(&self, name: &str) -> Option<&DeferredTensor> {
209 self.deferred.get(name)
210 }
211
212 /// Every deferred tensor, name-sorted (NUMERIC on a trailing index, so
213 /// `embedders.10` sorts after `embedders.2` — a lexicographic sort here
214 /// silently mis-maps the n-gram tables, which cost a real debugging
215 /// session the first time).
216 pub fn deferred_sorted(&self) -> Vec<(&String, &DeferredTensor)> {
217 let mut v: Vec<_> = self.deferred.iter().collect();
218 v.sort_by_key(|(n, _)| split_trailing_index(n));
219 v
220 }
221
222 /// Wrap a pre-built map. Used by alternate loaders (e.g.
223 /// `fast_weights::FastSafetensorsLoader`, and the RDMA weight loader in
224 /// `spark-storage`, which lives in a different crate and so needs this pub).
225 pub fn from_map(weights: HashMap<String, WeightTensor>) -> Self {
226 Self {
227 weights,
228 deferred: HashMap::new(),
229 }
230 }
231
232 /// Get a weight tensor by name. Fails fast if not found.
233 pub fn get(&self, name: &str) -> Result<&WeightTensor> {
234 self.weights
235 .get(name)
236 .ok_or_else(|| anyhow::anyhow!("Weight '{name}' not found in store"))
237 }
238
239 /// Check if a weight exists.
240 pub fn contains(&self, name: &str) -> bool {
241 self.weights.contains_key(name)
242 }
243
244 /// Number of loaded weights.
245 pub fn len(&self) -> usize {
246 self.weights.len()
247 }
248
249 /// True if no weights are loaded.
250 pub fn is_empty(&self) -> bool {
251 self.weights.is_empty()
252 }
253
254 /// Device bytes the store still holds. Not the on-disk load estimate:
255 /// this shrinks as `free_matching` drops tensors the binders replaced.
256 pub fn resident_bytes(&self) -> usize {
257 self.weights.values().map(|t| t.byte_size()).sum()
258 }
259
260 /// Iterator over all weight names.
261 pub fn names(&self) -> impl Iterator<Item = &str> {
262 self.weights.keys().map(|s| s.as_str())
263 }
264
265 /// Free and forget every tensor whose name matches `pred`. Returns
266 /// `(tensors freed, bytes freed)`.
267 ///
268 /// For loaders that do NOT bind zero-copy from the store's device pointers:
269 /// they upload their own copy, so the original is dead weight the moment the
270 /// binder returns, and on a unified-memory GB10 that duplicate is the
271 /// difference between fitting a KV cache and not.
272 ///
273 /// 🪤 The caller owns the "is it dead?" question. A tensor bound zero-copy
274 /// (every routed expert, and the fused per-expert views in
275 /// `weight_loader/step3p7.rs`) is still live in a layer struct — freeing it
276 /// here is a use-after-free with no diagnostic. Match narrowly.
277 ///
278 /// Per-entry free is sound for the same reason `release` gives below: the
279 /// loaders allocate one `gpu.alloc` per tensor, and no loader inserts an
280 /// `.offset()` view of a shared block into this map.
281 pub fn free_matching(
282 &mut self,
283 gpu: &dyn GpuBackend,
284 pred: impl Fn(&str) -> bool,
285 ) -> Result<(usize, usize)> {
286 let doomed: Vec<String> = self.weights.keys().filter(|n| pred(n)).cloned().collect();
287 let (mut count, mut bytes) = (0usize, 0usize);
288 for name in doomed {
289 // `remove` before `free`: the map must never hold a pointer to
290 // memory that is gone, even if the free below fails.
291 let Some(t) = self.weights.remove(&name) else {
292 continue;
293 };
294 bytes += t.byte_size();
295 gpu.free(t.ptr)
296 .map_err(|e| e.context(format!("freeing weight {name}")))?;
297 count += 1;
298 }
299 Ok((count, bytes))
300 }
301
302 /// Total bytes across all weight tensors on the GPU.
303 pub fn total_bytes(&self) -> usize {
304 self.weights.values().map(|w| w.byte_size()).sum()
305 }
306
307 /// Check if any tensor has FP8 dtype.
308 pub fn has_fp8_weights(&self) -> bool {
309 self.weights
310 .values()
311 .any(|w| matches!(w.dtype, WeightDtype::FP8E4M3))
312 }
313
314 /// Number of per-layer FP8 KV-cache scale tensors (`*.k_scale`) the
315 /// checkpoint ships. `>0` means the model carries calibrated KV scales, so
316 /// FP8 KV needs no online calibration; `0` means the scales default to 1.0
317 /// (which clips BF16 into E4M3 range), so online calibration or a non-FP8 KV
318 /// dtype is required. Used to log the right guidance at serve time.
319 pub fn fp8_kv_scale_count(&self) -> usize {
320 self.names().filter(|n| n.ends_with(".k_scale")).count()
321 }
322}
323
324/// SBIO IORouter trait for weight loading.
325pub trait WeightLoader {
326 fn load(
327 &self,
328 model_dir: &Path,
329 gpu: &dyn GpuBackend,
330 oom_reserve_bytes: usize,
331 ) -> Result<WeightStore>;
332}
333
334/// Loads weights from safetensors files using mmap.
335pub struct SafetensorsLoader {
336 /// EP rank (0-based). Only used when ep_world_size > 1.
337 pub ep_rank: usize,
338 /// EP world size. When > 1, remote expert tensors are skipped.
339 pub ep_world_size: usize,
340 /// Total number of MoE experts in the model (for EP partitioning).
341 pub num_experts: usize,
342 /// Override for the peak memory multiplier in the pre-flight OOM check.
343 /// Set from QuantFormat::peak_memory_multiplier() in the caller.
344 /// When None, the pre-flight uses its own heuristic (1.3x NVFP4 / 1.5x FP8).
345 pub peak_memory_multiplier: Option<f64>,
346 /// Skip the W4A4 `*.input_scale` activation scales at load.
347 ///
348 /// ModelOpt NVFP4 checkpoints ship one 0-dim F32 scalar per quantized
349 /// projection. On a 512-expert model that is ~74k four-byte allocations,
350 /// each taking a full allocation granule — GBs of padding for values
351 /// Atlas never reads, because it serves w4a16 (BF16 activations) and the
352 /// NVFP4 loader already treats the key as optional.
353 ///
354 /// OPT-IN: `step3p7` reads this key on its own path, so it must stay off
355 /// unless the model's loader is known not to need it.
356 pub skip_activation_scales: bool,
357 /// Skip `mtp.*` tensors at load.
358 ///
359 /// For models whose loader deliberately does not build an MTP head,
360 /// uploading its weights is pure waste — on Qwen3.8-Flash-Next that is a
361 /// 1.49 GB expert shard plus the MTP backbone, held resident while the KV
362 /// cache goes without.
363 ///
364 /// OPT-IN: a model that DOES build an MTP head must keep them, so this is
365 /// set only where `load_mtp_weights` is known to return `None`.
366 pub skip_mtp: bool,
367}
368
369impl Default for SafetensorsLoader {
370 fn default() -> Self {
371 Self::new()
372 }
373}
374
375impl SafetensorsLoader {
376 /// Create a loader with no expert parallelism (loads all tensors).
377 pub fn new() -> Self {
378 Self {
379 ep_rank: 0,
380 ep_world_size: 1,
381 num_experts: 0,
382 peak_memory_multiplier: None,
383 skip_activation_scales: false,
384 skip_mtp: false,
385 }
386 }
387
388 /// Create a loader with EP-aware filtering.
389 pub fn with_ep(ep_rank: usize, ep_world_size: usize, num_experts: usize) -> Self {
390 Self {
391 ep_rank,
392 ep_world_size,
393 num_experts,
394 peak_memory_multiplier: None,
395 skip_activation_scales: false,
396 skip_mtp: false,
397 }
398 }
399
400 /// Check if a tensor should be skipped under EP.
401 /// Skips `*.experts.{E}.*` tensors where E is not in local range.
402 /// MTP head experts are never skipped (small, fully replicated).
403 ///
404 /// 🪤 The MTP exemption keys on a leading `mtp.` — a DeepSeek-style name.
405 /// GLM-5.3 puts its MTP head at `model.language_model.layers.45.*` with no
406 /// `mtp.` prefix, so that layer's routed experts ARE sharded on GLM. Fine
407 /// while the MTP head is out of scope; revisit before enabling it.
408 ///
409 /// `pub` so residency can be PROVEN against a real checkpoint index
410 /// without collectives (see `spark-model/tests/glm53_ep_residency.rs`).
411 pub fn should_skip_tensor(&self, name: &str) -> bool {
412 // MTP head weights for a model whose loader does not build one.
413 if self.skip_mtp && name.starts_with("mtp.") {
414 return true;
415 }
416 // W4A4 activation scales: never read on the w4a16 path (the NVFP4
417 // loader falls back to `DevicePtr::NULL`), and 4-byte allocations are
418 // almost pure granule padding at expert scale.
419 if self.skip_activation_scales && name.ends_with(".input_scale") {
420 return true;
421 }
422 if self.ep_world_size <= 1 {
423 return false;
424 }
425 // MTP head experts are small — always replicate, never shard.
426 if name.starts_with("mtp.") {
427 return false;
428 }
429 // Parse expert index from patterns like "*.experts.42.gate_proj*"
430 if let Some(idx) = parse_expert_index(name) {
431 let per_rank = self.num_experts / self.ep_world_size;
432 let local_start = self.ep_rank * per_rank;
433 let local_end = if self.ep_rank == self.ep_world_size - 1 {
434 self.num_experts
435 } else {
436 local_start + per_rank
437 };
438 idx < local_start || idx >= local_end
439 } else {
440 false // Non-expert tensors are always loaded (replicated)
441 }
442 }
443}
444
445/// Split a tensor name into (everything but its last numeric path segment,
446/// that segment as a number) so names sort NUMERICALLY on the index.
447/// `embedders.2` must precede `embedders.10`; a plain lexicographic sort puts
448/// `10` first and silently mis-maps every table after the ninth.
449pub mod adapter;
450mod gguf;
451mod loader;
452pub mod mlx_int8;
453pub use gguf::{GgufLoader, config_from_gguf_dir, find_gguf};
454pub(crate) use loader::estimate_load_bytes;
455// Platform-independent: consumed by the unix-only fast-weights (O_DIRECT) path
456// AND by the GGUF loader, which builds everywhere. Gating this on `unix` broke
457// the Windows CUDA build the moment `gguf.rs` started using it.
458pub(crate) use loader::check_oom_guard;
459// Consumed by the unix-only fast-weights (O_DIRECT) loader path.
460#[cfg(unix)]
461pub(crate) use loader::estimate_has_fp8;
462
463mod name_utils;
464pub(crate) use name_utils::split_trailing_index;
465pub use name_utils::{is_ngram_table, parse_expert_index};
466
467#[cfg(test)]
468mod packed_q2_tests;
469mod prefix_detect;
470pub use prefix_detect::auto_detect_weight_prefix;
471
472/// Release every weight tensor.
473///
474/// Safe to free per-entry because the loaders allocate per-tensor: the fast
475/// path calls `gpu.alloc(meta.len)` once per tensor before inserting it
476/// (`fast_weights/mod.rs:360-388`), and no loader inserts an `.offset()` view of
477/// a shared block into this map. (Fused per-expert views DO exist — see
478/// `weight_loader/step3p7.rs:93` — but they live in the layer structs that own
479/// the fused allocation, not here, so this cannot double-free them.)
480impl atlas_core::scope::ModelResource<dyn GpuBackend> for WeightStore {
481 fn label(&self) -> &'static str {
482 "weight store"
483 }
484
485 fn release(&mut self, gpu: &dyn GpuBackend) -> anyhow::Result<()> {
486 let mut first_error = None;
487 // `drain` rather than iterate: the map must not be left holding
488 // pointers to memory that is gone, and it makes this idempotent.
489 for (name, tensor) in self.weights.drain() {
490 if let Err(e) = gpu.free(tensor.ptr)
491 && first_error.is_none()
492 {
493 first_error = Some(e.context(format!("freeing weight {name}")));
494 }
495 }
496 match first_error {
497 Some(e) => Err(e),
498 None => Ok(()),
499 }
500 }
501}
502
503#[cfg(test)]
504mod teardown_tests;