diff --git a/bench/results/2026-10-04-windows-mapped-release/README.md b/bench/results/2026-10-04-windows-mapped-release/README.md new file mode 100644 index 00000000..c6ebc26e --- /dev/null +++ b/bench/results/2026-10-04-windows-mapped-release/README.md @@ -0,0 +1,143 @@ +# Windows mapped expert-page release + +Measured October 4, 2026, against upstream `6f32ec070f23ced9f50e704d854d775da52591ab` (0.1.39). +The same patched executable was run with `STRATA_FILE_RELEASE=0` and `STRATA_FILE_RELEASE=1`. +Releasing file-backed expert pages after GPU copies substantially increased available physical RAM on this +machine. Prefill was slightly slower. This is a memory-pressure improvement, not a general speed claim. + +## What changes + +Windows `FileExpertSource::release()` uses `VirtualUnlock` on complete interior pages of its read-only file views. +Windows documents that unlocked pages are removed from the process working set even when the call returns +`FALSE` with `ERROR_NOT_LOCKED`. Other errors are reported. The mapping stays valid and later reads fault in the +original bytes. Shared boundary pages are retained. The code resolves file spans directly, so it does not trim +resident complements, CUDA-pinned buffers or the temporary buffers used to assemble GGUF experts. + +Existing cache-upload release calls use this implementation. Two additional calls release pages after prefill's +lent cache slots have finished refilling, in serving and one-shot generation. Other platforms are unchanged. +`STRATA_FILE_RELEASE=1` enables it; unset, `0`, or any other value leaves it disabled. The switch is read once +per engine process, so restart the engine when changing it. + +This builds on the existing working-set handling in [#467](https://github.com/Niko1221/Strata/issues/467) and the +mapped-arena work in [#640](https://github.com/Niko1221/Strata/pull/640). Multi-GPU placement already exists upstream; +this patch does not implement it. See Microsoft's [VirtualUnlock documentation](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualunlock). + +## Configuration + +| Component | Measured configuration | +| --- | --- | +| System | Windows 11 Pro build 26200, Core i9-14900HX, 31.77 GiB usable RAM, 2 x 16 GB DDR5-5600 | +| GPU 0 | RTX 4080 Laptop, 12,282 MiB VRAM; also drives the desktop | +| GPU 1 | RTX 3090, 24,576 MiB VRAM, Thunderbolt eGPU | +| Links | Engine H2D probes approximately 12.3-12.9 GB/s and 2.4 GB/s respectively; no CUDA peer read/write | +| Driver | NVIDIA 616.56 | +| Storage | Model and pack on an internal WD PC SN560 NVMe | +| Build | MSVC 19.29.30157, CUDA 13.1.80, Release, AVX2 portable, SM 86/89, native experts enabled | +| Model | `ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF`, IQ2_XS, with MTP | +| Placement | GPUs `0,1`, layer split 12, stage-weight trim, mapped experts | +| Runtime | Context 32768, int8 KV, 15 pool workers, auto expert cache and prefill, spec 4, minimum draft probability 0.5 | + +GPU 0 held 6,144 expert pairs (about 8.00 GiB), GPU 1 held 13,381 (about 18.15 GiB); 19,525 of 24,576 pairs in total. +Prefill selected 8192 and borrowed approximately 3.77 GiB of expert cache on each GPU. The native pack used +`experts.bin` (35,454,976,000 bytes), `dense.bin` (1,538,035,200 bytes), and the GGUF PLE table on disk. +Power was AC; the existing power plan, drivers and system-managed pagefile were not changed. + +Model revision: `ed59f92082b1e93c0e96d60a8b11aab089b52f09`. +MTP checkpoint revision: `de4b8e4d43b917e7706784d8bb445c9af86a3540`. +llama.cpp revision: `3cf03257f219afbe7334045ff7c6a06ac68c627d`. +The two downloaded GGUF shards were fully SHA-256 verified: + +| Shard | Bytes | SHA-256 | +| --- | ---: | --- | +| 1 | 39,225,954,592 | `92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7` | +| 2 | 28,800,138,432 | `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113` | + +The measured prototype executable had SHA-256 +`9118b02dcc0ad4bd8398ba033c641feb93800e0eeecea59ee42be141e4a186fc`. +It predates the submitted patch's decision to default the switch to OFF. Explicit `0` and `1` have the same +behavior in both versions; the numbers below are from the prototype, not a benchmark of the final rebuild. + +## Measurements + +Each arm had one excluded short warmup followed by three fresh prompts at each length, with 256 output tokens, +temperature zero and thinking disabled. Prompts ask for explanations of synthetic integer-processing code. +The harness checks that all prompt tokens were processed, no prefix tokens were reused, the response completed, +and exactly one request was recorded by the idle dedicated server. Actual prompt lengths were 1023, 4096 and 16384. + +Medians of three requests per cell: + +| Prompt | Prefill OFF / ON, tok/s | Decode OFF / ON, tok/s | Client TTFT OFF / ON, s | +| --- | ---: | ---: | ---: | +| 1K | 263.68 / 253.83 | 77.35 / 77.65 | 3.93 / 4.07 | +| 4K | 583.51 / 558.24 | 81.99 / 94.17 | 7.06 / 7.38 | +| 16K | 1045.85 / 1000.16 | 80.88 / 84.93 | 15.73 / 16.45 | + +An independent Windows monitor sampled host RAM, process working sets, commit, pagefile use and physical-disk +counters approximately once per second. The following window includes warmup and gaps between requests, from +the first request's start to the last request's finish. GiB means bytes divided by 2^30. + +| Metric | Release OFF | Release ON | +| --- | ---: | ---: | +| Available RAM, median | 0.512 GiB | 12.187 GiB | +| Available RAM, minimum | 0.277 GiB | 6.110 GiB | +| Engine working set, median | 23.379 GiB | 11.946 GiB | +| Engine nonprivate working set, median | 20.460 GiB | 8.689 GiB | +| System commit, median | 51.880 GiB | 51.973 GiB | +| Engine private commit, median | 36.807 GiB | 36.804 GiB | +| Pagefile use, median | 1.233 GiB | 1.218 GiB | +| Internal physical-disk reads, total | 16.750 GiB | 16.809 GiB | + +The benefit was available physical RAM. Commit was effectively unchanged; this does not solve a commit-limit +failure or eliminate the need for pagefile capacity. Physical reads were also effectively unchanged. +Nonprivate working-set bytes include file mappings and shared images, not only model pages. Physical-disk +counters are system-wide and omit about 1.1-1.3 seconds at the sampled interval edges. The external disk was idle. + +These were sequential OFF-then-ON runs on one machine, with warm engines and retained OS file-cache history. +The adaptive expert cache remained enabled. The OS cache was not flushed; this is not a cold-SSD experiment. +Three repetitions provide observed ranges, not confidence intervals. Code-explanation outputs differed between +the two arms despite identical measured requests; speculative decode rates are workload-dependent. Prefill +throughput dropped 3.7-4.4%, and median whole-request time changed by +3.5%, -1.1% and +2.9% at 1K, 4K and 16K. +These observations do not establish a decode-speed improvement, output equivalence, or results on other hardware. + +## Reproduction and checks + +`benchmark.py` and `monitor_windows.py` are the scripts used for these measurements (the raw per-trial export and the harness +self-tests were left out of the repository). The switch was called `STRATA_ARENA_RELEASE` in the prototype that measured this; +it is `STRATA_FILE_RELEASE` here, because the old name already means the opposite elsewhere (`=0` keeps experts a GPU holds). +The benchmark needs the repository's normal server/tokenizer dependencies; the Windows monitor also needs psutil. + +Start a dedicated server on `127.0.0.1:18080` using a configuration with the runtime settings above, the patched +engine, and `"env": {"STRATA_FILE_RELEASE": "0"}`. Wait until the engine is loaded and idle. In another terminal, +run the monitor against the server process ID, and then the benchmark (replace the uppercase placeholders): + +```powershell +python bench/results/2026-10-04-windows-mapped-release/monitor_windows.py --server-pid SERVER_PID --out off-host.jsonl --stop-file off-monitor.stop +``` + +```powershell +python bench/results/2026-10-04-windows-mapped-release/benchmark.py --pack PACK_DIR --config CONFIG_JSON --label release-off --out results-off --targets 1024,4096,16384 --runs 3 --max-tokens 256 +``` + +Stop the monitor by creating its stop file. Unload and stop the server, change only the release value to `1`, +restart, and repeat with new ON output paths. Keep available VRAM, background workloads and model files stable. +For host summaries, select samples with `min(started_epoch_s) <= epoch_s <= max(finished_epoch_s)` from the +benchmark's results, including warmup. Compute sample medians/minima and physical-disk last-minus-first counters. +Sum `windows_memory` counters for `strata.exe` processes only; nonprivate working set is total minus private. + +The C++ tests cover canonical and variable native layouts, full-page alignment, preserved boundary pages, +three release/read cycles with byte-for-byte checks, invalid indices, a closed source, and three GGUF roles +across two shards. Build with `STRATA_BUILD_TESTS=ON` and `STRATA_NATIVE_EXPERTS=ON`, then run +`ctest --test-dir BUILD_DIR -R "^(file_expert_source_test|expert_layout_test)$" --output-on-failure` in fresh +processes with the switch unset, `0`, and `1`. + +The final submitted source was rebuilt with the toolchain above. Both C++ tests passed with the switch unset, +`0`, and `1`. That rebuilt engine also completed a warmup and one fresh +request each at 1023 and 4096 prompt tokens, generating 256 tokens per measured request on both GPUs with release +enabled. This was an inference smoke test, not a replacement for the prototype's OFF/ON performance comparison. +Its executable SHA-256 is `9f1e96c36b2ddb530422ee37734606491c0f4c3c9b720095c68d63953e89913b`. + +Additional prototype checks with release ON completed 30 requests without runtime errors: 21 of 24 objective +checks passed, with three JSON-only checks failing because of Markdown fences. All 24 objective responses and +statuses matched the official engine with the same GPU placement, including those three failures. Six prose +requests were unscored. Needle retrieval passed near 1K/4K/16K tokens at 50% depth. The functional battery was not +run on the release-OFF prototype, and these limited checks do not prove general model quality or token parity. diff --git a/bench/results/2026-10-04-windows-mapped-release/benchmark.py b/bench/results/2026-10-04-windows-mapped-release/benchmark.py new file mode 100644 index 00000000..c2872000 --- /dev/null +++ b/bench/results/2026-10-04-windows-mapped-release/benchmark.py @@ -0,0 +1,381 @@ +#!/usr/bin/env python3 +"""Serial fresh-prompt benchmark, adapted from the community MI50/RTX 5090 harness. + +Start a dedicated Strata server separately. This script never starts or stops it. +Expert adaptation and the OS file cache stay warm between requests; prefix reuse +is rejected. Engine file-tier counters describe decode, not physical disk reads. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import statistics +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path + + +def write_json(path, value): + path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + + +def get(url, timeout=30): + with urllib.request.urlopen(url, timeout=timeout) as response: + return json.load(response) + + +def digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode("utf-8")).hexdigest() + + +def executable_record(config): + """Resolve the configured binary exactly as serve/server.py does, without executing it.""" + executable = Path(config["exe"]) + if not executable.is_absolute(): + executable = Path(config.get("cwd") or ".") / executable + executable = executable.resolve() + checksum = hashlib.sha256() + with executable.open("rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b""): + checksum.update(block) + return {"path": str(executable), "sha256": checksum.hexdigest(), "size_bytes": executable.stat().st_size} + + +def engine_provenance_record(path, executable): + """Keep compact build provenance and verify its executable artifact, when recorded.""" + path = path.resolve() + raw = path.read_bytes() + source = json.loads(raw.decode("utf-8-sig")) + artifacts = source.get("artifacts", {}) + if isinstance(artifacts, list): + entries = [(entry["file"], entry) for entry in artifacts] + elif isinstance(artifacts, dict): + entries = list(artifacts.items()) + else: + raise ValueError("Provenance artifacts must be a list or dictionary") + matches = [entry for name, entry in entries + if Path(name).name.casefold() == Path(executable["path"]).name.casefold()] + if len(matches) > 1: + raise ValueError("Provenance has multiple artifacts matching the configured executable") + expected = matches[0]["sha256"].lower() if matches else None + if expected is not None and expected != executable["sha256"]: + raise ValueError("Provenance executable SHA-256 does not match the configured executable") + toolchain_keys = ("cmake", "ninja", "msvc", "windows_sdk", "nvcc", "cuda", "cuda_architectures", + "cxx_standard", "cuda_standard", "build_type", "portable_avx2", "msvc_runtime", + "parallel_jobs", "tests_built") + toolchain = {key: value for key, value in source.get("toolchain", {}).items() if key in toolchain_keys} + # Release BUILD.json records CUDA and target architectures at the top level. + toolchain.update({key: source[key] for key in ("cuda", "archs", "ptx", "portable") if key in source}) + return {"path": str(path), "sha256": hashlib.sha256(raw).hexdigest(), + "version": source.get("strata_version", source.get("version")), "commit": source.get("commit"), + "fingerprint": source.get("engine_source_fingerprint", source.get("source_fingerprint")), + "toolchain": toolchain, "repository": source.get("fork_repository"), + "llama_cpp_commit": source.get("llama_cpp_pinned_commit"), + "executable_hash_verified": expected is not None, "recorded_executable_sha256": expected} + + +def validate_completion(before, after, chunks, expected, finish, done, text): + if not done: + raise RuntimeError("The stream ended without [DONE]") + if not text: + raise RuntimeError("The response contained no text") + if finish not in ("length", "stop"): + raise RuntimeError(f"Unsuccessful finish reason: {finish!r}") + if after["totals"]["requests"] != before["totals"]["requests"] + 1: + raise RuntimeError("Request counter mismatch; another client or engine restart invalidated this trial") + if after["live"]["state"] != "idle" or after["live"].get("queued", 0): + raise RuntimeError("The dedicated server was not idle after the request") + engine = after["requests"][0] + usage_chunk = next((chunk for chunk in reversed(chunks) if "usage" in chunk), None) + if not usage_chunk or not usage_chunk.get("timings"): + raise RuntimeError("The final stream chunk lacks usage or engine timings") + usage, timings = usage_chunk["usage"], usage_chunk["timings"] + if engine.get("reused") != 0 or usage["prompt_tokens_details"]["cached_tokens"] != 0: + raise RuntimeError("Fresh prompt reused cached tokens; restart this arm before resuming") + if engine["prompt_tokens"] != expected or usage["prompt_tokens"] != expected: + raise RuntimeError(f"Prompt token count mismatch; expected {expected}") + if engine.get("prompt_total") != expected or engine.get("prompt_read") != expected: + raise RuntimeError("The engine did not report reading the complete prompt") + if engine["finish"] != finish or engine["output_tokens"] != usage["completion_tokens"]: + raise RuntimeError("Stream usage or finish reason does not match /metrics") + if timings["prompt_n"] != expected or timings["predicted_n"] != usage["completion_tokens"]: + raise RuntimeError("Final stream timings do not match the completed request") + for name, timing_name in (("prompt_ms", "prompt_ms"), ("decode_ms", "predicted_ms")): + if engine[name] <= 0 or abs(engine[name] - timings[timing_name]) > 0.11: + raise RuntimeError(f"Invalid or mismatched engine timing: {name}") + if engine["engine_generated"] <= 0: + raise RuntimeError("The engine reported no generated tokens") + return engine, usage, timings + + +def perform(url, out, session, label, attempt, req, expected, interval=1.0, timeout=1800): + stem = f"{label}-attempt-{attempt}" + body = json.dumps(req, ensure_ascii=False).encode("utf-8") + (out / f"{stem}-request.json").write_bytes(body + b"\n") + row = {"label": label, "attempt": attempt, "session": session, "status": "failed", + "expected_prompt_tokens": expected, "request_sha256": hashlib.sha256(body).hexdigest(), + "started_epoch_s": time.time(), "raw_stream": f"{stem}-sse.jsonl", + "telemetry": f"{stem}-telemetry.jsonl", "text": "", "reasoning": ""} + chunks, texts, reasoning, telemetry_errors = [], [], [], [] + stop = threading.Event() + monitor = None + started = None + + def sample(output): + metrics = get(url + "/metrics") + hardware = dict(metrics["hardware"]) + if hardware.get("ram_total") is not None and hardware.get("ram_used") is not None: + hardware["ram_available"] = hardware["ram_total"] - hardware["ram_used"] + sample_row = {"epoch_s": time.time(), "metrics_time": metrics.get("time"), + "live": metrics["live"], "hardware": hardware, + "completed_requests": metrics["totals"]["requests"]} + output.write(json.dumps(sample_row) + "\n") + output.flush() + + def monitor_loop(output): + while not stop.wait(interval): + try: + sample(output) + except Exception as error: + telemetry_errors.append(f"{type(error).__name__}: {error}") + output.write(json.dumps({"epoch_s": time.time(), "error": telemetry_errors[-1]}) + "\n") + output.flush() + break + + try: + before = get(url + "/metrics") + row["metrics_before"] = before + if before["live"]["state"] != "idle" or before["live"].get("queued", 0): + raise RuntimeError("The dedicated server must already be loaded and idle") + if expected + req["max_tokens"] > before["engine"]["max_context"]: + raise RuntimeError("Prompt plus output cap exceeds the configured context") + with (out / row["telemetry"]).open("w", encoding="utf-8") as telemetry: + sample(telemetry) + monitor = threading.Thread(target=monitor_loop, args=(telemetry,), daemon=True) + monitor.start() + try: + with (out / row["raw_stream"]).open("w", encoding="utf-8") as raw: + started = time.perf_counter() + first, finish, done = None, None, False + wire = urllib.request.Request(url + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(wire, timeout=timeout) as response: + for line in response: + raw.write(json.dumps({"elapsed_s": time.perf_counter() - started, + "line": line.decode("utf-8")}, ensure_ascii=False) + "\n") + raw.flush() + if not line.startswith(b"data:"): + continue + payload = line[5:].strip() + if payload == b"[DONE]": + done = True + break + chunk = json.loads(payload) + chunks.append(chunk) + if chunk.get("error"): + raise RuntimeError(f"Stream error: {chunk['error']}") + for choice in chunk.get("choices", []): + delta = choice.get("delta", {}) + content = delta.get("content") or "" + thought = delta.get("reasoning_content") or "" + if (content or thought) and first is None: + first = time.perf_counter() - started + texts.append(content) + reasoning.append(thought) + finish = choice.get("finish_reason") or finish + row.update(client_ttft_s=first, client_elapsed_s=time.perf_counter() - started, + finish_reason=finish, stream_done=done) + after = get(url + "/metrics") + row["metrics_after"] = after + engine, usage, timings = validate_completion(before, after, chunks, expected, + finish, done, "".join(texts + reasoning)) + row.update(engine=engine, usage=usage, timings=timings, + prefill_tok_s=expected / (engine["prompt_ms"] / 1000), + decode_tok_s=engine["engine_generated"] / (engine["decode_ms"] / 1000)) + finally: + stop.set() + monitor.join() + try: + sample(telemetry) + except Exception as error: + telemetry_errors.append(f"{type(error).__name__}: {error}") + if telemetry_errors: + raise RuntimeError("Telemetry failed: " + "; ".join(telemetry_errors)) + row["status"] = "ok" + except urllib.error.HTTPError as error: + row["error"] = {"type": type(error).__name__, "message": str(error), "http_status": error.code, + "body": error.read().decode("utf-8", errors="replace")} + except Exception as error: + row["error"] = {"type": type(error).__name__, "message": str(error)} + finally: + stop.set() + if monitor is not None and monitor.is_alive(): + monitor.join() + row.update(text="".join(texts), reasoning="".join(reasoning), finished_epoch_s=time.time()) + if started is not None and "client_elapsed_s" not in row: + row["client_elapsed_s"] = time.perf_counter() - started + write_json(out / f"{stem}-record.json", row) + write_json(out / f"{stem}-chunks.json", chunks) + return row + + +def summary(rows, targets): + groups = {} + for target in targets: + selected = [r for r in rows if r["label"].startswith(f"tokens-{target}-")] + good = [r for r in selected if r["status"] == "ok"] + fields = ("client_ttft_s", "client_elapsed_s", "prefill_tok_s", "decode_tok_s") + groups[str(target)] = {"successful_runs": len(good), "failed_attempts": len(selected) - len(good), + **{field: {"median": statistics.median(v), "min": min(v), "max": max(v)} + for field in fields if (v := [r[field] for r in good])}} + return groups + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[3]) + parser.add_argument("--pack", type=Path, required=True) + parser.add_argument("--config", type=Path, help="Server configuration, saved with relevant fields only") + parser.add_argument("--engine-provenance", type=Path, + help="Build provenance JSON or release BUILD.json; requires --config") + parser.add_argument("--url", default="http://127.0.0.1:18080") + parser.add_argument("--model", default="strata") + parser.add_argument("--label", required=True, help="Configuration label, such as iq2-xs-3090-resident") + parser.add_argument("--out", type=Path, required=True, help="A separate directory for each configuration") + parser.add_argument("--targets", default="1024,4096,16384") + parser.add_argument("--runs", type=int, default=3) + parser.add_argument("--max-tokens", type=int, default=256) + parser.add_argument("--timeout", type=float, default=1800) + parser.add_argument("--telemetry-interval", type=float, default=1.0) + parser.add_argument("--resume", action="store_true", help="Keep completed trials and preserve failed attempts") + args = parser.parse_args() + targets = [int(value) for value in args.targets.split(",")] + if not targets or min(targets) <= 0 or len(set(targets)) != len(targets): + parser.error("Targets must be unique positive token counts") + if args.runs < 1 or args.max_tokens < 1 or args.timeout <= 0 or args.telemetry_interval <= 0: + parser.error("Runs, output cap, timeout, and telemetry interval must be positive") + if args.engine_provenance and not args.config: + parser.error("--engine-provenance requires --config to identify the executable") + args.root, args.pack, args.out = args.root.resolve(), args.pack.resolve(), args.out.resolve() + url = args.url.rstrip("/") + sys.path[:0] = [str(args.root), str(args.root / "tools")] + from strata_tokenizer import Tokenizer + from serve.frontend import ChatTemplate, openai_to_messages + + directory = args.pack / "tokenizer" + vocab = json.loads((directory / "vocab.json").read_text(encoding="utf-8")) + tokens = [None] * len(vocab) + for token, number in vocab.items(): + tokens[number] = token + tokenizer = Tokenizer(tokens, (directory / "merges.txt").read_text(encoding="utf-8").splitlines(), + json.loads((directory / "token_type.json").read_text(encoding="utf-8"))) + template = ChatTemplate(directory / "chat_template.jinja") + + def request(content, maximum=args.max_tokens): + return {"model": args.model, "messages": [{"role": "user", "content": content}], + "temperature": 0, "reasoning_effort": "none", "max_tokens": maximum, + "stream": True, "stream_options": {"include_usage": True}} + + def count(req): + messages, tools, kwargs = openai_to_messages(req) + return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True)) + + initial = get(url + "/metrics") + if initial["live"]["state"] != "idle" or initial["live"].get("queued", 0): + raise RuntimeError("Start a dedicated, loaded and idle server before this benchmark") + config = {} + executable = None + if args.config: + source = json.loads(args.config.read_text(encoding="utf-8-sig")) + executable = executable_record(source) + keys = ("exe", "cwd", "args", "gpu", "layer_split", "split_skip_if_fits", "backend", "tokenizer", "log", + "model_name", "parallel", "expert_profile_save", "expert_profile_save_every") + config = {key: source[key] for key in keys if key in source} + compute_variables = {"CUDA_VISIBLE_DEVICES", "CUDA_DEVICE_ORDER", "STRATA_STAGE_TRIM", "STRATA_SPLIT_OWN", + "STRATA_ARENA_PIN_GIB", "STRATA_RESIDENT_PIN", "STRATA_RESIDENT_HEADROOM_GIB", + "STRATA_ARENA_MMAP", "STRATA_PREFILL_HELP", "STRATA_FETCH_THREADS", "STRATA_LOOKAHEAD", + "STRATA_DECODE_TIMING", "STRATA_SPLIT_TIMING", "STRATA_VERIFY_PROFILE", + "STRATA_SPLIT_MISS_MS", "STRATA_PF_FUSED", "STRATA_FILE_RELEASE"} + config["env"] = {key: value for key, value in source.get("env", {}).items() + if key in compute_variables} + revision = subprocess.run(["git", "-c", f"safe.directory={args.root.as_posix()}", "rev-parse", "HEAD"], + cwd=args.root, capture_output=True, text=True, check=True).stdout.strip() + provenance = engine_provenance_record(args.engine_provenance, executable) if args.engine_provenance else None + manifest = {"label": args.label, "frontend_source_commit": revision, "pack": str(args.pack), + "config": config, "engine_executable": executable, + "engine_provenance": provenance, "engine_reported_version": initial["engine"].get("version"), + "targets": targets, "runs": args.runs, "max_tokens": args.max_tokens, + "model": args.model, "server_model": initial["engine"]["model"], + "max_context": initial["engine"]["max_context"], + "hardware_static": initial.get("hardware_static"), + "tokenizer_sha256": {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ("vocab.json", "merges.txt", "token_type.json", "chat_template.jinja")}, + "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "method": "Serial warm-engine trials; default adaptive expert state retained; zero prompt reuse required", + "disk_counter_note": "file_mb is the decode file tier, possibly OS-cached; disk_read_mb is system-wide physical I/O"} + manifest_path = args.out / "manifest.json" + if manifest_path.exists(): + if not args.resume: + raise RuntimeError("Output already has a manifest; use a new output directory or --resume") + if digest(json.loads(manifest_path.read_text(encoding="utf-8"))) != digest(manifest): + raise RuntimeError("Resume manifest differs; use a new output directory") + elif args.resume: + raise RuntimeError("Cannot resume: output has no manifest") + args.out.mkdir(parents=True, exist_ok=True) + write_json(manifest_path, manifest) + rows_path = args.out / "results.json" + rows = json.loads(rows_path.read_text(encoding="utf-8")) if args.resume and rows_path.exists() else [] + session = uuid.uuid4().hex[:12] + write_json(args.out / f"session-{session}.json", {"session": session, "epoch_s": time.time(), + "python": sys.version, "platform": platform.platform(), "initial_metrics": initial, + "initial_status": get(url + "/v1/status"), "resumed": args.resume}) + + def run(label, req): + if any(row["label"] == label and row["status"] == "ok" for row in rows): + print("skip completed", label, flush=True) + return + attempt = sum(row["label"] == label for row in rows) + 1 + print("start", args.label, label, "tokens", count(req), flush=True) + row = perform(url, args.out, session, label, attempt, req, count(req), + args.telemetry_interval, args.timeout) + rows.append(row) + write_json(rows_path, rows) + write_json(args.out / "summary.json", summary(rows, targets)) + print(row["status"], label, json.dumps({key: row.get(key) for key in + ("client_ttft_s", "prefill_tok_s", "decode_tok_s", "error")}), flush=True) + if row["status"] != "ok": + raise RuntimeError(f"Benchmark stopped after failed trial {label}; evidence was retained") + + run(f"warmup-{session}", request(f"Warmup {session}. Reply with exactly the word READY.", 16)) + filler = "\n".join(f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003" + for i in range(12000)) + ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, " + "modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.") + for target in targets: + for trial in range(1, args.runs + 1): + # Checkpoints cover a complete turn or >=16K prompt tokens by default; + # this early differing nonce prevents a whole checkpoint from matching. + prefix = f"Benchmark nonce: series-{target}-trial-{trial}.\nReview this synthetic Python module:\n" + low, high = 0, len(filler) + while low < high: + middle = (low + high + 1) // 2 + if count(request(prefix + filler[:middle] + ending)) <= target: + low = middle + else: + high = middle - 1 + req = request(prefix + filler[:low] + ending) + if not target - 20 <= count(req) <= target: + raise RuntimeError(f"Could not construct target {target}: {count(req)}") + run(f"tokens-{target}-run-{trial}", req) + print("Complete:", args.out / "summary.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/bench/results/2026-10-04-windows-mapped-release/monitor_windows.py b/bench/results/2026-10-04-windows-mapped-release/monitor_windows.py new file mode 100644 index 00000000..e2b0c8bd --- /dev/null +++ b/bench/results/2026-10-04-windows-mapped-release/monitor_windows.py @@ -0,0 +1,139 @@ +"""Record Windows host memory and physical-disk counters during a local experiment.""" +from __future__ import annotations + +import argparse +import ctypes +from ctypes import wintypes +import json +from pathlib import Path +import time + +import psutil + + +class PerformanceInformation(ctypes.Structure): + _fields_ = [("cb", wintypes.DWORD)] + [ + (name, ctypes.c_size_t) for name in ( + "CommitTotal", "CommitLimit", "CommitPeak", "PhysicalTotal", + "PhysicalAvailable", "SystemCache", "KernelTotal", "KernelPaged", + "KernelNonpaged", "PageSize", + ) + ] + [(name, wintypes.DWORD) for name in ( + "HandleCount", "ProcessCount", "ThreadCount", + )] + + +performance = ctypes.WinDLL("psapi", use_last_error=True).GetPerformanceInfo +performance.argtypes = [ctypes.POINTER(PerformanceInformation), wintypes.DWORD] +performance.restype = wintypes.BOOL + + +class ProcessMemoryCounters(ctypes.Structure): + _fields_ = [("cb", wintypes.DWORD), ("page_fault_count", wintypes.DWORD)] + [ + (name, ctypes.c_size_t) for name in ( + "peak_working_set_bytes", "working_set_bytes", "peak_paged_pool_bytes", + "paged_pool_bytes", "peak_nonpaged_pool_bytes", "nonpaged_pool_bytes", + "commit_bytes", "peak_commit_bytes", "private_commit_bytes", + "private_working_set_bytes", + ) + ] + [("shared_commit_bytes", ctypes.c_ulonglong)] + + +kernel = ctypes.WinDLL("kernel32", use_last_error=True) +kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] +kernel.OpenProcess.restype = wintypes.HANDLE +kernel.CloseHandle.argtypes = [wintypes.HANDLE] +kernel.CloseHandle.restype = wintypes.BOOL +process_memory = ctypes.WinDLL("psapi", use_last_error=True).GetProcessMemoryInfo +process_memory.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessMemoryCounters), wintypes.DWORD] +process_memory.restype = wintypes.BOOL + + +def extended_memory(process): + handle = kernel.OpenProcess(0x1000, False, process.pid) # PROCESS_QUERY_LIMITED_INFORMATION + if not handle: + if not process.is_running(): + raise psutil.NoSuchProcess(process.pid) + raise ctypes.WinError(ctypes.get_last_error()) + try: + info = ProcessMemoryCounters() + info.cb = ctypes.sizeof(info) + if not process_memory(handle, ctypes.byref(info), info.cb): + raise ctypes.WinError(ctypes.get_last_error()) + return {name: getattr(info, name) for name, _ in info._fields_ if name != "cb"} + finally: + kernel.CloseHandle(handle) + + +def sample(server): + info = PerformanceInformation() + info.cb = ctypes.sizeof(info) + if not performance(ctypes.byref(info), info.cb): + raise ctypes.WinError(ctypes.get_last_error()) + processes = [] + if server is not None: + try: + descendants = [server, *server.children(recursive=True)] + except psutil.NoSuchProcess: + descendants = [] + for process in descendants: + try: + with process.oneshot(): + processes.append({ + "pid": process.pid, + "name": process.name(), + "memory": process.memory_info()._asdict(), + "windows_memory": extended_memory(process), + "cpu_seconds": process.cpu_times()._asdict(), + "io_counters": process.io_counters()._asdict(), + }) + except psutil.NoSuchProcess: + continue + battery = psutil.sensors_battery() + return { + "epoch_s": time.time(), + "memory": psutil.virtual_memory()._asdict(), + "pagefile": psutil.swap_memory()._asdict(), + "commit_bytes": info.CommitTotal * info.PageSize, + "commit_limit_bytes": info.CommitLimit * info.PageSize, + "commit_peak_bytes": info.CommitPeak * info.PageSize, + "system_cache_bytes": info.SystemCache * info.PageSize, + "physical_disks": { + name: counters._asdict() + for name, counters in psutil.disk_io_counters(perdisk=True).items() + }, + "ac_power": battery.power_plugged if battery is not None else None, + "processes": processes, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--server-pid", type=int) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--stop-file", type=Path, required=True) + parser.add_argument("--interval", type=float, default=1.0) + parser.add_argument("--samples", type=int, help="Optional bounded diagnostic run") + args = parser.parse_args() + if args.interval <= 0 or (args.samples is not None and args.samples < 1): + parser.error("Interval and sample limit must be positive") + if args.stop_file.exists(): + parser.error("The stop file already exists; choose a new experiment path") + server = psutil.Process(args.server_pid) if args.server_pid is not None else None + args.out.parent.mkdir(parents=True, exist_ok=True) + with args.out.open("x", encoding="utf-8") as output: + count = 0 + while not args.stop_file.exists(): + started = time.monotonic() + output.write(json.dumps(sample(server)) + "\n") + output.flush() + count += 1 + if args.samples is not None and count >= args.samples: + break + if server is not None and not server.is_running(): + break + time.sleep(max(0, args.interval - (time.monotonic() - started))) + + +if __name__ == "__main__": + main() diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 0fffc11b..79e9f2a9 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -171,6 +171,15 @@ start writes `experts.bin` (when the drive has room for it), later starts map it are handed back to the OS. Run it with `--pcie-frac 0` (the GPUs get no mapped alias). Without the variable nothing changes. +**Releasing mapped expert pages on Windows (opt-in):** `STRATA_FILE_RELEASE=1` lets `FileExpertSource` trim the +full file-backed pages of experts after their GPU uploads complete, including the slots lent to prefill and then +refilled. It works with `experts.bin` and the direct GGUF views; shared boundary pages and private/pinned buffers +are left alone. Unset or `0` keeps the previous behavior. On one 32 GB Windows 11 laptop with an RTX 4080 Laptop +and a Thunderbolt RTX 3090, IQ2_XS with `--mmap-experts --layer-split 12 --trim-stage-weights` raised median available +RAM from 0.51 to 12.19 GiB across 1K/4K/16K prompt trials, with 3.7-4.4% lower prefill throughput. It did not reduce +committed memory or physical SSD reads. This is a working-set hint, not an unmap or a guarantee that the OS drops +its file cache. See the [configuration, measurements and limits](../bench/results/2026-10-04-windows-mapped-release/README.md). + **Low-RAM mode without `experts.bin` (engine 0.1.31):** for the native packs (IQ2_XS, IQ3_XXS, IQ3_S, the Coder, Swift, Q2_0 packed by `tools/iq_pack.py`; not the canonical Q2_0 pack setup makes for AVX-512 CPUs) the mapped mode no longer needs the pack's `experts.bin`: when the pack has none, the engine @@ -183,16 +192,23 @@ engine fetches a layer's missing experts on 8 threads (`STRATA_FETCH_THREADS`) w **A RAM budget (engine 0.1.31, `--resident-budget-gib N`):** the resident variant for a model whose experts do not all fit: the N GiB of experts the GPU cache does not hold that the expert profile ranks hottest are copied into RAM at -start (locked; page-locked when the driver allows the whole budget), and the rest are read from the files through the -OS file cache. It implies `--mmap-experts` and leaves 4 GB of free RAM (a larger N is clamped to that less 256 MiB, -with a message; #403: a clamped budget no longer fails the safety check that follows, and a budget that cannot be -kept at all is a warning, with every expert read from the files). Setup sets N with `--resident-budget-gib N`. With +start (locked; page-locked when the driver allows the whole budget), and the rest are read from the files. +It implies `--mmap-experts` and leaves 4 GiB of headroom. On Windows, available commit capacity also +limits the budget; a larger N is clamped to the smaller limit less 4 GiB and a 256 MiB margin, with a message. +A clamped budget no longer fails the safety check that follows (#403). A budget that cannot be kept at all is a +warning, with every expert read from the files. Setup sets N with `--resident-budget-gib N`. With the GGUF read in place it also warms the next layer's likely experts: while the CPU works on a layer, a thread applies the next layer's router to this layer's input and asks the OS for the pages of the predicted experts that neither the GPU nor the RAM budget holds (only pages - the experts computed are the same; `STRATA_LOOKAHEAD=0` turns it off). This is what runs [Unsloth's UD-Q4_K_XL](UNSLOTH_Q4.md) (72 GiB of experts) on a 64 GB PC: 7-8.5 tokens/s at N = 40 on an RTX 5070, against ~3 tokens/s before these changes. +**Read-ahead at start (Linux):** the weights, the native dense matrices, the GPU cache's fill from the profile, the +resident RAM copy and the MTP draft files are asked for ahead of their reads (madvise / posix_fadvise WILLNEED in +128 KiB steps), so the drive sees a deep queue instead of one page fault at a time. Measured on a Gen3 NVMe (RTX 5090, +32 GB, Q2_0 resident at 262K): ready in 70 s instead of ~920 s; the fill went from 39 MB/s to 3.2 GB/s. +`STRATA_READ_AHEAD=0` turns it off; `STRATA_FILL_AHEAD=N` sets how many fill pairs are asked for ahead (default 256). + **How much came from where:** with `--stats` the engine prints the tiers of the decode (`expert tiers`: blobs from the RAM copy, blobs and MB from the files, the time spent reading them; `routing prefetch`: how many of the file reads had been warmed). The server log has the same per request (`expert tiers: GPU ... hits ...; RAM ... blobs, files ... diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index bd9226c6..231ab8bd 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -21,6 +21,18 @@ Update it (NVIDIA App or [nvidia.com/drivers](https://www.nvidia.com/drivers)), **It says port 8080 is already in use.** Strata is already running. Look for its window. Or another program uses the port: `START-HERE.bat --port 8081`. +Only an address that is really taken says "already in use". Any other reason (Windows keeps the port reserved, or +the config's `"host"` is not an address of this PC) is printed as what the OS said, with what to change (#769). + +**"Windows blocked the Strata engine (or the image encoder) ... Smart App Control".** +On a clean Windows 11, Smart App Control refuses programs that are not signed, and Strata's `strata.exe` and +`strata-vision.exe` are not (#735). Turn it off (Windows Security > App & browser control > Smart App Control +settings; it cannot be turned back on without a reset of Windows), or, if only the image encoder is blocked, run +`START-HERE.bat --setup --vision no`. + +**A new engine misbehaves after an update.** +An update keeps the engine it replaced in `engine\.previous` (one generation, about 210 MiB). +`python setup.py --rollback-engine` puts it back (and keeps the newer one there: run it again to go forward) (#670). **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. @@ -36,6 +48,10 @@ Install what it names (links are printed), then run it again. Everything already **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). +On Linux the engine now asks the kernel to read the model files ahead (a cold start went from ~920 s to 70 s on one +PC); `STRATA_READ_AHEAD=0` turns that off. On Linux with transparent huge pages on `always`, the arena no longer asks +for `MADV_HUGEPAGE` on top (a fragmented machine spent minutes compacting memory, #771); `STRATA_NO_ARENA_THP=1` skips +that request on any setting. ## While it answers diff --git a/docs/UNSLOTH_Q4.md b/docs/UNSLOTH_Q4.md index 9e260101..5a87468e 100644 --- a/docs/UNSLOTH_Q4.md +++ b/docs/UNSLOTH_Q4.md @@ -140,11 +140,17 @@ model's (`data/expert-profile.bin`); it ranks the same 48 x 512 experts and deci budget take first. **Choosing the RAM budget N:** your RAM minus 20-24 GB (the OS, the engine itself, the 126 MB router copy, and room for -the OS file cache that serves the rest). On 64 GB, 40. The engine clamps a budget larger than the RAM it finds free -(minus 4 GB and a 256 MiB margin) and says so; before #403's fix such a clamped budget could then fail the start. Everything above N comes from the SSD for every token, so N is the setting that matters +the OS file cache that serves the rest). On 64 GB, 40. The engine checks available RAM and, on Windows, available +commit capacity. If N exceeds the smaller value minus 4 GiB headroom, it reduces N to that amount minus a 256 MiB +margin and reports which limit applies. Before #403's fix a clamped budget could then fail the safety check. +Everything above N comes from the SSD for every token, so N is the setting that matters most; a bigger budget was faster in every measurement (24 / 32 / 40 GiB). When the driver page-locks the whole budget (24 GiB did on this PC, 32 and 40 did not), the GPU also computes a share of the misses over PCIe, as in the resident -low-RAM mode; `STRATA_RESIDENT_PIN=0` keeps the budget locked only (the CPU then computes every miss). +low-RAM mode; `STRATA_RESIDENT_PIN=0` uses ordinary pageable memory (the CPU then computes every miss). + +On Windows, the allocation log reports available physical RAM and commit capacity before allocation and after a +failure. Free RAM alone does not guarantee that Windows can commit the requested memory. If the pageable fallback +also fails, the warning preserves both the GPU allocation or mapping error and the `malloc` error. **Context:** measured at 4K. The KV cache takes VRAM from the expert cache, so a longer context makes decoding slower; 8K is a reasonable start on 12 GB. `--kv int8` halves the KV cache's VRAM. diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 1e6285ae..d579c544 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -72,6 +72,7 @@ bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64 struct HostMemory { uint64_t available = 0; uint64_t cgroup_limit = ~uint64_t{0}; + uint64_t commit = ~uint64_t{0}; ///< available Windows commit capacity; ~0 when not reported }; /// Linux reads `meminfo`, `self_cgroup` and the cgroup tree under `cgroup_root` (the parameters are for tests; the @@ -82,6 +83,10 @@ bool host_available_memory(HostMemory& m, const std::string& meminfo = "/proc/me const std::string& self_cgroup = "/proc/self/cgroup", const std::string& cgroup_root = "/sys/fs/cgroup"); +/// Bound a resident budget by RAM and commit capacity after headroom; leave 256 MiB more when clamping. +/// Pass UINT64_MAX for commit when the platform does not report it. +uint64_t clamp_resident_budget(uint64_t requested, uint64_t physical, uint64_t commit, uint64_t headroom); + /// 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( @@ -157,6 +162,10 @@ public: /// The blob's bytes into `dst` (blob_bytes(layer) of them). Safe from several threads for a source whose /// `transient` can be true. virtual bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst); + /// Asks the OS for these pairs' bytes ahead of the `blob` calls that read them. False (nothing asked) by default. + virtual bool advise_pairs(const std::pair* pairs, int64_t n) const { + (void) pairs; (void) n; return false; + } /// The `n` experts of `layer` the CPU is about to ask `blob` for, all at once: a source that reads a file may /// fetch them in parallel. The bytes `blob` then returns are the same. Default: nothing. virtual void prefetch(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } @@ -443,15 +452,16 @@ public: /// working set instead. `pin = false` is ordinary pageable memory (the ROCm arm: large pinned allocations /// can fail there, and it is what the HIP measurements used). /// - `lend_from_slot` >= 0: the GPU-cache slots from there to the end are the prompt path's lend region; their - /// experts are kept in RAM too, from the last slot down, as far as `available RAM - headroom_bytes` allows + /// experts are kept in RAM too, from the last slot down, as far as available memory minus headroom allows /// (a lent slot's expert is streamed during the prompt and copied back after it). /// - the rest (the experts no slot holds) must fit that budget, or nothing is allocated and this returns false. /// /// CS-T, `budget_bytes` > 0 (`--resident-budget-gib`): only as many of those experts as fit `budget_bytes`, taken /// in `rank` order (the expert profile: the hottest after the GPU cache's), are copied; the rest stay on the /// mapped files (the SSD tier). No lend region then (a lent slot's expert is read from the files). - /// #467: `budget_bytes` = `kResidentWhatFits` is that path sized by the RAM alone (available minus the headroom - /// and the #403 margin) - the soft --resident-experts mode's second try when the whole complement does not fit; + /// Available memory is limited by both RAM and commit capacity on Windows. + /// #467: `budget_bytes` = `kResidentWhatFits` sizes that path from available memory minus headroom and the #403 + /// margin - the soft --resident-experts mode's second try when the whole complement does not fit; /// false when not even one expert fits. On Windows the mapped experts leave the working set before any reading. static constexpr uint64_t kResidentWhatFits = ~0ull; bool pin_cache_complement( @@ -517,7 +527,8 @@ public: double file_ms() const { return (double) file_us_.load(std::memory_order_relaxed) / 1000.0; } /// Threads `prefetch` reads the GGUF with (STRATA_FETCH_THREADS, default 8). void set_fetch_threads(int n) { fetch_threads_ = n < 1 ? 1 : n; } - /// #286 (Windows): read the experts straight from the drive (FILE_FLAG_NO_BUFFERING, overlapped) instead of + /// #286: read the experts straight from the drive (Windows: FILE_FLAG_NO_BUFFERING, overlapped; Linux: O_DIRECT and + /// the kernel's asynchronous reads) instead of /// through the mapped files - the GGUF in place, or a pack's experts.bin - when the file cache could not keep them /// 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 @@ -533,8 +544,14 @@ public: /// #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); + /// Mapped reads: asks the OS for these pairs' blobs ahead (platform::advise_willneed). False when unbuffered, + /// when read-ahead is off, or before `open`. + bool advise_pairs(const std::pair* pairs, int64_t n) const override; const uint8_t* blob(int64_t layer, int64_t expert) override; + /// Windows, opt-in with STRATA_FILE_RELEASE=1: trim the file mapping's full pages after their expert reaches + /// VRAM. Never touches the resident complement or staging buffers. Disabled by default. + uint64_t release(int64_t layer, int64_t expert) override; bool pinned(int64_t layer, int64_t expert) const override; const uint8_t* device_alias(int64_t layer, int64_t expert) const override; bool pcie_layer(int64_t layer) const override; @@ -552,6 +569,8 @@ public: /// Of the blobs the file tier read for the decode, how many had been warmed for their layer beforehand. int64_t warmed_hits() const { return warm_hits_.load(std::memory_order_relaxed); } int64_t warmed() const { return warm_count_.load(std::memory_order_relaxed); } + /// #286: blobs an unbuffered read could not deliver, read through the mapping instead (0 when all went direct). + int64_t direct_fallbacks() const { return direct_fallbacks_.load(std::memory_order_relaxed); } /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only /// interesting once Phase 3 makes it not so. @@ -570,12 +589,12 @@ private: struct Fill { size_t v; int64_t layer, e; uint8_t* dst; }; /// The claimed buffers' blobs: one overlapped batch when unbuffered, else the fetch threads' mapped copies. void fill_many(const std::vector& todo); - /// #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. + /// #286: the blobs from the drive, unbuffered: every role's 4 KiB-aligned window is read at once (overlapped on + /// Windows, io_submit on Linux) 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 direct_; ///< #286: per file, an unbuffered handle (Windows) or O_DIRECT fd (Linux) std::vector role_file_; ///< 3 x n_layers: index into maps_ / direct_ /// blobs assembled in the stage buffers (`blob` hands those out): the GGUF in place, or any unbuffered source bool staged() const { return !role_ptr_.empty() || !direct_.empty(); } @@ -609,6 +628,7 @@ private: std::atomic file_blob_bytes_{0}, file_us_{0}; std::unique_ptr[]> warm_stamp_; ///< per (layer, expert): epoch_ + 1 when warmed std::atomic warm_hits_{0}, warm_count_{0}; + mutable std::atomic direct_fallbacks_{0}; std::unordered_map stage_of_; uint64_t stage_blob_ = 0; uint64_t stage_seq_ = 0; @@ -733,8 +753,9 @@ private: /// layout's type and dimensions, and inside the file. `native` is the --native shard (see set_gguf). bool check_experts_gguf(const std::string& native, const strata::kernels::cpu::ExpertLayout& lay, std::string& err); /// Fills `dst` (lay.total bytes, the experts.bin layout) from the GGUF files, one role at a time. -/// `unbuffered`: each chunk read past the file cache (Windows). +/// `unbuffered`: each chunk read past the file cache (Windows); `ready`: layer l is written only once +/// *ready > l + 1 (an arena that is still being registered). LoadStats load_experts_gguf(const std::string& native, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, - int threads, bool unbuffered = false); + int threads, bool unbuffered = false, const std::atomic* ready = nullptr); } // namespace strata::core diff --git a/include/strata/core/pinned.hpp b/include/strata/core/pinned.hpp index 28a6f987..51d0948f 100644 --- a/include/strata/core/pinned.hpp +++ b/include/strata/core/pinned.hpp @@ -14,6 +14,7 @@ // fallback is the common case and not an error path. #pragma once +#include #include #include #include @@ -51,6 +52,14 @@ struct PinnedArena { /// existing allocation path. Population/coordination and backing-file lifetime remain the caller's job. PinnedArena(uint64_t bytes, const std::vector& bounds, uint64_t max_pinned_bytes = 0, const std::string& shared_file = {}, uint64_t shared_pack_hash = 0); + /// #285: reserve only; the caller registers the slices with register_slices(), on a thread, while its readers + /// fill the ones already registered (one registration of the whole arena cost ~2.5 s at 33 GiB of 4 KB pages). + struct Deferred {}; + PinnedArena(uint64_t bytes, const std::vector& bounds, Deferred); + /// Registers the deferred slices in order, publishing how many are done in `ready`, and INT_MAX once it + /// returns (a slice CUDA refuses ends the registration, and the rest is kept resident by the working-set lock). + void register_slices(std::atomic& ready); + std::vector bounds_; std::vector slice_starts; void* mapping_base = nullptr; ///< actual mapping start; differs from base when a shared-file header exists uint64_t mapping_bytes = 0; ///< bytes to release from mapping_base @@ -101,14 +110,19 @@ struct LoadStats { LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_bytes, uint64_t blobs_per_layer, uint64_t layers, int threads, uint64_t chunk); /// Plan v0.3 P6: the same with one byte range per layer (`layer_off[L]`, `layer_bytes[L]`). +/// `ready` (optional): layer L is written only once *ready > L + 1 - its slice and the next one registered (a +/// PinnedArena registering its slices meanwhile: writing a page while cudaHostRegister runs on it corrupted the +/// arena under WDDM, even on large pages; a layer boundary inside a page puts that page in both registrations). LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk); + const std::vector& layer_bytes, int threads, uint64_t chunk, + const std::atomic* ready = nullptr); /// The same ranges read UNBUFFERED straight into `dst` (Windows): no staging buffer and no file-cache copy - the /// drive's DMA lands where the experts live. Every range, `dst` and `chunk` must be 4 KiB aligned; returns ok = /// false with an empty `error` when they are not (or off Windows), and the caller falls back to load_experts_ranges. LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk); + const std::vector& layer_bytes, int threads, uint64_t chunk, + const std::atomic* ready = nullptr); /// Whether the expert files are better read unbuffered (Windows; false elsewhere): a timed probe of random 64 KiB /// reads says they are not in the OS file cache (a cached read takes ~10 us, the drive ~80), and the RAM left diff --git a/include/strata/platform/memory.hpp b/include/strata/platform/memory.hpp index 202a3bf2..954f1589 100644 --- a/include/strata/platform/memory.hpp +++ b/include/strata/platform/memory.hpp @@ -43,4 +43,12 @@ inline bool file_cache_keeps(uint64_t avail, uint64_t arena_bytes, uint64_t read return room >= read_bytes; } +/// Whether `advise_willneed` asks the OS for anything: not on Windows, nor with STRATA_READ_AHEAD=0. +bool read_ahead_enabled(); +/// Asks the OS to start reading [p, p + bytes) of a file mapping, without waiting. Linux reads at most one +/// readahead window per request, so the range is asked for in 128 KiB steps. +void advise_willneed(const void* p, uint64_t bytes); +/// The same for [offset, offset + bytes) of an open file. +void advise_willneed(int fd, uint64_t offset, uint64_t bytes); + } // namespace strata::platform diff --git a/serve/server.py b/serve/server.py index f7251a87..34e85059 100644 --- a/serve/server.py +++ b/serve/server.py @@ -36,6 +36,7 @@ import select import signal import socket import struct +import shutil import subprocess import sys import tempfile @@ -64,6 +65,66 @@ from serve.responses import ResponsesError, error_body as responses_error_body IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" + + +def popen(what: str, args: list, **kw): + """#735: subprocess.Popen, but Windows' refusal to start a program (WinError 4551, or 1260 when a policy blocks it: + Smart App Control on a clean Windows 11 blocks an exe that is not signed) is said in words instead of a bare + OSError.""" + try: + return subprocess.Popen(args, **kw) + except OSError as e: + if getattr(e, "winerror", None) in (4551, 1260): + raise OSError(f"Windows blocked {what} ({args[0]}): Smart App Control, or an application-control policy, does " + "not let a program that is not signed run. Turn Smart App Control off (Windows Security > App " + "& browser control > Smart App Control settings), or - for the image encoder only - run setup " + "with --vision no (see docs/TROUBLESHOOTING.md)") from e + raise + + +def listen_problem(host: str, port: int, e: OSError) -> str: + """#769: why the server cannot listen. Only an address that is taken says "already in use"; anything else (a port + Windows keeps reserved, an address this PC does not have, no permission) says what the OS said.""" + import errno + code = getattr(e, "winerror", None) or e.errno + if code in (errno.EADDRINUSE, 10048): + return (f"port {port} is already in use - is Strata (or another server) already running? " + f"Close it, or start this one with a different --port") + what = e.strerror or str(e) + if code in (10013, errno.EACCES): + hint = ("Windows may keep this port for itself (see `netsh int ipv4 show excludedportrange protocol=tcp`) " + "or a firewall rule forbids it: start this one with a different --port") + elif code in (10049, errno.EADDRNOTAVAIL): + hint = f"{host} is not an address of this PC: check \"host\" in the model's strata-.json or --host" + else: + hint = "check --host and --port" + return f"cannot listen on {host}:{port}: {what} [{code}]. {hint}" + + +def combined_embeddings_path(vision_dir: Path, nbytes: int) -> Path: + """#874: where one request's combined image-embeddings file goes. Every request with images rewrites it (it is + deleted after the request), which on a disk is steady heavy writing: on Linux it goes to /dev/shm when that has + room (the engine reads it back at once), on Windows the file is opened short-lived (the cache is not forced out + to the drive). Anywhere else, or when /dev/shm is too small (Docker's default is 64 MB), it stays in the encoder's + own directory, as before.""" + name = f"req-{uuid.uuid4().hex[:12]}.sve" + shm = Path("/dev/shm") + if os.name != "nt" and shm.is_dir() and os.access(shm, os.W_OK): + try: + if shutil.disk_usage(shm).free > 2 * nbytes + (16 << 20): + return shm / f"strata-vision-{os.getpid()}-{name}" + except OSError: + pass + return Path(vision_dir) / name + + +def write_temporary(path: Path, parts: list) -> None: + """#874: write `parts` (files) one after the other into `path`; on Windows with FILE_ATTRIBUTE_TEMPORARY + (os.O_SHORT_LIVED), so the file normally never reaches the drive before it is deleted.""" + flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0) | getattr(os, "O_SHORT_LIVED", 0) + with os.fdopen(os.open(path, flags, 0o600), "wb") as f: + for part in parts: + f.write(Path(part).read_bytes()) # #458: the trailing effort turn ("effort_position": "end"); low is the template's own sentence, medium (which the # template says nothing for: no xhigh sentence is medium there) says it, since the xhigh one stays at the top EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n" @@ -513,8 +574,15 @@ class StrataEngine: if os.environ.get("STRATA_REQUEST_LINES") and os.path.abspath(log) not in _echoing: _echoing.add(os.path.abspath(log)) threading.Thread(target=echo_requests, args=(log, os.path.getsize(log)), daemon=True).start() - self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) + if log: # #779: when an engine started (a crash report has the time) + try: + self.log.write(f"[strata] {time.strftime('%Y-%m-%d %H:%M:%S')} engine started: {exe} --serve " + f"{' '.join(args)}\n") + self.log.flush() + except OSError: + pass + self.proc = popen("the Strata engine", [exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) contain(self.proc) # ends with the server, however it ends (Windows) self.max_context = 0 for line in self.proc.stdout: @@ -1368,8 +1436,29 @@ class Vision: lines and writes each image's embeddings; results are cached by the image's hash, so a conversation that sends the same picture again (every turn, with most clients) encodes it once.""" + @staticmethod + def work_dir() -> Path: + """#480: the directory for the encoder's files. The engine reads the embeddings file named in a `GENI` line + and the encoder the output named in an `ENC ` line, both split at spaces, so a space in the path + (a %TEMP% under a user name with a space) broke every image. The system temp directory is used while its path + has no space, then the working directory, then the system drive's root; the plain temp directory is the last + resort (the encoder's own files are then named relative to it, see `_start`).""" + for parent in (None, Path.cwd(), Path(os.environ.get("SystemDrive", "C:") + os.sep)): + try: + d = Path(tempfile.mkdtemp(prefix="strata-vision-", dir=parent)) + except OSError: + continue # not writable, or no such drive + if " " not in str(d): + return d + try: + d.rmdir() # just created, so still empty + except OSError: + pass + return Path(tempfile.mkdtemp(prefix="strata-vision-")) + def __init__(self, cfg: dict, log=None, env: dict | None = None): - args = [cfg["exe"], "--mmproj", cfg["mmproj"], "--model", cfg["model"]] + absolute = lambda p: os.path.abspath(p) if os.path.dirname(str(p)) else p # the encoder runs in its own dir (#480) # noqa: E731 + args = [absolute(cfg["exe"]), "--mmproj", absolute(cfg["mmproj"]), "--model", absolute(cfg["model"])] if cfg.get("gpu"): args.append("--gpu") if cfg.get("threads"): @@ -1378,7 +1467,7 @@ class Vision: args += ["--max-tokens", str(cfg["max_tokens"])] if cfg.get("min_tokens"): # #767: mtmd's image_min_tokens (a hand-edited key) args += ["--min-tokens", str(cfg["min_tokens"])] - self.dir = Path(tempfile.mkdtemp(prefix="strata-vision-")) + self.dir = self.work_dir() self.spawn = (args, log, env) # to start it again after an unload self.stopped = False self._start() @@ -1387,8 +1476,10 @@ class Vision: def _start(self): args, log, env = self.spawn - self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL, - text=True, encoding="utf-8", bufsize=1, env=env) + # cwd is the encoder's directory: the ENC lines name the files relative to it (#480: no space in the line) + self.proc = popen("the image encoder", args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=log or subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1, env=env, + cwd=self.dir) contain(self.proc) line = self.proc.stdout.readline() if not line.startswith("READY"): @@ -1489,7 +1580,7 @@ class Vision: img, out = self.dir / f"{key}.img", self.dir / f"{key}.sve" img.write_bytes(data) try: - self.proc.stdin.write(f"ENC {img} {out}\n") + self.proc.stdin.write(f"ENC {img.name} {out.name}\n") # relative to the encoder's cwd (#480) self.proc.stdin.flush() line = self.proc.stdout.readline().strip() finally: # #352: also when the encoder's pipe is gone @@ -2433,11 +2524,9 @@ class Service: # The request's images in one file for GENI (~10 MB a picture), written once nothing above refuses the # request: one refused after it (the engine starting, no room) left it in the vision directory for good, # one more for every retry of a 503. run() deletes it; drop_embeddings() if run() never starts. - combined = self.vision.dir / f"req-{uuid.uuid4().hex[:12]}.sve" + combined = combined_embeddings_path(self.vision.dir, sum(Path(p).stat().st_size for p, _ in encoded)) self.embeddings.path = combined # first, so a half-written one is found as well - with open(combined, "wb") as f: - for path, _ in encoded: - f.write(path.read_bytes()) + write_temporary(combined, [p for p, _ in encoded]) return ids, kwargs.get("enable_thinking", True) is not False, max_new def drop_embeddings(self) -> None: @@ -4404,9 +4493,8 @@ def main() -> int: a.host = a.host or cfg.get("host") or "127.0.0.1" # issue #26: the run scripts pass no --host, the config can try: # before the minutes of loading: is the port free? Server((a.host, a.port), BaseHTTPRequestHandler).server_close() - except OSError: - ap.error(f"port {a.port} is already in use - is Strata (or another server) already running? " - f"Close it, or start this one with a different --port") + except OSError as e: + ap.error(listen_problem(a.host, a.port, e)) if cfg.get("tokenizer"): a.tokenizer = cfg["tokenizer"] tok = ByteTokenizer() diff --git a/serve/test_server.py b/serve/test_server.py index 4130ede1..01d19827 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -453,6 +453,111 @@ class ImageMarkers(unittest.TestCase): self.assertEqual(svc.encode_prompt(msgs, tools, {}), old(msgs, tools)) +class VisionTempFiles(unittest.TestCase): + """#480 (a TEMP path with a space), #874 (the per-request embeddings file), #735 (Smart App Control).""" + + def test_work_dir_has_no_space_when_temp_has_one(self): + from serve.server import Vision + with tempfile.TemporaryDirectory() as base: + spaced = Path(base) / "John Smith" + spaced.mkdir() + with mock.patch.object(tempfile, "tempdir", str(spaced)): + d = Vision.work_dir() + try: + self.assertNotIn(" ", str(d)) + self.assertTrue(d.is_dir()) + finally: + d.rmdir() + + def test_enc_line_names_files_relative_to_the_encoder_dir(self): + from serve.server import Vision + + class Pipe: + def __init__(self): + self.lines = [] + + def write(self, s): + self.lines.append(s) + + def flush(self): + pass + + pipe = Pipe() + v = Vision.__new__(Vision) + v.dir, v.lock, v.cache = Path(tempfile.mkdtemp(prefix="strata-vision-test-")), threading.Lock(), {} + v.proc = mock.Mock(stdin=pipe, stdout=mock.Mock(readline=lambda: "OK 7 1 1 1\n")) + try: + with mock.patch.object(Vision, "load", return_value=b""), \ + mock.patch.object(Vision, "normalize", return_value=b"png"): + out, n = v.encode("x") + self.assertEqual(n, 7) + self.assertEqual(out.parent, v.dir) # the cache keeps the full path + name = out.name + self.assertEqual(pipe.lines, [f"ENC {name[:-4]}.img {name}\n"]) + finally: + shutil_rmtree(v.dir) + + def test_combined_file_is_written_whole_and_removable(self): + from serve.server import combined_embeddings_path, write_temporary + with tempfile.TemporaryDirectory() as d: + a, b = Path(d) / "a.sve", Path(d) / "b.sve" + a.write_bytes(b"AAAA") + b.write_bytes(b"BB") + path = combined_embeddings_path(Path(d), 6) + try: + write_temporary(path, [a, b]) + self.assertEqual(path.read_bytes(), b"AAAABB") + finally: + path.unlink(missing_ok=True) + + def test_combined_file_stays_off_a_small_shm(self): + from serve.server import combined_embeddings_path + with tempfile.TemporaryDirectory() as d: + if os.name == "nt": + self.assertEqual(combined_embeddings_path(Path(d), 1).parent, Path(d)) + return + with mock.patch("serve.server.shutil.disk_usage", return_value=SimpleNamespace(free=1 << 20)): + self.assertEqual(combined_embeddings_path(Path(d), 1 << 20).parent, Path(d)) + + def test_smart_app_control_is_said_in_words(self): + import subprocess + from serve.server import popen + for code in (4551, 1260): + err = OSError(22, "blocked") + err.winerror = code + with self.subTest(winerror=code), mock.patch.object(subprocess, "Popen", side_effect=err): + with self.assertRaises(OSError) as cm: + popen("the image encoder", ["strata-vision.exe"]) + self.assertIn("Smart App Control", str(cm.exception)) + self.assertIn("--vision no", str(cm.exception)) + with mock.patch.object(subprocess, "Popen", side_effect=FileNotFoundError("gone")): + with self.assertRaises(FileNotFoundError): + popen("x", ["x"]) + + +class ListenProblem(unittest.TestCase): + """#769: only an address that is taken is "already in use".""" + + def test_messages(self): + import errno + from serve.server import listen_problem + self.assertIn("already in use", listen_problem("127.0.0.1", 8080, OSError(errno.EADDRINUSE, "in use"))) + e = OSError(10013, "forbidden") + e.winerror = 10013 + text = listen_problem("127.0.0.1", 8080, e) + self.assertNotIn("already in use", text) + self.assertIn("forbidden", text) + self.assertIn("different --port", text) + text = listen_problem("10.9.9.9", 8080, OSError(errno.EADDRNOTAVAIL, "cannot assign")) + self.assertIn("10.9.9.9 is not an address of this PC", text) + self.assertNotIn("already in use", text) + + +def shutil_rmtree(path): + import shutil + shutil.rmtree(path, ignore_errors=True) + + class ThinkTokenizer(ByteTokenizer): """The byte tokenizer with the model's reasoning markers as specials that are matched even without parse_special, as the real tokenizer does (GGUF token type 4).""" diff --git a/serve/test_winjob.py b/serve/test_winjob.py index 31b617ab..d7b3df6b 100644 --- a/serve/test_winjob.py +++ b/serve/test_winjob.py @@ -65,3 +65,18 @@ class TestWinJob(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +@unittest.skipUnless(os.name == "nt", "power throttling is a Windows setting") +class TestNoThrottle(unittest.TestCase): + def test_a_contained_child_is_opted_out_of_power_throttling(self): + # #691: contain() also sets ProcessPowerThrottling (EcoQoS off), so a minimized server window does not move the + # engine to the E-cores + from serve import winjob + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) + try: + self.assertTrue(winjob.no_throttle(int(child._handle))) + self.assertTrue(winjob.contain(child)) + finally: + child.kill() + child.wait(10) diff --git a/serve/winjob.py b/serve/winjob.py index 008642a0..7eb58eef 100644 --- a/serve/winjob.py +++ b/serve/winjob.py @@ -4,7 +4,8 @@ Closing the console window, Task Manager or a crash end the server without runni the vision encoder and the MCP servers kept running on their own. `contain(proc)` puts a child in a job object that is set to kill everything in it when its last handle closes - and the only handle is this process's, which the OS closes however the server ends. Processes the child starts later join the same job. The server itself stays out of -the job, so a browser that `--open` starts is not tied to it. Elsewhere, and if the job cannot be made, a no-op. +the job, so a browser that `--open` starts is not tied to it. Each child (and the server) is also opted out of Windows +power throttling, see `no_throttle` (#691). Elsewhere, and if the job cannot be made, a no-op. """ from __future__ import annotations @@ -57,6 +58,27 @@ if os.name == "nt": return None return job + class _PowerThrottling(ctypes.Structure): + _fields_ = [("Version", wintypes.ULONG), ("ControlMask", wintypes.ULONG), ("StateMask", wintypes.ULONG)] + + _k32.SetProcessInformation.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD) + _k32.GetCurrentProcess.restype = wintypes.HANDLE + + def no_throttle(handle) -> bool: + """Opt a process out of Windows power throttling (EcoQoS). Without it Windows 11 treats a process whose console + window is minimized as background work and, on a hybrid CPU, moves its threads to the E-cores: generation + slowed by about 20% while the server window was minimized (#691, i9-13980HX: 36.6 -> 43.2 tok/s).""" + for mask in (0x1 | 0x4, 0x1): # EXECUTION_SPEED and IGNORE_TIMER_RESOLUTION, both off (Windows 11); + info = _PowerThrottling(1, mask, 0) # Windows 10 knows the first only: ERROR_INVALID_PARAMETER for both + if _k32.SetProcessInformation(handle, 4, ctypes.byref(info), ctypes.sizeof(info)): # ProcessPowerThrottling + return True + return False + + no_throttle(_k32.GetCurrentProcess()) # the server itself (tokenizing, streaming) too +else: + def no_throttle(handle) -> bool: + return False + def contain(proc) -> bool: """Put a started subprocess.Popen in the kill-on-close job. True if it is in; False (harmlessly) otherwise.""" @@ -69,6 +91,7 @@ def contain(proc) -> bool: if not _job: return False try: + no_throttle(int(proc._handle)) return bool(_k32.AssignProcessToJobObject(_job, int(proc._handle))) except (AttributeError, OSError, ValueError): return False diff --git a/setup.py b/setup.py index 96864095..fa5bc4c3 100644 --- a/setup.py +++ b/setup.py @@ -178,7 +178,9 @@ UNSLOTH_RAM_LEFT_GB = 24 # RAM beside the budget: the OS, the engine, and # from the final context (final / 262144, at least 1) itself (below), keeps an explicit # --rope-scaling/--rope-scale, and refuses an explicit --rope-scaling none there - the stock angles past # the trained range are out of spec. -CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288] +# 204800 (200K) sits between 128K and 256K: it is inside the trained 262144, so it needs no rope scaling and +# costs ~2.8 GB of 8-bit KV with IQ3_S (vs ~3.6 GB at 256K) - a middle step for PCs that cannot hold 256K. +CONTEXTS = [8192, 32768, 65536, 131072, 204800, 262144, 393216, 524288] # The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. FAMILIES = { "qwen": {"title": "Qwen3.8-Flash-Next", "by": "Qwen; GSQ-RCO quants by ISTA-DASLab", @@ -253,9 +255,28 @@ def fail(msg, hint=None): sys.exit(1) +def flush_typed_ahead() -> None: + """#841: keys pressed while setup was busy (a download, a build) are not answers to the next question: Enter pressed + to "wake" a slow step answered "Go on anyway?" with its default. Dropped before a question is asked, on a terminal + only (a pipe or a test keeps its input).""" + try: + if not sys.stdin.isatty(): + return + if WIN: + import msvcrt + while msvcrt.kbhit(): + msvcrt.getwch() + else: + import termios + termios.tcflush(sys.stdin.fileno(), termios.TCIFLUSH) + except (ImportError, OSError, ValueError, AttributeError): + pass + + def ask(question, choices, default, yes): if yes: return default + flush_typed_ahead() while True: try: a = input(f"{question} [{default}]: ").strip() @@ -355,15 +376,9 @@ def cpu_cores(): classes.append(raw[at + 9]) at += size else: - seen = {} - for cpu in sorted(Path("/sys/devices/system/cpu").glob("cpu[0-9]*"), key=lambda p: int(p.name[3:])): - cap = cpu / "cpu_capacity" - pkg, core = cpu / "topology" / "physical_package_id", cpu / "topology" / "core_id" - if not cap.exists(): - return None - key = (pkg.read_text().strip(), core.read_text().strip()) if pkg.exists() and core.exists() else cpu.name - seen.setdefault(key, int(cap.read_text().strip())) - classes = list(seen.values()) + classes = linux_core_classes() + if classes is None: + return None except (OSError, ValueError, AttributeError): return None if not classes or max(classes) == min(classes): @@ -372,6 +387,52 @@ def cpu_cores(): return p, len(classes) - p +def linux_core_classes(sys_root: str = "/sys"): + """One class per physical core on Linux: 1 for a P-core, 0 for an E-core; None when the kernel does not say. + #798: Intel's hybrid PMU lists (cpu_core/cpus, cpu_atom/cpus) when they exist; else cpu_capacity, where an E-core is + one under 90% of the largest - Turbo Boost Max 3.0 gives the "favored" P-cores a slightly higher capacity (1024 + against 1012), so "below the maximum" counted 2 of a Core Ultra 7 270K Plus's 8 P-cores.""" + pmu = linux_hybrid_pmu(sys_root + "/devices") + seen = {} + for cpu in sorted((Path(sys_root) / "devices" / "system" / "cpu").glob("cpu[0-9]*"), key=lambda p: int(p.name[3:])): + cap = cpu / "cpu_capacity" + pkg, core = cpu / "topology" / "physical_package_id", cpu / "topology" / "core_id" + if not cap.exists() and pmu is None: + return None + key = (pkg.read_text(encoding="utf-8").strip(), core.read_text(encoding="utf-8").strip()) \ + if pkg.exists() and core.exists() else cpu.name + if pmu is not None: + seen.setdefault(key, 0 if int(cpu.name[3:]) in pmu[1] else 1) + else: + seen.setdefault(key, int(cap.read_text(encoding="utf-8").strip())) + classes = list(seen.values()) + if pmu is None: + top = max(classes, default=0) + classes = [1 if c * 10 >= top * 9 else 0 for c in classes] + return classes + + +def cpulist(text: str) -> set: + """A kernel cpulist ("0-7,16") as a set of CPU numbers.""" + out = set() + for part in text.strip().split(","): + lo, _, hi = part.strip().partition("-") + if lo.isdigit(): + out.update(range(int(lo), int(hi or lo) + 1)) + return out + + +def linux_hybrid_pmu(root: str = "/sys/devices"): + """#798: (P-core CPUs, E-core CPUs) from Intel's hybrid PMU lists (cpu_core/cpus, cpu_atom/cpus), or None on a CPU + that has no such lists.""" + try: + p = cpulist((Path(root) / "cpu_core" / "cpus").read_text(encoding="utf-8")) + e = cpulist((Path(root) / "cpu_atom" / "cpus").read_text(encoding="utf-8")) + except OSError: + return None + return (p, e) if p and e else None + + def hybrid_pool_workers(cores) -> int | None: """#642 (Hardin22's measurement): on a hybrid CPU the expert pool runs best on the P-cores but the host loop's one plus HALF of the E-cores - an E-core runs the expert kernels ~2.2x slower and each layer waits for its slowest @@ -541,6 +602,13 @@ def gpus(): return found +def gpu_drives_display(g) -> bool: + """#779: True when nvidia-smi says this card has a display attached (display_active Enabled): its desktop needs + VRAM too, and a full expert cache beside it has crashed laptops.""" + text = out(["nvidia-smi", "-i", str(g.get("index", 0)), "--query-gpu=display_active", "--format=csv,noheader"]) + return text.strip().lower() == "enabled" + + GPU_PICK = None # --gpu N (issue #51); None: the card with the most VRAM SPLIT_MIN_VRAM_GB = 8 # a card sharing a model holds the dense weights and its own # prompt buffers too (docs/MULTI_GPU.md) @@ -725,7 +793,7 @@ def engine_archs(toolkit=13): """The GPU generations the installed engine has code for: (archs, ptx), or None when there is none.""" info = engine_dir(toolkit) / "BUILD.json" try: - meta = json.loads(info.read_text()) + meta = json.loads(info.read_text(encoding="utf-8")) except (OSError, ValueError): return None return [int(x) for x in meta.get("archs", [])], bool(meta.get("ptx")) @@ -734,7 +802,7 @@ def engine_archs(toolkit=13): def engine_archs_hip(): """The AMD architectures the installed HIP engine was compiled for ("gfx1201", ...), or None.""" try: - meta = json.loads((ROOT / "engine" / "BUILD.json").read_text()) + meta = json.loads((ROOT / "engine" / "BUILD.json").read_text(encoding="utf-8")) except (OSError, ValueError): return None return [str(x) for x in meta.get("archs", [])] if meta.get("backend") == "hip" else None @@ -839,20 +907,24 @@ def unsloth_split_need_gb(model="UD-Q4_K_XL") -> float: return MODELS[model]["download_gb"] + UNSLOTH_RAM_LEFT_GB -def split_budget(cfg: dict) -> bool: +def split_budget(cfg: dict, yes: bool = False, explicit: bool = False) -> bool: """#498: a UD-Q4_K_XL config (its RAM budget, --resident-budget-gib) started on several GPUs. The engine refuses the budget with a layer split (it exited with code 2), so the split runs without it - all the experts loaded into - RAM at start - where the RAM holds the GGUFs and 24 GB more; else setup stops, before the config is saved. True - when the config changed.""" + RAM at start - where the RAM holds the GGUFs and 24 GB more; else setup says so and asks (#737: a recommendation, + not a wall - 128 GB ran it fine): a "no" stops, before the config is saved; `explicit` (--gpus) with --yes goes on. + True when the config changed.""" a = cfg.get("args", []) if "--resident-budget-gib" not in a: return False model = budget_model(cfg) need, ram = unsloth_split_need_gb(model), ram_gb() if ram < need: - 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)") + confirm_risk(f"{model} cannot share its RAM budget across GPUs (the engine has no layer split with it), and " + f"without the budget it needs ~{need:.0f} GB of RAM (its GGUF files and {UNSLOTH_RAM_LEFT_GB} GB " + f"more); this PC has {ram:.0f} GB. The estimate is a worst case: a 128 GB PC ran it (#737), but " + "it may page or stall here.", explicit, yes, + f"{model} on several GPUs needs ~{need:.0f} GB of RAM; this PC 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(f"{model} on several GPUs: no RAM budget (the engine has none with a layer split) - all its experts are " @@ -1066,6 +1138,8 @@ def download(url, dst: Path, what=None): return have = part.stat().st_size if part.exists() else 0 for attempt in range(30): + if total and have >= total: # stopped after the last byte, before the rename: nothing to + break # ask for (a range past the end is a 416, retried 30 times) try: req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={have}-"}) with urllib.request.urlopen(req, timeout=60) as r, open(part, "ab" if have else "wb") as f: @@ -1251,6 +1325,11 @@ def check_shards(shards): if have < need: fail(f"{s.name} is short: {have:,} of {need:,} bytes ({need - have:,} missing)", "delete it and run setup again (or copy the whole file into --gguf-dir)") + if len(g.tensors) == 1 and have - need >= 64: # (a few bytes may be the last tensor's alignment padding) + # #657: a shard that holds one tensor (the PLE table) is exactly as long as that tensor; extra bytes are a + # damaged or wrong file that the engine would refuse at start ("PLE table size mismatch") + fail(f"{s.name} is longer than its tensor: {have:,} bytes, {need:,} expected ({have - need:,} extra)", + f"delete {s.name} and its .done mark and run setup again") def get_llama_cpp(): @@ -1315,7 +1394,7 @@ def pip_install(packages, what): requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the pinned dependencies it already has count as installed.""" stamp = Path(sys.prefix) / ".strata-pip.json" - have = json.loads(stamp.read_text()) if stamp.exists() else [] + have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else [] bare = {p.lower() for p in have if req_name(p) == p.lower()} need = [p for p in packages if p not in have and req_name(p) not in bare and not (bare and "==" in p and _installed(req_name(p)))] @@ -1469,7 +1548,8 @@ _WIN_AMD_DID = {0x744C: "gfx1100", 0x7448: "gfx1100", 0x745E: "gfx1100", 0x7480: "gfx1102", # RX 7600 / 7600 XT 0x7590: "gfx1200", # RX 9060 XT 0x7550: "gfx1201", 0x7551: "gfx1201", # RX 9070 / 9070 XT, AI PRO R9700 - 0x73BF: "gfx1030", 0x73AF: "gfx1030", 0x73A5: "gfx1030"} # RX 6800 / 6800 XT / 6900 XT / 6950 XT + 0x73BF: "gfx1030", 0x73AF: "gfx1030", 0x73A5: "gfx1030", # RX 6800 / 6800 XT / 6900 XT / 6950 XT + 0x73DF: "gfx1031"} # RX 6700 XT / 6750 XT / 6800M (#881) _WIN_AMD_NAME = ((re.compile(r"\b9070\b|R9700", re.I), "gfx1201"), (re.compile(r"\b9060\b", re.I), "gfx1200"), (re.compile(r"RX\s*7900|W7900|W7800", re.I), "gfx1100"), @@ -1582,7 +1662,7 @@ def hip_devices(probe: Path | None = None, text: str | None = None) -> list[dict if text is None: probe = probe or ROOT / "engine" / ("strata-device.exe" if WIN else "strata-device") try: - hip_engine = json.loads((probe.parent / "BUILD.json").read_text()).get("backend") == "hip" + hip_engine = json.loads((probe.parent / "BUILD.json").read_text(encoding="utf-8")).get("backend") == "hip" except (OSError, ValueError): hip_engine = False if not probe.exists() or not hip_engine: @@ -1623,7 +1703,7 @@ def hip_devices(probe: Path | None = None, text: str | None = None) -> list[dict def hip_lib_dirs(eng: Path) -> list[Path]: """Where the ready-made Windows HIP engine's ROCm DLLs are (its BUILD.json "lib_dirs", relative to engine/).""" try: - rel = json.loads((eng / "BUILD.json").read_text()).get("lib_dirs") or [] + rel = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("lib_dirs") or [] except (OSError, ValueError): rel = [] return [eng / d for d in rel if (eng / d).is_dir()] @@ -1690,7 +1770,7 @@ def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None: info = eng / "BUILD.json" if info.exists() and (eng / EXE).exists(): try: - meta = json.loads(info.read_text()) + meta = json.loads(info.read_text(encoding="utf-8")) except ValueError: meta = {} ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) @@ -1723,7 +1803,7 @@ def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None: with zipfile.ZipFile(z) as f: f.extractall(tmp) try: - meta = json.loads((tmp / "BUILD.json").read_text()) + meta = json.loads((tmp / "BUILD.json").read_text(encoding="utf-8")) except (OSError, ValueError): meta = {} ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) @@ -1733,17 +1813,14 @@ def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None: elif ver < WIN_HIP_MIN_ENGINE: why = f"it is version {meta.get('version')}; this setup needs {'.'.join(map(str, WIN_HIP_MIN_ENGINE))}" elif gpu["arch"] not in meta.get("archs", []): - why = f"it is built for {', '.join(meta.get('archs', []))}; your GPU is {gpu['arch']}" + why = (f"it is built for {', '.join(meta.get('archs', []))}; your GPU is {gpu['arch']}. A card it has no code " + "for runs from a self-build of the engine: see docs/AMD_HIP.md (--build)") # #881 if why: warn(f"the ready-made AMD engine at {base} cannot be used: {why}") shutil.rmtree(tmp, ignore_errors=True) drop_archive(z) return None - for p in tmp.iterdir(): - dst = eng / p.name - if dst.exists(): - shutil.rmtree(dst) if dst.is_dir() else dst.unlink() - p.replace(dst) + install_unpacked(tmp, eng) shutil.rmtree(tmp, ignore_errors=True) drop_archive(z) hip_runtime_beside_exe(eng) # #468 #461 @@ -1755,7 +1832,7 @@ def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None: def rocm_version(root): """(major, minor) of a ROCm install, from rocm-core's header; None when it has none.""" try: - text = (Path(root) / "include" / "rocm-core" / "rocm_version.h").read_text() + text = (Path(root) / "include" / "rocm-core" / "rocm_version.h").read_text(encoding="utf-8") return tuple(int(re.search(rf"#define\s+ROCM_VERSION_{k}\s+(\d+)", text).group(1)) for k in ("MAJOR", "MINOR")) except (OSError, AttributeError, ValueError): return None @@ -1793,7 +1870,7 @@ def rocm_root(archs): "wheels come per family", "install ROCm 7 system-wide, or use cards of one family (--gpu N for one card)") index = indexes[0] stamp = Path(sys.prefix) / ".strata-rocm.json" - have = json.loads(stamp.read_text()) if stamp.exists() else {} + have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {} if have.get("version") != ROCM_VERSION or have.get("index") != index: say(f" Installing ROCm {ROCM_VERSION} for AMD GPUs into .venv (AMD's TheRock wheels, ~10 GB, no sudo) ...") pip = [sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--index-url", index] @@ -1823,7 +1900,7 @@ def hipblaslt_version(lib_dirs): header of the ROCm whose libraries the engine loads; None when not found.""" for d in lib_dirs: try: - text = (Path(d).parent / "include" / "hipblaslt" / "hipblaslt-version.h").read_text() + text = (Path(d).parent / "include" / "hipblaslt" / "hipblaslt-version.h").read_text(encoding="utf-8") v = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", text).group(1)) for k in ("MAJOR", "MINOR", "PATCH")] except (OSError, AttributeError, ValueError): @@ -1839,7 +1916,7 @@ def hipblaslt_table(arch, lib_dirs, ver=None): ver = ver or hipblaslt_version(lib_dirs) table = ROOT / "tools" / "hip" / f"{arch}-hipblaslt-{ver}.txt" if ver is not None and table.exists(): - head = table.read_text().split("\n", 2)[:2] + head = table.read_text(encoding="utf-8").split("\n", 2)[:2] if f"STRATA_HIPBLASLT_TUNING_V1 {arch} {ver}" in (h.strip() for h in head): ok(f"hipBLASLt tuning table: {table.name} (faster prompts)") return table @@ -1858,7 +1935,7 @@ def build_engine_hip(gpu, llama, vision="none") -> Path: eng = ROOT / "engine" eng.mkdir(exist_ok=True) stamp = eng / "BUILD.json" - meta = json.loads(stamp.read_text()) if stamp.exists() else {} + meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {} src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) archs = sorted(set(gpu.get("archs") or [gpu["arch"]])) has_archs = set(archs) <= set(meta.get("archs", [])) @@ -1921,7 +1998,8 @@ def build_vision_cpu(eng: Path, stamp: Path, meta: dict, llama, vsrc) -> Path: if not ((eng / VEXE).exists() and meta.get("vision_src") == vsrc): say(" Compiling the image encoder (for the CPU) ...") cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision", "strata-vision", - [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=OFF"], None, "") + [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=OFF"], find_vcvars() if WIN else None, + "build-vision-cpu.bat" if WIN else "") # #881: MSVC's environment on Windows, as the CUDA path has shutil.copy2(ROOT / "build-vision" / "bin" / VEXE, eng / VEXE) stamp.write_text(json.dumps({**meta, "vision": "cpu", "vision_src": vsrc}, indent=1)) ok(f"engine: {eng / EXE}, image encoder (CPU): {eng / VEXE}") @@ -1945,6 +2023,70 @@ def prebuilt_bases(url_base) -> list[str]: return [PREBUILT_TAG_URL.format(version=source_version()), base] +PREVIOUS_ENGINE = ".previous" + + +def engine_version_of(folder: Path) -> str: + try: + return str(json.loads((folder / "BUILD.json").read_text(encoding="utf-8")).get("version", "?")) + except (OSError, ValueError): + return "?" + + +def install_unpacked(tmp: Path, eng: Path) -> None: + """#670: the unpacked engine (tmp) replaces the installed one in `eng`, which is kept, one generation, in + eng/.previous (about 210 MiB): a new engine that turns out bad has a way back (`setup.py --rollback-engine`). The + swap is all or nothing: a failure part-way puts the old files back instead of leaving a mix of old and new.""" + prev = eng / PREVIOUS_ENGINE + new = list(tmp.iterdir()) + old = [eng / p.name for p in new if p.name != PREVIOUS_ENGINE and (eng / p.name).exists()] + shutil.rmtree(prev, ignore_errors=True) + moved, placed = [], [] + try: + if old: + prev.mkdir() + for dst in old: + shutil.move(str(dst), str(prev / dst.name)) + moved.append(dst) + for p in new: + p.replace(eng / p.name) + placed.append(eng / p.name) + except OSError: + for dst in placed: # back to the old engine, whole + shutil.rmtree(dst) if dst.is_dir() else dst.unlink(missing_ok=True) + for dst in moved: + shutil.move(str(prev / dst.name), str(dst)) + shutil.rmtree(prev, ignore_errors=True) + raise + if moved: + ok(f"the engine it replaced ({engine_version_of(prev)}) is kept in {prev}; " + "setup.py --rollback-engine puts it back") + + +def rollback_engine(toolkit=13) -> int: + """#670: `setup.py --rollback-engine`: the engine kept in engine/.previous becomes the installed one again, and the + one it replaces is kept in its place (run it again to go forward).""" + eng = engine_dir(toolkit) + prev = eng / PREVIOUS_ENGINE + if not prev.is_dir() or not any(prev.iterdir()): + warn(f"no earlier engine is kept in {prev} (one is kept when an update replaces the engine)") + return 1 + swap = eng / ".swap" + shutil.rmtree(swap, ignore_errors=True) + swap.mkdir() + was = engine_version_of(eng) + for p in list(prev.iterdir()): # what the earlier engine has: the current copy goes aside + cur = eng / p.name + if cur.exists(): + shutil.move(str(cur), str(swap / p.name)) + shutil.move(str(p), str(cur)) + for p in list(swap.iterdir()): + shutil.move(str(p), str(prev / p.name)) + shutil.rmtree(swap, ignore_errors=True) + ok(f"engine {engine_version_of(eng)} is installed again (it replaced {was}, which is kept in {prev})") + return 0 + + def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | None: """The ready-made engine in engine/ (kept between runs), or None when there is none for this PC. updating: called to replace an installed engine, which starts instead when this fails (no compile). @@ -1952,8 +2094,8 @@ def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | No eng = engine_dir(toolkit) asset = CUDA12_ASSET if int(toolkit) == 12 else PREBUILT_ASSET info = eng / "BUILD.json" - if info.exists() and (eng / EXE).exists() and json.loads(info.read_text()).get("backend") != "hip": - meta = json.loads(info.read_text()) + if info.exists() and (eng / EXE).exists() and json.loads(info.read_text(encoding="utf-8")).get("backend") != "hip": + meta = json.loads(info.read_text(encoding="utf-8")) ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) if meta.get("source") == "local": # compiled here: build_engine checks its source and cards return None @@ -1991,9 +2133,13 @@ def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | No download(base + asset, z, "Strata engine") tmp = eng / "_unpack" shutil.rmtree(tmp, ignore_errors=True) - with zipfile.ZipFile(z) as f: - f.extractall(tmp) - meta = json.loads((tmp / "BUILD.json").read_text()) + try: + with zipfile.ZipFile(z) as f: + f.extractall(tmp) + except zipfile.BadZipFile: # not a zip, or a damaged one: a kept .done mark would make + drop_archive(z) # every later run fail on it instead of downloading it again + raise + meta = json.loads((tmp / "BUILD.json").read_text(encoding="utf-8")) if tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) < MIN_ENGINE: need = ".".join(map(str, MIN_ENGINE)) if updating: # these files are newer than the published release (#58) @@ -2014,11 +2160,7 @@ def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | No shutil.rmtree(tmp, ignore_errors=True) drop_archive(z) return None - for p in tmp.iterdir(): - dst = eng / p.name - if dst.exists(): - shutil.rmtree(dst) if dst.is_dir() else dst.unlink() - p.replace(dst) + install_unpacked(tmp, eng) shutil.rmtree(tmp, ignore_errors=True) drop_archive(z) if not (eng / EXE).exists(): @@ -2046,7 +2188,7 @@ def update_installed_engine(url_base, toolkit=None) -> None: info = eng / "BUILD.json" if not info.exists() or not (eng / EXE).exists(): return - meta_text = info.read_text() + meta_text = info.read_text(encoding="utf-8") meta = json.loads(meta_text) if meta.get("backend") == "hip" and WIN: # AMD on Windows: the ready-made HIP engine, when older ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) @@ -2217,6 +2359,9 @@ def cmake_build(src, bdir, target, defs, vcvars, bat_name): # A failed build is tried once more: CUDA 13.0's ptxas now and then fails to parse a PTX file it just wrote, and # the same command then gets past it (issue #45); a second attempt only compiles what is still missing. if WIN: + if vcvars is None: # #881: the build needs MSVC's environment + fail("the Visual Studio C++ build tools were not found", + "install them (Visual Studio 2019 or 2022, workload 'Desktop development with C++') and run setup again") bat = ROOT / bat_name q = lambda c: " ".join(f'"{x}"' if " " in str(x) else str(x) for x in c) # noqa: E731 bat.write_text(f'@echo off\r\ncall "{vcvars}" >nul\r\n{q(conf)} || exit /b 1\r\n{q(build)} && exit /b 0\r\n' @@ -2284,7 +2429,7 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path: eng = engine_dir(toolkit) eng.mkdir(exist_ok=True) stamp = eng / "BUILD.json" - meta = json.loads(stamp.read_text()) if stamp.exists() else {} + meta = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else {} want_vision = vision != "none" local = meta.get("source") == "local" src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) @@ -2453,8 +2598,17 @@ def unsloth_together(a, model, ram, gpu, chosen) -> bool: names = " + ".join(gpu_name(g) for g in chosen) need = unsloth_split_need_gb(model) if ram < need: - warn(f"{model} runs on one GPU here: on several it has no RAM budget and needs ~{need:.0f} GB of RAM (its GGUF " - f"files and {UNSLOTH_RAM_LEFT_GB} GB more), this PC has {ram:.0f} - using {gpu_name(gpu)} only") + note = (f"{model} on several GPUs has no RAM budget and needs ~{need:.0f} GB of RAM (its GGUF files and " + f"{UNSLOTH_RAM_LEFT_GB} GB more), this PC has {ram:.0f}; the estimate is a worst case (#737: a 128 GB PC " + "ran it)") + if a.gpus and a.resident_budget_gib is None: # #737: asked for by name: a question, not a refusal + confirm_risk(note + ", but it may page or stall here", True, a.yes, + f"{model} on several GPUs needs ~{need:.0f} GB of RAM; this PC has {ram:.0f} GB", + f"start it on one GPU: --gpus {gpu['index']}", " Use them together anyway?") + ok(f"{model} on {names}, as you chose (--gpus), with {ram:.0f} GB of RAM") + return True + warn(f"{note} - using {gpu_name(gpu)} only (--gpus " + ",".join(str(g["index"]) for g in chosen) + + " uses them together anyway)") return False if a.resident_budget_gib is not None: warn(f"--resident-budget-gib has no layer split: {model} runs on one GPU with it - using {gpu_name(gpu)} only " @@ -2523,8 +2677,10 @@ def ctx_ram_need(model, ctx, low_ram=False): def ram_ctx(model, ram, low_ram=False) -> int: """#406: the longest context the RAM rule recommends: 128K, or longer where the estimate fits this PC's RAM. It - is part of the recommended default (the smaller of it and the GPU's rule); a longer choice is kept, with a note.""" - return max(c for c in CONTEXTS if c <= 131072 or (ctx_ram_need(model, c, low_ram) or 0) <= ram) + is part of the recommended default (the smaller of it and the GPU's rule); a longer choice is kept, with a note. + The 200K menu step is never the recommendation (#608).""" + # 204800 (#608) is a menu step between 128K and 256K, never the recommendation: where 256K does not fit, 128K stays + return max(c for c in CONTEXTS if c <= 131072 or (c != 204800 and (ctx_ram_need(model, c, low_ram) or 0) <= ram)) def settings_path() -> Path: @@ -2679,7 +2835,7 @@ def data_folder(requested: str | None) -> tuple: (folder / d).rmdir() # empty now except OSError: pass - for c in folder.glob("strata-*.json"): + for c in model_config_files(folder): repoint_config(c, folder, dest) if has_data(folder): elsewhere.append(folder) # in use, or a copy the data folder already has @@ -2733,6 +2889,35 @@ def carry_over(old: dict, cfg: dict) -> list[str]: if isinstance(mm, str) and Path(mm).name != Path(str(nv.get("mmproj"))).name and Path(mm).is_file(): nv["mmproj"] = mm kept.append("vision mmproj") + kept += carry_profile_args(old, cfg) + return kept + + +def flag_value(args: list, flag: str): + """The value after `flag` in an argument list, or None.""" + for i, a in enumerate(args[:-1]): + if a == flag: + return str(args[i + 1]) + return None + + +def carry_profile_args(old: dict, cfg: dict) -> list[str]: + """#775: a learned expert profile the user wired in by hand (--expert-profile , --expert-profile-save + ) survives a setup run: setup writes the shipped profile, which a measured one of their own beats (2.5-3.1x at + 256K on a 16 GB card in the report). Their --expert-profile replaces the shipped one only when it is another file + that still exists; --expert-profile-save is kept when the new config has none. The names kept are returned.""" + oargs, nargs = old.get("args"), cfg.get("args") + if not isinstance(oargs, list) or not isinstance(nargs, list): + return [] + kept = [] + mine, shipped = flag_value(oargs, "--expert-profile"), flag_value(nargs, "--expert-profile") + if mine and shipped and Path(mine).name != Path(shipped).name and Path(mine).is_file(): + nargs[nargs.index("--expert-profile") + 1] = mine + kept.append("args --expert-profile") + save = flag_value(oargs, "--expert-profile-save") + if save and flag_value(nargs, "--expert-profile-save") is None: + nargs += ["--expert-profile-save", save] + kept.append("args --expert-profile-save") return kept @@ -2795,13 +2980,19 @@ def readable_config(path: Path) -> bool: return False +def model_config_files(folder: Path) -> list: + """#346: the strata-*.json files of a folder that can be model configs. The server keeps a config's Chat settings + next to it as strata-.shared-settings.json: it matches the pattern but is no config (no exe, no args).""" + return [p for p in folder.glob("strata-*.json") if not p.name.endswith(".shared-settings.json")] + + def previous_config(elsewhere_first: list, settings: dict): """The most recently used model config of another Strata folder on this PC, for a folder that has none yet. One that does not parse (an empty or cut-off file, #459) is skipped with a warning: the newest readable one is used, and with none this copy is set up as a fresh install.""" cands = [] for folder in [*elsewhere_first, *other_installs(settings)]: - cands += list(folder.glob("strata-*.json")) + cands += model_config_files(folder) cands = [c for c in dict.fromkeys(cands) if c.is_file()] return next((c for c in sorted(cands, key=lambda p: p.stat().st_mtime, reverse=True) if readable_config(c)), None) @@ -2857,7 +3048,7 @@ def model_config(path: Path) -> bool: def installed_configs(): - return [p for p in sorted(ROOT.glob("strata-*.json"), key=lambda p: p.stat().st_mtime, reverse=True) + return [p for p in sorted(model_config_files(ROOT), key=lambda p: p.stat().st_mtime, reverse=True) if model_config(p)] @@ -2872,7 +3063,7 @@ def engine_version(exe: Path) -> tuple: engine is not necessarily the source's version: when compiling a `git pull` fails, the previous engine is kept (issue #49).""" try: - meta = json.loads((Path(exe).parent / "BUILD.json").read_text()) + meta = json.loads((Path(exe).parent / "BUILD.json").read_text(encoding="utf-8")) except (OSError, ValueError): meta = {} v = str(meta.get("version") or "") @@ -3115,7 +3306,7 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ "set it up for these cards: ./setup.sh --setup --backend hip --gpus " + ",".join(map(str, gpu))) cfg["gpu"], cfg["gpus_asked"] = gpu, True cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" - split_budget(cfg) # #498: before it is saved (it stops when the RAM is short) + split_budget(cfg, yes, True) # #498: before it is saved (asks when the RAM is short, #737) write_config(cfg_path, cfg) gpu = None elif gpu is not None: @@ -3143,7 +3334,7 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ check_gpus(gpu, found, yes=yes, named=True) cfg["gpu"], cfg["gpus_asked"] = gpu, True cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" - split_budget(cfg) # #498: before it is saved (it stops when the RAM is short) + split_budget(cfg, yes, True) # #498: before it is saved (asks when the RAM is short, #737) recommend_remote_expert_opt(cfg) write_config(cfg_path, cfg) gpu = None @@ -3344,6 +3535,7 @@ def parallel_note(asked: int | None, vram_gbs, arena_gb: float, ctx: int, kv: st return lines +DISPLAY_RESERVE_MIB = 1500 # #779: the tip for an NVIDIA card that also drives a display DESKTOP_RESERVE_MIB = 3072 # #560 #516: what kept a KDE/Wayland desktop alive beside a full expert cache @@ -3408,7 +3600,7 @@ def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: return cfg eng = engine_dir(tk) info = eng / "BUILD.json" - meta = json.loads(info.read_text()) + meta = json.loads(info.read_text(encoding="utf-8")) say() say(" The installed engine has no code for " + ", ".join(f"{g['name']} (sm_{g['arch']})" for g in missing) + ": it is compiled for " + ("these cards" if len(cards) > 1 else "it") + " now.") @@ -3416,7 +3608,7 @@ def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: archs = sorted({int(x) for x in meta.get("archs", [])} | {int(g["arch"]) for g in cards}) vision = meta.get("vision") or ("gpu" if (eng / VEXE).exists() else "none") build_engine({**main, "archs": archs}, vision, yes, get_llama_cpp(), toolkit=tk) - dirs = json.loads(info.read_text()).get("cuda_dirs") or [] + dirs = json.loads(info.read_text(encoding="utf-8")).get("cuda_dirs") or [] cfg["lib_dirs"] = dirs + [d for d in cfg.get("lib_dirs") or [] if d not in dirs] write_config(cfg_path, cfg) return cfg @@ -3426,7 +3618,7 @@ def get_cuda12_engine(url_base, gpu, vision, yes, build=False) -> Path: """The experimental CUDA 12 engine for these cards (gpu["archs"]): the ready-made one (Windows) with NVIDIA's CUDA 12 libraries, or compiled here with a CUDA 12.x toolkit (Linux, --build, or no ready-made one).""" eng = None if build else get_prebuilt(url_base, gpu, vision, toolkit=12) - if eng is not None and json.loads((eng / "BUILD.json").read_text()).get("source") != "local": + if eng is not None and json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("source") != "local": pip_cuda_libs(12) if vision != "none" and not (eng / VEXE).exists(): eng = None @@ -3435,7 +3627,7 @@ def get_cuda12_engine(url_base, gpu, vision, yes, build=False) -> Path: def engine_lib_dirs(eng: Path, toolkit=13) -> list: """The library folders a CUDA engine loads from: its own (a compiled one: the toolkit's), else pip's wheels.""" - meta = json.loads((eng / "BUILD.json").read_text()) + meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) return meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(toolkit) @@ -3594,6 +3786,8 @@ def main() -> int: ap.add_argument("--update", action="store_true", help="update the installed engine, Python packages and model settings as a start would, without " "starting the model (UPDATE.bat / update.sh run it after a git pull)") + ap.add_argument("--rollback-engine", action="store_true", + help="put back the engine an update replaced (kept in engine/.previous), and keep the current one there") ap.add_argument("--build", action="store_true", help="compile the engine instead of using the ready-made one") ap.add_argument("--cuda", choices=["12", "13", "auto"], default=os.environ.get("STRATA_CUDA") or None, help="NVIDIA: the CUDA toolkit of this model's engine. auto (default): CUDA 13, the ready-made " @@ -3653,6 +3847,9 @@ def main() -> int: if a.models_dir is None: a.models_dir = str(data / "models") + if a.rollback_engine: # #670 + return rollback_engine(12 if a.cuda == "12" else 13) + # ---- 0. already installed: just start it have = installed_configs() if a.update: # #475: UPDATE.bat / update.sh - never starts the model @@ -4127,16 +4324,16 @@ def main() -> int: else: eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision, **({"toolkit": 12} if cuda_tk == 12 else {})) - if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text()).get("source") != "local": + if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("source") != "local": pip_cuda_libs(cuda_tk) if vision != "none" and not (eng / VEXE).exists(): warn("the ready-made engine has no image encoder: compiling it") eng = None else: - vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text()), gpu, vision) + vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text(encoding="utf-8")), gpu, vision) if eng is None: eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk) - meta = json.loads((eng / "BUILD.json").read_text()) + meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH lib_dirs = [str(d) for d in hip_lib_dirs(eng)] else: @@ -4200,7 +4397,7 @@ def main() -> int: if not (pack / "index.txt").exists() or not (pack / "experts.bin").exists(): # index.txt is written last say(" Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ...") run([sys.executable, str(ROOT / "tools" / "strata_pack.py"), "build", "--gguf", str(shards[0]), - "--out", str(pack), "--skip-hash"], env=env) + "--out", str(pack), "--skip-hash", "--force"], env=env) # --force: #634 refuses an occupied pack run([sys.executable, str(ROOT / "tools" / "pack_index.py"), "--pack", str(pack)], env=env) if not (pack / "tokenizer" / "vocab.json").exists(): run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(shards[0]), @@ -4340,6 +4537,9 @@ def main() -> int: elif hip and a.vram_reserve_mib is None and linux_desktop(): for line in desktop_reserve_note(): # #560 #516: a recommendation: nothing changes say(" " + line) + if not hip and not multi and a.vram_reserve_mib is None and gpu_drives_display(gpu): + say(" tip: this card drives a display. If the PC freezes or the screen goes black once the model is loaded " + f"(#779), keep more VRAM free: run setup again with --vram-reserve-mib {DISPLAY_RESERVE_MIB}") # a tip only if esp is not None: # the package's profile, with llama.cpp's flags (the engine takes the same ones) args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44", diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index f62ea07c..67175de6 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -44,6 +45,11 @@ #include #include #endif +#if defined(__linux__) +#include +#include // the kernel's own asynchronous reads (io_submit): no library, allowed by Docker's seccomp +#include +#endif // a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform #ifndef STRATA_FSEEK64 @@ -73,6 +79,14 @@ bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64 return true; } +uint64_t clamp_resident_budget(uint64_t requested, uint64_t physical, uint64_t commit, uint64_t headroom) { + const uint64_t available = std::min(physical, commit); + const uint64_t room = available > headroom ? available - headroom : 0; + if (requested <= room) return requested; + const uint64_t margin = 256ull << 20; + return room > margin ? room - margin : 0; +} + bool make_cache_complement_plan( int64_t n_layers, int64_t n_expert, const std::vector& layer_blob_bytes, const std::vector>& primary_gpu_pairs, @@ -231,6 +245,7 @@ bool host_available_memory(HostMemory& m, const std::string& meminfo, const std: status.dwLength = sizeof(status); if (!GlobalMemoryStatusEx(&status)) return false; m.available = (uint64_t) status.ullAvailPhys; + m.commit = (uint64_t) status.ullAvailPageFile; return m.available > 0; #elif defined(__linux__) // MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES. @@ -324,13 +339,76 @@ bool host_available_memory(HostMemory& m, const std::string& meminfo, const std: namespace { -bool available_memory_bytes(uint64_t& bytes) { +bool available_memory_bytes(uint64_t& bytes, uint64_t* commit = nullptr) { detail::HostMemory m; if (!detail::host_available_memory(m)) return false; bytes = m.available; + if (commit != nullptr) *commit = m.commit; return bytes > 0; } +void log_complement_memory(const char* stage, uint64_t requested) { +#if defined(_WIN32) + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + if (!GlobalMemoryStatusEx(&status)) { + std::fprintf(stderr, "FileExpertSource: %s: GlobalMemoryStatusEx failed (error %lu)\n", stage, GetLastError()); + return; + } + std::fprintf(stderr, "FileExpertSource: %s: requested %.2f GiB, available RAM %.2f GiB, available commit %.2f GiB " + "(limit %.2f GiB), available virtual address space %.2f GiB\n", + stage, (double) requested / 1073741824.0, (double) status.ullAvailPhys / 1073741824.0, + (double) status.ullAvailPageFile / 1073741824.0, (double) status.ullTotalPageFile / 1073741824.0, + (double) status.ullAvailVirtual / 1073741824.0); +#else + (void) stage; + (void) requested; +#endif +} + +/// #286: an unbuffered file handle - a HANDLE on Windows, an O_DIRECT descriptor (as a pointer-sized integer) on Linux. +void close_direct(void* h) { +#if defined(_WIN32) + CloseHandle((HANDLE) h); +#else + ::close((int) (intptr_t) h); +#endif +} + +/// #286/#577: whether the file tier reads its `read_bytes` unbuffered, beside `arena_bytes` of RAM copy still to be +/// taken. Windows times probe reads too (experts_unbuffered); on Linux the same rule as its `cache_counts = false` +/// arm decides: whether the file cache could keep those bytes at all, from MemAvailable and the tightest cgroup +/// limit (host_available_memory). STRATA_UNBUFFERED_LOAD=1 / 0 forces it either way, as on Windows. +bool file_tier_unbuffered(const std::vector& paths, uint64_t arena_bytes, uint64_t read_bytes, + std::string& why) { +#if defined(_WIN32) + return experts_unbuffered(paths, arena_bytes, why, /*cache_counts=*/false, read_bytes); +#elif defined(__linux__) + (void) paths; + if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') { + why = std::string("STRATA_UNBUFFERED_LOAD=") + env; + return env[0] != '0'; + } + uint64_t avail = 0; + if (!available_memory_bytes(avail)) { + why = "the available RAM is unknown"; + return false; + } + const bool keepable = strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes); + char msg[256]; + 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) read_bytes / (1ull << 30), + keepable ? "can" : "cannot"); + why = msg; + return !keepable; +#else + (void) paths; (void) arena_bytes; (void) read_bytes; + why = "through the file cache (no unbuffered reads on this platform)"; + return false; +#endif +} + } // namespace // ================================ THE FILE-BACKED SOURCE ================================ @@ -496,6 +574,7 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64 if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: mmap failed on " + path; return false; } fd_ = fd; base_ = (const uint8_t*) view; + paths_.assign(1, path); // #286: open_direct opens it again with O_DIRECT #endif blobs_ = (int64_t) blob_count; n_layers_ = n_layers; @@ -559,9 +638,7 @@ void FileExpertSource::close() { role_bytes_.clear(); role_file_.clear(); paths_.clear(); -#if defined(_WIN32) - for (void* h : direct_) CloseHandle((HANDLE) h); -#endif + for (void* h : direct_) close_direct(h); direct_.clear(); { std::lock_guard lk(stage_mu_); @@ -703,6 +780,7 @@ bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* d if (!direct_.empty()) { // #286: from the drive; a failed read falls back to the mapping below const Fill f{0, layer, expert, dst}; if (read_direct(&f, 1)) return true; + direct_fallbacks_.fetch_add(1, std::memory_order_relaxed); } if (!role_ptr_.empty()) { uint64_t at = 0; @@ -857,6 +935,23 @@ void FileExpertSource::prefetch_pairs(const std::pair* pairs, fill_many(todo); } +bool FileExpertSource::advise_pairs(const std::pair* pairs, int64_t n) const { + if (base_ == nullptr || !direct_.empty() || !strata::platform::read_ahead_enabled()) return false; + for (int64_t i = 0; pairs != nullptr && i < n; ++i) { + const int64_t l = pairs[i].first, e = pairs[i].second; + if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue; + if (role_ptr_.empty()) { // experts.bin: the blob is one contiguous range + if (const uint8_t* b = mapped_blob(l, e)) strata::platform::advise_willneed(b, layer_blob_bytes_[(size_t) l]); + continue; + } + for (int r = 0; r < 3; ++r) { + const size_t k = (size_t) (3 * l + r); + strata::platform::advise_willneed(role_ptr_[k] + (size_t) ((uint64_t) e * role_bytes_[k]), role_bytes_[k]); + } + } + return true; +} + void FileExpertSource::fill_many(const std::vector& todo) { if (todo.empty()) return; if (!direct_.empty()) { @@ -949,6 +1044,23 @@ bool FileExpertSource::open_direct(std::string& why) { for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b); } return true; +#elif defined(__linux__) + // O_DIRECT: the reads bypass the page cache, as FILE_FLAG_NO_BUFFERING does (4 KiB-aligned windows, read_direct) + for (const std::string& path : paths_) { + const int fd = ::open(path.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC); + if (fd < 0) { + why += "; cannot open " + path + " with O_DIRECT (" + std::strerror(errno) + "), read through the file cache"; + for (void* d : direct_) close_direct(d); + direct_.clear(); + return false; + } + direct_.push_back((void*) (intptr_t) fd); + } + if (role_ptr_.empty()) { // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob + std::lock_guard lk(stage_mu_); + for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b); + } + return true; #else (void) why; return false; @@ -956,7 +1068,7 @@ bool FileExpertSource::open_direct(std::string& why) { } bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) { -#if defined(_WIN32) +#if defined(_WIN32) || defined(__linux__) if (base_ == nullptr || paths_.empty() || !direct_.empty()) { why = !direct_.empty() ? "already unbuffered" : "no expert files open"; return !direct_.empty(); @@ -965,17 +1077,17 @@ bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) { // 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; + if (!file_tier_unbuffered(paths_, arena, experts - arena, why)) return false; return open_direct(why); #else (void) ram_bytes; - why = "through the file cache (not Windows)"; + why = "through the file cache (no unbuffered reads on this platform)"; return false; #endif } bool FileExpertSource::recheck_unbuffered(std::string& why) { -#if defined(_WIN32) +#if defined(_WIN32) || defined(__linux__) if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') { why = std::string("STRATA_UNBUFFERED_LOAD=") + env; return !direct_.empty(); @@ -990,7 +1102,7 @@ bool FileExpertSource::recheck_unbuffered(std::string& why) { 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); + const bool ub = file_tier_unbuffered(paths_, 0, read, w); char head[96]; std::snprintf(head, sizeof head, "re-checked with the RAM copy built (%.2f GiB): ", (double) complement_bytes_ / 1073741824.0); @@ -998,11 +1110,11 @@ bool FileExpertSource::recheck_unbuffered(std::string& why) { 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); + for (void* d : direct_) close_direct(d); direct_.clear(); return false; #else - why = "through the file cache (not Windows)"; + why = "through the file cache (no unbuffered reads on this platform)"; return false; #endif } @@ -1121,6 +1233,148 @@ bool FileExpertSource::read_direct(const Fill* fills, size_t n) const { std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n); } return true; +#elif defined(__linux__) + // Linux: O_DIRECT descriptors (open_direct) and the kernel's asynchronous reads - every window of the batch is + // queued with one io_submit before the first wait, so the drive sees the batch as one queue, as the overlapped + // ReadFiles above do. No NTFS here: windows are merged only where they touch (the 4 KiB rounding of adjacent + // slices, consecutive experts of a role), never across a gap that would be read for nothing. Each thread has its + // own context and aligned buffer, kept for its next batch, so concurrent batches never see each other's events. + constexpr uint64_t kSector = 4096, kMerge = 32ull << 20; + constexpr long kDepth = 256; // requests in flight per thread; a larger batch is read in waves of this many + struct Window { int file; uint64_t a0, size, skip, n, at; uint8_t* dst; size_t req; uint64_t in_req; }; + struct Req { int fd; uint64_t a0, size, pos; }; + struct Scratch { + uint8_t* buf = nullptr; + size_t cap = 0; + aio_context_t ctx = 0; + std::vector win; + std::vector order; + std::vector req; + std::vector got; + std::vector cb; + std::vector cbp; + std::vector ev; + ~Scratch() { + std::free(buf); + if (ctx != 0) (void) syscall(SYS_io_destroy, ctx); + } + }; + thread_local Scratch sc; + if (sc.ctx == 0 && syscall(SYS_io_setup, kDepth, &sc.ctx) != 0) { + sc.ctx = 0; + return false; // no AIO (a seccomp profile, aio-max-nr): the caller falls back to the mapped copy + } + sc.win.clear(); + for (size_t k = 0; k < n; ++k) { + const Fill& f = fills[k]; + if (f.dst == nullptr || f.layer < 0 || f.e < 0 || f.layer >= n_layers_ || f.e >= n_expert_) return false; + if (role_ptr_.empty()) { // experts.bin: the blob is one contiguous range + const uint64_t per = layer_blob_bytes_[(size_t) f.layer]; + const uint64_t off = layer_offsets_[(size_t) f.layer] + (uint64_t) f.e * per; + const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector; + sc.win.push_back({0, a0, a1 - a0, off - a0, per, 0, f.dst, 0, 0}); + continue; + } + uint64_t at = 0; + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * f.layer + r); + const uint64_t per = role_bytes_[i]; + const Map& m = maps_[(size_t) role_file_[i]]; + const uint64_t off = (uint64_t) (role_ptr_[i] - m.base) + (uint64_t) f.e * per; + const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector; + sc.win.push_back({role_file_[i], a0, a1 - a0, off - a0, per, at, f.dst, 0, 0}); + at += per; + } + } + sc.order.resize(sc.win.size()); + for (size_t w = 0; w < sc.win.size(); ++w) sc.order[w] = w; + std::sort(sc.order.begin(), sc.order.end(), [&](size_t a, size_t b) { + return sc.win[a].file != sc.win[b].file ? sc.win[a].file < sc.win[b].file : sc.win[a].a0 < sc.win[b].a0; + }); + sc.req.clear(); + uint64_t total = 0; + int last_file = -1; + for (size_t w : sc.order) { + Window& x = sc.win[w]; + if (!sc.req.empty() && x.file == last_file) { + Req& q = sc.req.back(); + const uint64_t end = q.a0 + q.size, xend = x.a0 + x.size; + if (x.a0 <= end && std::max(end, xend) - q.a0 <= kMerge) { + if (xend > end) { + total += xend - end; + q.size = xend - q.a0; + } + x.req = sc.req.size() - 1; + x.in_req = x.a0 - q.a0; + continue; + } + } + sc.req.push_back({(int) (intptr_t) direct_[(size_t) x.file], x.a0, x.size, total}); + total += x.size; + last_file = x.file; + x.req = sc.req.size() - 1; + x.in_req = 0; + } + if (total > sc.cap) { + std::free(sc.buf); + sc.cap = (size_t) ((total + (1u << 20) - 1) >> 20 << 20); + void* p = nullptr; + sc.buf = posix_memalign(&p, (size_t) kSector, sc.cap) == 0 ? (uint8_t*) p : nullptr; + if (sc.buf == nullptr) { sc.cap = 0; return false; } + } + sc.got.assign(sc.req.size(), -1); + sc.cb.resize(std::min(sc.req.size(), (size_t) kDepth)); + sc.cbp.resize(sc.cb.size()); + sc.ev.resize(sc.cb.size()); + bool ok = true; + for (size_t w0 = 0; ok && w0 < sc.req.size(); w0 += (size_t) kDepth) { + const size_t wn = std::min((size_t) kDepth, sc.req.size() - w0); + for (size_t j = 0; j < wn; ++j) { + const Req& r = sc.req[w0 + j]; + iocb& c = sc.cb[j]; + std::memset(&c, 0, sizeof c); + c.aio_lio_opcode = IOCB_CMD_PREAD; + c.aio_fildes = (uint32_t) r.fd; + c.aio_buf = (uint64_t) (uintptr_t) (sc.buf + r.pos); + c.aio_nbytes = r.size; + c.aio_offset = (int64_t) r.a0; + c.aio_data = (uint64_t) (w0 + j); + sc.cbp[j] = &c; + } + // every request of the wave queued; a refused submit ends the batch once what was queued has completed + // (the kernel still writes into the buffer until then) + size_t queued = 0; + while (queued < wn) { + const long r = syscall(SYS_io_submit, sc.ctx, (long) (wn - queued), sc.cbp.data() + queued); + if (r > 0) { queued += (size_t) r; continue; } + if (r < 0 && errno == EINTR) continue; + ok = false; + break; + } + for (size_t done = 0; done < queued;) { + const long r = syscall(SYS_io_getevents, sc.ctx, 1L, (long) (queued - done), sc.ev.data(), nullptr); + if (r < 0) { + if (errno == EINTR) continue; + // the context is in an unknown state: drop it (io_destroy waits for what is still in flight) + (void) syscall(SYS_io_destroy, sc.ctx); + sc.ctx = 0; + return false; + } + for (long j = 0; j < r; ++j) { + const io_event& e = sc.ev[(size_t) j]; + sc.got[(size_t) e.data] = e.res; + if (e.res < 0) ok = false; + } + done += (size_t) r; + } + } + if (!ok) return false; + for (const Window& x : sc.win) { + // a request may run past the end of the file: only the role's own bytes have to arrive + if (sc.got[x.req] < 0 || (uint64_t) sc.got[x.req] < x.in_req + x.skip + x.n) return false; + std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n); + } + return true; #else (void) fills; (void) n; return false; @@ -1328,11 +1582,64 @@ const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) cons return base_ + (size_t) offset; } +uint64_t FileExpertSource::release(int64_t layer, int64_t expert) { +#if defined(_WIN32) + static const bool enabled = [] { + const char* v = std::getenv("STRATA_FILE_RELEASE"); + return v != nullptr && std::strcmp(v, "1") == 0; + }(); + if (!enabled || base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) + return 0; + static const uint64_t page = [] { + SYSTEM_INFO info{}; + GetSystemInfo(&info); + return (uint64_t) info.dwPageSize; + }(); + // These read-only file views are not CUDA-registered. blob() may instead return pinned RAM or an exchange + // buffer, so resolve the file spans directly. A shared boundary page stays for the neighboring expert. + auto trim = [&](const uint8_t* p, uint64_t bytes) -> uint64_t { + const uint64_t misalignment = (uintptr_t) p % page; + const uint64_t skip = misalignment == 0 ? 0 : page - misalignment; + if (bytes <= skip) return 0; + const uint64_t whole = (bytes - skip) / page * page; + if (whole == 0) return 0; + SetLastError(ERROR_SUCCESS); + if (!VirtualUnlock((LPVOID) (p + (size_t) skip), (SIZE_T) whole)) { + const DWORD error = GetLastError(); + // VirtualUnlock trims an unlocked range and reports FALSE / ERROR_NOT_LOCKED for that success. + if (error != ERROR_NOT_LOCKED) { + std::fprintf(stderr, "FileExpertSource: cannot trim mapped pages for layer %lld expert %lld " + "(%llu bytes, Windows error %lu)\n", + (long long) layer, (long long) expert, (unsigned long long) whole, + (unsigned long) error); + std::fflush(stderr); + return 0; + } + } + return whole; // bytes advised, not a measurement of physical RAM reclaimed + }; + if (role_ptr_.empty()) { + const uint8_t* p = mapped_blob(layer, expert); + return p == nullptr ? 0 : trim(p, layer_blob_bytes_[(size_t) layer]); + } + uint64_t bytes = 0; + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * layer + r); + bytes += trim(role_ptr_[i] + (size_t) ((uint64_t) expert * role_bytes_[i]), role_bytes_[i]); + } + return bytes; +#else + (void) layer; (void) expert; + return 0; +#endif +} + bool FileExpertSource::pin_cache_complement( const ExpertCache& cache, std::string& err, bool pin, const std::vector>& additional_gpu_pairs, int64_t lend_from_slot, uint64_t headroom_bytes, uint64_t budget_bytes, const std::vector>* rank) { err.clear(); + const auto pin_t0 = std::chrono::steady_clock::now(); if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; } if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; } if (!cache.valid()) { err = "FileExpertSource: the GPU expert cache is not open"; return false; } @@ -1383,32 +1690,33 @@ bool FileExpertSource::pin_cache_complement( } #endif const bool what_fits = budget_bytes == kResidentWhatFits; // #467: the soft mode's second try - uint64_t budget_physical = 0; // #403: the RAM reading a budget was sized from (0: no budget) + uint64_t budget_physical = 0; // #403: reuse the memory snapshot a budget was sized from + uint64_t budget_commit = std::numeric_limits::max(); if (budget_bytes > 0) { // CS-T: a RAM budget. The complement's experts in `rank` order (the expert profile, hottest first) while - // they fit, the rest left on the mapped files; clamped to what the RAM has room for. + // they fit, the rest left on the mapped files; Windows commit capacity also limits the allocation (#730). uint64_t physical = 0; - if (!available_memory_bytes(physical)) { - err = "FileExpertSource: cannot determine available RAM for --resident-budget-gib"; + if (!available_memory_bytes(physical, &budget_commit)) { + err = "FileExpertSource: cannot determine available memory for --resident-budget-gib"; return false; } budget_physical = physical; - const uint64_t room = physical > headroom_bytes ? physical - headroom_bytes : 0; - if (budget_bytes > room) { + const uint64_t available = std::min(physical, budget_commit); + const char* limit = budget_commit < physical ? "commit" : "RAM"; + const uint64_t clamped = detail::clamp_resident_budget(budget_bytes, physical, budget_commit, headroom_bytes); + if (budget_bytes > clamped) { // #403: 256 MiB under the room, so the engine's own allocations after this reading still leave the // headroom (a budget clamped to exactly the room failed the safety check below on a reading a few MB // lower). An unclamped budget is unchanged. - const uint64_t margin = 256ull << 20; - const uint64_t clamped = room > margin ? room - margin : 0; if (what_fits) - std::fprintf(stderr, "FileExpertSource: RAM room for the complement: %.2f GiB (%.2f GiB available " + std::fprintf(stderr, "FileExpertSource: room for the complement: %.2f GiB (%.2f GiB available %s " "minus %.0f GiB headroom and a 0.25 GiB margin)\n", - (double) clamped / 1073741824.0, (double) physical / 1073741824.0, + (double) clamped / 1073741824.0, (double) available / 1073741824.0, limit, (double) headroom_bytes / 1073741824.0); else - std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f is more than the RAM has room for " - "(%.2f GiB available minus %.0f GiB headroom and a 0.25 GiB margin): %.2f GiB\n", - (double) budget_bytes / 1073741824.0, (double) physical / 1073741824.0, + std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f exceeds available %s " + "(%.2f GiB minus %.0f GiB headroom and a 0.25 GiB margin): %.2f GiB\n", + (double) budget_bytes / 1073741824.0, limit, (double) available / 1073741824.0, (double) headroom_bytes / 1073741824.0, (double) clamped / 1073741824.0); budget_bytes = clamped; } @@ -1427,7 +1735,7 @@ bool FileExpertSource::pin_cache_complement( ++held; } if (what_fits && held == 0) { // #467: nothing to keep - the caller's plain mmap fallback, not an empty copy - err = "FileExpertSource: the RAM has no room for any expert of the complement"; + err = "FileExpertSource: available memory cannot hold any expert of the complement"; return false; } std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does " @@ -1444,18 +1752,20 @@ bool FileExpertSource::pin_cache_complement( // #403: with a budget, the reading it was sized from - a second reading a few MB lower (the engine's own // allocations, the file cache) failed a budget the first one had clamped. (A budget turns `lend` off.) uint64_t physical = budget_physical; - if (physical == 0 && !available_memory_bytes(physical)) { - err = "FileExpertSource: cannot determine available RAM for the resident-memory safety check"; + uint64_t commit = budget_commit; + if (physical == 0 && !available_memory_bytes(physical, &commit)) { + err = "FileExpertSource: cannot determine available memory for the resident-memory safety check"; return false; } - budget = physical > headroom_bytes ? physical - headroom_bytes : 0; + const uint64_t available = std::min(physical, commit); + budget = available > headroom_bytes ? available - headroom_bytes : 0; if (bytes > budget) { char message[320]; std::snprintf(message, sizeof message, - "FileExpertSource: resident complement %.2f GiB exceeds available RAM (%.2f GiB) minus the " + "FileExpertSource: resident complement %.2f GiB exceeds available %s (%.2f GiB) minus the " "%.0f GiB safety headroom", - (double) bytes / 1073741824.0, (double) physical / 1073741824.0, - (double) headroom_bytes / 1073741824.0); + (double) bytes / 1073741824.0, commit < physical ? "commit" : "RAM", + (double) available / 1073741824.0, (double) headroom_bytes / 1073741824.0); err = message; return false; } @@ -1498,6 +1808,7 @@ bool FileExpertSource::pin_cache_complement( if (bytes > 0) { std::fprintf(stderr, "FileExpertSource: allocating %.2f GiB %s cache complement\n", (double) bytes / 1073741824.0, pin ? "page-locked" : "pageable resident"); + log_complement_memory("before complement allocation", bytes); std::fflush(stderr); if (pin) { const cudaError_t allocated = cudaHostAlloc(&arena, (size_t) bytes, @@ -1524,9 +1835,19 @@ bool FileExpertSource::pin_cache_complement( } } if (arena == nullptr) { + if (!note.empty()) { + std::fprintf(stderr, "FileExpertSource: %s; trying pageable memory\n", note.c_str()); + log_complement_memory("before pageable allocation", bytes); + std::fflush(stderr); + } + errno = 0; arena = std::malloc((size_t) bytes); if (arena == nullptr) { - err = "FileExpertSource: pageable resident complement allocation failed"; + const int allocation_errno = errno; + err = "FileExpertSource: pageable resident complement allocation failed (malloc errno " + + std::to_string(allocation_errno) + ": " + std::strerror(allocation_errno) + ")"; + if (!note.empty()) err += "; " + note; + log_complement_memory("after pageable allocation failure", bytes); return false; } if (pin) { @@ -1603,6 +1924,7 @@ bool FileExpertSource::pin_cache_complement( std::atomic copied{0}; std::atomic failed{false}; std::mutex fail_mu; + const auto copy_t0 = std::chrono::steady_clock::now(); std::string fail_msg; auto fail = [&](const std::string& m) { std::lock_guard lock(fail_mu); @@ -1624,6 +1946,13 @@ bool FileExpertSource::pin_cache_complement( batch.clear(); return true; }; + if (direct_.empty()) { // mapped reads: ask for the layer's blobs before copying them + std::vector> ahead; + for (int64_t expert = 0; expert < n_expert_; ++expert) + if (offsets[(size_t) layer * (size_t) n_expert_ + (size_t) expert] != kNoComplement) + ahead.emplace_back((int32_t) layer, (int32_t) expert); + (void) advise_pairs(ahead.data(), (int64_t) ahead.size()); + } for (int64_t expert = 0; expert < n_expert_; ++expert) { const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; const uint64_t offset = offsets[index]; @@ -1674,8 +2003,9 @@ bool FileExpertSource::pin_cache_complement( #endif const int64_t done = layers_done.fetch_add(1) + 1; if (done % 8 == 0 || done == n_layers_) - std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB)\n", - (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0); + std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB, %.0f s)\n", + (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0, + std::chrono::duration(std::chrono::steady_clock::now() - copy_t0).count()); } }; { @@ -1710,9 +2040,10 @@ bool FileExpertSource::pin_cache_complement( complement_lock_off_ = lock_off; complement_lent_slots_ = lend ? n_slots - keep_from : 0; complement_ready_ = true; - std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB%s%s\n", + std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB in %.0f s%s%s\n", complement_pinned_ ? "mapped pinned" : pin ? "locked resident" : "pageable resident", (double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0, + std::chrono::duration(std::chrono::steady_clock::now() - pin_t0).count(), note.empty() ? "" : "; ", note.c_str()); if (lend) std::fprintf(stderr, "FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM " @@ -2638,7 +2969,13 @@ bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::Exp // `unbuffered` (Windows, experts_unbuffered): each chunk's 4 KiB-aligned window is read with FILE_FLAG_NO_BUFFERING into // an aligned buffer and scattered into the blobs - no copy through the file cache when the drive is read anyway. LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, - int threads, bool unbuffered) { + int threads, bool unbuffered, const std::atomic* ready) { + // `ready`: layer l is written only once *ready > l + 1 (a PinnedArena registering its slices meanwhile; the next + // slice too, since its registration starts on the page that may hold this layer's tail) + auto wait_ready = [ready](int64_t l) { + if (ready != nullptr) + while (ready->load(std::memory_order_acquire) <= l + 1) std::this_thread::yield(); + }; LoadStats st; st.layers = (uint64_t) lay.n_layers; const auto t0 = std::chrono::steady_clock::now(); @@ -2668,6 +3005,7 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata: for (;;) { const int64_t l = next.fetch_add(1); if (l >= lay.n_layers || bad) break; + wait_ready(l); const auto& fm = lay.fmt[(size_t) l]; const uint64_t blob = lay.bytes[(size_t) l]; const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; @@ -2746,6 +3084,7 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata: for (;;) { const int64_t l = next.fetch_add(1); if (l >= lay.n_layers || bad) break; + wait_ready(l); const auto& fm = lay.fmt[(size_t) l]; const uint64_t blob = lay.bytes[(size_t) l]; const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; @@ -2916,8 +3255,20 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert); } bounds.push_back(want); - PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes, - shared_arena_file, pack_hash); + // #285: on Windows the per-layer registration runs on a thread ahead of the readers, which wait for their + // layer's slice (the whole arena registered before the load cost ~2.5 s at 33 GiB of 4 KB pages, not hidden). + // Only where the whole arena would be registered: no cap (STRATA_ARENA_PIN_GIB, multi-GPU), no shared arena. + // Linux keeps the whole-arena pin (#253). STRATA_DEFERRED_REGISTER=0: the registration before the load. +#ifdef _WIN32 + const char* defer_env = std::getenv("STRATA_DEFERRED_REGISTER"); + const bool deferred = max_pinned_bytes == 0 && arena_pin_cap_gib() == -1 && shared_arena_file.empty() && + (defer_env == nullptr || defer_env[0] != '0'); +#else + const bool deferred = false; +#endif + PinnedArena* a = deferred ? new PinnedArena(want + (uint64_t) blob, bounds, PinnedArena::Deferred{}) + : new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes, + shared_arena_file, pack_hash); if (!a->valid()) { const std::string why = a->note; delete a; @@ -2942,13 +3293,25 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 const bool unbuffered = experts_unbuffered(files, want + (uint64_t) blob, why); const int readers = unbuffered ? std::max(threads, 16) : threads; // 16 keep a PCIe 5 drive's queue full LoadStats st; - if (from_gguf) { - st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered); - } else { - if (unbuffered) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20); - if (!unbuffered || (!st.ok && st.error.empty())) // unaligned ranges: the buffered reader - st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20); + std::atomic ready{0}; + std::thread reg; + if (deferred) { + int dev = 0; + cudaGetDevice(&dev); + reg = std::thread([a, &ready, dev] { + cudaSetDevice(dev); + a->register_slices(ready); + }); } + const std::atomic* rp = deferred ? &ready : nullptr; + if (from_gguf) { + st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered, rp); + } else { + if (unbuffered) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20, rp); + if (!unbuffered || (!st.ok && st.error.empty())) // unaligned ranges: the buffered reader + st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20, rp); + } + if (reg.joinable()) reg.join(); std::fprintf(stderr, "strata generate: expert arena read %s (%s)\n", unbuffered ? "unbuffered" : "through the file cache", why.c_str()); if (!st.ok) { @@ -2961,6 +3324,10 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 err = "ArenaExpertSource: the load read " + std::to_string(st.bytes) + " B of " + std::to_string(want); return false; } + if (std::getenv("STRATA_VERIFY_ARENA") != nullptr) { // tests: the loaded arena's checksum, any loader + std::fprintf(stderr, "strata generate: expert arena checksum %016llx (%.2f GiB)\n", + (unsigned long long) fnv1a64(a->data(), want), (double) want / (1ull << 30)); + } // the first start: write experts.bin for the mapped starts after this one - only when the drive has room for it // and 2 GiB more (a full drive fails other writes too); otherwise this start says so and runs pinned as before std::error_code space_ec; diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index da0cbacd..d6a47fb1 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -5,6 +5,7 @@ #include "strata/core/native_head.hpp" #include "strata/core/peer_experts.hpp" +#include "strata/platform/memory.hpp" #include "strata/kernels/bf16_gemv.hpp" #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/elementwise.hpp" @@ -106,6 +107,9 @@ bool read_file(const std::string& path, std::vector& out) { if (STRATA_FILE_SEEK64(f, 0, SEEK_END) != 0) return false; const long long n = (long long) STRATA_FILE_TELL64(f); if (n < 0 || STRATA_FILE_SEEK64(f, 0, SEEK_SET) != 0) return false; +#if !defined(_WIN32) + strata::platform::advise_willneed(fileno(f), 0, (uint64_t) n); +#endif out.resize((size_t) n); return n == 0 || std::fread(out.data(), 1, (size_t) n, f) == (size_t) n; } @@ -287,6 +291,9 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session ~Closer() { if (f != nullptr) std::fclose(f); } } closer{f}; if (cudaMalloc((void**) &experts_, bytes) != cudaSuccess) { err = "mtp: the 512 experts do not fit in VRAM"; return false; } +#if !defined(_WIN32) + strata::platform::advise_willneed(fileno(f), 0, bytes); +#endif std::vector chunk(64u << 20); for (uint64_t off = 0; off < bytes;) { const uint64_t n = std::min(chunk.size(), bytes - off); diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp index b5c33a8b..ffa9bdae 100644 --- a/src/core/native_dense.cpp +++ b/src/core/native_dense.cpp @@ -3,6 +3,7 @@ #include "strata/core/weights.hpp" #include "strata/artifact/gguf_reader.hpp" #include "strata/kernels/native_mmvq.hpp" +#include "strata/platform/memory.hpp" #include #include @@ -205,6 +206,10 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl if (next != offsets.end() && bytes > *next - tensor.offset) { err = "native dense: overlapping payload " + tensor.name; return false; } + // the uploads below read these: ask for them now so the reads overlap + if (eligible(tensor, include_ple_key) && !outside(tensor.name) && + strata::kernels::native_mmvq_supported(tensor.type)) + strata::platform::advise_willneed(gguf.tensor_data(tensor), bytes); } for (const auto& tensor : gguf.tensors()) { if (!eligible(tensor, include_ple_key) || outside(tensor.name)) continue; diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index 7c976b2d..aee19df0 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -2,6 +2,7 @@ #include "strata/artifact/gguf_reader.hpp" #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/native_mmvq.hpp" +#include "strata/platform/memory.hpp" #include #include @@ -48,6 +49,7 @@ bool NativeHead::load(const std::vector& shards, int64_t n_in, int6 cudaError_t status = cudaMalloc(&weights, bytes); if (status == cudaSuccess) status = cudaMalloc(&scratch, strata::kernels::native_q8_1_bytes((int) n_in, 1)); + strata::platform::advise_willneed(gguf.tensor_data(*tensor), bytes); if (status == cudaSuccess) status = cudaMemcpy(weights, gguf.tensor_data(*tensor), bytes, cudaMemcpyHostToDevice); if (status != cudaSuccess) { @@ -133,6 +135,7 @@ bool NativeEmbed::load(const std::vector& shards, int64_t n_embd, i bytes_ = 0; return false; } + strata::platform::advise_willneed(gguf.tensor_data(*t), bytes_); // copied out of the mapping below if (cudaHostAlloc(&host_, bytes_, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) { // Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts // themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM diff --git a/src/core/peer_experts.cpp b/src/core/peer_experts.cpp index bf6284a6..ad88bda8 100644 --- a/src/core/peer_experts.cpp +++ b/src/core/peer_experts.cpp @@ -156,7 +156,12 @@ bool PeerExperts::open(int device, const std::vector // open() zeroes the arena with cudaMemset on the legacy stream, which is not ordered against the non-blocking // refill stream: wait for it, or the zeroing can land on top of the fills if (!ck(cudaDeviceSynchronize(), "arena zeroing", err)) { close(); return false; } - for (const auto& pr : pick) { + // mapped reads: advise the next kAhead pairs so their reads overlap + constexpr size_t kAhead = 256; + const bool advise = src.advise_pairs(pick.data(), (int64_t) std::min(kAhead, pick.size())); + for (size_t i = 0; i < pick.size(); ++i) { + const auto& pr = pick[i]; + if (advise && i + kAhead < pick.size()) (void) src.advise_pairs(&pick[i + kAhead], 1); const int32_t slot = cache_.admit(pr.first, pr.second); const uint8_t* b = src.blob(pr.first, pr.second); if (slot < 0 || b == nullptr || !cache_.fill_slot(slot, b, refill_, err, (int64_t) lay.blob_bytes(pr.first))) { diff --git a/src/core/pinned.cu b/src/core/pinned.cu index fbc3b3c7..12cda847 100644 --- a/src/core/pinned.cu +++ b/src/core/pinned.cu @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -238,7 +239,29 @@ void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::st const uintptr_t end = aligned + bytes, raw_end = start + padded; if (raw_end > end) munmap((void*) end, raw_end - end); void* p = (void*) aligned; - if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && madvise(p, bytes, MADV_HUGEPAGE) == 0) { + // #771: with THP "always" the kernel already backs this mapping with huge pages where it can; the extra + // MADV_HUGEPAGE only adds direct reclaim and compaction on every fault (defrag=madvise), which on a fragmented + // machine stretched a 25 s start to 432 s. So it is not asked for there. STRATA_NO_ARENA_THP=1 skips it + // anywhere (the request alone; STRATA_NO_LARGEPAGES also skips the hugetlb try). + std::string thp_mode; + if (std::FILE* f = std::fopen("/sys/kernel/mm/transparent_hugepage/enabled", "r")) { + char line[128] = {0}; + if (std::fgets(line, sizeof line, f) != nullptr) { + const char* open = std::strchr(line, '['); + const char* close = open ? std::strchr(open, ']') : nullptr; + if (open && close) thp_mode.assign(open + 1, close); + } + std::fclose(f); + } + const bool skip_thp_request = std::getenv("STRATA_NO_ARENA_THP") != nullptr || thp_mode == "always"; + if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && skip_thp_request) { + const std::string four_k = "; using 4 KB pages"; + if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0) + note.resize(note.size() - four_k.size()); + note += std::getenv("STRATA_NO_ARENA_THP") != nullptr + ? "; transparent huge pages skipped (STRATA_NO_ARENA_THP)" + : "; transparent huge pages are on for every mapping (THP always): MADV_HUGEPAGE not requested"; + } else if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && madvise(p, bytes, MADV_HUGEPAGE) == 0) { const std::string four_k = "; using 4 KB pages"; if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0) note.resize(note.size() - four_k.size()); @@ -389,7 +412,9 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, " GiB); " + note; if (registered_bytes < bytes) { const char* env = std::getenv("STRATA_ARENA_LOCK"); - if (env == nullptr || std::string(env) != "0") { + if (backing == PageBacking::LargePages) { // #779: large pages cannot be paged out: nothing to lock + note = "large pages are resident without a lock; " + note; + } else if (env == nullptr || std::string(env) != "0") { const strata::platform::LockResult lr = strata::platform::lock_resident((uint8_t*) base + registered_bytes, bytes - registered_bytes); locked_bytes = lr.locked_bytes; @@ -415,7 +440,9 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, // and the CPU pool's rate then depends on the OS; locking it through the working set needs no // special privilege. STRATA_ARENA_LOCK=0 is the A/B arm. const char* env = std::getenv("STRATA_ARENA_LOCK"); - if (env == nullptr || std::string(env) != "0") { + if (backing == PageBacking::LargePages) { // #779: large pages cannot be paged out: nothing to lock + note = "large pages are resident without a lock; " + note; + } else if (env == nullptr || std::string(env) != "0") { const strata::platform::LockResult lr = strata::platform::lock_resident(base, bytes); locked_bytes = lr.locked_bytes; note = lr.note + "; " + note; @@ -426,6 +453,48 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, } } +PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, Deferred) + : capacity(bytes), bounds_(bounds) { + if (bytes == 0 || bounds.size() < 2) return; + base = reserve(bytes, backing, note, std::string{}, 0, mapping_base, mapping_bytes); + if (base != nullptr && mapping_base == nullptr) { + mapping_base = base; + mapping_bytes = bytes; + } + slice_bytes = 1; // sliced: one registration per layer +} + +void PinnedArena::register_slices(std::atomic& ready) { + const int n = (int) bounds_.size() - 1; + int i = 0; + for (; base != nullptr && i < n; ++i) { + const uint64_t off = bounds_[(size_t) i], len = bounds_[(size_t) i + 1] - off; + if (cudaHostRegister((uint8_t*) base + off, (size_t) len, cudaHostRegisterPortable | cudaHostRegisterMapped) != + cudaSuccess) { + (void) cudaGetLastError(); + break; + } + slice_starts.push_back(off); + registered_bytes = off + len; + ++registered_slices; + ready.store(i + 1, std::memory_order_release); + } + note = "cudaHostRegister per layer, pipelined with the load: " + std::to_string(registered_slices) + " of " + + std::to_string(n) + " slices pinned; " + note; + if (i < n && base != nullptr) { // the rest stays resident through the working-set lock, as the sliced fallback does + const char* env = std::getenv("STRATA_ARENA_LOCK"); + if (backing == PageBacking::LargePages) { // #779: large pages cannot be paged out: nothing to lock + note = "large pages are resident without a lock; " + note; + } else if (env == nullptr || std::string(env) != "0") { + const strata::platform::LockResult lr = + strata::platform::lock_resident((uint8_t*) base + registered_bytes, capacity - registered_bytes); + locked_bytes = lr.locked_bytes; + note = lr.note + "; " + note; + } + } + ready.store(INT_MAX, std::memory_order_release); // every slice done (or given up on) +} + PinnedArena::~PinnedArena() { if (base) { if (locked_bytes) strata::platform::unlock_resident((uint8_t*) base + (slice_bytes ? registered_bytes : 0), locked_bytes); @@ -449,19 +518,20 @@ LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_byte } LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk) { + const std::vector& layer_bytes, int threads, uint64_t chunk, + const std::atomic* ready) { LoadStats st; st.ok = false; #ifdef _WIN32 constexpr uint64_t kAlign = 4096; if (((uintptr_t) dst % kAlign) != 0 || chunk == 0 || chunk % kAlign != 0) return st; - struct Piece { uint64_t off, n; }; + struct Piece { uint64_t off, n; int layer; }; std::vector pieces; uint64_t bytes = 0; for (size_t L = 0; L < layer_off.size(); ++L) { if (layer_off[L] % kAlign != 0 || layer_bytes[L] % kAlign != 0) return st; for (uint64_t p = 0; p < layer_bytes[L]; p += chunk) - pieces.push_back({layer_off[L] + p, std::min(chunk, layer_bytes[L] - p)}); + pieces.push_back({layer_off[L] + p, std::min(chunk, layer_bytes[L] - p), (int) L}); bytes += layer_bytes[L]; } if (threads < 1) threads = 1; @@ -485,6 +555,8 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std:: for (;;) { const size_t i = next.fetch_add(1); if (i >= pieces.size()) break; + if (ready != nullptr) // the slice must be registered before its pages are touched + while (ready->load(std::memory_order_acquire) <= pieces[i].layer + 1) std::this_thread::yield(); OVERLAPPED ov{}; ov.Offset = (DWORD) pieces[i].off; ov.OffsetHigh = (DWORD) (pieces[i].off >> 32); @@ -515,7 +587,7 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std:: st.bytes = bytes; st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); #else - (void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk; + (void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk; (void) ready; #endif return st; } @@ -590,7 +662,8 @@ bool experts_unbuffered(const std::vector& files, uint64_t arena_by } LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector& layer_off, - const std::vector& layer_bytes, int threads, uint64_t chunk) { + const std::vector& layer_bytes, int threads, uint64_t chunk, + const std::atomic* ready) { LoadStats st; const uint64_t layers = (uint64_t) layer_off.size(); st.layers = layers; @@ -631,6 +704,8 @@ LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std:: for (;;) { const uint64_t L = next_layer.fetch_add(1); if (L >= layers) break; + if (ready != nullptr) // the slice must be registered before its pages are touched + while (ready->load(std::memory_order_acquire) <= (int) L + 1) std::this_thread::yield(); const uint64_t off = layer_off[(size_t) L]; uint64_t remaining = layer_bytes[(size_t) L]; uint64_t pos = 0; diff --git a/src/core/weights.cpp b/src/core/weights.cpp index 8b42f84f..6409736b 100644 --- a/src/core/weights.cpp +++ b/src/core/weights.cpp @@ -2,6 +2,7 @@ #include "strata/core/weights.hpp" #include "strata/kernels/f16_bits.hpp" +#include "strata/platform/memory.hpp" #include @@ -279,6 +280,12 @@ bool WeightTable::load(const std::string& pack_dir, void* arena_base, uint64_t a cur = std::fopen(p.c_str(), "rb"); if (!cur) { err = "cannot open " + p; cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; } cur_file = r.file; +#if !defined(_WIN32) + // ask for this file's remaining rows up front so their reads overlap + for (size_t j = row_i; j < rows.size(); ++j) + if (rows[j].file == r.file && !skipped[j]) + strata::platform::advise_willneed(fileno(cur), rows[j].src_off, rows[j].src_bytes); +#endif } // ---- the segment list: what this tensor's bytes are, plane by plane, in both forms diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index c6446293..4d0d4fbe 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -177,6 +177,30 @@ CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { return v; }; + // #798: a cpulist ("0-7,16") of one of the hybrid PMU's CPU sets: /sys/devices/cpu_core/cpus and cpu_atom/cpus + auto cpulist_read = [](const char* path, std::vector& out) -> bool { + std::FILE* f = std::fopen(path, "r"); + if (!f) return false; + char text[1024] = {0}; + const size_t n = std::fread(text, 1, sizeof text - 1, f); + std::fclose(f); + text[n] = '\0'; + for (const char* p = text; *p;) { + char* end = nullptr; + const long lo = std::strtol(p, &end, 10); + if (end == p) break; + long hi = lo; + if (*end == '-') { + p = end + 1; + hi = std::strtol(p, &end, 10); + } + for (long c = lo; c <= hi && c < 4096; ++c) out.push_back((int) c); + p = end; + while (*p == ',' || *p == ' ' || *p == '\n') ++p; + } + return !out.empty(); + }; + std::vector allowed; std::vector allowed_mask; if (detail::get_thread_affinity(allowed_mask, &allowed) != 0) { @@ -215,10 +239,23 @@ CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { all_cpus.push_back(cl); } - topo.is_hybrid = (max_cap > 0 && max_cap > min_cap); + // #798: which CPUs are E-cores. Intel's hybrid PMU lists them (cpu_atom/cpus beside cpu_core/cpus); without it a + // CPU is an E-core when its capacity is under 90% of the largest. Turbo Boost Max 3.0 gives the "favored" + // P-cores a slightly higher capacity (1024 against 1012 on a Core Ultra 7 270K Plus): "capacity == the maximum" + // counted 2 of its 8 P-cores and started 1 pool worker. + std::vector pmu_core, pmu_atom; + const bool pmu = cpulist_read("/sys/devices/cpu_core/cpus", pmu_core) && + cpulist_read("/sys/devices/cpu_atom/cpus", pmu_atom); + auto is_e = [&](const CoreLinux& cl) { + if (pmu) return std::find(pmu_atom.begin(), pmu_atom.end(), cl.cpu) != pmu_atom.end(); + return max_cap > 0 && cl.cap > 0 && cl.cap * 10 < max_cap * 9; + }; + bool any_e = false, any_p = false; + for (const auto& cl : all_cpus) (is_e(cl) ? any_e : any_p) = true; + topo.is_hybrid = any_e && any_p; if (topo.is_hybrid) { for (const auto& cl : all_cpus) { - if (cl.cap == max_cap) { + if (!is_e(cl)) { if (!cl.is_sibling) topo.p_cores++; topo.p_threads++; } else { @@ -233,7 +270,9 @@ CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { if (affinity == PoolAffinity::All || !topo.is_hybrid) { if (topo.is_hybrid) // #642: the P-cores first (see the Windows branch) std::stable_sort(all_cpus.begin(), all_cpus.end(), - [](const CoreLinux& x, const CoreLinux& y) { return x.cap > y.cap; }); + [&](const CoreLinux& x, const CoreLinux& y) { + return is_e(x) != is_e(y) ? !is_e(x) : x.cap > y.cap; + }); for (const auto& cl : all_cpus) { if (!cl.is_sibling) topo.worker_cores.push_back(cl.cpu); } @@ -250,7 +289,7 @@ CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { std::vector e_cores; for (const auto& cl : all_cpus) { - if (cl.cap == max_cap) { + if (!is_e(cl)) { if (!cl.is_sibling) p_primaries.push_back(cl.cpu); else p_siblings.push_back(cl.cpu); } else { diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 406213c3..4667745f 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -304,6 +304,8 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO (unsigned long long) t->offset, (unsigned long long) have, (unsigned long long) impl_->file->data_start()); err = buf; + if (alone && have > need) // #657: extra bytes after the table: a damaged or wrong file, not a format question + err += "; the file is longer than its table - delete it and its .done mark and run setup again"; close(); return false; } diff --git a/src/platform/memory.cpp b/src/platform/memory.cpp index f3b40e8d..a43ecef2 100644 --- a/src/platform/memory.cpp +++ b/src/platform/memory.cpp @@ -8,6 +8,9 @@ #include #include #else +#include +#include +#include #include #include #endif @@ -108,6 +111,10 @@ uint64_t total_physical_memory() { ms.dwLength = sizeof ms; return GlobalMemoryStatusEx(&ms) ? (uint64_t) ms.ullTotalPhys : 0; } + +bool read_ahead_enabled() { return false; } +void advise_willneed(const void*, uint64_t) {} +void advise_willneed(int, uint64_t, uint64_t) {} #else LockResult lock_resident(void* p, uint64_t bytes) { LockResult r; @@ -133,6 +140,32 @@ uint64_t total_physical_memory() { const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGE_SIZE); return pages > 0 && page > 0 ? (uint64_t) pages * (uint64_t) page : 0; } + +namespace { +constexpr uint64_t kAdviseStep = 128ull << 10; +} + +bool read_ahead_enabled() { + static const bool on = [] { + const char* v = std::getenv("STRATA_READ_AHEAD"); + return v == nullptr || std::atoi(v) != 0; + }(); + return on; +} + +void advise_willneed(const void* p, uint64_t bytes) { + if (p == nullptr || bytes == 0 || !read_ahead_enabled()) return; + const long ps = sysconf(_SC_PAGE_SIZE); + const uintptr_t pg = ps > 0 ? (uintptr_t) ps : 4096, end = (uintptr_t) p + bytes; + for (uintptr_t a = (uintptr_t) p & ~(pg - 1); a < end; a += kAdviseStep) + (void) madvise((void*) a, (size_t) std::min(kAdviseStep, end - a), MADV_WILLNEED); +} + +void advise_willneed(int fd, uint64_t offset, uint64_t bytes) { + if (fd < 0 || !read_ahead_enabled()) return; + for (uint64_t at = 0; at < bytes; at += kAdviseStep) + (void) posix_fadvise(fd, (off_t) (offset + at), (off_t) std::min(kAdviseStep, bytes - at), POSIX_FADV_WILLNEED); +} #endif } // namespace strata::platform diff --git a/src/program/generate.cpp b/src/program/generate.cpp index af31325d..7309f558 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2395,6 +2395,7 @@ int main(int argc, char** argv) { return 2; } const strata::core::ModelGeometry g0; + const auto embed_t0 = std::chrono::steady_clock::now(); if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g0.n_embd, 248320, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); @@ -2402,9 +2403,10 @@ int main(int argc, char** argv) { } strata::core::set_native_embed(&native_embed); std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding " - "%s in mapped host memory (%.0f MiB)\n", + "%s in mapped host memory (%.0f MiB, %.1f s)\n", o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6, - strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0); + strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0, + std::chrono::duration(std::chrono::steady_clock::now() - embed_t0).count()); } // Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back // to the expert cache with --native). `--keep-canonical` loads both, as before. @@ -2491,14 +2493,21 @@ int main(int argc, char** argv) { (unsigned long long) (total_b >> 20)); return 1; } + auto load_t0 = std::chrono::steady_clock::now(); + auto load_s = [&] { + const auto t = std::chrono::steady_clock::now(); + const double s = std::chrono::duration(t - load_t0).count(); + load_t0 = t; + return s; + }; strata::core::WeightTable wt; if (!wt.load(o.pack, arena, pool_bytes, err, skip.empty() ? nullptr : &skip)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } - std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s (%zu canonical tensors skipped: " - "served natively)\n", - (unsigned long long) (pool_bytes >> 20), o.pack.c_str(), skip.size()); + std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s in %.1f s (%zu canonical tensors " + "skipped: served natively)\n", + (unsigned long long) (pool_bytes >> 20), o.pack.c_str(), load_s(), skip.size()); strata::core::NativeDense native_dense; if (!o.native_dense_gguf.empty()) { @@ -2506,8 +2515,8 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: native dense projections: %s\n", err.c_str()); return 1; } - std::fprintf(stderr, "strata generate: %zu native projection matrices, %.2f MiB of weights\n", - native_dense.tensor_count(), (double) native_dense.weight_bytes() / (1024.0 * 1024.0)); + std::fprintf(stderr, "strata generate: %zu native projection matrices, %.2f MiB of weights, in %.1f s\n", + native_dense.tensor_count(), (double) native_dense.weight_bytes() / (1024.0 * 1024.0), load_s()); } strata::kernels::gr_set_fp32_activations(o.gr_fp32_activations); @@ -3371,12 +3380,14 @@ int main(int argc, char** argv) { 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 + const auto head_t0 = std::chrono::steady_clock::now(); 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::fprintf(stderr, "strata generate: experimental native Q5_K head, %llu bytes, in %.1f s\n", + (unsigned long long) native_head.weight_bytes(), + std::chrono::duration(std::chrono::steady_clock::now() - head_t0).count()); } std::vector logits((size_t) n_vocab); float* d_logits = nullptr; @@ -3480,11 +3491,18 @@ int main(int argc, char** argv) { // #286: with a RAM budget the hottest experts live in it, and the rest are read from the drive unbuffered // when the file cache could not keep them beside the budget anyway (a 32 GB PC) - the mapped reads' page // faults are small requests on the critical path, and their pages take the RAM the budget was sized for - if (o.resident_budget > 0 || std::getenv("STRATA_UNBUFFERED_LOAD") != nullptr) { + // #773: without a RAM budget there is no RAM copy and the file cache IS the expert tier (measured on a + // 32 GB, 2 x 16 GB rig: forcing unbuffered reads there re-read 163-629 GB from the drive and halved the + // speed), so STRATA_UNBUFFERED_LOAD=1 is not honoured in that mode + if (o.resident_budget > 0) { std::string why; const bool ub = src.set_unbuffered(o.resident_budget, why); std::fprintf(stderr, "strata generate: the file tier reads %s (%s)\n", ub ? "unbuffered" : "through the file cache", why.c_str()); + } else if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0' && + env[0] != '0') { + std::fprintf(stderr, "strata generate: the file tier reads through the file cache (STRATA_UNBUFFERED_LOAD=%s " + "ignored: without --resident-budget-gib the file cache holds the experts)\n", env); } srcp = &src; } else { @@ -3664,6 +3682,13 @@ int main(int argc, char** argv) { used += b; sized_slots.push_back((int64_t) lay.blob_bytes(pr.first)); } + // #831: the sized-slots loop walks the profile's pairs, so the profile's length is the ceiling; an explicit + // --expert-cache above it used to be cut with no word. A warning only (what is allocated does not change). + if (!auto_cache && o.expert_cache > 0 && sized_slots.size() == profile.size() && (size_t) o.expert_cache > profile.size()) + std::fprintf(stderr, "strata generate: WARNING: --expert-cache %d is more than the %zu pairs of the profile %s: " + "%zu slots (the profile is the ceiling on a native pack; a profile that ranks every " + "(layer, expert) pair lifts it - tools/make_profile.py)\n", o.expert_cache, + profile.size(), o.expert_profile.c_str(), profile.size()); o.expert_cache = (int) sized_slots.size(); } // #533: --vram-elastic: the cache in physical segments (the VRAM command resizes it between requests). One GPU, @@ -3815,12 +3840,24 @@ int main(int argc, char** argv) { // #286: an unbuffered file tier reads the pairs in batches of 64, the next batch while this one is copied std::future ahead; auto read_batch = [&](int64_t at) { src.prefetch_pairs(profile.data() + at, std::min(64, want - at)); }; + // mapped reads: advise the next `fill_ahead` pairs so their reads overlap; STRATA_FILL_AHEAD=0 turns it off + int64_t fill_ahead = 0; + if (!per_layer && srcp == &src && !src.unbuffered()) { + const char* v = std::getenv("STRATA_FILL_AHEAD"); + fill_ahead = v == nullptr ? 256 : std::max(0, std::atoi(v)); + if (fill_ahead > 0 && !src.advise_pairs(profile.data(), std::min(fill_ahead, want))) fill_ahead = 0; + std::fprintf(stderr, "strata generate: the profile fill asks for %lld pairs ahead (STRATA_FILL_AHEAD)\n", + (long long) fill_ahead); + } + const auto fill_t0 = std::chrono::steady_clock::now(); + uint64_t fill_bytes = 0; for (int64_t i = 0; i < want; ++i) { if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) { if (ahead.valid()) ahead.get(); else read_batch(i); if (i + 64 < want) ahead = std::async(std::launch::async, read_batch, i + 64); } + if (fill_ahead > 0 && i + fill_ahead < want) (void) src.advise_pairs(profile.data() + i + fill_ahead, 1); const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second); if (slot == strata::core::kNotResident) { if (per_layer) continue; @@ -3833,8 +3870,10 @@ int main(int argc, char** argv) { (long long) i, err.c_str()); return 1; } + fill_bytes += strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first); ++prefilled; } + const double fill_s = std::chrono::duration(std::chrono::steady_clock::now() - fill_t0).count(); // **AND ONE SLOT IS READ BACK AND COMPARED.** A residency table that is right about indices and wrong // about bytes produces a plausible token, which is this project's most expensive failure mode; the // cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup. @@ -3845,8 +3884,10 @@ int main(int argc, char** argv) { return 1; } mem_mark("the profile fill"); - std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile; slot 0 verified\n", - (long long) prefilled, (long long) (per_layer ? xcache.slots() : want)); + std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile in %.1f s (%.0f MB/s); " + "slot 0 verified\n", + (long long) prefilled, (long long) (per_layer ? xcache.slots() : want), fill_s, + fill_s > 0 ? (double) fill_bytes / 1e6 / fill_s : 0.0); } for (auto& stp : stages) { @@ -3870,9 +3911,23 @@ int main(int argc, char** argv) { used += b; sized.push_back((int64_t) lay.blob_bytes(pr.first)); } - if (sized.empty() || - !(native_pack ? st.cache.open_sized(sized, g.n_layers, g.n_expert, err) - : st.cache.open((int64_t) sized.size(), g.n_layers, g.n_expert, (int64_t) lay.max_blob, err))) { + // #841: a stage's cache can fail to open with the VRAM free (the card's allocation is also charged to the + // Windows commit, or the free figure ran high): it is tried again with 90% of the slots, up to 3 times, each + // try said. Nothing changes when the first open works. + bool stage_open = false; + for (int attempt = 0; !sized.empty(); ++attempt) { + stage_open = native_pack ? st.cache.open_sized(sized, g.n_layers, g.n_expert, err) + : st.cache.open((int64_t) sized.size(), g.n_layers, g.n_expert, (int64_t) lay.max_blob, err); + if (stage_open || attempt >= 3) break; + (void) cudaGetLastError(); + const size_t keep = sized.size() * 9 / 10; + std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s; trying %zu of %zu slots " + "(try %d of 3)\n", st.dev, err.c_str(), keep, sized.size(), attempt + 1); + if (keep == 0) break; + st.cache.close(); + sized.resize(keep); + } + if (!stage_open) { std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev, sized.empty() ? "no room" : err.c_str()); return 1; @@ -4948,7 +5003,7 @@ int main(int argc, char** argv) { std::string whole_err; if (!resident_ok && o.resident_soft) { // #467: the whole complement does not fit - keep what does, the hottest by the profile, through the #403 - // budget path (sized by the RAM alone) instead of none: the misses outside it read the same file bytes + // budget path (sized by available memory) instead of none: the misses outside it read the same file bytes // the mmap fallback reads, so the answers are unchanged. Nothing pinned: the old fallback below. whole_err = err; resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, -1, o.resident_headroom, @@ -4991,17 +5046,18 @@ int main(int argc, char** argv) { // #403: a RAM budget that cannot be kept is not a reason to stop - the experts it would have held are // read from the files like the ones outside it (pin_cache_complement leaves nothing half-built) std::fprintf(stderr, "strata generate: WARNING: the RAM budget (--resident-budget-gib) cannot be kept (%s); " - "every expert the GPU does not hold is read from the model files through the OS file " - "cache (--mmap-experts), which is slower\n", err.c_str()); + "every expert the GPU does not hold is read from the model files %s " + "(--mmap-experts), which is slower\n", err.c_str(), + src.unbuffered() ? "with unbuffered I/O" : "through the OS file cache"); } else { 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) + // the file cache keeps those, and every refill after a prompt read the drive instead). Windows and Linux: the + // unbuffered reads exist there +#if defined(_WIN32) || defined(__linux__) if (o.mmap_experts && o.resident_budget > 0) { std::string why; const bool was = src.unbuffered(); @@ -7781,6 +7837,11 @@ int main(int argc, char** argv) { auto refill_wait = [&](PfPart& p, std::string& e) -> bool { const strata::core::OnDevice on(p.dev); if (!p.cache->sync_queued(e)) return false; +#if defined(_WIN32) + // The copies have landed: the file pages touched by the loan need not stay in the working set. + for (const auto& [i, slot] : p.lent) + srcp->release(i / g.n_expert, i % g.n_expert); +#endif p.lent.clear(); p.lent_chunk = 0; return true; @@ -9260,6 +9321,10 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: refilling the lent slots failed: %s\n", err.c_str()); return 1; } +#if defined(_WIN32) + for (const auto& [i, slot] : lent) + srcp->release(i / g.n_expert, i % g.n_expert); +#endif res_put(d_res); std::fprintf(stderr, "strata generate: %zu lent slots refilled in %.1f ms\n", lent.size(), std::chrono::duration(Clock::now() - tr).count()); diff --git a/tests/core/expert_layout_test.cpp b/tests/core/expert_layout_test.cpp index 35d1accf..ffdf1c66 100644 --- a/tests/core/expert_layout_test.cpp +++ b/tests/core/expert_layout_test.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -223,6 +224,16 @@ void arena() { const uint8_t* b = fs.blob(l, e); const size_t n = (size_t) L.blob_bytes(l); same = same && b != nullptr && std::memcmp(b, dst.data() + L.blob_offset(l, e), n) == 0; + copies = copies && fs.copy_blob(l, e, buf.data()) && + std::memcmp(buf.data(), dst.data() + L.blob_offset(l, e), n) == 0; + const uint64_t released = fs.release(l, e); +#if defined(_WIN32) + const char* setting = std::getenv("STRATA_FILE_RELEASE"); + const bool enabled = setting != nullptr && std::strcmp(setting, "1") == 0; + check(enabled ? released > 0 : released == 0, "GGUF mapped release honors its opt-in switch"); +#else + check(released == 0, "GGUF mapped release remains unchanged outside Windows"); +#endif copies = copies && fs.copy_blob(l, e, buf.data()) && std::memcmp(buf.data(), dst.data() + L.blob_offset(l, e), n) == 0; transient = transient && fs.transient(l, e); diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp index f0b47c78..56590970 100644 --- a/tests/core/file_expert_source_test.cpp +++ b/tests/core/file_expert_source_test.cpp @@ -12,8 +12,13 @@ #include #include #include +#include +#include +#include #include #include +#include +#include #include #include #include @@ -24,6 +29,16 @@ #include #include +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX +#endif +#define PSAPI_VERSION 2 +#include +#include +#endif + namespace fs = std::filesystem; namespace { @@ -35,9 +50,9 @@ void require(bool ok, const std::string& message) { struct TempDirectory { fs::path path; - TempDirectory() { + explicit TempDirectory(const fs::path& base = fs::temp_directory_path()) { const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); - path = fs::temp_directory_path() / ("strata-file-source-test-" + std::to_string(stamp)); + path = base / ("strata-file-source-test-" + std::to_string(stamp)); fs::create_directories(path); } @@ -82,6 +97,48 @@ void check_file_size_rejection(strata::core::FileExpertSource& source, const fs: require(!source.mapped() && !err.empty(), "oversized-file rejection left the source mapped or unreported"); } +#if defined(_WIN32) +void check_mapped_release(strata::core::FileExpertSource& source, int64_t layer, int64_t expert, uint64_t bytes) { + const uint8_t* p = source.blob(layer, expert); + require(p != nullptr, "release fixture has no mapped blob"); + const std::vector saved(p, p + (size_t) bytes); + SYSTEM_INFO info{}; + GetSystemInfo(&info); + const uintptr_t page = info.dwPageSize; + const uintptr_t first = ((uintptr_t) p + page - 1) / page * page; + const uintptr_t end = ((uintptr_t) p + bytes) / page * page; + require(end > first, "release fixture has no full interior page"); + auto resident = [&](uintptr_t address) { + PSAPI_WORKING_SET_EX_INFORMATION state{}; + state.VirtualAddress = (void*) address; + require(QueryWorkingSetEx(GetCurrentProcess(), &state, sizeof state) != 0, + "QueryWorkingSetEx failed for the release fixture"); + return state.VirtualAttributes.Valid != 0; + }; + const char* setting = std::getenv("STRATA_FILE_RELEASE"); + const bool enabled = setting != nullptr && std::strcmp(setting, "1") == 0; + for (int round = 0; round < 3; ++round) { + require(std::memcmp(p, saved.data(), saved.size()) == 0, "release changed the mapped expert bytes"); + require(resident(first), "reading the expert did not bring its interior page into the working set"); + const uint64_t released = source.release(layer, expert); + require(released == (enabled ? end - first : 0), "release did not honor full pages or its opt-in switch"); + // Off: the page stays. On: Windows may keep a trimmed page on its standby list and map it back at once, so a + // page that is still valid is reported, not failed (the byte count above is the contract). + if (!enabled) require(resident(first), "release trimmed pages with the switch off"); + else if (resident(first)) std::fprintf(stderr, "note: the trimmed page is already back in the working set\n"); + if ((uintptr_t) p < first) + require(resident((uintptr_t) p), "release trimmed the expert's shared first page"); + if (end < (uintptr_t) p + bytes) + require(resident(end), "release trimmed the expert's shared last page"); + } + require(std::memcmp(p, saved.data(), saved.size()) == 0, "the expert changed after repeated release/read cycles"); + require(source.release(-1, expert) == 0 && source.release(layer, -1) == 0 && + source.release(std::numeric_limits::max(), expert) == 0 && + source.release(layer, std::numeric_limits::max()) == 0, + "release accepted an invalid layer or expert"); +} +#endif + void test_canonical_layout() { using namespace strata::core; using namespace strata::kernels::cpu; @@ -113,6 +170,10 @@ void test_canonical_layout() { source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr, "canonical bounds check accepted an invalid layer or expert"); require(source.reads() == 3, "invalid canonical lookups changed the read count"); +#if defined(_WIN32) + check_mapped_release(source, 0, 0, BLOB); + check_mapped_release(source, 0, 1, BLOB); +#endif check_file_size_rejection(source, dir.path, layers, experts, total); create_pack(dir.path, total, {{layer_bytes, 'c'}}); @@ -122,6 +183,7 @@ void test_canonical_layout() { const uint8_t* reopened = source.blob(1, 0); require(reopened && source.reads() == 1 && reopened[0] == 'c', "reopened canonical source kept stale state"); source.close(); + require(source.release(0, 0) == 0, "a closed file source released pages"); } #if defined(STRATA_NATIVE_EXPERTS) @@ -176,6 +238,10 @@ void test_native_variable_layout() { source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr, "native bounds check accepted an invalid layer or expert"); require(source.reads() == 4, "invalid native lookups changed the read count"); +#if defined(_WIN32) + check_mapped_release(source, 0, 1, first_fmt.bytes); + check_mapped_release(source, 1, 1, second_fmt.bytes); +#endif check_file_size_rejection(source, dir.path, layers, experts, total); create_pack(dir.path, total, {{layer0_bytes, 'c'}}); @@ -256,6 +322,35 @@ void test_resident_exchange() { require(offsets == before, "exchanging back did not restore the plan"); } +void test_resident_memory_budget() { + using strata::core::detail::clamp_resident_budget; + constexpr uint64_t GiB = 1ull << 30, margin = 256ull << 20, headroom = 4 * GiB; + constexpr uint64_t unlimited = std::numeric_limits::max(); + // #730: RAM can hold the requested cache, but Windows cannot commit it. + require(clamp_resident_budget(66 * GiB, 69 * GiB, 47 * GiB, headroom) == 43 * GiB - margin, + "a RAM budget exceeded available commit capacity"); + require(clamp_resident_budget(66 * GiB, 47 * GiB, 69 * GiB, headroom) == 43 * GiB - margin, + "a RAM budget exceeded available physical memory"); + require(clamp_resident_budget(40 * GiB, 69 * GiB, 47 * GiB, headroom) == 40 * GiB, + "a smaller explicit budget was changed"); + require(clamp_resident_budget(unlimited, 69 * GiB, 47 * GiB, headroom) == 43 * GiB - margin, + "the what-fits budget ignored commit capacity"); + require(clamp_resident_budget(66 * GiB, 47 * GiB, unlimited, headroom) == 43 * GiB - margin, + "a platform without a commit reading lost its RAM limit"); + require(clamp_resident_budget(43 * GiB, 69 * GiB, 47 * GiB, headroom) == 43 * GiB, + "a budget that exactly fits received the clamping margin"); + require(clamp_resident_budget(66 * GiB, 69 * GiB, 0, headroom) == 0, + "exhausted commit capacity was treated as unlimited"); + require(clamp_resident_budget(66 * GiB, 0, 69 * GiB, headroom) == 0, + "exhausted RAM produced a positive budget"); + require(clamp_resident_budget(66 * GiB, 69 * GiB, headroom - 1, headroom) == 0 && + clamp_resident_budget(66 * GiB, 69 * GiB, headroom, headroom) == 0, + "subtracting headroom underflowed"); + require(clamp_resident_budget(66 * GiB, 69 * GiB, headroom + margin - 1, headroom) == 0 && + clamp_resident_budget(66 * GiB, 69 * GiB, headroom + margin, headroom) == 0, + "subtracting the clamping margin underflowed"); +} + void test_cgroup_memory_budget() { using namespace strata::core::detail; constexpr uint64_t GiB = 1ull << 30; @@ -291,6 +386,76 @@ void test_cgroup_memory_budget() { "missing memory.stat counters did not fail closed"); } +void set_env(const char* name, const char* value) { +#if defined(_WIN32) + _putenv_s(name, value != nullptr ? value : ""); +#else + if (value != nullptr) setenv(name, value, 1); + else unsetenv(name); +#endif +} + +// #286: the unbuffered file tier (Windows: FILE_FLAG_NO_BUFFERING; Linux: O_DIRECT + io_submit) hands out the same +// bytes as the mapping - one blob at a time, a batch of adjacent experts (merged into one request), and copy_blob - and +// never falls back to the mapping. The pack lives in the working directory, not the temp directory: a tmpfs /tmp has +// no O_DIRECT, and there the test says so and skips. +void test_unbuffered_reads() { + using namespace strata::core; + using namespace strata::kernels::cpu; + constexpr int64_t layers = 2; + constexpr int64_t experts = 3; + const uint64_t layer_bytes = (uint64_t) experts * BLOB; + const uint64_t total = (uint64_t) layers * layer_bytes; + TempDirectory dir(fs::current_path()); + std::string err; + require(expert_layout_load(dir.path.string(), layers, experts, err), "could not load canonical layout: " + err); + std::vector bytes((size_t) total); + uint64_t x = 0x9E3779B97F4A7C15ull; + for (uint8_t& b : bytes) { + x = x * 6364136223846793005ull + 1442695040888963407ull; + b = (uint8_t) (x >> 56); + } + { + std::ofstream out(dir.path / "experts.bin", std::ios::binary | std::ios::trunc); + out.write((const char*) bytes.data(), (std::streamsize) bytes.size()); + require((bool) out, "could not write the synthetic experts.bin"); + } + FileExpertSource source; + require(source.open(dir.path.string(), layers, experts, err), "could not map the synthetic pack: " + err); + set_env("STRATA_UNBUFFERED_LOAD", "1"); + std::string why; + const bool unbuffered = source.set_unbuffered(0, why); + set_env("STRATA_UNBUFFERED_LOAD", nullptr); +#if defined(_WIN32) || defined(__linux__) + if (!unbuffered) { + std::cout << "file_expert_source_test: unbuffered reads skipped (" << why << ")\n"; + source.close(); + return; + } +#else + require(!unbuffered, "unbuffered reads on a platform without them"); + source.close(); + return; +#endif + require(source.unbuffered(), "set_unbuffered succeeded but the source is not unbuffered"); + const int64_t batch[experts] = {0, 1, 2}; + source.prefetch(1, batch, experts); // layer 1 in one batch: three adjacent blobs + for (int64_t l = 0; l < layers; ++l) + for (int64_t e = 0; e < experts; ++e) { + const uint8_t* b = source.blob(l, e); + require(b != nullptr, "an unbuffered blob lookup failed"); + require(std::memcmp(b, bytes.data() + (size_t) (l * (int64_t) layer_bytes + e * (int64_t) BLOB), + (size_t) BLOB) == 0, + "an unbuffered blob differs from the file"); + } + std::vector copy((size_t) BLOB); + require(source.copy_blob(0, 2, copy.data()) && + std::memcmp(copy.data(), bytes.data() + (size_t) (2 * BLOB), (size_t) BLOB) == 0, + "an unbuffered copy_blob differs from the file"); + require(source.direct_fallbacks() == 0, "an unbuffered read fell back to the mapping"); + source.close(); +} + // #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() { @@ -308,7 +473,10 @@ void test_host_memory() { root = (t.path / "fs").string(); auto probe = [&](const std::string& self) { put("cgroup", self); - return host_available_memory(m, mi, cg, root); + m.commit = 0; + const bool ok = host_available_memory(m, mi, cg, root); + require(m.commit == ~0ull, "Linux memory probe retained a commit limit"); + return ok; }; // 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"); @@ -337,6 +505,11 @@ void test_host_memory() { 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"); +#if defined(_WIN32) + require(m.commit != ~0ull, "Windows memory probe did not report commit capacity"); +#else + require(m.commit == ~0ull, "a platform without commit accounting imposed a limit"); +#endif (void) GiB; #endif } @@ -435,9 +608,11 @@ int main(int argc, char** argv) { test_complement_plan(); test_resident_lend_region(); test_resident_exchange(); + test_resident_memory_budget(); test_cgroup_memory_budget(); test_host_memory(); test_canonical_layout(); + test_unbuffered_reads(); #if defined(STRATA_NATIVE_EXPERTS) test_native_variable_layout(); #endif diff --git a/tools/hip/package_windows.py b/tools/hip/package_windows.py index e6298815..12738f19 100644 --- a/tools/hip/package_windows.py +++ b/tools/hip/package_windows.py @@ -142,8 +142,8 @@ def main() -> int: (lic / "NOTICE.txt").write_text(NOTICE.format(rocm=a.rocm_version, dlls="\n".join(" " + d for d in shipped)), encoding="utf-8") - version = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text()).group(1) - hl = (a.rocm / "include" / "hipblaslt" / "hipblaslt-version.h").read_text() + version = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8")).group(1) + hl = (a.rocm / "include" / "hipblaslt" / "hipblaslt-version.h").read_text(encoding="utf-8") hlv = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", hl).group(1)) for k in ("MAJOR", "MINOR", "PATCH")] meta = {"source": "prebuilt", "backend": "hip", "platform": "windows-x64", "version": version, "archs": archs, "rocm": a.rocm_version, "hipblaslt_version": hlv[0] * 100000 + hlv[1] * 100 + hlv[2], "vision": "none", diff --git a/tools/iq_pack.py b/tools/iq_pack.py index 86766755..5ce0e4a5 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -84,9 +84,9 @@ FORM = { "ple_norm_query.weight": "F32", "ssm_a": "F32", "ssm_conv1d.weight": "F32", "ssm_dt.bias": "F32", "ssm_norm.weight": "F32", } -# PLE key encodings left in the GGUF for the engine's native PLE key (Q2_0; Q8_0 in UD-Q4_K_XL). Other quantized -# keys take the BF16 path (--compat-bf16), as before. -NATIVE_PLE_KEY = {"Q2_0", "Q8_0"} +# PLE key encodings left in the GGUF for the engine's native PLE key: the formats NativeDense serves (Q2_0; Q8_0 in +# UD-Q4_K_XL; IQ3_XXS and IQ4_XS, #381). Other quantized keys take the BF16 path (--compat-bf16), as before. +NATIVE_PLE_KEY = {"Q2_0", "Q8_0", "IQ3_XXS", "IQ4_XS"} KIND = {"BF16": "4", "F16": "5", "F32": "2"} diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 6857715a..8962d093 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -78,7 +78,7 @@ FALLBACK_FAMILIES = { "(UD-Q4_K_XL, 111 GB: experimental)", "tag": "unsloth-", "vision": False}, } -FALLBACK_CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288] +FALLBACK_CONTEXTS = [8192, 32768, 65536, 131072, 204800, 262144, 393216, 524288] BENCH_PROMPT = ("Write a short story (about 300 words) about a lighthouse keeper who finds a message in a bottle. " "Plain prose, no title.") @@ -480,7 +480,8 @@ class Strata: # ---- what is installed def configs(self) -> list[Path]: - return sorted(self.root.glob("strata-*.json"), key=lambda p: p.stat().st_mtime, reverse=True) + return sorted((p for p in self.root.glob("strata-*.json") if not p.name.endswith(".shared-settings.json")), + key=lambda p: p.stat().st_mtime, reverse=True) # #346: the Chat settings file is no config @staticmethod def read_config(path: Path) -> dict: diff --git a/tools/strata_pack.py b/tools/strata_pack.py index 31fbe226..985d93db 100644 --- a/tools/strata_pack.py +++ b/tools/strata_pack.py @@ -203,7 +203,28 @@ def sha256(path: pathlib.Path, chunk: int = 1 << 24) -> str: return h.hexdigest() -def build(gguf: pathlib.Path, out_dir: pathlib.Path, n_layers: int | None, skip_hash: bool) -> int: +# The files the engine reads a pack's identity from (src/core/expert_source.cpp, the fingerprint): one of them in +# --out means the directory already holds a pack, this tool's or iq_pack.py's. experts.bin on its own does not: +# build writes manifest.json last, so experts.bin without it is a build that did not finish, and is rebuilt. +PACK_MARKERS = ("manifest.json", "index.txt", "native_experts.txt") + + +def occupied(out_dir: pathlib.Path) -> pathlib.Path | None: + """The pack marker already in `out_dir`, or None when the directory is empty, absent or holds no pack.""" + for name in PACK_MARKERS: + if (out_dir / name).exists(): + return out_dir / name + return None + + +def build(gguf: pathlib.Path, out_dir: pathlib.Path, n_layers: int | None, skip_hash: bool, force: bool = False) -> int: + # refused before anything is opened or written: build used to mkdir(exist_ok=True) and overwrite experts.bin, + # dense.bin, embd.bin and manifest.json of whatever pack was there, with nothing said + marker = None if force else occupied(out_dir) # --force: setup rebuilding a pack that lost index.txt or experts.bin + if marker is not None: + print("%s already holds a pack (%s is there) - refusing to build; delete the directory, pass another " + "--out, or --force to rebuild it" % (out_dir, marker.name)) + return 1 out_dir.mkdir(parents=True, exist_ok=True) g = G.GGUFFile(gguf) head, flen = open_shard(gguf) @@ -402,6 +423,7 @@ def main() -> int: b.add_argument("--out", required=True) b.add_argument("--layers", type=int, default=None, help="expert layers to emit (default 48)") b.add_argument("--skip-hash", action="store_true") + b.add_argument("--force", action="store_true", help="build into a directory that already holds a pack (#634)") v = sub.add_parser("verify") v.add_argument("--gguf", required=True) v.add_argument("--out", required=True) @@ -413,7 +435,7 @@ def main() -> int: n.add_argument("--out", required=True) args = ap.parse_args() if args.cmd == "build": - return build(pathlib.Path(args.gguf), pathlib.Path(args.out), args.layers, args.skip_hash) + return build(pathlib.Path(args.gguf), pathlib.Path(args.out), args.layers, args.skip_hash, args.force) if args.cmd == "verify": return verify(pathlib.Path(args.gguf), pathlib.Path(args.out), args.limit, args.expert_every) return info(pathlib.Path(args.out)) diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 1c83db47..9758b41e 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -121,11 +121,35 @@ class CompatibilityTests(unittest.TestCase): def test_q2_ple_and_large_tensors_stay_native(self): self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q2_0")) self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q8_0")) - self.assertTrue(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ3_XXS")) + self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ3_XXS")) + self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ4_XS")) + self.assertTrue(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q6_K")) for name in ["blk.0.ffn_gate_exps.weight", "token_embd.weight", "output.weight", "per_layer_token_embd.weight", "blk.0.attn_qkv.weight"]: self.assertFalse(iq_pack.needs_bf16(name, "IQ3_XXS")) + def test_iq_ple_keys_are_indexed_without_conversion(self): + for kind, block_bytes in [(Q.IQ3_XXS, 98), (Q.IQ4_XS, 136)]: + with self.subTest(kind=kind), tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + source = root / "model.gguf" + writer = GGUFWriter(source, "qwen4exp") + writer.add_tensor("blk.1.ple_key.weight", np.zeros((2, block_bytes), dtype=np.uint8), + raw_dtype=kind) + writer.write_header_to_file() + writer.write_kv_data_to_file() + writer.write_tensors_to_file() + writer.close() + before = source.read_bytes() + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 0) + _, rows = iq_pack.read_index(root / "index.txt") + row = rows["blk.1.ple_key.weight"] + self.assertEqual(row[2], "0") + self.assertEqual((root / "dense.bin").read_bytes(), b"") + self.assertEqual(json.loads((root / "conversions.json").read_text())["tensors"], []) + self.assertEqual(source.read_bytes(), before) + def test_experts_bin_is_kept_only_with_this_ggufs_blobs(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index 61a12237..94cc0c39 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -230,6 +230,22 @@ class WindowsDetection(unittest.TestCase): self.assertEqual(g[0]["driver"], "32.0.21013.1000") self.assertEqual([setup.amd_problem(x) is None for x in g], [True, False, True]) + def test_rx_6800m_is_gfx1031(self): + """#881: PCI 73DF (RX 6700 XT / 6750 XT / 6800M) is gfx1031, not an unknown id.""" + self.assertEqual(setup.win_amd_arch(0x73DF, "AMD Radeon RX 6800M"), "gfx1031") + self.assertIsNone(setup.amd_problem({"arch": "gfx1031"})) + + def test_cpu_vision_build_uses_the_visual_studio_environment(self): + """#881: build_vision_cpu on Windows hands cmake_build the vcvars file and a real .bat name (it passed None and + an empty name before).""" + calls = [] + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "WIN", True), mock.patch.object(setup, "find_vcvars", return_value=Path("C:/vs/vcvars64.bat")), mock.patch.object(setup, "cmake_build", lambda *a: calls.append(a)), mock.patch.object(setup, "ROOT", Path(d)), mock.patch.object(setup.shutil, "copy2"): + eng = Path(d) / "engine" + eng.mkdir() + setup.build_vision_cpu(eng, eng / "BUILD.json", {}, Path("llama"), "src1") + self.assertEqual(calls[0][4], Path("C:/vs/vcvars64.bat")) + self.assertTrue(calls[0][5].endswith(".bat")) + def test_registry_alone(self): """No WMI answer: the registry's own list (which can hold a removed card).""" g = setup.amd_gpus_windows([], self.REGISTRY) diff --git a/tools/test_setup_config.py b/tools/test_setup_config.py index cd297645..d031891c 100644 --- a/tools/test_setup_config.py +++ b/tools/test_setup_config.py @@ -114,6 +114,39 @@ class CarryOver(unittest.TestCase): self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"exe": "e", "args": []}) self.assertEqual((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8"), "{cut off") + def test_display_tip_and_typed_ahead_flush(self): + # #779: the tip only when nvidia-smi says the card drives a display; #841: typed-ahead keys are dropped on a tty + with unittest.mock.patch.object(setup, "out", lambda cmd: "Enabled\n"): + self.assertTrue(setup.gpu_drives_display({"index": 0})) + with unittest.mock.patch.object(setup, "out", lambda cmd: "Disabled\n"), unittest.mock.patch.object(setup, "out") as o: + o.return_value = "Disabled\n" + self.assertFalse(setup.gpu_drives_display({"index": 1})) + self.assertIn("1", o.call_args[0][0]) + with unittest.mock.patch.object(setup, "out", lambda cmd: ""): + self.assertFalse(setup.gpu_drives_display({"index": 0})) + with unittest.mock.patch.object(setup.sys, "stdin") as stdin: + stdin.isatty.return_value = False + setup.flush_typed_ahead() # a pipe: nothing touched + stdin.fileno.assert_not_called() + + def test_a_learned_expert_profile_is_carried(self): + # #775: --expert-profile / --expert-profile-save added by hand survive a setup run + with tempfile.TemporaryDirectory() as d: + mine = Path(d) / "learned.bin" + mine.write_bytes(b"x") + old = {"args": ["--kv", "int8", "--expert-profile", str(mine), "--expert-profile-save", str(mine)]} + new = {"args": ["--kv", "int8", "--expert-profile", "/data/expert-profile.bin", "--expert-cache", "auto"]} + self.assertEqual(setup.carry_over(old, new), ["args --expert-profile", "args --expert-profile-save"]) + self.assertEqual(setup.flag_value(new["args"], "--expert-profile"), str(mine)) + self.assertEqual(setup.flag_value(new["args"], "--expert-profile-save"), str(mine)) + # the shipped profile named again, or a file that is gone: setup's own stays + gone = {"args": ["--expert-profile", str(Path(d) / "gone.bin")]} + new = {"args": ["--expert-profile", "/data/expert-profile.bin"]} + self.assertEqual(setup.carry_over(gone, new), []) + self.assertEqual(new["args"], ["--expert-profile", "/data/expert-profile.bin"]) + same = {"args": ["--expert-profile", "/old/expert-profile.bin"]} + self.assertEqual(setup.carry_over(same, new), []) + def test_a_missing_mmproj_is_not_carried(self): old = {"vision": {"mmproj": "/nowhere/mmproj-Q8_0.gguf", "gpu": True}} new = {"vision": {"mmproj": "/data/mmproj-BF16.gguf", "gpu": True}} diff --git a/tools/test_setup_configs.py b/tools/test_setup_configs.py new file mode 100644 index 00000000..1ef01947 --- /dev/null +++ b/tools/test_setup_configs.py @@ -0,0 +1,63 @@ +"""Tests for the model configs setup.py lists: the server keeps a config's Chat settings next to it as +`strata-.shared-settings.json`, which matches the configs' own `strata-*.json` but is not one (no exe, no +args), so the start menu and the "set up like the last one" lookup must leave it out. + + python -m unittest tools.test_setup_configs +""" +from __future__ import annotations + +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 + +CONFIG = {"exe": "engine/strata.exe", "args": ["--max-context", "131072"]} +SHARED = {"reasoning_effort": "high", "temperature": 0.6} + + +def write(folder: Path, name: str, data: dict) -> Path: + path = folder / name + path.write_text(json.dumps(data), encoding="utf-8") + return path + + +class ModelConfigs(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.dir = Path(tmp.name) + self.config = write(self.dir, "strata-iq3_s.json", CONFIG) + self.shared = write(self.dir, "strata-iq3_s.shared-settings.json", SHARED) + # previous_config also looks into the Strata folders next to this checkout: keep the real ones out + patch = mock.patch.object(setup, "other_installs", return_value=[]) + patch.start() + self.addCleanup(patch.stop) + + def test_the_start_menu_lists_the_config_but_not_its_shared_settings(self): + with mock.patch.object(setup, "ROOT", self.dir): + self.assertEqual(setup.installed_configs(), [self.config]) + + def test_the_last_config_of_another_install_is_never_its_shared_settings(self): + # the shared settings are written after the config (the first time Chat settings are saved), so they are + # the newest strata-*.json there + later = self.config.stat().st_mtime + 60 + os.utime(self.shared, (later, later)) + self.assertEqual(setup.previous_config([self.dir], {}), self.config) + + def test_a_folder_with_only_shared_settings_has_no_config(self): + self.config.unlink() + with mock.patch.object(setup, "ROOT", self.dir): + self.assertEqual(setup.installed_configs(), []) + self.assertIsNone(setup.previous_config([self.dir], {})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_engine_keep.py b/tools/test_setup_engine_keep.py new file mode 100644 index 00000000..6667837c --- /dev/null +++ b/tools/test_setup_engine_keep.py @@ -0,0 +1,94 @@ +"""#670: an engine update keeps the engine it replaces in engine/.previous (one generation), the swap is all or +nothing, and `setup.py --rollback-engine` puts the kept one back. + + python -m unittest tools.test_setup_engine_keep +""" +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 + + +def engine(folder: Path, version: str, exe: bytes) -> None: + folder.mkdir(parents=True, exist_ok=True) + (folder / "BUILD.json").write_text(json.dumps({"version": version}), encoding="utf-8") + (folder / "strata.exe").write_bytes(exe) + (folder / "lib").mkdir(exist_ok=True) + (folder / "lib" / "x.dll").write_bytes(exe) + + +class KeepPrevious(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.eng = self.root / "engine" + self.new = self.eng / "_unpack" + + def test_the_replaced_engine_is_kept_and_rolled_back(self): + engine(self.eng, "0.1.39", b"old") + engine(self.new, "0.1.40", b"new") + setup.install_unpacked(self.new, self.eng) + self.assertEqual((self.eng / "strata.exe").read_bytes(), b"new") + self.assertEqual(setup.engine_version_of(self.eng), "0.1.40") + prev = self.eng / ".previous" + self.assertEqual((prev / "strata.exe").read_bytes(), b"old") + self.assertEqual((prev / "lib" / "x.dll").read_bytes(), b"old") + self.assertEqual(setup.engine_version_of(prev), "0.1.39") + with mock.patch.object(setup, "ROOT", self.root): + self.assertEqual(setup.rollback_engine(), 0) + self.assertEqual((self.eng / "strata.exe").read_bytes(), b"old") + self.assertEqual(setup.engine_version_of(self.eng), "0.1.39") + self.assertEqual(setup.engine_version_of(prev), "0.1.40") # forward again + self.assertEqual(setup.rollback_engine(), 0) + self.assertEqual((self.eng / "strata.exe").read_bytes(), b"new") + + def test_one_generation_only(self): + engine(self.eng, "0.1.38", b"a") + for version, exe in (("0.1.39", b"b"), ("0.1.40", b"c")): + engine(self.new, version, exe) + setup.install_unpacked(self.new, self.eng) + for p in self.new.iterdir(): # (get_prebuilt removes what is left of the unpack) + p.unlink() if p.is_file() else None + self.assertEqual(setup.engine_version_of(self.eng / ".previous"), "0.1.39") + + def test_a_first_install_keeps_nothing(self): + self.eng.mkdir() + engine(self.new, "0.1.40", b"new") + setup.install_unpacked(self.new, self.eng) + self.assertEqual((self.eng / "strata.exe").read_bytes(), b"new") + self.assertFalse((self.eng / ".previous").exists()) + with mock.patch.object(setup, "ROOT", self.root): + self.assertEqual(setup.rollback_engine(), 1) + + def test_a_failure_part_way_leaves_the_old_engine_whole(self): + engine(self.eng, "0.1.39", b"old") + engine(self.new, "0.1.40", b"new") + real = Path.replace + calls = [] + + def flaky(self_, target): + calls.append(self_.name) + if len(calls) == 2: + raise PermissionError("held open") + return real(self_, target) + + with mock.patch.object(Path, "replace", flaky), self.assertRaises(OSError): + setup.install_unpacked(self.new, self.eng) + self.assertEqual((self.eng / "strata.exe").read_bytes(), b"old") + self.assertEqual((self.eng / "lib" / "x.dll").read_bytes(), b"old") + self.assertEqual(setup.engine_version_of(self.eng), "0.1.39") + self.assertFalse((self.eng / ".previous").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_hybrid.py b/tools/test_setup_hybrid.py index a5b9a164..3a5882ee 100644 --- a/tools/test_setup_hybrid.py +++ b/tools/test_setup_hybrid.py @@ -6,6 +6,7 @@ half of the E-cores) and writes nothing new anywhere else; a calibration's measu from __future__ import annotations import sys +import tempfile import unittest from pathlib import Path from unittest import mock @@ -17,6 +18,57 @@ import setup # noqa: E402 from test_setup_golden import PROFILES, install # noqa: E402 +def fake_sys(root: Path, caps: list, pmu=None, smt=False) -> None: + """A /sys tree: cpu N's capacity (and, with smt, a sibling CPU per core), and the hybrid PMU lists when given.""" + cpu_dir = root / "devices" / "system" / "cpu" + n = 0 + for core, cap in enumerate(caps): + for _ in range(2 if smt and cap >= 1000 else 1): + d = cpu_dir / f"cpu{n}" + (d / "topology").mkdir(parents=True) + (d / "topology" / "physical_package_id").write_text("0") + (d / "topology" / "core_id").write_text(str(core)) + (d / "cpu_capacity").write_text(str(cap)) + n += 1 + if pmu: + for name, lst in zip(("cpu_core", "cpu_atom"), pmu): + (root / "devices" / name).mkdir(parents=True) + (root / "devices" / name / "cpus").write_text(lst + "\n") + + +class LinuxCores(unittest.TestCase): + """#798: Turbo Boost Max 3.0's "favored" P-cores have a slightly higher cpu_capacity.""" + + def classes(self, caps, **kw): + with tempfile.TemporaryDirectory() as d: + fake_sys(Path(d), caps, **kw) + cl = setup.linux_core_classes(d) + if not cl or max(cl) == min(cl): + return None + p = sum(1 for c in cl if c == max(cl)) + return p, len(cl) - p + + def test_favored_cores_do_not_hide_the_p_cores(self): + caps = [1024, 1012, 1024, 1012, 1012, 1012, 1012, 1012] + [768] * 16 # Core Ultra 7 270K Plus + self.assertEqual(self.classes(caps), (8, 16)) # by capacity: >= 90% of the largest + self.assertEqual(self.classes(caps, pmu=("0-7", "8-23")), (8, 16)) # by the PMU lists + self.assertEqual(setup.hybrid_pool_workers((8, 16)), 15) + + def test_plain_capacities_and_plain_cpus(self): + self.assertEqual(self.classes([1024] * 8 + [512] * 8), (8, 8)) + self.assertIsNone(self.classes([1024] * 8)) # no E-cores + self.assertIsNone(self.classes([1024, 1012, 1012, 1012])) # favored cores only: not hybrid + + def test_smt_siblings_count_once(self): + self.assertEqual(self.classes([1024, 1012] * 4 + [768] * 8, smt=True, pmu=("0-15", "16-23")), (8, 8)) + + def test_no_capacity_files_and_no_pmu_says_nothing(self): + with tempfile.TemporaryDirectory() as d: + fake_sys(Path(d), [1024, 768]) + (Path(d) / "devices/system/cpu/cpu1/cpu_capacity").unlink() + self.assertIsNone(setup.linux_core_classes(d)) + + class HybridWorkers(unittest.TestCase): def test_rule(self): self.assertIsNone(setup.hybrid_pool_workers(None)) diff --git a/tools/test_setup_pins.py b/tools/test_setup_pins.py index c600f692..2d8a08af 100644 --- a/tools/test_setup_pins.py +++ b/tools/test_setup_pins.py @@ -81,6 +81,26 @@ class HuggingFacePins(unittest.TestCase): self.assertEqual([m for m, _ in seen], ["HEAD", "HEAD", "GET"]) self.assertTrue(all("/resolve/main/" in u for _, u in seen[1:])) + def test_a_complete_part_is_finished_without_a_request(self): + """A .part with every byte (setup stopped between the last byte and the rename): renamed, not resumed with a + range past its end - the server answers that with 416, which download() retried 30 times, 10 s apart.""" + seen = [] + + def urlopen(req, timeout=None): + seen.append((req.get_method(), req.headers.get("Range"))) + if req.get_method() == "HEAD": + return Response(b"model bytes") + raise urllib.error.HTTPError(req.full_url, 416, "Range Not Satisfiable", {}, None) + + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ + mock.patch.object(setup.time, "sleep", lambda s: None): + dst = Path(d) / "m.gguf" + dst.with_name("m.gguf.part").write_bytes(b"model bytes") + quiet(setup.download, "https://example.com/m.gguf", dst) + self.assertEqual(dst.read_bytes(), b"model bytes") + self.assertTrue(setup.done(dst)) + self.assertEqual(seen, [("HEAD", None)]) + def test_mtp_fetch_is_pinned_and_falls_back(self): import mtp_fetch self.assertRegex(mtp_fetch.REPO, SHA) @@ -216,6 +236,21 @@ class Engine(unittest.TestCase): self.assertFalse(z.exists()) self.assertFalse(z.with_name(z.name + ".done").exists()) + def test_an_archive_that_does_not_unpack_is_not_kept(self): + """#397, for an archive that does not unpack (not a zip, or a damaged one): it kept its zip and .done mark, + so every later run failed on it, even after the right one was published.""" + with tempfile.TemporaryDirectory() as folder: # a --prebuilt folder, through the real download() + asset = Path(folder) / setup.PREBUILT_ASSET + asset.write_bytes(b"not a zip") + with self.assertRaises(zipfile.BadZipFile): + quiet(setup.get_prebuilt, folder, {"arch": 89}, "gpu") + with zipfile.ZipFile(asset, "w") as z: + z.writestr("BUILD.json", json.dumps({"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]})) + z.writestr(setup.EXE, b"engine") + eng, _ = quiet(setup.get_prebuilt, folder, {"arch": 89}, "gpu") + self.assertEqual(eng, self.root / "engine") + self.assertEqual((self.root / "engine" / setup.EXE).read_bytes(), b"engine") + def test_an_installed_engine_is_kept(self): (self.root / "engine" / "BUILD.json").write_text(json.dumps( {"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]})) diff --git a/tools/test_setup_risk.py b/tools/test_setup_risk.py index 3e569a98..0cce5269 100644 --- a/tools/test_setup_risk.py +++ b/tools/test_setup_risk.py @@ -89,6 +89,13 @@ class Context(unittest.TestCase): self.assertEqual(setup.ram_ctx("IQ3_XXS", 95.8), 524288) # 43 + 7.2 + 24 GB fits 96 self.assertEqual(setup.ram_ctx("IQ3_S", 76.5), 131072) self.assertEqual(setup.ram_ctx("IQ3_S", 78.5), 262144) + # #608: where the 200K estimate fits and the 256K one does not, the rule stays at 128K (200K is a menu step) + self.assertLessEqual(setup.ctx_ram_need("IQ3_S", 204800), 78.5) + self.assertGreater(setup.ctx_ram_need("IQ3_S", 262144), 77.5) + self.assertEqual(setup.ram_ctx("IQ3_S", 77.5), 131072) + for ram in range(16, 200): + for model in ("IQ3_S", "IQ3_XXS", "Q2_0"): + self.assertNotEqual(setup.ram_ctx(model, float(ram)), 204800) self.assertEqual(setup.ram_ctx("Q2_0", 31.9), 524288) # other sizes: no RAM rule self.assertEqual(setup.ram_ctx("IQ3_XXS", 31.9, low_ram=True), 524288) # the KV cache is in VRAM there self.assertIsNone(setup.ctx_ram_need("IQ3_XXS", 262144, low_ram=True)) @@ -106,13 +113,25 @@ class Context(unittest.TestCase): def test_a_picked_256k_is_kept_and_the_menu_says_the_risk(self): code, out, cfg, asked = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start"], - answers={"Context?": "5"}) + answers={"Context?": "6"}) self.assertEqual(code, 0, out) self.assertEqual(arg(cfg, "--max-context"), "262144") self.assertIn("256K tokens (needs ~78 GB RAM, this PC has 64: may run out of memory)", out) self.assertIn("128K tokens (recommended for your GPU)\n", out) self.assertIn("Kept as you chose", out) + def test_a_200k_choice_is_kept(self): + """#406: 200K was added between the 128K rule and 256K - it is inside the trained 262144, so no rope scaling, + and a pick of it is kept with the note 256K gets instead of being capped to 128K.""" + code, out, cfg, _ = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start"], + answers={"Context?": "5"}) + self.assertEqual(code, 0, out) + self.assertEqual(arg(cfg, "--max-context"), "204800") + self.assertNotIn("--rope-scaling", cfg["args"]) + self.assertIn("200K tokens (needs ~77 GB RAM, this PC has 64: may run out of memory)", out) + self.assertIn("200K with IQ3_S needs ~77 GB of RAM by setup's estimate", out) + self.assertIn("Kept as you chose", out) + def test_low_ram_mode_keeps_262k_without_a_ram_note(self): ram, found = PROFILES["32GB-2x24GB"] # #364 code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "IQ3_XXS", "--no-start", diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index 9b9d271d..faf8bc50 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -329,10 +329,9 @@ class Main(Base): self.assertIsNone(cfg) def test_one_gpu_and_no_images(self): - code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--vision", "yes", "--low-ram", "on"], - n_gpus=2) + code, out, cfg = self.main(["--context", "8192", "--vision", "yes", "--low-ram", "on"], n_gpus=2) self.assertEqual(code, 0, out) - self.assertIn("runs on one GPU", out) + self.assertIn("(NVIDIA GeForce RTX 5070, 12 GB) only (--gpus 0,1 uses them together anyway)", out) self.assertIn("images are not available with UD-Q4_K_XL", out) self.assertIn("--low-ram on does not apply", out) self.assertNotIn("layer_split", cfg) @@ -352,14 +351,21 @@ class Main(Base): self.assertIn("OS file cache", out) self.assertNotIn("RAM budget: ", out) - def test_split_refused_without_the_ram(self): + def test_split_without_the_ram_is_a_warning_not_a_wall(self): + # #737: below the worst-case estimate (a 128 GB PC ran it) the split is still the user's call need = setup.unsloth_split_need_gb() self.assertAlmostEqual(need, setup.MODELS[M]["download_gb"] + setup.UNSLOTH_RAM_LEFT_GB) - code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1"], n_gpus=2, ram=127.8) + code, out, cfg = self.main(["--context", "8192"], n_gpus=2, ram=127.8) # no --gpus: stays on one GPU self.assertEqual(code, 0, out) - self.assertIn("runs on one GPU here", out) + self.assertIn("uses them together anyway", out) self.assertNotIn("layer_split", cfg) self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "71") # all of them + code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1"], n_gpus=2, ram=127.8) # asked for by name + self.assertEqual(code, 0, out) + self.assertIn("worst case", out) + self.assertIn("as you chose (--gpus), with 128 GB of RAM", out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertNotIn("--resident-budget-gib", cfg["args"]) def test_an_explicit_budget_keeps_one_gpu(self): code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--resident-budget-gib", "60"], n_gpus=2, @@ -550,14 +556,21 @@ class LayerSplit(unittest.TestCase): self.assertEqual(cfg["args"], ["--pack", "p", "--kv", "int8", "--remote-expert-opt"]) # 0.1.39b: #578 self.assertIn("no RAM budget", out) - def test_start_with_gpus_refused_without_the_ram(self): - code, out, cfg, started = self.start(63.7) + def test_start_with_gpus_without_the_ram_is_asked(self): + # #737: a warning and a question (default no), not a wall; --gpus with --yes is the consent + code, out, cfg, started = self.start(63.7, offered="n") # asked: "n" stops, nothing saved self.assertEqual(code, 1) self.assertFalse(started) self.assertIn("cannot share its RAM budget across GPUs", out) self.assertIn("--gpu N", out) - self.assertEqual(cfg["gpu"], 0) # nothing saved + self.assertEqual(cfg["gpu"], 0) self.assertIn("--resident-budget-gib", cfg["args"]) + code, out, cfg, started = self.start(63.7) # --gpus + --yes: goes on, no budget + self.assertIsNone(code, out) + self.assertTrue(started) + self.assertIn("cannot share its RAM budget across GPUs", out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertNotIn("--resident-budget-gib", cfg["args"]) def test_offered_at_a_start(self): code, out, cfg, _ = self.start(165.0, gpu=None, offered="") # Enter: one GPU (the default here) diff --git a/tools/test_shards.py b/tools/test_shards.py index 6d8ba397..28e94df2 100644 --- a/tools/test_shards.py +++ b/tools/test_shards.py @@ -1,5 +1,6 @@ -"""A missing or short model shard is named with its numbers, and a pack's verify reads back the source hash -its manifest recorded - over a minimal GGUF written here (no download, no model, no GPU). +"""A missing or short model shard is named with its numbers, a pack's verify reads back the source hash its +manifest recorded, and a pack's build refuses an output directory that already holds one - over a minimal GGUF +written here (no download, no model, no GPU). python -m unittest tools.test_shards """ @@ -71,6 +72,23 @@ class ShardCheck(unittest.TestCase): self.assertIn(f"{whole - 40:,} of {whole:,} bytes", msg) self.assertIn("40 missing", msg) + def test_single_tensor_shard_with_extra_bytes_is_refused(self): + # #657: the PLE table's shard is exactly as long as its one tensor; 612 extra bytes are a damaged file + s = self.dir / "m-00002-of-00002.gguf" + whole = write_gguf(s, names=("per_layer_token_embd.weight",)) + S.check_shards([s]) + s.write_bytes(s.read_bytes() + bytes(612)) + with self.assertRaises(Stop) as cm: + S.check_shards([s]) + msg = str(cm.exception) + self.assertIn("m-00002-of-00002.gguf is longer than its tensor", msg) + self.assertIn(f"{whole + 612:,} bytes, {whole:,} expected", msg) + # a shard with several tensors is not held to the rule + t = self.dir / "m-00001-of-00002.gguf" + write_gguf(t) + t.write_bytes(t.read_bytes() + bytes(612)) + S.check_shards([t]) + def test_truncated_header_is_refused(self): s = self.dir / "m-00001-of-00002.gguf" write_gguf(s) @@ -115,5 +133,67 @@ class PackVerifyHash(unittest.TestCase): self.assertEqual(self.run_verify({"shard1_sha256": "0" * 64}, limit=1)[0], 0) # --limit stays quick +class PackBuildOccupied(unittest.TestCase): + """build refuses an --out that already holds a pack before it opens the GGUF or writes a byte; an empty or absent + directory goes on into the build. The GGUF reader is replaced by a sentinel, so "went on" is the sentinel + raised at the first thing build does after the check (a real build needs the model's shards).""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.dir = Path(self.tmp.name) + self.saved = strata_pack.G.GGUFFile + strata_pack.G.GGUFFile = lambda path: (_ for _ in ()).throw(Stop(str(path))) + + def tearDown(self): + strata_pack.G.GGUFFile = self.saved + self.tmp.cleanup() + + def run_build(self, out): + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rc = strata_pack.build(self.dir / "m-00001-of-00002.gguf", out, None, True) + return rc, buf.getvalue() + + def test_occupied_dir_is_refused_naming_it(self): + for marker in ("manifest.json", "index.txt", "native_experts.txt"): # strata_pack.PACK_MARKERS + with self.subTest(marker=marker): + out = self.dir / marker.replace(".", "-") + out.mkdir() + (out / marker).write_text("the pack that was there", encoding="utf-8") + (out / "experts.bin").write_bytes(b"its experts") + rc, text = self.run_build(out) + self.assertEqual(rc, 1) + self.assertIn(str(out), text) + self.assertIn(marker, text) + self.assertEqual(sorted(p.name for p in out.iterdir()), sorted(["experts.bin", marker])) + self.assertEqual((out / marker).read_text(encoding="utf-8"), "the pack that was there") + self.assertEqual((out / "experts.bin").read_bytes(), b"its experts") + + def test_empty_or_absent_dir_proceeds(self): + empty = self.dir / "empty" + empty.mkdir() + for out in (empty, self.dir / "absent" / "pack"): + with self.subTest(out=out.name), self.assertRaises(Stop): + self.run_build(out) + self.assertTrue(out.is_dir()) + + def test_force_builds_into_an_occupied_dir(self): + # #634: setup rebuilds a pack that lost its index.txt or experts.bin with --force + out = self.dir / "forced" + out.mkdir() + (out / "manifest.json").write_text("the pack that was there", encoding="utf-8") + buf = io.StringIO() + with contextlib.redirect_stdout(buf), self.assertRaises(Stop): + strata_pack.build(self.dir / "m-00001-of-00002.gguf", out, None, True, True) + + def test_unfinished_build_is_rebuilt(self): + # experts.bin without manifest.json is a build that stopped before its last file: not a pack, rebuilt as before + out = self.dir / "unfinished" + out.mkdir() + (out / "experts.bin").write_bytes(b"part") + with self.assertRaises(Stop): + self.run_build(out) + + if __name__ == "__main__": unittest.main() diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index 99e51f35..c766f943 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -18,6 +18,10 @@ #include "mtmd-helper.h" #include +#if !defined(_WIN32) +#include +#include +#endif #include #include #include @@ -90,6 +94,20 @@ int main(int argc, char** argv) { mtmd_helper_log_set(quiet_log, nullptr); llama_backend_init(); + const auto load_t0 = std::chrono::steady_clock::now(); +#if !defined(_WIN32) + // ask the OS for the projector file up front (128 KiB steps) so the loader's sequential reads find it cached; + // STRATA_READ_AHEAD=0 turns it off, as in the engine + if (const char* ra = std::getenv("STRATA_READ_AHEAD"); ra == nullptr || std::atoi(ra) != 0) { + const int fd = open(mmproj.c_str(), O_RDONLY); + if (fd >= 0) { + const off_t n = lseek(fd, 0, SEEK_END); + for (off_t at = 0; at < n; at += (off_t) (128 << 10)) + (void) posix_fadvise(fd, at, std::min((off_t) (128 << 10), n - at), POSIX_FADV_WILLNEED); + close(fd); + } + } +#endif llama_model_params mp = llama_model_default_params(); mp.vocab_only = true; llama_model* text = llama_model_load_from_file(model.c_str(), mp); @@ -111,6 +129,8 @@ int main(int argc, char** argv) { std::fflush(stdout); return 1; } + std::fprintf(stderr, "strata-vision: model files loaded in %.1f s\n", + std::chrono::duration(std::chrono::steady_clock::now() - load_t0).count()); // a vocab-only model reports no hparams, so the width comes from the projector: its output is the model's input int n_embd = 0; { @@ -129,6 +149,7 @@ int main(int argc, char** argv) { // (~6 s at 1,024 tokens). if (!gpu) std::fprintf(stderr, "strata-vision: on the CPU, %d threads, no warm-up\n", threads); else { + const auto warm_t0 = std::chrono::steady_clock::now(); const uint32_t side = 2048; std::vector rgb((size_t) side * side * 3, 128); mtmd_bitmap* bm = mtmd_bitmap_init(side, side, rgb.data()); @@ -144,7 +165,8 @@ int main(int argc, char** argv) { warm_tokens = (int) mtmd_input_chunk_get_n_tokens(ch); } } - std::fprintf(stderr, "strata-vision: warmed up at %d image tokens\n", warm_tokens); + std::fprintf(stderr, "strata-vision: warmed up at %d image tokens in %.1f s\n", warm_tokens, + std::chrono::duration(std::chrono::steady_clock::now() - warm_t0).count()); mtmd_input_chunks_free(chunks); if (bm) mtmd_bitmap_free(bm); }