diff --git a/CMakeLists.txt b/CMakeLists.txt index ff8766b2..69dc0253 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -69,6 +69,13 @@ if(STRATA_BUILD_CONVERSATION_TESTS) endif() if(STRATA_ENABLE_CUDA) + # #585: CMake links CUDA code with the STATIC runtime by default, and the targets below also link CUDA::cudart (the + # DLL's import library). MSVC with a CUDA 12.x toolkit - the experimental Pascal/Volta build - then fails with + # LNK1169 (every cudart symbol defined twice); GNU ld lets it pass. That build links the shared runtime alone. The + # ready-made engine (CUDA 13, no STRATA_EXPERIMENTAL_SM60) is unchanged; -DCMAKE_CUDA_RUNTIME_LIBRARY overrides. + if(MSVC AND STRATA_EXPERIMENTAL_SM60 AND NOT DEFINED CMAKE_CUDA_RUNTIME_LIBRARY) + set(CMAKE_CUDA_RUNTIME_LIBRARY Shared) + endif() enable_language(CUDA) # `enable_language(CUDA)` gives the .cu compile rules but NOT the imported targets, so `CUDA::cudart` has to # be brought in explicitly for the host-side tests that call cudaMalloc themselves. diff --git a/README.md b/README.md index 0959ca85..1c3c93b6 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,9 @@ word, so 60 tokens per second is faster than you can read. -A card with more VRAM is faster: an RTX 3090 (24 GB) should write roughly 100-140 tokens per second. Long chats, +NVIDIA: Q2_0 with engine 0.1.36, the other rows with 0.1.26 (4K answers, 32K prompts; the full tables are in +[DETAILS.md](docs/DETAILS.md#speed-measured)). A card with more VRAM is faster: an RTX 3090 (24 GB) should write +roughly 100-140 tokens per second. Long chats, other cards: [speed of each model](docs/MODELS.md#how-fast-is-each-size), [community results](docs/COMMUNITY_BENCHMARKS.md).

