Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(stream): keep streamed model code native and preserve tokenizer trust (#1933)
Alpamys Makazhan6a0d167739b3
diff --git a/benchmarks/probe-rtx5070-moonlight-16b.md b/benchmarks/probe-rtx5070-moonlight-16b.mdnew file mode 100644index 00000000..9d4fb7d5--- /dev/null+++ b/benchmarks/probe-rtx5070-moonlight-16b.md@@ -0,0 +1,112 @@+# Probe: LoRA on Moonlight-16B-A3B (DeepSeek-V3 architecture) with streaming, RTX 5070 Laptop 8 GB++Status: **both arms COMPLETE** (runs 2026-10-14 18:53Z-18:59Z). The rule in section 2 was committed in d1396a508 before any run. The product-path check COMPLETES too (section 4.1, 2026-10-15).++`moonshotai/Moonlight-16B-A3B`: `model_type: deepseek_v3` (checked in its+`config.json` before anything was built), 27 layers, 64 routed experts + 2 shared+per MoE layer, top-6, 15.96 B parameters, 31.92 GB of bf16 safetensors. It is+the same decoder Kimi K2 uses, at 1/64 of the size. It does not fit the 8 GB+card resident, at bf16 or at NF4 (~8.5 GB of weights alone).++## 1. Question++Does a LoRA training step of Moonlight-16B run on this laptop under layer+streaming (#1914, routed experts fused and at bf16) and under expert streaming+(the per-expert NF4 layout)? What are its seconds per step, tokens per second,+peak VRAM and peak host memory in each mode?++## 2. Decision rule (written before any run)++Harness: `benchmarks/harness/moe_stream_step.py`, real weights, random token ids,+`--seq 512 --batch 1 --steps 5 --lora-r 8`, LoRA on the attention projections+(Moonlight has `q_lora_rank: null`, so `q_proj`, `kv_a_proj_with_mqa`,+`kv_b_proj`, `o_proj`). Two stores, sharded once beforehand (the sharding time is+reported, not judged):++- arm **L**: `--expert-layout fused`, `--tier disk`. Attention, shared and dense MLP are NF4; the routed experts stay bf16 in the layer files.+- arm **E**: `--expert-layout per_expert`, `--tier ram`. Every expert matrix is NF4, read one expert at a time.++Order: L, E, then E, L (two rounds, interleaved). Step 0 of every run is warm-up+and is reported but not used.++- An arm **COMPLETES** iff in both rounds:+ - all 5 steps finish with a finite loss and finite adapter gradients;+ - peak allocated VRAM is at most 7,500 MiB (the card has 8,151 MiB; above that, Windows spills to shared memory silently);+ - the process's peak working set stays below 20 GB (the owner's 10 GB-free floor on a 31.7 GB box).+- Reported, with no threshold:+ - the median seconds of steps 1-4 per run, and tokens/s = 512 / that;+ - expert bytes read per step;+ - layer loads;+ - store bytes on disk;+ - shard seconds.++ Speed is not the goal: no number is promised before the run.+- A product-path check follows (outside this rule's numbers): `soup train` with a+ `soup.yaml` on this base, one epoch over a small alpaca file. It **COMPLETES**+ iff it finishes with a finite loss and writes an adapter. Wall time and the+ first/last logged loss are reported.++## 3. Box state++- AC power on. Free RAM before each run was 12.6, 13.9, 13.6 and 13.8 GB; GPU ~114 MiB in use (the desktop).+- A measurement hold was on the board for 18:50Z-19:00Z, and the other sessions confirmed no pytest. D: had 711 GB free.+- Software: torch 2.14.0+cu130, transformers 5.17.0, bitsandbytes 0.50.2.+- Harness `benchmarks/harness/moe_stream_step.py` at 9cbe1cd20 (merged into this branch as bd97a5d4b).+- **Two earlier runs (18:49Z, 18:51Z) were discarded.** The harness then computed `grads_finite` after `optimizer.zero_grad(set_to_none=True)`, so it was always true (a review found it). The fix moved the check to right after `backward`; all four runs below are after the fix.+- Stores, sharded once beforehand from the bf16 checkpoint on D: (both NF4 with double quantisation; seconds not judged):+ - fused: 30,598,520,590 bytes, 61.7 s;+ - per_expert: 9,235,807,046 bytes, 51.3 s.+- The fused store had just been written and is 29 GB on a 31.7 GB box, so part of it was very likely in the page cache: arm L's reads are NOT cold-disk reads. Arm E's expert reads are direct I/O, bypassing the cache.++## 4. Results++Real weights, random token ids, seq 512, batch 1, LoRA r 8 on `q_proj` / `kv_a_proj_with_mqa` / `kv_b_proj` / `o_proj` (3,552,768 trainable parameters). Every step of every run had a finite loss and 216 of 216 adapter gradients present and finite. Raw JSON: `benchmarks/results/probe-rtx5070/moonlight/`.++| run | arm | steps 1-4 seconds | median | tokens/s | peak alloc VRAM | peak reserved | peak working set | expert reads per step | expert GB per step |+|---|---|---|---|---|---|---|---|---|---|+| r1 | L | 9.81, 9.80, 9.84, 9.83 | 9.82 | 52.1 | 3,993 MiB | 4,264 MiB | 6.76 GB | 0 | 0 |+| r1 | E | 20.30, 18.08, 16.95, 17.99 | 18.04 | 28.4 | 1,882 MiB | 2,138 MiB | 4.60 GB | 4,089-4,287 | 18.25-19.13 |+| r2 | E | 16.89, 18.41, 18.03, 15.92 | 17.46 | 29.3 | 1,882 MiB | 2,138 MiB | 4.60 GB | 4,086-4,296 | 18.23-19.17 |+| r2 | L | 8.84, 8.91, 8.95, 17.36 | 8.93 | 57.3 | 3,993 MiB | 4,264 MiB | 6.76 GB | 0 | 0 |++- Step 0 (warm-up, not used): L 12.95 s and 11.01 s; E 20.22 s and 18.28 s.+- Arm L's last step in r2 (17.36 s) is an outlier at twice its neighbours. It is reported, not dropped; the median absorbs it.+- An expert read is one expert fetched once.+- 26 MoE layers x 64 experts x 3 passes (forward, checkpoint recompute, backward) caps a step at 4,992 reads. The 4,086-4,296 measured means random ids routed to ~82-86% of the experts per pass.++### 4.1 Product path: `soup train`++2026-10-15 08:36:52Z to 08:45:39Z, AC power, 14 GB RAM free before, GPU idle, the other+sessions told beforehand. Code at 2846155470 (branch `feat/moe-moonlight`). Command:+`soup train --config soup.yaml --trust-remote-code --yes`, run from `D:/soup-bench` with+`SOUP_LAYER_STREAM_CACHE_DIR=D:/soup-bench/soup-cache`.++The config:+- base: the local Moonlight-16B-A3B checkpoint;+- `task: sft` on `examples/data/alpaca_tiny.jsonl` (9 train rows, 1 validation row);+- `max_length 512`, `epochs 3`, `batch_size 1`, `quantization: 4bit`;+- `stream_layers: true`, `stream_source: auto`;+- LoRA r 8 on `q_proj`, `kv_a_proj_with_mqa`, `kv_b_proj`, `o_proj`.++`--trust-remote-code` reaches only the tokenizer, which Moonlight ships as remote code; the+model is transformers' own class (this branch's fix).++What Soup reported:+- **Tier and VRAM plan.** `stream_source: auto` fell back to the NVMe disk tier, because the 30.60 GB store does not fit in RAM. The VRAM plan was 2 x 1,159 MB layer buffers plus a 671 MB vocabulary slot, with a predicted peak of ~4.32 GB; the reported peak was 3.1 of 7.9 GB.+- **Steps.** 27 steps in 422.7 s, ~15.7 s per step, with short alpaca rows.+- **Loss.** Training loss 4.922 at step 10, then 3.124 at step 20; mean train loss 3.866; validation loss after epoch 3 was 3.472.+- **Adapter.** Written: `adapter_model.safetensors`, 7,134,912 bytes, plus `checkpoint-27`.++**COMPLETES:** finite loss, adapter written. A 9-row dataset says nothing about quality; this+shows that the CLI path, from config to adapter, runs on this base on an 8 GB card.++## 5. Verdict++**Both arms COMPLETE.** LoRA training steps of Moonlight-16B, a 16 B-parameter DeepSeek-V3-architecture MoE that does not fit this 8 GB card resident, run on the laptop:++- **layer streaming:** 3.9 GB peak VRAM, ~52-57 tokens/s, store partly in the page cache;+- **expert streaming:** 1.9 GB peak VRAM, ~28-29 tokens/s, direct-I/O expert reads.++**Expert streaming halves the VRAM and is about half as fast here.** It reads each routed expert three times per step, one at a time and synchronously (~19 GB per step). Layer streaming reads whole layers through the async reader from a partly cached store.++**The page-cache caveat means arm L's speed is not a cold-disk number.** These are tokens/s of random-id steps, with no claim about convergence.diff --git a/benchmarks/results/probe-rtx5070/moonlight/prep-experts.json b/benchmarks/results/probe-rtx5070/moonlight/prep-experts.jsonnew file mode 100644index 00000000..522141a8--- /dev/null+++ b/benchmarks/results/probe-rtx5070/moonlight/prep-experts.json@@ -0,0 +1,42 @@+{+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids",+ "args": {+ "store": "D:/soup-bench/moonlight-experts",+ "weights": "D:/soup-bench/models/Moonlight-16B-A3B",+ "model": null,+ "expert_layout": "per_expert",+ "out": "C:/Users/user/projects/soup-wt/moe-moonlight/benchmarks/results/probe-rtx5070/moonlight/prep-experts.json",+ "seq": 512,+ "batch": 1,+ "steps": 0,+ "lora_r": 8,+ "buffers": 2,+ "tier": "ram",+ "no_pin": false,+ "seed": 3,+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids"+ },+ "steps": [],+ "shard_seconds": 51.3,+ "store_bytes": 9235807046,+ "build_seconds": 2.21,+ "trainable_params": 3552768,+ "stats": {+ "n_layers": 27,+ "buffers": 2,+ "buffer_bytes": 775083920,+ "large_buffer_bytes": 671088640,+ "store_bytes": 1808693332,+ "pinned": true,+ "pinned_bytes": 2147483648,+ "tier": "ram",+ "read_ahead": null,+ "disk_bytes": 0,+ "layer_loads": 0,+ "large_loads": 0,+ "device": "cuda",+ "total_params": 15960111936,+ "expert_fetches": 0,+ "expert_bytes_read": 0+ }+}diff --git a/benchmarks/results/probe-rtx5070/moonlight/prep-fused.json b/benchmarks/results/probe-rtx5070/moonlight/prep-fused.jsonnew file mode 100644index 00000000..b0ad5dd1--- /dev/null+++ b/benchmarks/results/probe-rtx5070/moonlight/prep-fused.json@@ -0,0 +1,42 @@+{+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids",+ "args": {+ "store": "D:/soup-bench/moonlight-fused",+ "weights": "D:/soup-bench/models/Moonlight-16B-A3B",+ "model": null,+ "expert_layout": "fused",+ "out": "C:/Users/user/projects/soup-wt/moe-moonlight/benchmarks/results/probe-rtx5070/moonlight/prep-fused.json",+ "seq": 512,+ "batch": 1,+ "steps": 0,+ "lora_r": 8,+ "buffers": 2,+ "tier": "disk",+ "no_pin": false,+ "seed": 3,+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids"+ },+ "steps": [],+ "shard_seconds": 61.7,+ "store_bytes": 30598520590,+ "build_seconds": 2.08,+ "trainable_params": 3552768,+ "stats": {+ "n_layers": 27,+ "buffers": 2,+ "buffer_bytes": 2989676432,+ "large_buffer_bytes": 671088640,+ "store_bytes": 3632172724,+ "pinned": true,+ "pinned_bytes": 4294967296,+ "tier": "disk",+ "read_ahead": 2,+ "disk_bytes": 30598395988,+ "layer_loads": 0,+ "large_loads": 0,+ "device": "cuda",+ "total_params": 15960111936,+ "expert_fetches": 0,+ "expert_bytes_read": 0+ }+}diff --git a/benchmarks/results/probe-rtx5070/moonlight/r1-E.json b/benchmarks/results/probe-rtx5070/moonlight/r1-E.jsonnew file mode 100644index 00000000..91bbf047--- /dev/null+++ b/benchmarks/results/probe-rtx5070/moonlight/r1-E.json@@ -0,0 +1,120 @@+{+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids",+ "args": {+ "store": "D:/soup-bench/moonlight-experts",+ "weights": null,+ "model": "D:/soup-bench/models/Moonlight-16B-A3B",+ "expert_layout": "per_expert",+ "out": "C:/Users/user/projects/soup-wt/moe-moonlight/benchmarks/results/probe-rtx5070/moonlight/r1-E.json",+ "seq": 512,+ "batch": 1,+ "steps": 5,+ "lora_r": 8,+ "buffers": 2,+ "tier": "ram",+ "no_pin": false,+ "seed": 3,+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids"+ },+ "steps": [+ {+ "step": 0,+ "seconds": 20.22,+ "tokens_per_second": 25.316,+ "loss": 13.843466758728027,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4260,+ "expert_bytes_read": 19010948640,+ "layer_loads": 52,+ "peak_vram_mib": 1810,+ "peak_reserved_mib": 2096,+ "peak_host_bytes_so_far": 4585168896+ },+ {+ "step": 1,+ "seconds": 20.3,+ "tokens_per_second": 25.227,+ "loss": 13.815112113952637,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4287,+ "expert_bytes_read": 19131440568,+ "layer_loads": 50,+ "peak_vram_mib": 1882,+ "peak_reserved_mib": 2138,+ "peak_host_bytes_so_far": 4597211136+ },+ {+ "step": 2,+ "seconds": 18.08,+ "tokens_per_second": 28.319,+ "loss": 13.84924602508545,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4278,+ "expert_bytes_read": 19091276592,+ "layer_loads": 50,+ "peak_vram_mib": 1882,+ "peak_reserved_mib": 2138,+ "peak_host_bytes_so_far": 4597219328+ },+ {+ "step": 3,+ "seconds": 16.95,+ "tokens_per_second": 30.212,+ "loss": 13.727147102355957,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4218,+ "expert_bytes_read": 18823516752,+ "layer_loads": 50,+ "peak_vram_mib": 1882,+ "peak_reserved_mib": 2138,+ "peak_host_bytes_so_far": 4598808576+ },+ {+ "step": 4,+ "seconds": 17.99,+ "tokens_per_second": 28.456,+ "loss": 13.60991382598877,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4089,+ "expert_bytes_read": 18247833096,+ "layer_loads": 50,+ "peak_vram_mib": 1882,+ "peak_reserved_mib": 2138,+ "peak_host_bytes_so_far": 4598951936+ }+ ],+ "store_bytes": 9235807046,+ "store_expert_layout": "per_expert",+ "store_quant": "nf4",+ "store_double_quant": true,+ "build_seconds": 2.88,+ "trainable_params": 3552768,+ "stats": {+ "n_layers": 27,+ "buffers": 2,+ "buffer_bytes": 775083920,+ "large_buffer_bytes": 671088640,+ "store_bytes": 1808693332,+ "pinned": true,+ "pinned_bytes": 2147483648,+ "tier": "ram",+ "read_ahead": null,+ "disk_bytes": 0,+ "layer_loads": 252,+ "large_loads": 11,+ "device": "cuda",+ "total_params": 15960111936,+ "expert_fetches": 21132,+ "expert_bytes_read": 94305015648+ }+}diff --git a/benchmarks/results/probe-rtx5070/moonlight/r1-L.json b/benchmarks/results/probe-rtx5070/moonlight/r1-L.jsonnew file mode 100644index 00000000..daf088e2--- /dev/null+++ b/benchmarks/results/probe-rtx5070/moonlight/r1-L.json@@ -0,0 +1,120 @@+{+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids",+ "args": {+ "store": "D:/soup-bench/moonlight-fused",+ "weights": null,+ "model": "D:/soup-bench/models/Moonlight-16B-A3B",+ "expert_layout": "per_expert",+ "out": "C:/Users/user/projects/soup-wt/moe-moonlight/benchmarks/results/probe-rtx5070/moonlight/r1-L.json",+ "seq": 512,+ "batch": 1,+ "steps": 5,+ "lora_r": 8,+ "buffers": 2,+ "tier": "disk",+ "no_pin": false,+ "seed": 3,+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids"+ },+ "steps": [+ {+ "step": 0,+ "seconds": 12.95,+ "tokens_per_second": 39.536,+ "loss": 13.82626724243164,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 52,+ "peak_vram_mib": 3922,+ "peak_reserved_mib": 4256,+ "peak_host_bytes_so_far": 6756941824+ },+ {+ "step": 1,+ "seconds": 9.81,+ "tokens_per_second": 52.212,+ "loss": 13.789729118347168,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 50,+ "peak_vram_mib": 3993,+ "peak_reserved_mib": 4264,+ "peak_host_bytes_so_far": 6758592512+ },+ {+ "step": 2,+ "seconds": 9.8,+ "tokens_per_second": 52.228,+ "loss": 13.822641372680664,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 50,+ "peak_vram_mib": 3993,+ "peak_reserved_mib": 4264,+ "peak_host_bytes_so_far": 6758600704+ },+ {+ "step": 3,+ "seconds": 9.84,+ "tokens_per_second": 52.026,+ "loss": 13.696900367736816,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 50,+ "peak_vram_mib": 3993,+ "peak_reserved_mib": 4264,+ "peak_host_bytes_so_far": 6758723584+ },+ {+ "step": 4,+ "seconds": 9.83,+ "tokens_per_second": 52.081,+ "loss": 13.600563049316406,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 50,+ "peak_vram_mib": 3993,+ "peak_reserved_mib": 4264,+ "peak_host_bytes_so_far": 6758838272+ }+ ],+ "store_bytes": 30598520590,+ "store_expert_layout": "fused",+ "store_quant": "nf4",+ "store_double_quant": true,+ "build_seconds": 2.05,+ "trainable_params": 3552768,+ "stats": {+ "n_layers": 27,+ "buffers": 2,+ "buffer_bytes": 2989676432,+ "large_buffer_bytes": 671088640,+ "store_bytes": 3632172724,+ "pinned": true,+ "pinned_bytes": 4294967296,+ "tier": "disk",+ "read_ahead": 2,+ "disk_bytes": 30598395988,+ "layer_loads": 252,+ "large_loads": 11,+ "device": "cuda",+ "total_params": 15960111936,+ "expert_fetches": 0,+ "expert_bytes_read": 0+ }+}diff --git a/benchmarks/results/probe-rtx5070/moonlight/r2-E.json b/benchmarks/results/probe-rtx5070/moonlight/r2-E.jsonnew file mode 100644index 00000000..805dd991--- /dev/null+++ b/benchmarks/results/probe-rtx5070/moonlight/r2-E.json@@ -0,0 +1,120 @@+{+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids",+ "args": {+ "store": "D:/soup-bench/moonlight-experts",+ "weights": null,+ "model": "D:/soup-bench/models/Moonlight-16B-A3B",+ "expert_layout": "per_expert",+ "out": "C:/Users/user/projects/soup-wt/moe-moonlight/benchmarks/results/probe-rtx5070/moonlight/r2-E.json",+ "seq": 512,+ "batch": 1,+ "steps": 5,+ "lora_r": 8,+ "buffers": 2,+ "tier": "ram",+ "no_pin": false,+ "seed": 3,+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids"+ },+ "steps": [+ {+ "step": 0,+ "seconds": 18.28,+ "tokens_per_second": 28.01,+ "loss": 13.843466758728027,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4260,+ "expert_bytes_read": 19010948640,+ "layer_loads": 52,+ "peak_vram_mib": 1810,+ "peak_reserved_mib": 2096,+ "peak_host_bytes_so_far": 4585226240+ },+ {+ "step": 1,+ "seconds": 16.89,+ "tokens_per_second": 30.316,+ "loss": 13.810023307800293,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4296,+ "expert_bytes_read": 19171604544,+ "layer_loads": 50,+ "peak_vram_mib": 1882,+ "peak_reserved_mib": 2138,+ "peak_host_bytes_so_far": 4596514816+ },+ {+ "step": 2,+ "seconds": 18.41,+ "tokens_per_second": 27.805,+ "loss": 13.846870422363281,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4287,+ "expert_bytes_read": 19131440568,+ "layer_loads": 50,+ "peak_vram_mib": 1882,+ "peak_reserved_mib": 2138,+ "peak_host_bytes_so_far": 4602892288+ },+ {+ "step": 3,+ "seconds": 18.03,+ "tokens_per_second": 28.405,+ "loss": 13.727837562561035,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4212,+ "expert_bytes_read": 18796740768,+ "layer_loads": 50,+ "peak_vram_mib": 1882,+ "peak_reserved_mib": 2138,+ "peak_host_bytes_so_far": 4604157952+ },+ {+ "step": 4,+ "seconds": 15.92,+ "tokens_per_second": 32.154,+ "loss": 13.612793922424316,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 4086,+ "expert_bytes_read": 18234445104,+ "layer_loads": 50,+ "peak_vram_mib": 1882,+ "peak_reserved_mib": 2138,+ "peak_host_bytes_so_far": 4604157952+ }+ ],+ "store_bytes": 9235807046,+ "store_expert_layout": "per_expert",+ "store_quant": "nf4",+ "store_double_quant": true,+ "build_seconds": 2.72,+ "trainable_params": 3552768,+ "stats": {+ "n_layers": 27,+ "buffers": 2,+ "buffer_bytes": 775083920,+ "large_buffer_bytes": 671088640,+ "store_bytes": 1808693332,+ "pinned": true,+ "pinned_bytes": 2147483648,+ "tier": "ram",+ "read_ahead": null,+ "disk_bytes": 0,+ "layer_loads": 252,+ "large_loads": 11,+ "device": "cuda",+ "total_params": 15960111936,+ "expert_fetches": 21141,+ "expert_bytes_read": 94345179624+ }+}diff --git a/benchmarks/results/probe-rtx5070/moonlight/r2-L.json b/benchmarks/results/probe-rtx5070/moonlight/r2-L.jsonnew file mode 100644index 00000000..b60e839f--- /dev/null+++ b/benchmarks/results/probe-rtx5070/moonlight/r2-L.json@@ -0,0 +1,120 @@+{+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids",+ "args": {+ "store": "D:/soup-bench/moonlight-fused",+ "weights": null,+ "model": "D:/soup-bench/models/Moonlight-16B-A3B",+ "expert_layout": "per_expert",+ "out": "C:/Users/user/projects/soup-wt/moe-moonlight/benchmarks/results/probe-rtx5070/moonlight/r2-L.json",+ "seq": 512,+ "batch": 1,+ "steps": 5,+ "lora_r": 8,+ "buffers": 2,+ "tier": "disk",+ "no_pin": false,+ "seed": 3,+ "label": "real weights (moonshotai/Moonlight-16B-A3B), random token ids"+ },+ "steps": [+ {+ "step": 0,+ "seconds": 11.01,+ "tokens_per_second": 46.484,+ "loss": 13.82626724243164,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 52,+ "peak_vram_mib": 3922,+ "peak_reserved_mib": 4256,+ "peak_host_bytes_so_far": 6757515264+ },+ {+ "step": 1,+ "seconds": 8.84,+ "tokens_per_second": 57.912,+ "loss": 13.790682792663574,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 50,+ "peak_vram_mib": 3993,+ "peak_reserved_mib": 4264,+ "peak_host_bytes_so_far": 6760054784+ },+ {+ "step": 2,+ "seconds": 8.91,+ "tokens_per_second": 57.486,+ "loss": 13.825260162353516,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 50,+ "peak_vram_mib": 3993,+ "peak_reserved_mib": 4264,+ "peak_host_bytes_so_far": 6760230912+ },+ {+ "step": 3,+ "seconds": 8.95,+ "tokens_per_second": 57.191,+ "loss": 13.696260452270508,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 50,+ "peak_vram_mib": 3993,+ "peak_reserved_mib": 4264,+ "peak_host_bytes_so_far": 6761537536+ },+ {+ "step": 4,+ "seconds": 17.36,+ "tokens_per_second": 29.495,+ "loss": 13.59728717803955,+ "loss_finite": true,+ "grads_finite": true,+ "grads_present": 216,+ "expert_fetches": 0,+ "expert_bytes_read": 0,+ "layer_loads": 50,+ "peak_vram_mib": 3993,+ "peak_reserved_mib": 4264,+ "peak_host_bytes_so_far": 6761734144+ }+ ],+ "store_bytes": 30598520590,+ "store_expert_layout": "fused",+ "store_quant": "nf4",+ "store_double_quant": true,+ "build_seconds": 2.25,+ "trainable_params": 3552768,+ "stats": {+ "n_layers": 27,+ "buffers": 2,+ "buffer_bytes": 2989676432,+ "large_buffer_bytes": 671088640,+ "store_bytes": 3632172724,+ "pinned": true,+ "pinned_bytes": 4294967296,+ "tier": "disk",+ "read_ahead": 2,+ "disk_bytes": 30598395988,+ "layer_loads": 252,+ "large_loads": 11,+ "device": "cuda",+ "total_params": 15960111936,+ "expert_fetches": 0,+ "expert_bytes_read": 0+ }+}diff --git a/changelog.d/0.76.0/1933.fixed.md b/changelog.d/0.76.0/1933.fixed.mdnew file mode 100644index 00000000..fb8994b5--- /dev/null+++ b/changelog.d/0.76.0/1933.fixed.md@@ -0,0 +1,5 @@+- **Layer streaming builds the streamed model from transformers' own class, even under+ `--trust-remote-code`.** The flag still reaches the tokenizer, which is where a repo like+ Moonlight-16B (remote-code tokenizer only) needs it; its remote modelling code lays the experts out+ differently from the stacked shards and could not be streamed. The dated 2026-10-15 Moonlight-16B+ LoRA run on an 8 GB card is recorded in `benchmarks/probe-rtx5070-moonlight-16b.md`. (#1933)diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex c33647ae..5fc5b928 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -458,6 +458,16 @@ training:soup train --config soup.yaml```+**Model and tokenizer code.** With `training.stream_layers: true`, Soup uses+Transformers' own implementation for the model config, the meta skeleton used by+setup probes, and the streamed model. `--trust-remote-code` still reaches the+tokenizer, so a supported model can use a tokenizer supplied as custom repository+code. For example, Moonlight-16B-A3B needs that flag for its tokenizer while its+`deepseek_v3` model uses the native implementation that matches Soup's stacked+expert shards. Streaming requires a supported native model implementation; the+flag does not enable custom model code on this path. The dated Moonlight hardware+runs are recorded in the [probe report](../benchmarks/probe-rtx5070-moonlight-16b.md).+**How it works.** LoRA adapters + their gradients + optimizer state stay resident in VRAM (they are small). The frozen base lives in CPU RAM, page-locked when the machine allows it, and is streamed: each decoder layer is copied into one of two pre-allocated VRAM buffers on a dedicated CUDA stream while the previous layer is still computing, so the load overlaps the compute. Vocabulary-sized `embed_tokens` and an untied `lm_head` use one additional shared slot: the embedding is loaded for the model input, then the same allocation is reused for the output head, whose copy is issued right after the embedding lookup (`StreamPrefetcher.head_prefetch_layer`, default `0`) rather than at the last decoder layer, and the embedding is reloaded into it at the tail of that step's backward pass so the copy overlaps the remaining compute instead of blocking the next step's first lookup. Each decoder layer is read **twice** per step — once in the forward pass and once when the backward pass recomputes it — because `dL/dx = Wᵀ · dL/dy` needs the weights to reach the layers below. That is physics, not an implementation detail, and it is why streaming costs time.For streamed NF4 on CUDA, Soup follows bitsandbytes' own 4-bit dispatch. When@@ -1014,6 +1024,10 @@ all-masked sequence or saving a non-finite adapter.Every command that loads a model now requires `--trust-remote-code` to execute custom Python from a model repo (`auto_map` in `config.json`). First-party orgs (Meta, Mistral, Qwen, Google, etc.) suppress the warning panel; everything else prints a `REMOTE CODE WARNING` panel before loading. Unknown-org local checkpoints with `auto_map` raise a friendly `ValueError` at construction time instead of silently exec'ing inside `from_pretrained`.+For [layer streaming](#layer-streaming-beta-v0720-nf4-v0722-disk--wider-archs-v0723-preference-losses-v0724),+the flag authorizes tokenizer code only; the model config, setup probes and model+always use the supported native Transformers implementation.+Coverage:- `soup train` (every task - SFT, DPO, GRPO, KTO, ORPO, SimPO, IPO, PPO, Reward Model, Pretrain, Embedding, BCO, and the unified Preference dispatcher; automatic evaluation after training follows the run's flag, see `docs/evaluation.md`)- `soup chat`, `soup serve`, `soup data download`, `soup eval auto`diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.pyindex 1ff5eaa9..09edf27f 100644--- a/src/soup_cli/trainer/stream_setup.py+++ b/src/soup_cli/trainer/stream_setup.py@@ -635,6 +635,25 @@ class StreamingSetupMixin:#: Set by :meth:`_setup_streaming_transformers`; absent on a resident run._stream_runtime = None+ #: ``trust_remote_code`` for the streamed MODEL (config, meta skeleton,+ #: install): always False. Every entry of ``SUPPORTED_STREAM_ARCHS`` passed+ #: its resident-vs-streamed parity gate on transformers' own class, and a hub+ #: repo's remote modelling code lays the same weights out differently+ #: (Moonlight's ``modeling_deepseek.py`` keeps one module per expert, so the+ #: shards would not fit it). The tokenizer still gets the user's+ #: ``trust_remote_code``: that is where such repos need it (Moonlight's+ #: tokenizer exists only as remote code).+ _STREAM_NATIVE_MODEL_CODE = False++ @classmethod+ def _stream_meta_skeleton(cls, base, *, dtype, quant):+ """The setup's meta probe of the streamed model, from native code."""+ from soup_cli.utils.layer_stream_runtime import build_meta_skeleton++ return build_meta_skeleton(+ base, dtype=dtype, quant=quant, trust_remote_code=cls._STREAM_NATIVE_MODEL_CODE+ )+@staticmethoddef _stream_shape_config(model_config):"""Text sub-config for multimodal wrappers; plain config otherwise."""@@ -746,7 +765,6 @@ class StreamingSetupMixin:)from soup_cli.utils.layer_stream_runtime import (RamSource,- build_meta_skeleton,build_streamed_model,expandable_segments_status,extras_resident_bytes,@@ -768,8 +786,10 @@ class StreamingSetupMixin:if self.tokenizer.pad_token is None:self.tokenizer.pad_token = self.tokenizer.eos_token+ # The streamed decoder is always transformers' own class (see+ # _STREAM_NATIVE_MODEL_CODE); trust_remote_code reaches the tokenizer only.model_config = AutoConfig.from_pretrained(- cfg.base, trust_remote_code=self._trust_remote_code+ cfg.base, trust_remote_code=self._STREAM_NATIVE_MODEL_CODE)# Allowlist, not a heuristic — a half-supported architecture streams# weights into the wrong module and mis-trains silently.@@ -930,22 +950,12 @@ class StreamingSetupMixin:# The probe is a meta skeleton and is the only model available here, so# the call happens while it is alive rather than at the attach below.if quant == QUANT_NF4:- probe = build_meta_skeleton(- cfg.base,- dtype=dtype,- quant=quant,- trust_remote_code=self._trust_remote_code,- )+ probe = self._stream_meta_skeleton(cfg.base, dtype=dtype, quant=quant)moe_targets = resolve_moe_lora_targets(probe, tcfg, None, console=console)quant_suffixes = quantised_layer_suffixes(probe)del probeelif tcfg.moe_lora:- probe = build_meta_skeleton(- cfg.base,- dtype=dtype,- quant=quant,- trust_remote_code=self._trust_remote_code,- )+ probe = self._stream_meta_skeleton(cfg.base, dtype=dtype, quant=quant)moe_targets = resolve_moe_lora_targets(probe, tcfg, None, console=console)del probe@@ -1231,7 +1241,7 @@ class StreamingSetupMixin:# gated on a real CUDA device.require_pin=(tcfg.stream_pin is True) and on_cuda,seed=tcfg.seed if getattr(tcfg, "seed", None) is not None else 0,- trust_remote_code=self._trust_remote_code,+ trust_remote_code=self._STREAM_NATIVE_MODEL_CODE,console=console,quant=quant,double_quant=double_quant,diff --git a/tests/test_deepseek_v3_streaming.py b/tests/test_deepseek_v3_streaming.pyindex e4c6d83d..aad1de95 100644--- a/tests/test_deepseek_v3_streaming.py+++ b/tests/test_deepseek_v3_streaming.py@@ -284,6 +284,37 @@ def test_setup_hands_the_config_layer_count_to_the_sharder_for_deepseek_v3_only(assert calls[0]["num_hidden_layers"] == expected+def test_streamed_model_is_built_from_native_code_while_the_tokenizer_trusts_remote(+ tmp_path, monkeypatch+):+ """Moonlight-16B (deepseek_v3) ships its tokenizer only as remote code, and its+ remote modelling code keeps one module per expert, which the stacked shards do+ not fit. So the tokenizer gets the user's trust_remote_code and the model side+ (config, skeleton, install) never does."""+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup++ calls = {}+ _drive_qwen4_streaming_setup(+ tmp_path, monkeypatch, arch="deepseek_v3", model_cfg=_deepseek_setup_cfg(),+ load_calls=calls, trust_remote_code=True,+ )+ assert [call["trust_remote_code"] for call in calls["tokenizer"]] == [True]+ assert [call["trust_remote_code"] for call in calls["config"]] == [False]+ assert [call["trust_remote_code"] for call in calls["build"]] == [False]+++def test_setup_meta_probe_is_built_from_native_code(monkeypatch):+ """The NF4 / moe_lora probe in the setup: the same rule as the model itself."""+ import soup_cli.utils.layer_stream_runtime as runtime+ from soup_cli.trainer.stream_setup import StreamingSetupMixin++ seen = []+ monkeypatch.setattr(runtime, "build_meta_skeleton", lambda *a, **k: seen.append(k) or "probe")+ probe = StreamingSetupMixin._stream_meta_skeleton("base", dtype="bfloat16", quant="nf4")+ assert probe == "probe"+ assert seen == [{"dtype": "bfloat16", "quant": "nf4", "trust_remote_code": False}]++def test_planner_fingerprints_config_json_for_deepseek_v3(tmp_path, monkeypatch):"""The planner must agree with the sharder (`source_identity_includes_config`),or it reports a stale cache as reusable and the disk pre-flight under-counts."""diff --git a/tests/test_issue602_qwen4_ple_streaming.py b/tests/test_issue602_qwen4_ple_streaming.pyindex ebc3a5f3..2bed5058 100644--- a/tests/test_issue602_qwen4_ple_streaming.py+++ b/tests/test_issue602_qwen4_ple_streaming.py@@ -685,6 +685,12 @@ def test_qwen4_ram_ple_refusal_is_independent_of_base_stream_source():)+def _record(calls, name, kwargs):+ """`_drive_qwen4_streaming_setup`'s optional call recorder."""+ if calls is not None:+ calls.setdefault(name, []).append(dict(kwargs))++def _drive_qwen4_streaming_setup(tmp_path,monkeypatch,@@ -693,6 +699,8 @@ def _drive_qwen4_streaming_setup(arch="qwen4_exp",model_cfg=None,shard_calls=None,+ load_calls=None,+ trust_remote_code=False,):"""Drive the real `_setup_streaming_transformers()` for a qwen4_exp base.@@ -708,7 +716,9 @@ def _drive_qwen4_streaming_setup(`arch` / `model_cfg` drive the same seam for another architecture(`tests/test_deepseek_v3_streaming.py`); `shard_calls`, when a list, receives- the keyword arguments of every `shard_checkpoint` call.+ the keyword arguments of every `shard_checkpoint` call; `load_calls`, when a+ dict, receives the keyword arguments of the tokenizer, config and+ `build_streamed_model` calls under "tokenizer", "config" and "build"."""import sysimport types@@ -721,7 +731,7 @@ def _drive_qwen4_streaming_setup(class _Wrapper(stream_setup.StreamingSetupMixin):def __init__(self):self.device = "cpu"- self._trust_remote_code = False+ self._trust_remote_code = trust_remote_codedef _stream_budget_lines(self, *_args, **_kwargs):return (), None@@ -807,10 +817,12 @@ def _drive_qwen4_streaming_setup(),)monkeypatch.setattr(- "transformers.AutoTokenizer.from_pretrained", lambda *_a, **_k: tokenizer+ "transformers.AutoTokenizer.from_pretrained",+ lambda *_a, **k: (_record(load_calls, "tokenizer", k), tokenizer)[1],)monkeypatch.setattr(- "transformers.AutoConfig.from_pretrained", lambda *_a, **_k: model_cfg+ "transformers.AutoConfig.from_pretrained",+ lambda *_a, **k: (_record(load_calls, "config", k), model_cfg)[1],)monkeypatch.setattr("peft.LoraConfig", lambda **kwargs: types.SimpleNamespace(**kwargs))monkeypatch.setattr(@@ -869,7 +881,10 @@ def _drive_qwen4_streaming_setup()monkeypatch.setattr("soup_cli.utils.layer_stream_runtime.build_streamed_model",- lambda **_kwargs: (types.SimpleNamespace(), runtime),+ lambda **kwargs: (+ _record(load_calls, "build", kwargs),+ (types.SimpleNamespace(), runtime),+ )[1],)reached = []