Buy Me A Coffee
diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 9d2cc704..0b8d0cce 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -173,6 +173,19 @@ been warmed). The server log has the same per request (`expert tiers: GPU ... hi blobs ... MB read`), and `GET /metrics` lists `ram_blobs`, `file_blobs` and `file_mb` for each recent request (with engine 0.1.31 or newer). It also lists each request's speculative drafts, `drafts_offered` and `drafts_accepted` (`null` when the engine did not report them), and their sums since the server started in `totals` (#457). +Its `hit_rate` is the VRAM share of the experts looked up while answering: experts the GPU reads over PCIe +(`--pcie-frac`) are not in it, so a higher `--pcie-frac` raises it even when decoding gets slower. `pcie_share` +(engine 0.1.39 or newer, #588) is their share of all routed experts, and the server log and the Monitor tab show it +beside the hit rate. + +**Where a decode window's time goes (profiling, #610):** start the server with `STRATA_DECODE_TIMING=1` (and +`STRATA_VERIFY_PROFILE=1` for the GPU's side) in the environment. After each request the engine log then has one +`strata decode timing:` line - windows, tokens per window, and per window the verify time split into the wait for the +GPU, the CPU expert pool (plan, activation quantization, jobs) and the stage, plus commit and draft - and one +`strata decode GPU stages (ms/window):` line with the GPU time of each stage (GDN and QSA layers, the VRAM expert +hits, the router, the head, ...). The GPU profile times every stage with events, so it slows the decode a little: +use it to compare, not to measure speed. This works with every pack; `--gpu-stages` (a one-token replay of +per-layer graphs) refuses a native (IQ) pack, which has no such graphs. Time to first token is prompt length / prompt speed: with Q2_0 about 4 s at 4K, 25 s at 32K, under 2 minutes at 128K and 4.5 minutes at 262K (engine 0.1.13 made long prompts about twice as fast, below). @@ -277,7 +290,7 @@ Everything else is installed for you the first time. | GPU | NVIDIA **RTX 20, 30, 40 or 50 series**, **12 GB VRAM or more** (8 GB runs, slowly). Measured on an RTX 5070 and an RTX 3090; RTX 20 (Turing, since 0.1.27) was tested by a contributor on an RTX 2070. Or AMD **Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700, RX 6800 / 6900 series**: [AMD_HIP.md](AMD_HIP.md). | | RAM | **64 GB** recommended (see the table above). | | CPU | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. | -| Disk | ~70-80 GB free for the model, ~6 GB for the MTP layer (+1 GB with images). **Q2_0 on an AVX-512 CPU** also writes a one-time ~40 GB copy of its experts for the fast CPU kernel. An NVMe SSD is strongly recommended. | +| Disk | ~70-80 GB free for the model, ~6 GB for the MTP layer (+1 GB with images). **Q2_0 on an AVX-512 CPU** also writes a one-time ~40 GB pack for the fast CPU kernel (34 GB of experts in its layout, plus the dense weights). An NVMe SSD is strongly recommended. | | OS | Windows 10/11, or Linux (Ubuntu 22.04/24.04 get everything installed automatically). | What the first start installs: in this folder `.venv/`, `engine/` and `third_party/`; the model files (`models/`, @@ -473,6 +486,10 @@ print(r.choices[0].message.content) part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in `strata-.json` sets it for every request; a request's own value wins, and `0` means no budget. Off by default; Anthropic's `"thinking": {"budget_tokens": N}` still only chooses the level, as above. +- **A reply stuck on one token is ended (0.1.39, #606).** When a reply repeats the same token 256 times in a row, the + server ends it there with `finish_reason` `"length"` and says so in its window: a model in a loop, or a broken + state that answers one token forever (#606 saw 36,689 tokens of `!`). `"repeat_stop_tokens": N` in + `strata-.json` sets the run length; `0` turns it off (for a request that really wants one token many times). - **Anthropic requests that don't ask for thinking (opt-in, 0.1.32, #278).** By default a `/v1/messages` request with no `"thinking"`, effort or budget thinks as the model's template does. `"anthropic_thinking": "on_request"` in `strata-.json` renders such a request without thinking - Anthropic's own rule, and what Claude Code's short @@ -872,6 +889,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. | Pictures are slow (10-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). | | A request never finishes: "reading the prompt", GPU "100%" at low power | The GPU ran out of VRAM (engines before 0.1.9 could end with ~30 MiB free at large contexts). Run `START-HERE.bat` once to get engine 0.1.9 or newer; the log then says `... MiB of VRAM free with everything loaded` (a few hundred) and names the `--vram-reserve-mib` to add if it is low. | | Generation stops mid-answer, GPU "100%", one CPU core busy | Fixed in engine 0.1.12 (issue #29, a race in the CPU expert pool on big-VRAM cards). Since then a request that stops moving ends with an error instead of hanging (after 2 minutes; 1 minute from 0.1.13): the log says `no progress for ... s ... (issue #29)` with where it stopped, and the next request starts the engine again. If you see that line, please open an issue with it. Engine 0.1.13 adds a stall report under it (what every expert-pool thread and the GPU handshake were doing, memory and page faults) and, on Windows, a `strata-stall-.dmp` file with every thread's stack: attach both. (`STRATA_WATCHDOG_S` sets the time in seconds; 0 turns it off.) Engine 0.1.14 fixes the stall those reports found (issue #31: with the IQ packs the host could wait forever inside the NVIDIA driver while copying experts in a verify window; the experts are now copied by a GPU kernel, `--pcie-mode dma` restores the old way). | +| `no progress for 60 s ... reading the prompt` on Linux, and the stall report says `threads waiting on the disk (state D): 16 ...` | The engine waits for the drive, not a deadlock: the n-gram table is read at random (`--ple-io direct`), which a rotational disk cannot keep up with (#605). The engine warns at start when the table is on one; `--ple-io ram` (Linux, needs RAM for the table) or the model on an SSD fixes it. Setup adds `--ple-io ram` itself on a rotational disk when the RAM holds the table (0.1.39). | | `the engine said nothing for ... s during the request` or `... did not finish the request after it was stopped (STOP)` | Issue #481: the engine and the server lost step (the engine waits for its next command, the server for the request's end; GPU at 0 %, nothing in the log). The server ends the engine after 300 s without a line from it during a request (while a prompt is read: each chunk may take three times the previous one's time, the first one up to its tokens at 50 tok/s more), the request ends with an error and the next request starts the engine again. `"engine_silence_s": 600` in `strata-.json` sets the time (0 = wait forever, as before). If you see it, please add the end of the engine log to #481. | | `out of memory: cudaFuncSetAttribute` in the log (IQ3_XXS, long prompt) | Fixed in engine 0.1.15: CUDA loaded a kernel's code when it was first needed, and mid-prompt there was no VRAM left for it. Run `START-HERE.bat` (Windows) or `./setup.sh` (Linux) once to update. | | Anything else | The engine log is `strata-.log` in this folder. | @@ -887,12 +905,14 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. the conversation while you chat). - **RAM:** all 24,576 experts, pinned. The CPU computes the experts that are not on the GPU **in place**, at the same time as the GPU works on the cached ones (AVX-512 / AVX2 kernels, ggml's for the i-quants). -- **SSD:** the 28.8 GB n-gram table, read a few rows per token through the OS cache. +- **SSD:** the 28.8 GB n-gram table, a few rows per token, read unbuffered past the OS cache (`--ple-io direct`, the + default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). - **Speculation:** the model's own MTP layer drafts up to 3 tokens; one pass over all 48 layers checks them. 2.4-3.2 tokens per pass on average. When the reply repeats the context (code edits, quoted text), **prompt lookup** (engine 0.1.7) drafts up to 5 tokens from the earlier copy, but only where its measured acceptance and cost say it pays: code edits 6-11% faster, other text unchanged. The drafts are checked like the MTP's, so the output is the same. -- **Prompts** are processed in 2,048-token chunks with the experts streamed to the GPU over PCIe. +- **Prompts** are processed in chunks of up to 8,192 tokens (`--prefill auto`; 32,768 opt-in) with the experts + streamed to the GPU over PCIe. The full story, with measurements, bottlenecks and what comes next: **[docs/paper/Strata-Paper.pdf](paper/Strata-Paper.pdf)**. diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 7af3a3e8..aec9d89d 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -151,6 +151,9 @@ says so and starts the engine you had. - **Where that data folder is:** `%APPDATA%\Strata\settings.json` on Windows, `~/.config/strata/settings.json` on Linux ([details](DETAILS.md#before-you-start)). - **The program itself:** `.venv/`, `engine/` and `third_party/` in the Strata folder. +- **Where github.com cannot be reached:** a build from source downloads llama.cpp's source (ggml, gguf-py) from + GitHub at the commit `LLAMA_CPP_COMMIT` in `setup.py` names. Put that commit's tree in `third_party/llama.cpp` + yourself (from a mirror or another PC) and setup uses it instead (#585). ## Setup's questions diff --git a/docs/MODELS.md b/docs/MODELS.md index 95a954d1..b2e0d00e 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -71,8 +71,9 @@ fetches the MTP draft layer (~6 GB, +1 GB with images). Shard 1 is the part of the model that gets loaded when it starts: its experts go into your **RAM**, the rest onto your graphics card (the second shard, a 29 GB lookup table, stays on the SSD). So it fits when your **RAM is at least -shard 1 + about 10 GB** for Windows and your other programs. With 64 GB of RAM every size fits (IQ3_S with little -else open); with 48 GB, Q2_0 and IQ2_XS. A bigger graphics card makes it faster, but it doesn't lower the RAM needed +the experts + about 10 GB** for Windows and your other programs - the experts are most of shard 1: 34 GB for Q2_0, +35.5 for IQ2_XS, 43 for IQ3_XXS, 50 for IQ3_S, 23 for the Coder (the dense weights in shard 1 go to the graphics +card). With 64 GB of RAM every size fits (IQ3_S with little else open); with 48 GB, Q2_0 and IQ2_XS. A bigger graphics card makes it faster, but it doesn't lower the RAM needed - except in the low-RAM mode below. ### A big graphics card and little RAM @@ -128,6 +129,15 @@ NVIDIA GPU (no images yet). Details and measurements: [UD-Q4_K_XL](UNSLOTH_Q4.md START-HERE.bat --setup --family unsloth --model UD-Q4_K_XL ``` +**Unsloth's UD-IQ4_XS** (experimental, 0.1.39, #621) is the smaller choice of the same family: a 94 GB download with +59.5 GB of experts (IQ3_S and IQ4_NL), between IQ3_S and UD-Q4_K_XL. Setup runs it the same way (a RAM budget of your +RAM minus 24 GB, the rest from the SSD), so on a 64 GB PC far fewer experts come from the SSD than with UD-Q4_K_XL, and +on 96 GB all of them stay in RAM. Not measured on NVIDIA yet: [details](UNSLOTH_Q4.md#ud-iq4_xs-experimental-setup-from-0139-621). + +``` +START-HERE.bat --setup --family unsloth --model UD-IQ4_XS +``` + ### OrcaRouter Uncensored IQ3_XXS For **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](ORCA.md). It needs an diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 6e0b0d96..2e9d975f 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -56,6 +56,11 @@ Or edit an existing config (`strata-*.json`), then restart: "layer_split": "auto" ``` +`"layer_split"` is `"auto"` (placed by each card's free VRAM) or the **first layer of each later card**: one rising +number per card after the first, not a count of layers per card. With 4 cards and a 48-layer model, `"24,36,42"` +(or `[24, 36, 42]`) puts layers 0-23 on the first card, 24-35 on the second, 36-41 on the third and 42-47 on the last. +The server checks it before the start and says what is wrong (0.1.39, #644). + **Skip the split when the first card holds everything** (opt-in, 0.1.31): `"split_skip_if_fits": true` in the config (engine flag `--split-skip-if-fits`, with `--layer-split auto`) runs on the first card alone when it holds every profiled expert plus the context's KV, the draft layer and the reserve, and says so in the log; otherwise the split diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 2d040b09..7287409e 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -25,6 +25,14 @@ Strata is already running. Look for its window. Or another program uses the port **Python or the build tools could not be installed.** Install what it names (links are printed), then run it again. Everything already done is kept. +**Linux: the engine does not compile (`unsupported GNU version`, or `exception specification is incompatible` for +`cospi`/`sinpi`/`rsqrt`).** Two known mismatches between the CUDA toolkit and a new Linux (#601): +- gcc newer than 14 (Ubuntu 26.04's default 15): CUDA 12.x and 13.0 refuse it. Install g++-14 and run + `CXX=g++-14 CUDAHOSTCXX=g++-14 ./setup.sh`. +- glibc 2.43 with CUDA 12.9: the toolkit's math headers clash with glibc's, already in CMake's first test compile. + Use CUDA 12.8 or 13.x instead. Setup takes the newest toolkit it finds; `STRATA_NVCC=/usr/local/cuda-12.8/bin/nvcc + ./setup.sh` makes it use that one (only that one). + **The first start takes minutes.** It is reading 34-55 GB into RAM; the second start is faster while the files are in the OS cache. Started from Task Scheduler, it can be 24x slower: see [Running it at startup](DETAILS.md#running-it-at-startup-task-scheduler). diff --git a/docs/UNSLOTH_Q4.md b/docs/UNSLOTH_Q4.md index 12d4d199..6bffe67f 100644 --- a/docs/UNSLOTH_Q4.md +++ b/docs/UNSLOTH_Q4.md @@ -221,10 +221,34 @@ engine with `--short-read` covering the positions to compare; llama.cpp's side w | `STRATA_PARTIAL_PIN=1` | Registers the hottest part of the RAM budget (up to `STRATA_PARTIAL_PIN_GIB`, default 24) with the GPU driver, so the GPU computes a share of the misses over PCIe (`--pcie-frac`). Measured no faster on this PC, and it changes the numerics of those experts (GPU kernels instead of the CPU's), so off. | | `STRATA_FETCH_THREADS=N` | Threads that read the experts from the GGUF while it answers (default 8; 16 was no faster). The prompt path has its own: `STRATA_STAGER_THREADS` (default 32 here) and `STRATA_STAGER_RING` (128). | +## UD-IQ4_XS (experimental, setup from 0.1.39, #621) + +Unsloth's `UD-IQ4_XS` at the same revision is in setup too: `START-HERE.bat --setup --family unsloth --model +UD-IQ4_XS` (engine 0.1.38 or newer). It sits between IQ3_S and UD-Q4_K_XL: its routed experts are IQ3_S gate/up (IQ4_XS +in one layer) with IQ4_NL downs (Q8_0 in five layers), 59.5 GB of them; the dense side (Q8_0 projections, the IQ4_NL +PLE table, a Q6_K head) is UD-Q4_K_XL's. Three shards, 93.7 GB: + +| File | Bytes | SHA-256 | +| --- | ---: | --- | +| `Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf` | 10,946,624 | `5ce89370720f8bf90890f439361282104c1aa1482d4013bb9a50923e758e71a4` | +| `Qwen3.8-Flash-Next-UD-IQ4_XS-00002-of-00003.gguf` | 49,835,229,856 | `577a38a2392b40ca2193cea502e1d92f60b8cd370675d308e0ec21885d9daaa7` | +| `Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00003.gguf` | 43,836,407,744 | `d4634e6d84f0ebb0940be15c90d3790bf6464e3dea3a1cddc567dc0e83ad8833` | + +Setup treats it like UD-Q4_K_XL (the list above): the same RAM budget (your RAM less 24 GB; at most all 55 GiB of its +experts, so a 96 GB PC holds all of them), the pack with `--compat-bf16`, no `experts.bin`, one GPU by default, no +images. It does not ask on AMD: its experts' formats have prompt kernels there too. + +What is known so far: it packs and runs on a Strix Halo (AMD gfx1151, 128 GB unified memory), where prompts read at +~820 tokens/s at 8K and 64K and the answers passed the retrieval checks at 8K and 64K. It has **not** been measured on +NVIDIA yet; please report what you see. One fidelity note that applies to every `--compat-bf16` pack (UD-Q4_K_XL too): +the pack rounds the file's Q8_0 hyper-connection projections to BF16, and on the Strix Halo that rounding put +perplexity 6-9% above llama.cpp's on the same file (teacher-forced, short context). Reading the Q8_0 values instead +closes most of that gap; it is measured on AMD only and not in this release. + ## Scope and validation -- Only UD-Q4_K_XL at revision `38bb39e` is targeted. Other Unsloth quantizations use formats this engine may not - have kernels for; the engine checks every layer's formats at start and refuses an unsupported one by name. +- UD-Q4_K_XL and UD-IQ4_XS at revision `38bb39e` are targeted. Other Unsloth quantizations use formats this engine may + not have kernels for; the engine checks every layer's formats at start and refuses an unsupported one by name. - Tests: the packer's synthetic 4-shard and conversion tests (`.venv/bin/python -m unittest discover -s tools -p test_iq_pack.py`); CTests `gguf_split_test`, `expert_layout_test`, `native_expert_parity_*` (the three real expert format pairs against ggml-cpu, the Q5_1 min term, Q8_0 rows), `prefill_mmq_kquant_test` (with `-DSTRATA_MMQ_KQUANTS=ON`: the diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index 4a708355..a5061bf0 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -16,14 +16,10 @@ // * `h_layer` held-out is **0.0456** - only 4.6% of (layer, token) pairs have all ten experts resident - so // this cannot be a per-layer grouped kernel and the three-way split is not an optimisation. // -// **WHAT THIS FILE IS AND IS NOT, TODAY.** It is the SLOT STORAGE and the RESIDENCY TABLE: it allocates the -// VRAM, fills it from the host arena, and answers `(layer, expert) -> slot or -1`. It does **not** yet compute -// anything - `moe_hit_grouped_s2` does not exist and the hit/miss split is not wired into the graph - so with -// the cache on and nothing consuming it, **the engine is slower by the fill cost and faster by nothing.** -// That is stated here rather than discovered from a benchmark, and it is why `--expert-cache` defaults to 0. -// -// The order of work is `Memory/R4-design-note.md` ยง7: slots and residency first, then the split, then the -// kernel. This is that first step, and the step it unblocks is the one that can be measured. +// **WHAT THIS FILE IS.** The SLOT STORAGE and the RESIDENCY TABLE: it allocates the VRAM, fills it from the host +// arena, and answers `(layer, expert) -> slot or -1`. It computes nothing itself: the GPU computes the experts it +// holds in the verify window's grouped kernels and the prompt path (the hit/miss split), and the CPU pool the rest. +// (Written when nothing consumed the slots yet and `--expert-cache` defaulted to 0; setup's configs use `auto`.) #pragma once #include diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 4c4d12f5..beaa5aa3 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -65,6 +65,22 @@ struct CgroupMemoryStat { /// Returns false when the required memory.stat counters were unavailable. bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes); +/// #633: the RAM this process can get. `available`: MemAvailable (Windows: the available physical memory), lowered +/// to the room under the tightest cgroup limit; `cgroup_limit`: that tightest limit itself (v2 memory.max of the group +/// and its ancestors, or v1 memory.limit_in_bytes), ~0 when there is none - what a container can never exceed. +struct HostMemory { + uint64_t available = 0; + uint64_t cgroup_limit = ~uint64_t{0}; +}; + +/// Linux reads `meminfo`, `self_cgroup` and the cgroup tree under `cgroup_root` (the parameters are for tests; the +/// defaults are the real files). cgroup v2 as before (an unreadable limit of a group that has one fails); cgroup v1's +/// memory controller (`/memory/`: memory.limit_in_bytes - memory.usage_in_bytes); no cgroup line at all is +/// MemAvailable alone. False when the RAM cannot be determined. +bool host_available_memory(HostMemory& m, const std::string& meminfo = "/proc/meminfo", + const std::string& self_cgroup = "/proc/self/cgroup", + const std::string& cgroup_root = "/sys/fs/cgroup"); + /// Build compact offsets for experts absent from both the primary GPU cache and an optional second GPU tier. /// Kept CPU-only so selection and byte accounting can be tested without initializing a GPU. bool make_cache_complement_plan( @@ -331,6 +347,9 @@ struct ExpertDispatch { GpuPlanSink* plan = nullptr; int pcie_num = 0; int64_t pcie_experts = 0; ///< distinct experts the GPU read over PCIe in verify windows + /// #588: routed (token, expert) entries the GPU computed from outside its cache in verify windows: read over PCIe + /// (--pcie-frac, kind 1) or on another GPU (kind 2). In neither cache_hits nor cache_refused. + int64_t offload_entries = 0; double ms_plan = 0, ms_actq = 0, ms_jobs = 0, ms_run = 0; ///< verify-window dispatch sections /// Plan v0.3 P6: decayed routing counts per (layer, expert) during decode (sized by the caller; empty = off), /// which the driver uses to swap the most-routed missing experts into the VRAM tier between rounds. @@ -480,8 +499,14 @@ public: /// beside `ram_bytes` (the RAM budget), cached now or not (their mapped pages would land in the working set); see /// experts_unbuffered. The mapped reads' page faults are one small request each, and the pages they bring in /// take the RAM the budget was sized for. `why` says what decided. + /// #577: `ram_bytes` counts up to every expert, and only the experts outside it are what the cache must keep. bool set_unbuffered(uint64_t ram_bytes, std::string& why); + /// #577: the same decision once the RAM copy is built (pin_cache_complement), from the RAM it really holds and the + /// expert bytes outside it; switches either way (startup only, nothing reading). Returns whether unbuffered. + bool recheck_unbuffered(std::string& why); bool unbuffered() const { return !direct_.empty(); } + /// Every expert's bytes (n_layers x n_expert blobs). + uint64_t expert_bytes() const; /// #286, unbuffered: assembles the blobs of these pairs ahead of the `blob` calls that will ask for them (the /// GPU cache's fill from the profile) - one batch of reads instead of one blob at a time. At most 64 pairs. void prefetch_pairs(const std::pair* pairs, int64_t n); @@ -524,6 +549,7 @@ private: /// #286: the blobs from the drive, unbuffered: every role's 4 KiB-aligned window is read at once (overlapped) /// into this thread's aligned buffer, then copied into place. False when a read fails. bool read_direct(const Fill* fills, size_t n) const; + bool open_direct(std::string& why); std::vector paths_; ///< the mapped files, as maps_ std::vector direct_; ///< #286: per file, an unbuffered overlapped handle (Windows) std::vector role_file_; ///< 3 x n_layers: index into maps_ / direct_ @@ -645,6 +671,8 @@ public: /// What backing was obtained and why, for the startup print. "The engine adapts to the machine it is on" is /// only true if the engine says what it got. const std::string& note() const { return note_; } + /// #633: set by `open` when the RAM available is less than the arena needs (a recommendation; it still loads) + const std::string& ram_warning() const { return ram_warning_; } double load_gib_per_second() const { return gib_per_s_; } // Loader fix: the load, split. `load_seconds()` is the wall clock of the load loop; the other two are // sums over the reader threads (see LoadStats), so on their own they say how much of that wall was spent @@ -662,6 +690,7 @@ private: int64_t n_expert_ = 0; int64_t reads_ = 0; std::string note_; + std::string ram_warning_; double gib_per_s_ = 0.0; double load_seconds_ = 0.0; double load_read_s_ = 0.0; diff --git a/include/strata/core/pinned.hpp b/include/strata/core/pinned.hpp index 9c9c3805..28a6f987 100644 --- a/include/strata/core/pinned.hpp +++ b/include/strata/core/pinned.hpp @@ -117,8 +117,11 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std:: /// STRATA_UNBUFFERED_LOAD=1 / 0 forces it. `why` says what decided. /// `cache_counts` false (the file tier with a RAM budget): only whether the files could be kept decides - their mapped /// pages land in the process's working set, so a partly cached file would still take the RAM the budget was sized for. +/// `read_bytes` (#577): the bytes the files are read for, when that is less than the files (the file tier reads only +/// the experts outside its RAM copy); `kAllFileBytes` = every byte of `files`. See platform::file_cache_keeps. +constexpr uint64_t kAllFileBytes = ~0ull; bool experts_unbuffered(const std::vector& files, uint64_t arena_bytes, std::string& why, - bool cache_counts = true); + bool cache_counts = true, uint64_t read_bytes = kAllFileBytes); // FNV-1a 64. Per layer, so a corrupt or short read names WHICH layer rather than just failing a whole-file // comparison - the same reason the Phase 1 tools report the first differing element. diff --git a/include/strata/kernels/q8_1_finite.hpp b/include/strata/kernels/q8_1_finite.hpp new file mode 100644 index 00000000..7826dbc5 --- /dev/null +++ b/include/strata/kernels/q8_1_finite.hpp @@ -0,0 +1,33 @@ +// include/strata/kernels/q8_1_finite.hpp - #606: the q8_1 activation block's scale and sum, kept finite. +// +// A q8_1 block stores its scale d = amax / 127 and the sum of its 32 raw activations as fp16. A sum past 65504 (one +// massive-activation dimension among 32 values is enough) rounds to inf, and d does past amax = 8.3M; the dot +// products then read inf * 0 = NaN, and a NaN in the residual ends as one token repeated (ggml-org/llama.cpp#23606 +// is the same defect). Clamped to the largest finite half, such a block gives an approximate product instead of NaN, +// and the values are held to the int8 range they then exceed. Every block that was finite before is stored bit for +// bit as before: values in (65504, 65520) round to 65504 anyway, and a finite block's |x / d| is at most 127. A NaN +// stays NaN (the comparisons are false for it), so STRATA_DBG_NAN still sees one. +#pragma once + +#include + +namespace strata::kernels { + +constexpr float kHalfMax = 65504.0f; + +__device__ __forceinline__ float q8_1_finite(const float v) { + return fabsf(v) > kHalfMax ? copysignf(kHalfMax, v) : v; +} + +/// The block's quantized value of `xi` for the (finite) scale `d`; `amax` = 0 is an all-zero block. +__device__ __forceinline__ int8_t q8_1_quant(const float xi, const float d, const float amax) { + if (amax == 0.0f) return 0; + const float q = roundf(xi / d); + return (int8_t) (q > 127.0f ? 127.0f : q < -127.0f ? -127.0f : q); +} + +__device__ __forceinline__ half2 q8_1_ds(const float d, const float sum) { + return make_half2(__float2half(q8_1_finite(d)), __float2half(q8_1_finite(sum))); +} + +} // namespace strata::kernels diff --git a/include/strata/platform/memory.hpp b/include/strata/platform/memory.hpp index ece6c9e4..202a3bf2 100644 --- a/include/strata/platform/memory.hpp +++ b/include/strata/platform/memory.hpp @@ -32,4 +32,15 @@ bool gpu_shared_memory_budget(const void* luid, uint64_t& budget, uint64_t& usag /// The machine's physical RAM in bytes (0 when unknown). uint64_t total_physical_memory(); +/// #357/#577: whether the OS file cache could keep the `read_bytes` the expert files are read for, beside +/// `arena_bytes` of RAM held by the engine's own copy of the experts and `margin` for everything else, with `avail` +/// bytes of RAM available. The file tier passes only the expert bytes it really reads from the files (the experts +/// outside its resident RAM copy) and the RAM that copy really holds - not every shard's bytes and the requested +/// budget, which on a 96 GB PC (#577) made the file tier read unbuffered when the cache could keep its reads. +inline bool file_cache_keeps(uint64_t avail, uint64_t arena_bytes, uint64_t read_bytes, + uint64_t margin = 4ull << 30) { + const uint64_t room = avail > arena_bytes + margin ? avail - arena_bytes - margin : 0; + return room >= read_bytes; +} + } // namespace strata::platform diff --git a/serve/server.py b/serve/server.py index 46e3fc36..6178f12d 100644 --- a/serve/server.py +++ b/serve/server.py @@ -59,6 +59,10 @@ from serve.structured import StructuredOutputError, prepare_format, validated_js IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" VISION_START = "<|vision_start|>" +# #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a +# broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens" +# sets it; 0 turns it off. +REPEAT_STOP_TOKENS = 256 # #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n\n\n" LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1") @@ -443,6 +447,8 @@ class StrataEngine: self.last.update(ram_blobs=int(f[11]), file_blobs=int(f[12]), file_mb=float(f[13])) if len(f) >= 15: # #471 (engine 0.1.36+): the prompt tokens actually read self.last.update(prompt_read=int(f[14])) + if len(f) >= 16: # #588 (engine 0.1.39+): routed experts read over PCIe + self.last.update(offloaded=int(f[15])) @staticmethod def sampling_keys(sampling: dict) -> str: @@ -789,12 +795,46 @@ def engine_silence_s(cfg: dict) -> float: return float(v) +def layer_split_value(cfg: dict) -> str: + """#644: the config's "layer_split" as the engine's --layer-split value: "auto" (the default), or the FIRST LAYER of + each later GPU's share - one rising number per GPU after the first, e.g. "24,36,42" for 4 GPUs (layers 0-23 on the + first card, 24-35, 36-41, 42 to the end) - as a string or a JSON list ([24, 36, 42]). ValueError with the format + and an example for anything else, such as per-card layer counts ("24,16,12,12").""" + v = cfg.get("layer_split") + if v is None or (isinstance(v, str) and v.strip().lower() in ("", "auto")): + return "auto" + n = len(gpu_list(cfg)) + items = v if isinstance(v, (list, tuple)) else str(v).split(",") if isinstance(v, (str, int)) else None + vals = [] + for x in items or []: + try: + if isinstance(x, bool) or isinstance(x, float): + raise ValueError + vals.append(int(str(x).strip())) + except ValueError: + vals = None + break + want = max(n - 1, 1) + example = ",".join(str(round(48 * (i + 1) / (want + 1))) for i in range(want)) + hint = (f'"layer_split" is the first layer of each later GPU, one rising number per GPU after the first ' + f'({want} for {n} GPUs), not a count of layers per card - e.g. "{example}" (or [{example.replace(",", ", ")}])' + f' for an even share of 48 layers, or "auto" (the default) to place them by each card\'s free VRAM') + if not vals: + raise ValueError(f"{hint}; got {v!r}") + if n > 1 and len(vals) != n - 1: + raise ValueError(f"{hint}; got {len(vals)} number(s) ({v!r}) for {n} GPUs") + if vals[0] < 2 or any(b <= a for a, b in zip(vals, vals[1:])): + raise ValueError(f"{hint}; got {v!r}, which does not rise from 2 or more") + return ",".join(str(x) for x in vals) + + def engine_args(cfg: dict) -> list[str]: """The engine's arguments: the config's, and with several GPUs the layer split across them ("layer_split" in the - config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32").""" + config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32"; see + layer_split_value).""" args = list(cfg["args"]) if len(gpu_list(cfg)) > 1 and "--layer-split" not in args: - args += ["--layer-split", str(cfg.get("layer_split") or "auto")] + args += ["--layer-split", layer_split_value(cfg)] # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV if len(gpu_list(cfg)) > 1 and cfg.get("split_skip_if_fits") and "--split-skip-if-fits" not in args: args.append("--split-skip-if-fits") @@ -989,6 +1029,7 @@ class Service: self.min_free_vram_mib = 0 self.before_load = None self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) + self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off) self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) + tokenizer.encode("<|endoftext|>", parse_special=True)) @@ -1436,6 +1477,7 @@ class Service: sampling = {**defaults, **req_values} parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True) detok, n, finish = Detokenizer(self.tok), 0, "length" + run_tok, run_len, repeated = None, 0, False # #606: the current run of one repeated token timings, before = None, None # this request's timings; the engine's `last` before it raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) emb = getattr(self.embeddings, "path", None) @@ -1485,6 +1527,11 @@ class Service: break raw_ids.append(t) seg.append(t) + run_len = run_len + 1 if t == run_tok else 1 + run_tok = t + if self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens: + repeated = True # #606: a degenerate output, not an answer: end it here + break evs = parser.feed(detok.push(t)) self._note(n, evs) last_print = self._progress(last_print) @@ -1538,6 +1585,11 @@ class Service: prompt = prompt + seg + extra if cancel.is_set(): finish = "cancel" + elif repeated: + print(f"[strata] the reply repeated one token ({self.tok.decode([run_tok])!r}) " + f"{run_len} times in a row: ended as \"length\" (repeat_stop_tokens in " + "strata-.json; 0 turns this off). If a new request with a short prompt does the " + "same, restart the server and report it (#606)", flush=True) except GeneratorExit: # the client disconnected mid-stream finish = "disconnect" raise @@ -1554,6 +1606,11 @@ class Service: cvec = (getattr(self.engine, "info", {}) or {}).get("cvec", 0) loaded = str(cvec) not in ("0", "", "None") hit_rate = round(last["hits"] / last["lookups"], 3) if last.get("lookups") else None + # #588: the share the GPU read over PCIe (--pcie-frac) or another GPU computed - not in + # the hit rate's lookups, which is the VRAM share of the rest (None: an older engine) + routed = (last.get("lookups") or 0) + (last.get("offloaded") or 0) + pcie_share = round(last["offloaded"] / routed, 3) \ + if last.get("offloaded") is not None and routed else None seen = prompt_tokens_seen(len(ids), last) # #471: < len(ids) when cancelled mid-read self.history.append({ "projection": (sampling or {}).get("experimental_speed_projection") is not False @@ -1566,7 +1623,7 @@ class Service: "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"), "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1) if n and last.get("generated") and last.get("decode_ms") else None, - "hit_rate": hit_rate, "ram_blobs": last.get("ram_blobs"), + "hit_rate": hit_rate, "pcie_share": pcie_share, "ram_blobs": last.get("ram_blobs"), "file_blobs": last.get("file_blobs"), "file_mb": last.get("file_mb"), # #457: the speculative drafts from the DONE line (None: the engine did not say) "drafts_offered": last.get("drafts_offered"), @@ -1590,6 +1647,8 @@ class Service: ft = self.status.get("first_token") rate = n / max(1e-6, now - ft) if ft else 0.0 hit_msg = f", expert cache {hit_rate*100:.1f}% hit" if hit_rate is not None else "" + if hit_msg and pcie_share: + hit_msg += f" (+{pcie_share*100:.1f}% of the routed experts over PCIe)" print(f"[strata] done: {n} tokens in {el:.0f} s ({rate:.1f} tok/s) " f"({finish}, cancel={cancel.is_set()}){hit_msg}", flush=True) if finish == "length" and parser.state == "reasoning": # #530 @@ -2914,7 +2973,11 @@ def main() -> int: print("model unloaded; the first request loads it ..." if lazy else "loading the model (the first start takes a minute or two) ...", flush=True) if len(gpu_list(cfg)) > 1: - print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True) + try: + split = layer_split_value(cfg) # #644: before the (minutes-long) start + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({split})", flush=True) # a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing # it is told about (WinError 2), so it is made absolute here exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"])) @@ -2977,6 +3040,10 @@ def main() -> int: if mode not in ("model", "on_request"): raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}") svc.anthropic_think_unasked = mode == "model" + rs = cfg.get("repeat_stop_tokens", REPEAT_STOP_TOKENS) # #606: opt-out with 0 + if isinstance(rs, bool) or not isinstance(rs, int) or rs < 0: + raise SystemExit(f"[strata] config \"repeat_stop_tokens\" must be a whole number >= 0 (0 = off), not {rs!r}") + svc.repeat_stop_tokens = rs if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request try: svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"] diff --git a/serve/test_server.py b/serve/test_server.py index 60a19269..546fb0c4 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -21,12 +21,14 @@ from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, Service, StrataEngine, # noqa: E402 - engine_args, prompt_tokens_seen, request_timings, serve, start_failure_hint) + engine_args, layer_split_value, prompt_tokens_seen, request_timings, serve, + start_failure_hint) from types import SimpleNamespace # noqa: E402 ROOT = Path(__file__).resolve().parents[1] CTX = 4096 -ANSWER = "x" * 2000 # longer than the old 1024 fallback: one token per byte +ANSWER = "xy" * 1000 # longer than the old 1024 fallback: one token per byte (#606: not +# one token repeated, which the server ends at 256) class RecordingEngine(MockEngine): @@ -805,6 +807,26 @@ class DraftCounts(unittest.TestCase): self.assertEqual((m["totals"]["drafts_offered"], m["totals"]["drafts_accepted"]), (17, 10)) +class PcieShare(unittest.TestCase): + """#588: the hit rate stays the VRAM share of the lookups; the routed experts the GPU read over PCIe (the DONE + line's 16th field, engine 0.1.39+) are given as their own share of all routed experts.""" + + def test_history(self): + tok = ByteTokenizer() + engine = DoneLineEngine(tok, "\n\nok", max_context=CTX, done_lines=[ + "DONE 4 20 40.0 30.0 stop 3 5 0 60 100 0 0 0.0 20 25", # 25 more over PCIe: 20% of 125 routed + "DONE 4 20 40.0 30.0 stop 3 5 0 60 100 0 0 0.0 20 0", + "DONE 4 20 40.0 30.0 stop 3 5 0 60 100 0 0 0.0 20"]) # an older engine + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + with contextlib.redirect_stdout(io.StringIO()) as out: + for _ in range(3): + list(svc.run(tok.encode("hi"), False, None, 10, {}, threading.Event())) + rows = list(svc.history) + self.assertEqual([r["hit_rate"] for r in rows], [0.6, 0.6, 0.6]) + self.assertEqual([r["pcie_share"] for r in rows], [0.2, 0.0, None]) + self.assertIn("expert cache 60.0% hit (+20.0% of the routed experts over PCIe)", out.getvalue()) + + class LearnedProfile(unittest.TestCase): """#477: "expert_profile_save" in the config: the engine saves its learned profile there, and the next start begins from it when it is a profile of the same model; without the key the arguments are unchanged.""" @@ -847,6 +869,67 @@ class LearnedProfile(unittest.TestCase): self.assertEqual(engine_args(cfg), ["--native", "x", "--expert-profile-save", "learned.bin"]) +class RepeatStop(unittest.TestCase): + """#606: one token repeated repeat_stop_tokens times in a row ends the reply as "length"; 0 turns it off.""" + + def run_reply(self, script, limit=None): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + if limit is not None: + svc.repeat_stop_tokens = limit + ids = tok.encode("hi") + with contextlib.redirect_stdout(io.StringIO()) as out: + done = [x for kind, x in svc.run(ids, False, None, 3000, {}, threading.Event()) if kind == "done"][0] + return done, out.getvalue() + + def test_a_long_run_is_ended(self): + done, log = self.run_reply("ok " + "!" * 1000 + " never") + self.assertEqual(done["finish"], "length") + self.assertEqual(done["completion_tokens"], 3 + 256) + self.assertIn("repeated one token ('!') 256 times", log) + + def test_short_runs_and_off(self): + done, _ = self.run_reply("=" * 255 + " fine") + self.assertEqual(done["finish"], "stop") + done, log = self.run_reply("!" * 1000, limit=0) + self.assertEqual((done["finish"], done["completion_tokens"]), ("stop", 1001)) + self.assertNotIn("repeated one token", log) + done, _ = self.run_reply("ab" * 400, limit=8) # alternating tokens are not one run + self.assertEqual(done["finish"], "stop") + + +class LayerSplit(unittest.TestCase): + """#644: "layer_split" is the first layer of each later GPU; a list is accepted, counts per card are not.""" + + def cfg(self, split, gpus=(2, 0, 1, 3)): + c = {"args": ["--native", "x"], "gpu": list(gpus)} + if split is not ...: + c["layer_split"] = split + return c + + def test_auto_and_absent(self): + for v in (..., None, "", "auto", "AUTO"): + self.assertEqual(engine_args(self.cfg(v))[-2:], ["--layer-split", "auto"]) + + def test_string_and_list(self): + self.assertEqual(engine_args(self.cfg("24,36,42"))[-2:], ["--layer-split", "24,36,42"]) + self.assertEqual(engine_args(self.cfg(" 24, 36 ,42 "))[-2:], ["--layer-split", "24,36,42"]) + self.assertEqual(engine_args(self.cfg([24, 36, 42]))[-2:], ["--layer-split", "24,36,42"]) + self.assertEqual(engine_args(self.cfg(18, gpus=(0, 1)))[-2:], ["--layer-split", "18"]) + self.assertEqual(engine_args(self.cfg([18], gpus=(0, 1)))[-2:], ["--layer-split", "18"]) + + def test_counts_per_card_are_refused_with_the_format(self): + for bad in ("24,16,12,12", [24, 16, 12, 12], "24,16,12", "24,36", "x", [24.5, 30, 40], "1,20,30", [True]): + with self.assertRaises(ValueError) as e: + layer_split_value(self.cfg(bad)) + self.assertIn("first layer of each later GPU", str(e.exception)) + self.assertIn('"12,24,36"', str(e.exception)) # the example for 4 GPUs + + def test_one_gpu_ignores_it(self): + self.assertEqual(engine_args({"args": ["--native", "x"], "gpu": [0], "layer_split": "24,16"}), + ["--native", "x"]) + + class DraftHeadHint(unittest.TestCase): """#474: a start that stopped at "the draft head does not fit" says what to change, from this start's log lines.""" diff --git a/serve/web/app.js b/serve/web/app.js index 6e8fa6b2..f6e56374 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -302,7 +302,9 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) { const [cls, text] = badge[r.finish] || ["", r.finish || "โ€“"]; const t = new Date(r.time * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit", second: "2-digit"}); const proj = r.projection == null ? "" : ` ${r.projection ? "ESP" : "stock"}`; - const hit = r.hit_rate == null ? "โ€“" : `${(r.hit_rate * 100).toFixed(1)}%`; + // #588: the VRAM share; the PCIe share (--pcie-frac) beside it when there is one + const hit = r.hit_rate == null ? "โ€“" : `${(r.hit_rate * 100).toFixed(1)}%` + + (r.pcie_share ? ` +${(r.pcie_share * 100).toFixed(1)}% PCIe` : ""); return `${esc(t)}${esc(text)}${proj}${fmt(r.prompt_tokens)} ${fmt(r.reused)}${fmt(r.output_tokens)}${fmt(r.decode_tok_s, 1)} ${hit}${fmt(r.duration_s, 1)} s`; diff --git a/serve/web/index.html b/serve/web/index.html index d858d2f0..fbccdad0 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -117,7 +117,7 @@

- +
TimeStatusPromptReusedOutputTok/sHit rateDuration
Tok/sVRAM hit rateDuration
No requests yet
diff --git a/setup.py b/setup.py index bc5cdd30..c4c9ce64 100644 --- a/setup.py +++ b/setup.py @@ -28,8 +28,8 @@ answers, no questions), --setup (install another model / change settings instead --host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off (EXPERIMENTAL, off by default), --models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-made -engine), --check (only check this PC), --resident-budget-gib N (UD-Q4_K_XL's experts in RAM), --kv-streaming -on|off|auto. +engine), --check (only check this PC), --resident-budget-gib N (UD-Q4_K_XL's or UD-IQ4_XS's experts in RAM), +--kv-streaming on|off|auto. Setup recommends, it never forces: the recommended answers are the defaults (--yes, or Enter), and a bigger choice than it recommends - a longer context, more GPUs, a bigger RAM budget, a size it thinks will not fit - is kept, with @@ -127,7 +127,14 @@ MODELS = { # keeps a RAM budget of them (--resident-budget-gib, chosen below) and reads the rest from the GGUF on the SSD "UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), EXPERIMENTAL: the best quality, but most experts come from the " "SSD on a 64 GB PC (7-8.5 tokens/s measured)", "download_gb": 111.3, "ram_gb": 48, - "arena_gb": 77.0, "families": ("unsloth",), "budget": True}, + "arena_gb": 77.0, "families": ("unsloth",), "budget": True, "nvidia_only": True}, + # #621 EXPERIMENTAL: Unsloth's UD-IQ4_XS - IQ3_S gate/up experts with IQ4_NL (43 layers) or Q8_0 (5) downs, the + # dense side as UD-Q4_K_XL's; three shards. Packed and run on a Strix Halo (AMD); not measured on NVIDIA yet. Its + # 59.5 GB of experts: a RAM budget of them, like UD-Q4_K_XL, but far fewer read from the SSD on a 64 GB PC + "UD-IQ4_XS": {"about": "~4-bit i-quant (Unsloth Dynamic), EXPERIMENTAL: between IQ3_S and UD-Q4_K_XL; part of " + "its experts come from the SSD on a 64 GB PC (not measured on NVIDIA yet)", + "download_gb": 93.7, "ram_gb": 48, "arena_gb": 59.5, "families": ("unsloth",), "budget": True, + "shards": 3, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00003.gguf", "engine": (0, 1, 38)}, } # The experimental Unsloth file's four shards at the pinned revision: name -> (bytes, sha256), checked after the # download (setup trusts no other model file by name and size alone either: check_shards reads their directories). @@ -141,6 +148,15 @@ UNSLOTH_SHARDS = { "Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf": (12087983520, "753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a"), } +# #621: UD-IQ4_XS's three shards at the same revision (sizes and SHA-256: the Hub's LFS pointers) +UNSLOTH_IQ4_XS_SHARDS = { + "Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf": + (10946624, "5ce89370720f8bf90890f439361282104c1aa1482d4013bb9a50923e758e71a4"), + "Qwen3.8-Flash-Next-UD-IQ4_XS-00002-of-00003.gguf": + (49835229856, "577a38a2392b40ca2193cea502e1d92f60b8cd370675d308e0ec21885d9daaa7"), + "Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00003.gguf": + (43836407744, "d4634e6d84f0ebb0940be15c90d3790bf6464e3dea3a1cddc567dc0e83ad8833"), +} UNSLOTH_ENGINE = (0, 1, 32) # the first engine setup configures for UD-Q4_K_XL (0.1.31 ran it by hand) UNSLOTH_RAM_LEFT_GB = 24 # RAM beside the budget: the OS, the engine, and the file cache the rest is read through # Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will @@ -173,14 +189,17 @@ FAMILIES = { "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF"), "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-coder", "profile": "expert-profile-coder.bin"}, - # EXPERIMENTAL: Unsloth's UD-Q4_K_XL of the original model (docs/UNSLOTH_Q4.md): four shards, no images yet - "unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "by": "Unsloth's 4-bit quantization (EXPERIMENTAL)", - "about": "4-bit, 111 GB download, most experts read from the SSD: slow (7-8.5 tokens/s on a 64 GB PC)", + # EXPERIMENTAL: Unsloth's UD-Q4_K_XL (four shards) and UD-IQ4_XS (three, #621) of the original model + # (docs/UNSLOTH_Q4.md); no images yet + "unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "by": "Unsloth's 4-bit quantizations (EXPERIMENTAL)", + "about": "UD-Q4_K_XL (111 GB download) or UD-IQ4_XS (94 GB); part of the experts read from the SSD: " + "slower (UD-Q4_K_XL: 7-8.5 tokens/s on a 64 GB PC)", "hf": hf("unsloth/Qwen3.8-Flash-Next-GGUF") + "{q}/", "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf", "shards": 4, "tag": "unsloth-", "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-unsloth", - "experimental": True, "vision": False, "pack_args": ["--compat-bf16"], "sha256": UNSLOTH_SHARDS}, + "experimental": True, "vision": False, "pack_args": ["--compat-bf16"], + "sha256": {**UNSLOTH_SHARDS, **UNSLOTH_IQ4_XS_SHARDS}}, } MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" # EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README @@ -608,6 +627,23 @@ def split_mmap(cfg: dict) -> bool: return True +def model_file(fam: dict, model: str, i: int) -> str: + """Shard i's file name: the family's pattern, or the model's own (#621: UD-IQ4_XS has three shards, not four).""" + return MODELS.get(model, {}).get("file", fam["file"]).format(q=model, i=i) + + +def model_shards(fam: dict, model: str) -> int: + return MODELS.get(model, {}).get("shards", fam.get("shards", 2)) + + +def budget_model(cfg: dict) -> str: + """The Unsloth model a config with a RAM budget runs, from its --native shard's name (UD-Q4_K_XL by default).""" + a = cfg.get("args", []) + native = Path(a[a.index("--native") + 1]).name.upper() if "--native" in a and a.index("--native") + 1 < len(a) \ + else "" + return next((m for m, d in MODELS.items() if d.get("budget") and f"-{m}-" in native), "UD-Q4_K_XL") + + def unsloth_split_need_gb(model="UD-Q4_K_XL") -> float: """#498: the RAM UD-Q4_K_XL needs on several GPUs, where it has no RAM budget (the engine refuses --resident-budget-gib with a layer split): its GGUF files and UNSLOTH_RAM_LEFT_GB more (~135 GB). Measured safe @@ -623,14 +659,15 @@ def split_budget(cfg: dict) -> bool: a = cfg.get("args", []) if "--resident-budget-gib" not in a: return False - need, ram = unsloth_split_need_gb(), ram_gb() + model = budget_model(cfg) + need, ram = unsloth_split_need_gb(model), ram_gb() if ram < need: - fail(f"UD-Q4_K_XL cannot share its RAM budget across GPUs (the engine has no layer split with it), and without " + fail(f"{model} cannot share its RAM budget across GPUs (the engine has no layer split with it), and without " f"the budget it needs ~{need:.0f} GB of RAM (its GGUF files and {UNSLOTH_RAM_LEFT_GB} GB more); this PC " f"has {ram:.0f} GB", "start it on one GPU: START-HERE.bat --gpu N (Linux: ./setup.sh --gpu N)") i = a.index("--resident-budget-gib") del a[i:i + 2] - ok("UD-Q4_K_XL on several GPUs: no RAM budget (the engine has none with a layer split) - all its experts are " + ok(f"{model} on several GPUs: no RAM budget (the engine has none with a layer split) - all its experts are " "loaded into RAM from the model files at start, and the files pass through the OS file cache (#498)") return True @@ -646,7 +683,7 @@ def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: return cfg # #498: UD-Q4_K_XL's RAM budget has no layer split; without it the RAM must hold the GGUFs and 24 GB more budget = "--resident-budget-gib" in cfg.get("args", []) - if budget and ram_gb() < unsloth_split_need_gb(): + if budget and ram_gb() < unsloth_split_need_gb(budget_model(cfg)): return cfg pair = can[:2] cfg["gpus_asked"] = True @@ -660,7 +697,7 @@ def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: say(" use). On both, the experts the GPUs do not hold are read through the OS file cache instead: faster in") say(" two reports (#364, #384), but RAM can fill up to 0 free during long prompts.") if budget: - say(" This model (UD-Q4_K_XL) runs on one GPU with a RAM budget of its experts (recommended: the tested") + say(f" This model ({budget_model(cfg)}) runs on one GPU with a RAM budget of its experts (recommended: the tested") say(" setup). On both it has no budget: all its experts are loaded into RAM at start, which this PC's RAM") say(" holds - about twice as fast in #498 (2x RTX 3090: 31 -> 64-78 tokens/s).") short = split_short(pair) # #448: one card recommended (asked "n" by default), as for --resident @@ -700,10 +737,25 @@ def gpu_info(pick=None): def find_nvcc(below=None): - """The newest CUDA toolkit's nvcc and its (major, minor); with `below`, the newest older than that version.""" + """The newest CUDA toolkit's nvcc and its (major, minor); with `below`, the newest older than that version. + #601: STRATA_NVCC= is the only one considered (a newer toolkit beside it that cannot build on this + PC - CUDA 12.9 with glibc 2.43 - is not taken instead).""" + pick = os.environ.get("STRATA_NVCC") + if pick: + if not Path(pick).exists(): + warn(f"STRATA_NVCC={pick}: no such file; looking for a CUDA toolkit as usual") + else: + v = re.search(r"release (\d+)\.(\d+)", out([pick, "--version"])) + ver = (int(v.group(1)), int(v.group(2))) if v else None + if ver and below is not None and ver >= below: + warn(f"STRATA_NVCC={pick} is CUDA {ver[0]}.{ver[1]}; this build needs one older than " + f"{below[0]}.{below[1]}") + return (None, None) + return (pick, ver) if ver else (None, None) cands = [shutil.which("nvcc")] - if os.environ.get("CUDA_PATH"): - cands.append(str(Path(os.environ["CUDA_PATH"]) / "bin" / ("nvcc.exe" if WIN else "nvcc"))) + for var in ("CUDA_PATH", "CUDA_HOME"): # CUDA_HOME: Linux's usual name (#601) + if os.environ.get(var): + cands.append(str(Path(os.environ[var]) / "bin" / ("nvcc.exe" if WIN else "nvcc"))) if WIN: base = Path(r"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA") if base.exists(): @@ -854,7 +906,7 @@ def gguf_dir_shards(folder: Path, fam: dict, model: str) -> list[Path]: engine and tools/iq_pack.py do. The published name first; else the one first shard in the folder whose name has the size in it (an upload split or named differently: -00001-of-00003, Unsloth's ...-00001-of-00004.gguf). A missing shard is check_shards' error later, as before.""" - first = folder / fam["file"].format(q=model, i=1) + first = folder / model_file(fam, model, 1) if not first.exists(): found = sorted(p for p in folder.glob("*-00001-of-*.gguf") if SHARD_NAME.search(p.name)) mine = [p for p in found if model.lower() in p.name.lower()] @@ -873,7 +925,8 @@ def gguf_dir_shards(folder: Path, fam: dict, model: str) -> list[Path]: GGUF_QUANT = re.compile(r"(? tuple | None: the original's sizes: the size tells them apart).""" for f, d in FAMILIES.items(): for m in MODELS: - if f in MODELS[m].get("families", ("qwen", "swift")) and name == d["file"].format(q=m, i=1): + if f in MODELS[m].get("families", ("qwen", "swift")) and name == model_file(d, m, 1): return f, m return None @@ -2479,6 +2532,22 @@ def is_wsl() -> bool: return sys.platform.startswith("linux") and "microsoft" in platform.uname().release.lower() +def rotational_disk(path) -> str | None: + """#605 (Linux): the disk's name when `path` is on a rotational disk (sysfs queue/rotational), else None.""" + if WIN: + return None + try: + st = os.stat(path) + p = Path(f"/sys/dev/block/{os.major(st.st_dev)}:{os.minor(st.st_dev)}").resolve() + for q in (p, p.parent): # a partition has its disk's queue + f = q / "queue" / "rotational" + if f.exists(): + return q.name if f.read_text().strip() == "1" else None + except (OSError, ValueError, AttributeError): + pass + return None + + def hardware_key(cfg: dict) -> str: """What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting (the context's KV cache and the image encoder take VRAM from the expert cache).""" @@ -2943,8 +3012,9 @@ def main() -> int: ap.add_argument("--gpus", help="several GPUs sharing one model, as nvidia-smi numbers them (AMD: as setup lists " "them): \"0,2\", or \"all\" (every card that can); the first is the main one. " "Saved, also when starting (see docs/MULTI_GPU.md)") - ap.add_argument("--layer-split", help="with --gpus: where each later GPU's layers start (\"18\", \"16,32\"); " - "default auto, placed from each GPU's free VRAM") + ap.add_argument("--layer-split", help="with --gpus: where each later GPU's layers start (\"18\", \"16,32\"), one " + "rising number per GPU after the first - not layers per card; default " + "auto, placed from each GPU's free VRAM") ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " "devices on your network (issue #26; set --api-key too)") ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)") @@ -2975,7 +3045,7 @@ def main() -> int: "this mode the experts the GPU does not hold are copied into RAM once when they fit (resident), " "else read through the OS file cache (mmap); resident / mmap force one of the two") ap.add_argument("--resident-budget-gib", type=float, metavar="N", - help="UD-Q4_K_XL: the GiB of its experts kept in RAM (default: the RAM less 24 GB, 40 on 64 GB; " + help="UD-Q4_K_XL, UD-IQ4_XS: the GiB of its experts kept in RAM (default: the RAM less 24 GB, 40 on 64 GB; " "more is kept as you choose, with a note)") ap.add_argument("--vram-reserve-mib", type=int, metavar="N", help="VRAM in MiB the engine leaves free for other programs (a game, another model; the engine's " @@ -3227,7 +3297,7 @@ def main() -> int: # the RAM holds the GGUFs and 24 GB more: then several, without the budget, if asked for (#498) warn(f"{model} is EXPERIMENTAL (docs/UNSLOTH_Q4.md): most of its experts are read from the SSD while it " "answers, so it is several times slower than the 2-3-bit models; quality checked against llama.cpp") - if hip: + if hip and MODELS[model].get("nvidia_only"): # #429 (jkuepker): checked before the 111 GB download. The HIP engine has no prompt kernels for its # Q4_K / Q5_K experts (STRATA_MMQ_KQUANTS is CUDA-only) and it has not been run on AMD: asked, not refused confirm_risk(f"{model} has not been run on AMD cards yet: its prompt kernels are NVIDIA-only, so on " @@ -3252,7 +3322,8 @@ def main() -> int: if a.low_ram not in ("auto", "off"): warn(f"--low-ram {a.low_ram} does not apply to {model}: it always reads part of its experts from the files") elif a.resident_budget_gib is not None: - warn(f"--resident-budget-gib is for UD-Q4_K_XL: {model} keeps all of its experts in RAM or in the low-RAM mode") + warn(f"--resident-budget-gib is for UD-Q4_K_XL and UD-IQ4_XS: {model} keeps all of its experts in RAM or in " + "the low-RAM mode") low_ram = budget is None and (a.low_ram in ("on", "resident", "mmap") or (a.low_ram == "auto" and low_ram_needed(model, ram))) if low_ram and multi and not low_ram_together(a, model, ram, gpu, chosen): @@ -3388,7 +3459,7 @@ def main() -> int: if family == "swift" else f"the experimental speed projection is not tested with {model}: left off") models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag shards = gguf_dir_shards(models_dir, fam, model) if a.gguf_dir else \ - [models_dir / fam["file"].format(q=model, i=i) for i in range(1, fam.get("shards", 2) + 1)] + [models_dir / model_file(fam, model, i) for i in range(1, model_shards(fam, model) + 1)] problem = gguf_dir_problem(models_dir, shards[0], fam, model) if a.gguf_dir else None if problem: # #444: files Strata cannot run, or another choice's files fail(*problem) @@ -3449,8 +3520,9 @@ def main() -> int: else: lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs() engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) - if budget is not None and engine_ver < UNSLOTH_ENGINE: # checked before the 111 GB download - fail(f"{model} needs engine {'.'.join(map(str, UNSLOTH_ENGINE))} or newer; this one is {meta.get('version')}", + need_engine = MODELS[model].get("engine", UNSLOTH_ENGINE) + if budget is not None and engine_ver < need_engine: # checked before the 94-111 GB download + fail(f"{model} needs engine {'.'.join(map(str, need_engine))} or newer; this one is {meta.get('version')}", "update Strata (or compile the engine with --build) and run setup again") ok(f"engine: {eng / EXE}") @@ -3561,6 +3633,19 @@ def main() -> int: "the OS file cache (run setup again after the next engine update)") if low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped args += ["--resident-experts" if resident else "--mmap-experts"] + disk = None if is_wsl() else rotational_disk(ple) # #605 (WSL's virtual disk says rotational) + if disk: + tensor = next((t for t in GGUFFile(ple).tensors if t.name == "per_layer_token_embd.weight"), None) + size = getattr(tensor, "expected_bytes", lambda: None)() + table_gb = size / 1e9 if size else 28.8 + if ram >= MODELS[model]["ram_gb"] + table_gb + 4: + args += ["--ple-io", "ram"] + ok(f"the model is on a rotational disk ({disk}): its {table_gb:.0f} GB n-gram table is kept in RAM " + "(--ple-io ram) - read from the disk at random, it can stall prompts for minutes (#605)") + else: + warn(f"the model is on a rotational disk ({disk}): its n-gram table is read from it at random, which can " + f"stall prompts for minutes (#605). An SSD is recommended; with ~{table_gb:.0f} GB more RAM, " + "--ple-io ram in the config's args keeps the table in RAM instead") # KV streaming: from 64K up the whole KV cache lives in RAM and only the part the attention reads (32K positions # per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It # costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 7.5 KB with 4-bit, so only when it fits. @@ -3597,6 +3682,10 @@ def main() -> int: elif budget is not None and budget > resident_budget_gib(model, ram, kv_ram_gb): warn(f"the KV cache's {kv_ram_gb:.1f} GB of RAM come on top of your {budget:g} GiB RAM budget (setup " f"would take them out of it: {resident_budget_gib(model, ram, kv_ram_gb)} GiB); kept as you chose") + elif ctx >= 65536: # #620: say why, so a regenerated config that lost --kv-resident is not a surprise + ok(f"KV streaming off: it needs ~{kv_ram_gb:.1f} GB of RAM beside the ~{MODELS[model]['ram_gb']} GB {model} " + f"uses, and this PC has {ram:.0f}; the KV cache stays in VRAM (fewer cached experts). --kv-streaming on " + "turns it on anyway") elif a.kv_streaming == "on": warn("--kv-streaming on: a context under 64K is not streamed (the attention's window holds all of it): off") if budget is not None and not q4_split: # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index c64909f5..08edd46b 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -217,18 +217,25 @@ bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current } #endif -bool available_memory_bytes(uint64_t& bytes) { +} // namespace + +namespace detail { + +bool host_available_memory(HostMemory& m, const std::string& meminfo, const std::string& self_cgroup, + const std::string& cgroup_root) { + m = HostMemory{}; #if defined(_WIN32) + (void) meminfo; (void) self_cgroup; (void) cgroup_root; MEMORYSTATUSEX status{}; status.dwLength = sizeof(status); if (!GlobalMemoryStatusEx(&status)) return false; - bytes = (uint64_t) status.ullAvailPhys; - return bytes > 0; + m.available = (uint64_t) status.ullAvailPhys; + return m.available > 0; #elif defined(__linux__) // MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES. - std::ifstream info("/proc/meminfo"); + std::ifstream info(meminfo); std::string line; - bytes = 0; + uint64_t bytes = 0; while (std::getline(info, line)) { std::istringstream fields(line); std::string key, unit; @@ -237,17 +244,26 @@ bool available_memory_bytes(uint64_t& bytes) { value <= std::numeric_limits::max() / 1024) bytes = value * 1024; } if (bytes == 0) return false; - // Account for the tightest cgroup-v2 ancestor limit when its normal mount is visible. + // Account for the tightest cgroup ancestor limit when its normal mount is visible. // This is a point-in-time guard, not a reservation against concurrent allocations. - std::ifstream groups("/proc/self/cgroup"); + std::ifstream groups(self_cgroup); if (!groups) return false; - bool resolved_v2 = false; + const std::filesystem::path root(cgroup_root); + bool v2 = false; + std::string v1_path; // the memory controller's group (cgroup v1), when there is no v2 line while (std::getline(groups, line)) { - if (line.rfind("0::/", 0) != 0) continue; - const std::filesystem::path root("/sys/fs/cgroup"); + if (line.rfind("0::/", 0) != 0) { + // v1: "N:controller[,controller]:/path" + const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1); + if (c2 == std::string::npos) continue; + std::istringstream ctl(line.substr(c1 + 1, c2 - c1 - 1)); + for (std::string c; std::getline(ctl, c, ',');) + if (c == "memory") v1_path = line.substr(c2 + 1); + continue; + } auto path = (root / line.substr(4)).lexically_normal(); if (path.string().rfind(root.string(), 0) != 0 || !std::filesystem::is_directory(path)) return false; - resolved_v2 = true; + v2 = true; while (path.string().rfind(root.string(), 0) == 0) { std::ifstream limit_file(path / "memory.max"), current_file(path / "memory.current"); std::string limit; @@ -261,28 +277,59 @@ bool available_memory_bytes(uint64_t& bytes) { size_t consumed = 0; const uint64_t cap = std::stoull(limit, &consumed); if (consumed != limit.size()) return false; - detail::CgroupMemoryStat stat; + CgroupMemoryStat stat; if (!read_cgroup_memory_stat(path, current, stat)) return false; uint64_t cgroup_available = 0; - if (!detail::cgroup_available_bytes(cap, stat, cgroup_available)) return false; + if (!cgroup_available_bytes(cap, stat, cgroup_available)) return false; bytes = std::min(bytes, cgroup_available); + m.cgroup_limit = std::min(m.cgroup_limit, cap); } catch (...) { return false; } } if (path == root) break; path = path.parent_path(); } } - return resolved_v2; + if (!v2 && !v1_path.empty()) { + // #633: cgroup v1 (older Docker hosts, RHEL 7/8): the memory controller's group and its ancestors. An + // unlimited group says a number near 2^63 (rounded to its page size); a group whose files are not + // visible (no mount in this namespace) is skipped - MemAvailable alone, as with no cgroup at all. + const std::filesystem::path mroot = root / "memory"; + auto path = (mroot / v1_path.substr(v1_path.rfind('/', 0) == 0 ? 1 : 0)).lexically_normal(); + while (path.string().rfind(mroot.string(), 0) == 0) { + std::ifstream limit_file(path / "memory.limit_in_bytes"), usage_file(path / "memory.usage_in_bytes"); + uint64_t cap = 0, usage = 0; + if (limit_file >> cap && usage_file >> usage && cap < (1ull << 62)) { + bytes = std::min(bytes, usage < cap ? cap - usage : 0); + m.cgroup_limit = std::min(m.cgroup_limit, cap); + } + if (path == mroot) break; + path = path.parent_path(); + } + } + m.available = bytes; + return true; #else + (void) meminfo; (void) self_cgroup; (void) cgroup_root; const long pages = sysconf(_SC_AVPHYS_PAGES); const long page_bytes = sysconf(_SC_PAGESIZE); if (pages <= 0 || page_bytes <= 0 || (uint64_t) pages > std::numeric_limits::max() / (uint64_t) page_bytes) return false; - bytes = (uint64_t) pages * (uint64_t) page_bytes; - return bytes > 0; + m.available = (uint64_t) pages * (uint64_t) page_bytes; + return m.available > 0; #endif } +} // namespace detail + +namespace { + +bool available_memory_bytes(uint64_t& bytes) { + detail::HostMemory m; + if (!detail::host_available_memory(m)) return false; + bytes = m.available; + return bytes > 0; +} + } // namespace // ================================ THE FILE-BACKED SOURCE ================================ @@ -872,13 +919,14 @@ void FileExpertSource::fill_many(const std::vector& todo) { for (auto& t : th) t.join(); } -bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) { +uint64_t FileExpertSource::expert_bytes() const { + uint64_t total = 0; + for (uint64_t b : layer_blob_bytes_) total += b * (uint64_t) n_expert_; + return total; +} + +bool FileExpertSource::open_direct(std::string& why) { #if defined(_WIN32) - if (base_ == nullptr || paths_.empty() || !direct_.empty()) { - why = !direct_.empty() ? "already unbuffered" : "no expert files open"; - return !direct_.empty(); - } - if (!experts_unbuffered(paths_, ram_bytes, why, /*cache_counts=*/false)) return false; for (const std::string& path : paths_) { const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); std::vector w((size_t) (wide > 0 ? wide : 1), L'\0'); @@ -899,6 +947,24 @@ bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) { for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b); } return true; +#else + (void) why; + return false; +#endif +} + +bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) { +#if defined(_WIN32) + if (base_ == nullptr || paths_.empty() || !direct_.empty()) { + why = !direct_.empty() ? "already unbuffered" : "no expert files open"; + return !direct_.empty(); + } + // #577: the file tier reads the experts outside the RAM copy, not every byte of the shards (dense weights, the + // PLE table), and the copy holds at most every expert - the budget asked for can be more than that + const uint64_t experts = expert_bytes(); + const uint64_t arena = std::min(ram_bytes, experts); + if (!experts_unbuffered(paths_, arena, why, /*cache_counts=*/false, experts - arena)) return false; + return open_direct(why); #else (void) ram_bytes; why = "through the file cache (not Windows)"; @@ -906,6 +972,39 @@ bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) { #endif } +bool FileExpertSource::recheck_unbuffered(std::string& why) { +#if defined(_WIN32) + if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') { + why = std::string("STRATA_UNBUFFERED_LOAD=") + env; + return !direct_.empty(); + } + if (base_ == nullptr || paths_.empty()) { + why = "no expert files open"; + return false; + } + // #577: the RAM copy is built (and already out of the available RAM), so what the file cache would have to keep + // is exactly the experts outside it - the GPU cache's (refilled after a prompt borrowed their slots) and the + // ones neither holds + const uint64_t experts = expert_bytes(); + const uint64_t read = experts > complement_bytes_ ? experts - complement_bytes_ : 0; + std::string w; + const bool ub = experts_unbuffered(paths_, 0, w, /*cache_counts=*/false, read); + char head[96]; + std::snprintf(head, sizeof head, "re-checked with the RAM copy built (%.2f GiB): ", + (double) complement_bytes_ / 1073741824.0); + why = head + w; + if (ub == !direct_.empty()) return ub; + if (ub) return open_direct(why); + // through the file cache after all: the mapped reads take over (staged() stays true for the GGUF in place) + for (void* d : direct_) CloseHandle((HANDLE) d); + direct_.clear(); + return false; +#else + why = "through the file cache (not Windows)"; + return false; +#endif +} + bool FileExpertSource::read_direct(const Fill* fills, size_t n) const { #if defined(_WIN32) // NTFS runs the unbuffered reads of a file one at a time while the file is mapped or cached anywhere (the engine @@ -2033,7 +2132,8 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 } if (kind[i] >= 0) { // CUDA0, PCIe, or a remote/peer result staged into this row below if (kind[i] == 0) ++d.cache_hits; - else if (kind[i] == 2 && d.peer != nullptr) ++d.peer_entries; + else ++d.offload_entries; // #588: PCIe or another GPU + if (kind[i] == 2 && d.peer != nullptr) ++d.peer_entries; // multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it if (!(kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct())) std::memset(row, 0, (size_t) H * sizeof(float)); @@ -2581,6 +2681,37 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 } } + // #633: THE RAM BEFORE THE ALLOCATION. On Linux the arena is an anonymous mapping that succeeds whatever the host + // has; its pages are committed as the load writes them, so a container whose memory limit is below the arena was + // killed by the OOM killer part-way through the load, without a message. A hard cgroup limit below it is + // certain to end that way: refused, with the numbers. Less RAM available than the arena (another program, an + // engine still exiting) is only a warning - the OS may make room - per the recommend-not-force rule. + ram_warning_.clear(); + // (a shared arena, --shared-expert-arena, may already be in RAM for another engine: not checked) + if (detail::HostMemory hm; shared_arena_file.empty() && detail::host_available_memory(hm)) { + const uint64_t need = want + (uint64_t) blob; + const double gib = 1073741824.0; + char buf[512]; + if (hm.cgroup_limit < need) { + std::snprintf(buf, sizeof buf, + "ArenaExpertSource: the expert arena needs %.2f GiB of RAM but this process's memory limit " + "(cgroup memory.max / memory.limit_in_bytes) is %.2f GiB: it would be killed while loading. " + "Raise the container's limit, or run with less RAM: --mmap-experts with " + "--resident-budget-gib N keeps only the hottest experts in RAM", + (double) need / gib, (double) hm.cgroup_limit / gib); + err = buf; + return false; + } + if (hm.available < need) { + std::snprintf(buf, sizeof buf, + "the expert arena needs %.2f GiB of RAM but %.2f GiB is available (%.2f GiB short): the load " + "may swap or be stopped by the OS. Close other programs (or wait for an engine that is " + "still exiting), or run with less RAM: --mmap-experts with --resident-budget-gib N", + (double) need / gib, (double) hm.available / gib, (double) (need - hm.available) / gib); + ram_warning_ = buf; + } + } + uint64_t pack_hash = 0; if (!shared_arena_file.empty() && !shared_arena_pack_hash(pack_dir, path, gguf_, lay, pack_hash, err)) return false; diff --git a/src/core/pinned.cu b/src/core/pinned.cu index e28307e0..780d93fb 100644 --- a/src/core/pinned.cu +++ b/src/core/pinned.cu @@ -503,7 +503,7 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std:: } bool experts_unbuffered(const std::vector& files, uint64_t arena_bytes, std::string& why, - bool cache_counts) { + bool cache_counts, uint64_t read_bytes) { const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); if (env != nullptr && env[0] != '\0') { why = std::string("STRATA_UNBUFFERED_LOAD=") + env; @@ -551,15 +551,21 @@ bool experts_unbuffered(const std::vector& files, uint64_t arena_by GlobalMemoryStatusEx(&ms); const uint64_t avail = ms.ullAvailPhys; // what the cache could keep beside the arena (~4 GiB for everything else) - const uint64_t room = avail > arena_bytes + (4ull << 30) ? avail - arena_bytes - (4ull << 30) : 0; - const bool keepable = room >= total_bytes; - char msg[200]; - std::snprintf(msg, sizeof msg, "%d of %d probe reads from the file cache; %.1f GiB available, %.1f GiB of files", - fast, n, (double) avail / (1ull << 30), (double) total_bytes / (1ull << 30)); + const uint64_t need = read_bytes == kAllFileBytes ? total_bytes : read_bytes; + const bool keepable = strata::platform::file_cache_keeps(avail, arena_bytes, need); + char msg[256]; + if (read_bytes == kAllFileBytes) + std::snprintf(msg, sizeof msg, "%d of %d probe reads from the file cache; %.1f GiB available, %.1f GiB of files", + fast, n, (double) avail / (1ull << 30), (double) total_bytes / (1ull << 30)); + else + std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB " + "of experts read from the files: the file cache %s keep them", + (double) avail / (1ull << 30), (double) arena_bytes / (1ull << 30), (double) need / (1ull << 30), + keepable ? "can" : "cannot"); why = msg; return (!cached || !cache_counts) && !keepable; #else - (void) files; (void) arena_bytes; (void) cache_counts; + (void) files; (void) arena_bytes; (void) cache_counts; (void) read_bytes; why = "buffered (not Windows)"; return false; #endif diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 522d8670..15be7d59 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -6,6 +6,7 @@ // included unchanged. #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/dp4a.hpp" +#include "strata/kernels/q8_1_finite.hpp" #include #include @@ -1026,11 +1027,11 @@ __device__ __forceinline__ void q8_1_store(const float xi, block_q8_1* __restric amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); sum += __shfl_xor_sync(0xffffffffu, sum, o); } - const float d = amax / 127.0f; - const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const float d = q8_1_finite(amax / 127.0f); // #606: q8_1_finite.hpp - the same bits for every finite block + const int8_t q = q8_1_quant(xi, d, amax); const long long ib = i / 32, iqs = i % 32; y[ib].qs[iqs] = q; - if (iqs == 0) y[ib].ds = make_half2(d, sum); + if (iqs == 0) y[ib].ds = q8_1_ds(d, sum); } __global__ void quantize_q8_1_kernel(const float* __restrict__ x, block_q8_1* __restrict__ y, long long n) { diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index e0a4c1bd..84748179 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -25,6 +25,7 @@ #include "strata/kernels/native_mmvq.hpp" #include "strata/kernels/dp4a.hpp" +#include "strata/kernels/q8_1_finite.hpp" #include "strata/kernels/iq_kernels.hpp" #include @@ -145,10 +146,10 @@ __global__ void native_quantize_q8_1_kernel(const float* __restrict__ x, const float xi = x[i]; const float amax = warp_max(fabsf(xi)); const float sum = warp_sum(xi); - const float d = amax / 127.0f; - const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const float d = q8_1_finite(amax / 127.0f); // #606: q8_1_finite.hpp - the same bits for every finite block + const int8_t q = q8_1_quant(xi, d, amax); y[i / Q8K].qs[i % Q8K] = q; - if (i % Q8K == 0) y[i / Q8K].ds = make_half2(d, sum); + if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum); } // Exact pinned vec_dot_q5_K_q8_1_impl_vmmq expression and integer dot order. diff --git a/src/kernels/iq_multi_parity.cpp b/src/kernels/iq_multi_parity.cpp index b497b747..ace6facf 100644 --- a/src/kernels/iq_multi_parity.cpp +++ b/src/kernels/iq_multi_parity.cpp @@ -16,6 +16,7 @@ // are set, small enough that the grouped path's SwiGLU output keeps a finite fp16 q8_1 scale. #include "strata/kernels/f16_bits.hpp" #include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" #include @@ -325,6 +326,71 @@ void bench(cudaStream_t s, std::mt19937& rng) { } } +// #606: both q8_1 activation quantizers (quantize_q8_1_rows and native_quantize_q8_1) against a host transcription +// of the 0.1.38 formula: every finite block bit for bit; a block whose sum (or scale) overflowed fp16 is now stored +// finite (the largest half, its sign), with its values in the int8 range. +void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) { + const int n = 2560, rows = 3, nb = n / 32; + std::vector x = random_x((size_t) rows * n, rng); + for (int i = 0; i < 32; ++i) x[(size_t) 5 * 32 + i] = 3000.0f; // sum 96,000: overflowed + for (int i = 0; i < 32; ++i) x[(size_t) 9 * 32 + i] = i == 3 ? -70000.0f : 0.5f; // sum -69,984.5 + for (int i = 0; i < 32; ++i) x[(size_t) 13 * 32 + i] = 2000.0f + i; // sum 64,496: finite, kept + x[(size_t) n + 40] = 2.0e7f; // amax / 127 overflowed too + float* dx = dalloc(x.size()); + ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + uint8_t* dq = dalloc((size_t) rows * nb * 36); + for (int path = 0; path < 2; ++path) { + if (path == 0) k::quantize_q8_1_rows(dx, rows, n, dq, s); + else k::native_quantize_q8_1(dx, dq, n, rows, s); + ck(cudaStreamSynchronize(s), "quantize"); + std::vector got((size_t) rows * nb * 36); + ck(cudaMemcpy(got.data(), dq, got.size(), cudaMemcpyDeviceToHost), "q"); + int same = 0, clamped = 0, bad = 0; + for (int b = 0; b < rows * nb; ++b) { + const float* v = x.data() + (size_t) b * 32; + float lane[32], amax = 0.0f; + for (int i = 0; i < 32; ++i) { lane[i] = v[i]; amax = std::max(amax, std::fabs(v[i])); } + for (int o = 16; o > 0; o >>= 1) { // the warp's butterfly: every lane ends with the same sum + float nx[32]; + for (int i = 0; i < 32; ++i) nx[i] = lane[i] + lane[i ^ o]; + std::memcpy(lane, nx, sizeof lane); + } + const float d = amax / 127.0f, sum = lane[0]; + const uint8_t* g = got.data() + (size_t) b * 36; + uint16_t gd, gs; + std::memcpy(&gd, g, 2); + std::memcpy(&gs, g + 2, 2); + const uint16_t od = k::f16_from_f32(d), os = k::f16_from_f32(sum); + const bool finite_before = (od & 0x7c00) != 0x7c00 && (os & 0x7c00) != 0x7c00; + if (finite_before) { + uint8_t want[36]; + std::memcpy(want, &od, 2); + std::memcpy(want + 2, &os, 2); + for (int i = 0; i < 32; ++i) // CUDA's roundf: half away from zero, as std::round + want[4 + i] = (uint8_t) (int8_t) (amax == 0.0f ? 0.0f : std::round(v[i] / d)); + // native_mmvq.cu is built with --use_fast_math (its divisions are approximate): there the sum must be + // the same bits, the scale within one fp16 step and each value within one step + bool near = path == 1 && gs == os && std::abs((int) gd - (int) od) <= 1; + for (int i = 0; near && i < 32; ++i) near = std::abs((int) (int8_t) g[4 + i] - (int) (int8_t) want[4 + i]) <= 1; + if (std::memcmp(want, g, 36) == 0 || near) ++same; + else { ++bad; std::printf(" q8_1 path %d block %d: changed although it was finite\n", path, b); } + } else { + const float fd = k::f32_from_f16(gd), fs = k::f32_from_f16(gs); + bool ok = std::isfinite(fd) && std::isfinite(fs) && fd > 0.0f && + ((os & 0x7c00) != 0x7c00 ? gs == os : std::fabs(fs) == 65504.0f && (fs < 0) == (sum < 0)); + for (int i = 0; i < 32; ++i) ok = ok && (int8_t) g[4 + i] >= -127 && (int8_t) g[4 + i] <= 127; + if (ok) ++clamped; + else { ++bad; std::printf(" q8_1 path %d block %d: d %g sum %g not finite and clamped\n", path, b, fd, fs); } + } + } + std::printf("q8_1 finite (%s): %d finite blocks as before, %d overflowed blocks clamped finite%s\n", + path == 0 ? "quantize_q8_1_rows" : "native_quantize_q8_1", same, clamped, bad ? " FAIL" : ""); + g_fail += bad + (clamped != 3); + } + cudaFree(dx); + cudaFree(dq); +} + } // namespace int main(int argc, char** argv) { @@ -340,6 +406,7 @@ int main(int argc, char** argv) { for (int dt : {20, 42}) check_grouped(gu, dt, 2560, 640, s, rng); // the model's shape check_grouped(gu, 23, 1024, 512, s, rng); // IQ4_XS down needs n_ff % 256 == 0 } + check_q8_1_finite(s, rng); if (do_bench) bench(s, rng); std::printf("iq_multi_parity: %d failures\n", g_fail); cudaStreamDestroy(s); diff --git a/src/platform/memory_test.cpp b/src/platform/memory_test.cpp index e5b4cde7..7346189d 100644 --- a/src/platform/memory_test.cpp +++ b/src/platform/memory_test.cpp @@ -13,7 +13,44 @@ #pragma comment(lib, "psapi.lib") #endif +namespace { +uint64_t gib(double g) { return (uint64_t) (g * 1073741824.0); } + +// #577: the file tier's unbuffered choice (true = the file cache keeps its reads, so they stay buffered) +int file_cache_keeps_cases() { + using strata::platform::file_cache_keeps; + struct Case { const char* what; double avail, arena, read; bool keeps; }; + const double experts = 71.7; // UD-Q4_K_XL's routed experts + const Case cases[] = { + // the reporter's 96 GB PC (83.0 GiB available at start): 0.1.38 passed the budget asked for and every + // shard's bytes (103.7 GiB) and went unbuffered + {"96 GB, 0.1.38's inputs (budget 72, all shards)", 83.0, 72.0, 103.7, false}, + {"96 GB, budget 72, before the copy (arena = all experts)", 83.0, experts, 0.0, true}, + {"96 GB, budget 72, copy built (48.94 resident)", 83.0 - 48.94, 0.0, experts - 48.94, true}, + {"96 GB, budget 40, before the copy", 83.0, 40.0, experts - 40.0, true}, + {"96 GB, budget 40, copy built", 83.0 - 40.0, 0.0, experts - 40.0, true}, + // #357/#362's low-RAM PCs stay unbuffered + {"64 GB, budget 40, before the copy", 55.0, 40.0, experts - 40.0, false}, + {"64 GB, budget 40, copy built", 15.0, 0.0, experts - 40.0, false}, + {"32 GB, budget 16, before the copy", 26.0, 16.0, experts - 16.0, false}, + {"32 GB, budget 16, copy built", 10.0, 0.0, experts - 16.0, false}, + {"32 GB, Q2_0 pack (34 GiB experts), budget 8", 26.0, 8.0, 34.0 - 8.0, false}, + {"nothing available", 0.0, 0.0, 1.0, false}, + {"arena larger than the RAM", 10.0, 20.0, 0.0, true}, + }; + int fail = 0; + for (const Case& c : cases) { + const bool got = file_cache_keeps(gib(c.avail), gib(c.arena), gib(c.read)); + std::printf("file_cache_keeps %-58s -> %s%s\n", c.what, got ? "buffered" : "unbuffered", + got == c.keeps ? "" : " <-- WRONG"); + fail |= got != c.keeps; + } + return fail; +} +} // namespace + int main() { + int fail_keeps = file_cache_keeps_cases(); const uint64_t bytes = 256ull << 20; void* p = std::malloc(bytes); if (p == nullptr) return 2; @@ -21,7 +58,7 @@ int main() { const strata::platform::LockResult r = strata::platform::lock_resident(p, bytes); std::printf("lock_resident: ok=%d locked=%llu MiB (%s)\n", (int) r.ok, (unsigned long long) (r.locked_bytes >> 20), r.note.c_str()); - int fail = !(r.ok && r.locked_bytes == bytes); + int fail = !(r.ok && r.locked_bytes == bytes) | fail_keeps; #if defined(_WIN32) PROCESS_MEMORY_COUNTERS pmc{}; GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a7c77d0e..b342b6fb 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -70,6 +70,8 @@ #else #include #include +#include +#include #endif #include @@ -113,6 +115,20 @@ bool under_wddm() { #endif } +// #620 #486: " (N MiB of M MiB VRAM free on this GPU)" for an allocation's failure message (clears the error first) +std::string vram_free_note() { + (void) cudaGetLastError(); + size_t free_b = 0, total_b = 0; + if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) { + (void) cudaGetLastError(); + return {}; + } + char buf[96]; + std::snprintf(buf, sizeof buf, " (%llu MiB of %llu MiB VRAM free on this GPU)", (unsigned long long) (free_b >> 20), + (unsigned long long) (total_b >> 20)); + return buf; +} + // perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each bool refill_blocking() { static const bool v = std::getenv("STRATA_REFILL_BLOCKING") != nullptr; @@ -791,6 +807,55 @@ std::string stage_text() { return s; } +#if !defined(_WIN32) +// #605: whether `path` is on a rotational disk (1), not (0) or unknown (-1), from sysfs; `dev` is the disk's name +int on_rotational_disk(const std::string& path, std::string& dev) { + struct stat st{}; + if (::stat(path.c_str(), &st) != 0) return -1; + char sys[64]; + std::snprintf(sys, sizeof sys, "/sys/dev/block/%u:%u", (unsigned) major(st.st_dev), (unsigned) minor(st.st_dev)); + std::error_code ec; + std::filesystem::path p = std::filesystem::canonical(sys, ec); + for (int up = 0; !ec && up < 2; ++up, p = p.parent_path()) { // a partition has its disk's queue + std::ifstream q(p / "queue" / "rotational"); + int r = -1; + if (q >> r) { + dev = p.filename().string(); + return r; + } + } + return -1; +} + +// #605: the engine's threads in uninterruptible sleep (state D - almost always waiting for the disk), and where +// (wchan): 16 threads in blk_io_schedule is a disk that cannot keep up, not a deadlock in the engine +void disk_wait_threads(std::FILE* f) { + std::map where; + int waiting = 0, threads = 0; + std::error_code ec; + for (const auto& e : std::filesystem::directory_iterator("/proc/self/task", ec)) { + ++threads; + std::ifstream st(e.path() / "stat"); + std::string line; + std::getline(st, line); + const size_t rp = line.rfind(')'); + if (rp == std::string::npos || rp + 2 >= line.size() || line[rp + 2] != 'D') continue; + ++waiting; + std::ifstream w(e.path() / "wchan"); + std::string wc; + std::getline(w, wc); + ++where[wc.empty() || wc == "0" ? "?" : wc]; + } + if (threads == 0) return; + std::string list; + for (const auto& [name, n] : where) list += (list.empty() ? " (" : ", ") + name + " x" + std::to_string(n); + if (!list.empty()) list += ")"; + std::fprintf(f, " threads waiting on the disk (state D): %d of %d%s%s\n", waiting, threads, list.c_str(), + waiting > 0 ? " - the engine is waiting for the drive: a rotational or failing disk with --ple-io " + "direct (#605: --ple-io ram), or a drive too slow for the reads asked of it" : ""); +} +#endif + void stall_report(std::FILE* f, uint64_t layers_during) { strata::core::Progress& p = strata::core::progress(); std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the " @@ -804,6 +869,9 @@ void stall_report(std::FILE* f, uint64_t layers_during) { } if (auto fn = strata::core::diag_pool_fn().load()) fn(f); if (auto fn = strata::core::diag_verify_fn().load()) fn(f); +#if !defined(_WIN32) + disk_wait_threads(f); +#endif const MemSample m = mem_sample(); std::fprintf(f, " memory: %llu MiB resident, %llu MiB %s, %llu MiB RAM available; %llu %s\n", m.rss_mib, m.commit_mib, @@ -1402,7 +1470,9 @@ int main(int argc, char** argv) { } if (!ok) { std::fprintf(stderr, "strata generate: --layer-split K[,K2..]|auto needs --serve, rising K from 2, and one " - "distinct GPU per K in --split-device (1..%d; or 0 with one K: the same GPU)\n", n_dev - 1); + "distinct GPU per K in --split-device (1..%d; or 0 with one K: the same GPU). K is the " + "FIRST LAYER of each later GPU, not a count of layers per card: \"24,36,42\" for 4 " + "GPUs, not \"24,12,6,6\" (got \"%s\")\n", n_dev - 1, o.layer_split.c_str()); return 2; } } @@ -2156,6 +2226,18 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } +#if !defined(_WIN32) + if (pio.mode == strata::kernels::PleIo::Direct) { + // #605: --ple-io direct's random reads (up to --ple-inflight at once) are for SSDs; a rotational disk + // can take longer than the stall watchdog's 60 s for one prompt chunk's rows. Recommended, not forced. + std::string dev; + if (!under_wddm() && on_rotational_disk(o.ple_gguf, dev) == 1) // (WSL's virtual disk says rotational) + std::fprintf(stderr, "strata generate: WARNING: the n-gram table (%s) is on a rotational disk (%s): " + "--ple-io direct reads it at random and can stall a prompt for minutes (#605). " + "--ple-io ram (it then needs RAM for the table) or the model on an SSD is " + "recommended\n", o.ple_gguf.c_str(), dev.c_str()); + } +#endif if (pio.lock) std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", ple_table.locked() ? "locked in RAM" : "loaded (not locked)", @@ -2637,8 +2719,9 @@ int main(int argc, char** argv) { const strata::core::WeightRef* wo_s = st.wt.find("output.weight"); if (wo_s == nullptr || (last && !o.native_head_gguf.empty() && !st.head.load(o.native_head_shards, g.n_embd, wo_s->ne1, err))) { - std::fprintf(stderr, "strata generate: layer split, CUDA%d head: %s\n", st.dev, - wo_s == nullptr ? "output.weight is missing" : err.c_str()); + std::fprintf(stderr, "strata generate: layer split, CUDA%d head: %s%s\n", st.dev, + wo_s == nullptr ? "output.weight is missing" : err.c_str(), + wo_s == nullptr ? "" : vram_free_note().c_str()); return 1; } size_t fb = 0, tb = 0; @@ -2662,7 +2745,32 @@ int main(int argc, char** argv) { static const strata::core::ModelGeometry draft_geometry{}; // with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device const strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1); - if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; } + } + // THE HEAD BEFORE THE CACHE, AND BEFORE THE ARENA. The expert cache takes what is free minus the reserve, so + // everything allocated after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after + // it and ate most of the 700 MiB: 128K IQ3_S ended with 30 MiB free, the driver paged, and a request stalled for + // good at its first verify window. Loaded first, the cache is sized around it. #620: and before the expert + // arena registers tens of GiB of host pages, like the drafter above - WDDM then refused the head's cudaMalloc on + // a 16 GB card with the desktop on the iGPU ("native head upload: out of memory" with GiBs free). + const strata::core::WeightRef* wo = wt.find("output.weight"); + if (wo == nullptr) { std::fprintf(stderr, "strata generate: output.weight is missing\n"); return 1; } + const int64_t n_vocab = wo->ne1; + strata::core::NativeHead native_head; + if (!o.native_head_gguf.empty() && !multi_gpu) { // a layer split's head is on its last stage + if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) { + std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: experimental native Q5_K head, %llu bytes\n", + (unsigned long long) native_head.weight_bytes()); + } + std::vector logits((size_t) n_vocab); + float* d_logits = nullptr; + if (cudaMalloc(&d_logits, (size_t) n_vocab * 4) != cudaSuccess) { + (void) cudaGetLastError(); + std::fprintf(stderr, "strata generate: the logits buffer failed%s\n", vram_free_note().c_str()); + return 1; } // Create the additional contexts after MTP has secured CUDA0 memory, but // before the host arena maps its expert pages into their address spaces. @@ -2785,6 +2893,8 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + if (!arena_src.ram_warning().empty()) // #633: said before the load's numbers, which it explains + std::fprintf(stderr, "strata generate: WARNING: %s\n", arena_src.ram_warning().c_str()); std::fprintf(stderr, "strata generate: expert arena: %s\n", arena_src.note().c_str()); std::fprintf(stderr, "strata generate: loaded %.2f GiB at %.2f GiB/s\n", (double) strata::kernels::cpu::expert_layout().total / (1024.0 * 1024 * 1024), @@ -2819,28 +2929,7 @@ int main(int argc, char** argv) { // numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for. mem_mark("the weights, the session and the drafter"); strata::core::ExpertCache xcache; - // THE HEAD BEFORE THE CACHE. The expert cache takes what is free minus the reserve, so everything allocated - // after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after it and ate most of - // the 700 MiB: 128K IQ3_S ended with 30 MiB free, the driver paged, and a request stalled for good at its first - // verify window. Loaded first, the cache is sized around it. - const strata::core::WeightRef* wo = wt.find("output.weight"); - if (wo == nullptr) { std::fprintf(stderr, "strata generate: output.weight is missing\n"); return 1; } - const int64_t n_vocab = wo->ne1; - strata::core::NativeHead native_head; - if (!o.native_head_gguf.empty() && !multi_gpu) { // a layer split's head is on its last stage - if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - std::fprintf(stderr, "strata generate: experimental native Q5_K head, %llu bytes\n", - (unsigned long long) native_head.weight_bytes()); - } - std::vector logits((size_t) n_vocab); - float* d_logits = nullptr; - if (cudaMalloc(&d_logits, (size_t) n_vocab * 4) != cudaSuccess) { - std::fprintf(stderr, "strata generate: the logits buffer failed\n"); - return 1; - } + // THE HEAD BEFORE THE CACHE: the native head and the logits are allocated above, before the expert arena (#620) const bool auto_cache = o.expert_cache < 0; bool reserve_adapted = false; // #496: the auto sizing lowered the reserve so a small card's cache fits if (o.expert_cache < 0) { @@ -3617,7 +3706,12 @@ int main(int argc, char** argv) { strata::core::doorbell_reset(db); double mix = 0, ffn = 0, post = 0; if (!strata::core::session_replay_stages(g, 0, 0, ss, gr, main_cs, mix, ffn, post, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + // #610: a native (IQ) pack captures no per-layer graphs; the serve path times its window's stages + std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), + native_pack ? " - a native (IQ) pack has no per-layer graphs to replay. Its decode window's GPU " + "stages are printed per request by the serve path instead: STRATA_VERIFY_PROFILE=1 " + "STRATA_DECODE_TIMING=1 with --serve (docs/DETAILS.md, \"Where a decode window's " + "time goes\")" : ""); return 1; } const int reps = 20; @@ -4082,6 +4176,19 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); return 1; } + // #577: the unbuffered choice above was made before the RAM copy existed, from the budget asked for; now the + // copy is built, decide again from the RAM it really holds and the expert bytes outside it (on a 96 GB PC + // the file cache keeps those, and every refill after a prompt read the drive instead). Windows only: the + // unbuffered reads exist there alone +#if defined(_WIN32) + if (o.mmap_experts && o.resident_budget > 0) { + std::string why; + const bool was = src.unbuffered(); + const bool ub = src.recheck_unbuffered(why); + std::fprintf(stderr, "strata generate: the file tier reads %s%s (%s)\n", + ub ? "unbuffered" : "through the file cache", ub == was ? "" : " (changed)", why.c_str()); + } +#endif } if (o.serve) { if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 || @@ -5698,6 +5805,7 @@ int main(int argc, char** argv) { const int64_t ram0 = src.ram_reads(), files0 = src.file_reads(); const uint64_t file_bytes0 = src.file_read_bytes(); const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused; + const int64_t offload0 = drive.d.offload_entries; // #588 if (cancelled) finish = "cancel"; while (!cancelled && produced_n < max_new) { int T = S_mtp; @@ -5945,6 +6053,7 @@ int main(int argc, char** argv) { } const int64_t req_hits = drive.d.cache_hits - decode_hits0; const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0; + const int64_t req_offload = drive.d.offload_entries - offload0; // #471: the prompt tokens this request read - all the fresh ones, or as far as the prompt pass got when a // cancel stopped it part-way (a cancelled request used to be logged and counted as having read them all) const int64_t fresh = n - resume; @@ -5952,11 +6061,15 @@ int main(int argc, char** argv) { // DONE [hits] [lookups] // [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest) // [prompt tokens read] (#471: fewer than - when a cancel stopped the read) - std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld\n", (long long) produced_n, + // [offloaded] (#588: the decode's routed experts the GPU read over PCIe or another GPU computed; + // not in [lookups]) + std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld\n", + (long long) produced_n, (long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered, (long long) resume, (long long) req_hits, (long long) req_look, (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), - (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n); + (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n, + (long long) req_offload); std::fflush(stdout); if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session // "12288 of 98179" when cancelled mid-read (#471), the rate from what was read @@ -5972,11 +6085,18 @@ int main(int argc, char** argv) { decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0, (long long) draft_accepted, (long long) draft_offered, checks.size(), cancelled ? " (cancelled)" : ""); // the VRAM share of the experts the pool looked up while decoding; experts it sent over PCIe for the GPU - // to read (--pcie-frac) are in neither count + // to read (--pcie-frac) are in neither count - #588: so that share is said beside it (raising --pcie-frac + // raises the hit rate while the PCIe reads may make the decode slower) if (req_look > 0) { - std::fprintf(stderr, "strata serve: decode expert cache hit rate: %.1f%% (%lld hits / %lld lookups)\n", + char off[160] = ""; + if (req_offload > 0) + std::snprintf(off, sizeof off, "; %lld more read by the GPU over PCIe or from another GPU (%.1f%% of " + "all %lld routed)", (long long) req_offload, + 100.0 * (double) req_offload / (double) (req_look + req_offload), + (long long) (req_look + req_offload)); + std::fprintf(stderr, "strata serve: decode expert cache hit rate: %.1f%% (%lld hits / %lld lookups)%s\n", 100.0 * (double) req_hits / (double) req_look, - (long long) req_hits, (long long) req_look); + (long long) req_hits, (long long) req_look, off); } // the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain // mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it) diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp index e86acc16..104507d1 100644 --- a/tests/core/file_expert_source_test.cpp +++ b/tests/core/file_expert_source_test.cpp @@ -288,6 +288,56 @@ void test_cgroup_memory_budget() { "missing memory.stat counters did not fail closed"); } +// #633: the host RAM probe with fake /proc and cgroup trees: v2 (a limit, "max", a missing or malformed limit), v1 +// (a limit, unlimited), and no cgroup line at all. Elsewhere than Linux it reads the machine's RAM. +void test_host_memory() { + using namespace strata::core::detail; + constexpr uint64_t GiB = 1ull << 30; + HostMemory m; +#if defined(__linux__) + TempDirectory t; + auto put = [&](const fs::path& rel, const std::string& text) { + fs::create_directories((t.path / rel).parent_path()); + std::ofstream(t.path / rel) << text; + }; + put("meminfo", "MemTotal: 134217728 kB\nMemAvailable: 104857600 kB\n"); // 100 GiB available + const std::string mi = (t.path / "meminfo").string(), cg = (t.path / "cgroup").string(), + root = (t.path / "fs").string(); + auto probe = [&](const std::string& self) { + put("cgroup", self); + return host_available_memory(m, mi, cg, root); + }; + // no cgroup line at all: MemAvailable alone (before #633: "cannot determine") + require(probe("") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "no cgroup: MemAvailable alone"); + // v2, a 48 GiB limit with 16 GiB charged, 4 GiB of it clean cache + put("fs/cgroup.controllers", "memory\n"); + put("fs/box/memory.max", std::to_string(48 * GiB) + "\n"); + put("fs/box/memory.current", std::to_string(16 * GiB) + "\n"); + put("fs/box/memory.stat", "inactive_file " + std::to_string(4 * GiB) + "\nfile_dirty 0\nfile_writeback 0\n"); + require(probe("0::/box\n") && m.available == 36 * GiB && m.cgroup_limit == 48 * GiB, "v2 limit"); + put("fs/box/memory.max", "max\n"); + require(probe("0::/box\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v2 max"); + put("fs/box/memory.max", "48G\n"); + require(!probe("0::/box\n"), "v2 malformed limit accepted"); + fs::remove(t.path / "fs/box/memory.max"); + require(!probe("0::/box\n"), "v2 group without memory.max accepted"); + // v1: the memory controller's group (a hybrid line list), a 32 GiB limit with 10 GiB used + put("fs/memory/docker/abc/memory.limit_in_bytes", std::to_string(32 * GiB) + "\n"); + put("fs/memory/docker/abc/memory.usage_in_bytes", std::to_string(10 * GiB) + "\n"); + put("fs/memory/memory.limit_in_bytes", "9223372036854771712\n"); // the root: unlimited + put("fs/memory/memory.usage_in_bytes", std::to_string(50 * GiB) + "\n"); + require(probe("12:cpu,cpuacct:/docker/abc\n4:memory:/docker/abc\n1:name=systemd:/docker/abc\n") && + m.available == 22 * GiB && m.cgroup_limit == 32 * GiB, "v1 limit"); + put("fs/memory/docker/abc/memory.limit_in_bytes", "9223372036854771712\n"); + require(probe("4:memory:/docker/abc\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v1 unlimited"); + // a v1 group not visible here (another namespace): MemAvailable alone + require(probe("4:memory:/elsewhere\n") && m.available == 100 * GiB, "v1 group not mounted"); +#else + require(host_available_memory(m) && m.available > 0 && m.cgroup_limit == ~0ull, "this PC's RAM"); + (void) GiB; +#endif +} + } // namespace int main() { @@ -296,6 +346,7 @@ int main() { test_resident_lend_region(); test_resident_exchange(); test_cgroup_memory_budget(); + test_host_memory(); test_canonical_layout(); #if defined(STRATA_NATIVE_EXPERTS) test_native_variable_layout(); diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 811c9bcf..6aa67f94 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -62,6 +62,9 @@ FALLBACK_MODELS = { "UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), EXPERIMENTAL: the best quality, but most experts come from the " "SSD on a 64 GB PC (7-8.5 tokens/s measured)", "download_gb": 111.3, "ram_gb": 48, "arena_gb": 77.0, "families": ("unsloth",), "budget": True}, + "UD-IQ4_XS": {"about": "~4-bit i-quant (Unsloth Dynamic), EXPERIMENTAL: between IQ3_S and UD-Q4_K_XL; part of " + "its experts come from the SSD on a 64 GB PC (not measured on NVIDIA yet)", + "download_gb": 93.7, "ram_gb": 48, "arena_gb": 59.5, "families": ("unsloth",), "budget": True}, } FALLBACK_FAMILIES = { "qwen": {"title": "Qwen3.8-Flash-Next", "about": "the original model", "tag": ""}, @@ -69,8 +72,9 @@ FALLBACK_FAMILIES = { "authors' numbers)", "tag": "swift-"}, "coder": {"title": "Qwen3.8-Flash-Next Coder", "about": "half the experts (code, tools, images kept): needs ~32 GB " "of RAM, faster; weaker outside coding", "tag": "coder-"}, - "unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "about": "4-bit, 111 GB download, most experts read from the " - "SSD: slow (7-8.5 tokens/s on a 64 GB PC)", + "unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "about": "UD-Q4_K_XL (111 GB download) or UD-IQ4_XS (94 GB); " + "part of the experts read from the SSD: slower " + "(UD-Q4_K_XL: 7-8.5 tokens/s on a 64 GB PC)", "tag": "unsloth-", "experimental": True, "vision": False}, } FALLBACK_CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288] diff --git a/tools/test_setup_choices.py b/tools/test_setup_choices.py index c7736b34..17b5487e 100644 --- a/tools/test_setup_choices.py +++ b/tools/test_setup_choices.py @@ -122,7 +122,7 @@ class GgufDirUnsupported(unittest.TestCase): self.assertEqual(msg, "Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf is UD-IQ3_XXS, a GGUF Strata " "cannot run") self.assertIn("ISTA-DASLab's GSQ-RCO files", hint) - self.assertIn("Unsloth's UD-Q4_K_XL only", hint) + self.assertIn("Unsloth's UD-Q4_K_XL and UD-IQ4_XS only", hint) def test_a_folder_without_the_choice_names_what_is_there(self): gsq = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-%05d-of-00002.gguf" % i for i in (1, 2)] @@ -145,7 +145,7 @@ class GgufDirUnsupported(unittest.TestCase): code, out, _, _ = install(ram, found, ["--gguf-dir", d, "--family", "unsloth", "--model", "IQ3_XXS"]) self.assertEqual(code, 1) self.assertIn("has no IQ3_XXS model file", out) - self.assertIn("choose one of: UD-Q4_K_XL (or IQ3_XXS: --family qwen --model IQ3_XXS, --family swift --model " + self.assertIn("choose one of: UD-Q4_K_XL, UD-IQ4_XS (or IQ3_XXS: --family qwen --model IQ3_XXS, --family swift --model " "IQ3_XXS)", out) self.assertIn("Strata runs ISTA-DASLab's GSQ-RCO files", out) @@ -189,6 +189,23 @@ class ExperimentalSm60(unittest.TestCase): mock.patch.object(setup, "out", lambda cmd: versions.get(cmd[0], "")): # #414 self.assertEqual(setup.find_nvcc(), (str(new), (13, 0))) self.assertEqual(setup.find_nvcc(below=(13, 0)), (str(old), (12, 9))) + # #601: STRATA_NVCC is the only one considered; CUDA_HOME is a candidate like CUDA_PATH + with mock.patch.dict(os.environ, {"STRATA_NVCC": str(old)}): + self.assertEqual(setup.find_nvcc(), (str(old), (12, 9))) + with mock.patch.dict(os.environ, {"STRATA_NVCC": str(new)}): + got, text = quiet(setup.find_nvcc, below=(13, 0)) + self.assertEqual(got, (None, None)) + self.assertIn("needs one older than 13.0", text) + with mock.patch.dict(os.environ, {"STRATA_NVCC": str(Path(d) / "missing")}): + got, text = quiet(setup.find_nvcc) + self.assertEqual(got, (str(new), (13, 0))) + self.assertIn("no such file", text) + with mock.patch.object(setup, "WIN", False), mock.patch.object(setup.shutil, "which", lambda n: None), \ + mock.patch.dict(os.environ, {"CUDA_HOME": str(Path(d) / "12")}), \ + mock.patch.object(setup, "out", lambda cmd: versions.get(cmd[0], "")): + os.environ.pop("CUDA_PATH", None) + got = setup.find_nvcc(below=(13, 0)) + self.assertEqual(got, (str(old), (12, 9))) def tools(self, archs, nvcc): seen = [] @@ -267,6 +284,40 @@ class HipVision(unittest.TestCase): self.assertNotIn("vision_src", meta) +class RotationalDisk(unittest.TestCase): + """#605: a model on a rotational disk gets --ple-io ram when the n-gram table fits the RAM, else a warning.""" + + def install(self, ram, disk): + from test_setup_golden import PROFILES, install + _, found = PROFILES["64GB-1x32GB"] + return install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"], + extra=[mock.patch.object(setup, "rotational_disk", lambda p: disk)]) + + def test_fits(self): + code, out, cfg, _ = self.install(127.8, "sdb") + self.assertEqual(code, 0, out) + a = cfg["args"] + self.assertEqual(a[a.index("--ple-io") + 1], "ram") + self.assertIn("rotational disk (sdb)", out) + + def test_does_not_fit(self): + code, out, cfg, _ = self.install(63.7, "sdb") + self.assertEqual(code, 0, out) + self.assertNotIn("--ple-io", cfg["args"]) + self.assertIn("An SSD is recommended", out) + + def test_ssd(self): + code, out, cfg, _ = self.install(127.8, None) + self.assertNotIn("--ple-io", cfg["args"]) + self.assertNotIn("rotational", out) + + def test_sysfs(self): + if not sys.platform.startswith("linux"): + self.assertIsNone(setup.rotational_disk(__file__)) # Windows: never + return + self.assertIn(setup.rotational_disk(__file__), (None,) + tuple(os.listdir("/sys/block"))) + + class VramReserve(unittest.TestCase): """#493: --vram-reserve-mib N - VRAM the engine leaves free for other programs - goes into the config only when given (the default config is tools/test_setup_golden.py's, unchanged), at setup and on a start.""" diff --git a/tools/test_setup_golden.py b/tools/test_setup_golden.py index 054c1c14..136b156d 100644 --- a/tools/test_setup_golden.py +++ b/tools/test_setup_golden.py @@ -102,6 +102,7 @@ def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()): mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, avx512)), mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "is_wsl", lambda: False), + mock.patch.object(setup, "rotational_disk", lambda p: None), # #605: the test PC's own disk mock.patch.object(setup, "free_gb", lambda p: 900.0), mock.patch.object(setup, "pip_install", lambda *a, **k: None), mock.patch.object(setup, "get_llama_cpp", lambda: t / "llama.cpp"), diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index a010b5e8..dab1e74c 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -126,7 +126,7 @@ class FakeGGUF: self.tensors = [types.SimpleNamespace(name=n) for n in names] -class Main(unittest.TestCase): +class Base(unittest.TestCase): """setup.main() for the Unsloth choice, every outside effect mocked.""" def setUp(self): @@ -139,7 +139,7 @@ class Main(unittest.TestCase): def tearDown(self): self.tmp.cleanup() - def main(self, argv, ram=63.7, version="0.1.32", n_gpus=1, model=True, amd=(), free=500.0): + def main(self, argv, ram=63.7, version="0.1.32", n_gpus=1, model=True, amd=(), free=500.0, m=M): eng = self.t / "engine" eng.mkdir(exist_ok=True) (eng / "BUILD.json").write_text(json.dumps({"version": version, "source": "local"})) @@ -166,6 +166,7 @@ class Main(unittest.TestCase): mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, True)), mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "free_gb", lambda p: free), + mock.patch.object(setup, "rotational_disk", lambda p: None), # #605: not the test PC's disk mock.patch.object(setup, "pip_install", lambda *a, **k: None), mock.patch.object(setup, "get_llama_cpp", lambda: self.t / "llama.cpp"), mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng), @@ -178,7 +179,7 @@ class Main(unittest.TestCase): mock.patch.object(setup, "saved_calibration", lambda cfg: None), mock.patch.object(setup, "start", mock.Mock(side_effect=AssertionError("started"))), mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}), - mock.patch.object(sys, "argv", ["setup.py", "--family", "unsloth", *(["--model", M] if model else []), + mock.patch.object(sys, "argv", ["setup.py", "--family", "unsloth", *(["--model", m] if model else []), "--yes", "--no-start", "--models-dir", str(self.t / "models"), *argv]), mock.patch("builtins.input", mock.Mock(side_effect=AssertionError("asked"))), @@ -187,9 +188,12 @@ class Main(unittest.TestCase): for p in patches: st.enter_context(p) code, out = quiet(setup.main) - cfg = self.t / "strata-unsloth-ud-q4_k_xl.json" + cfg = self.t / f"strata-unsloth-{m.lower()}.json" return code, out, (json.loads(cfg.read_text()) if cfg.exists() else None) +class Main(Base): + """UD-Q4_K_XL.""" + def test_install(self): code, out, cfg = self.main(["--context", "8192"]) self.assertEqual(code, 0, out) @@ -357,6 +361,76 @@ class Main(unittest.TestCase): self.assertIn("--resident-budget-gib", cfg["args"]) +X = "UD-IQ4_XS" + + +class IQ4XS(Base): + """#621 (EXPERIMENTAL): Unsloth's UD-IQ4_XS - three pinned shards, the same RAM-budget setup as UD-Q4_K_XL (the + pack with --compat-bf16, never experts.bin, one GPU, no images), engine 0.1.38 or newer, no AMD question.""" + + def test_pins(self): + fam = setup.FAMILIES["unsloth"] + names = [setup.model_file(fam, X, i) for i in range(1, setup.model_shards(fam, X) + 1)] + self.assertEqual(names, list(setup.UNSLOTH_IQ4_XS_SHARDS)) + self.assertEqual(sum(b for b, _ in setup.UNSLOTH_IQ4_XS_SHARDS.values()), 93682584224) + for n, (size, sha) in setup.UNSLOTH_IQ4_XS_SHARDS.items(): + self.assertRegex(sha, r"^[0-9a-f]{64}$") + self.assertEqual(fam["sha256"][n], (size, sha)) + for n in setup.UNSLOTH_SHARDS: # UD-Q4_K_XL's are still there + self.assertEqual(fam["sha256"][n], setup.UNSLOTH_SHARDS[n]) + self.assertAlmostEqual(setup.MODELS[X]["download_gb"], 93682584224 / 1e9, places=1) + self.assertEqual(setup.MODELS[X]["families"], ("unsloth",)) + self.assertEqual([m for m in setup.MODELS if "unsloth" in setup.MODELS[m].get("families", ())], [M, X]) + self.assertIsNone(setup.gguf_unsupported(names[0])) # #444: a file setup runs now + self.assertEqual(setup.gguf_choice(names[0]), ("unsloth", X)) + self.assertEqual(setup.budget_model({"args": ["--native", "/m/" + names[0]]}), X) + self.assertEqual(setup.budget_model({"args": ["--native", "/m/" + list(setup.UNSLOTH_SHARDS)[0]]}), M) + self.assertEqual(setup.budget_model({"args": []}), M) + + def test_budget(self): + self.assertEqual(setup.resident_budget_gib(X, 63.7), 40) + self.assertEqual(setup.resident_budget_gib(X, 95.8), 55) # at most all of them (59.5 GB) + self.assertAlmostEqual(setup.unsloth_split_need_gb(X), 93.7 + setup.UNSLOTH_RAM_LEFT_GB) + + def test_install(self): + code, out, cfg = self.main(["--context", "8192"], version="0.1.38", m=X) + self.assertEqual(code, 0, out) + self.assertIn("EXPERIMENTAL", out) + base = f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-IQ4_XS/" + self.assertEqual(self.downloads, [base + n for n in setup.UNSLOTH_IQ4_XS_SHARDS]) + self.assertEqual(self.verified, [(n, *v) for n, v in setup.UNSLOTH_IQ4_XS_SHARDS.items()]) + packs = [r for r in self.runs if r[1].endswith("iq_pack.py")] + self.assertEqual(len(packs), 1, self.runs) + self.assertIn("--compat-bf16", packs[0]) + self.assertNotIn("--experts-bin", packs[0]) + self.assertTrue(packs[0][packs[0].index("--gguf") + 1].endswith("UD-IQ4_XS-00001-of-00003.gguf")) + args = cfg["args"] + self.assertEqual(args[args.index("--resident-budget-gib") + 1], "40") + self.assertTrue(args[args.index("--native") + 1].endswith("UD-IQ4_XS-00001-of-00003.gguf")) + for flag in ("--ple-gguf", "--mmap-experts", "--resident-experts", "--vision"): + self.assertNotIn(flag, args) + self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-ud-iq4_xs") + with tempfile.TemporaryDirectory() as t: # a start reads the choice back + p = Path(t) / "strata-unsloth-ud-iq4_xs.json" + p.write_text(json.dumps(cfg)) + ch = setup.choices_from_config(p) + self.assertEqual((ch["family"], ch["model"]), ("unsloth", X)) + + def test_engine_0138(self): + code, out, cfg = self.main(["--context", "8192"], version="0.1.37", m=X) + self.assertEqual(code, 1) + self.assertIn("needs engine 0.1.38 or newer; this one is 0.1.37", out) + self.assertEqual(self.downloads, []) + + def test_amd_is_not_asked(self): + r9700 = [{"index": 0, "name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "arch": "gfx1201", + "driver": "amdgpu"}] + with mock.patch.object(setup, "get_prebuilt_hip", lambda *a, **k: self.t / "engine"): + code, out, cfg = self.main(["--context", "8192", "--backend", "hip"], version="0.1.38", amd=r9700, m=X) + self.assertNotIn("has not been run on AMD cards yet", out) + self.assertIn("RAM budget: 40 GiB of UD-IQ4_XS's experts", out) + + class LayerSplit(unittest.TestCase): """#498: UD-Q4_K_XL across GPUs - asked at setup (one GPU by default), and a start with --gpus no longer keeps the RAM budget the engine refuses with a split (it exited with code 2)."""