diff --git a/.github/ci/test_ci_plan.py b/.github/ci/test_ci_plan.py index e17621909..ed5ea1eaa 100644 --- a/.github/ci/test_ci_plan.py +++ b/.github/ci/test_ci_plan.py @@ -52,7 +52,7 @@ (["server/tools/export_ds4v_mmproj.py"], PY), (["server/tools/ds4_mix_converter/ds4_mix_converter.cpp"], CPP), (["server/examples/chat.py"], PY), - (["optimizations/pflash/tests/test_pflash.py"], PY), + (["optimizations/kvflash/tests/gate/scripts/kvlib.py"], PY), (["optimizations/megakernel/setup.py"], PY_MK), (["uv.lock"], PY_MK), # Both models run all C++/GPU/serve jobs. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77a6c2704..c79770218 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -226,7 +226,7 @@ jobs: - name: Populate venv with cu128 torch + setuptools # First pass: install the workspace's default deps. luce declares # torch (which uv pulls from the pytorch-cu128 index per - # [tool.uv.sources]) and pflash drags in setuptools. Megakernel is + # [tool.uv.sources], along with its setuptools dependency). Megakernel is # in the optional `megakernel` extra so its build does NOT run yet. run: uv sync --frozen diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 45a323ca0..bc7a370d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -43,10 +43,10 @@ After setup, run these commands from the repository root: ```bash git submodule update --init --recursive -# Python deps (workspace at the repo root; one .venv shared by dflash, pflash, +# Python deps (workspace at the repo root; one .venv shared by luce # and optionally megakernel). `uv` is the canonical installer; the legacy # per-subproject `python -m venv .venv && pip install …` flow still works. -uv sync # dflash + pflash deps +uv sync # luce workspace deps uv sync --extra megakernel # also compile the megakernel CUDA extension bash scripts/check_uv_workspace.sh # lockfile + frozen-sync import smoke diff --git a/Dockerfile b/Dockerfile index f70a41e05..b251c1dd1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -147,7 +147,6 @@ RUN cd /src/server/build \ COPY pyproject.toml uv.lock README.md /src/ COPY server/pyproject.toml server/README.md /src/server/ COPY server/scripts /src/server/scripts -COPY optimizations/pflash /src/optimizations/pflash COPY optimizations/megakernel /src/optimizations/megakernel # ─── Stage 2: runtime ─────────────────────────────────────────────────────── @@ -176,7 +175,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && rm -rf /var/lib/apt/lists/* # uv manages Python 3.12 (required by the workspace) and resolves the -# luce + pflash members declared in pyproject.toml. +# luce member declared in pyproject.toml. # uv (pinned) copied from the official image rather than `curl | sh`, so the # version is fixed and no remote installer script runs at build time. COPY --from=ghcr.io/astral-sh/uv:0.11.2 /uv /uvx /usr/local/bin/ @@ -198,7 +197,6 @@ WORKDIR /opt/lucebox-hub # benchmark. The host-side `lucebox.sh` is the supported way to drive this # image; the Python CLI inside owns all orchestration logic. COPY --from=builder /src/pyproject.toml /src/uv.lock /src/README.md /opt/lucebox-hub/ -COPY --from=builder /src/optimizations/pflash /opt/lucebox-hub/optimizations/pflash COPY --from=builder /src/optimizations/megakernel/pyproject.toml \ /src/optimizations/megakernel/README.md \ /opt/lucebox-hub/optimizations/megakernel/ @@ -266,7 +264,7 @@ RUN printf '%s\n%s\n' \ # cache is gone by the time the layer commits, so we don't double-pay. ENV UV_LINK_MODE=hardlink \ UV_NO_CACHE=1 -# --no-editable: install workspace members (pflash, lucebox-hub, and the +# --no-editable: install workspace members (lucebox-hub and the # luce server binding) as proper wheels rather than # source-linked editable installs. Without this, hatch-vcs's build hook # re-fires at runtime when `uv run` re-checks env consistency and tries diff --git a/Dockerfile.rocm b/Dockerfile.rocm index 75b7885bf..a97975b99 100644 --- a/Dockerfile.rocm +++ b/Dockerfile.rocm @@ -135,7 +135,6 @@ RUN cd /src/server/build \ COPY pyproject.toml uv.lock README.md /src/ COPY server/pyproject.toml server/README.md /src/server/ COPY server/scripts /src/server/scripts -COPY optimizations/pflash /src/optimizations/pflash COPY optimizations/megakernel /src/optimizations/megakernel # ─── Stage 2: runtime ─────────────────────────────────────────────────────── @@ -171,7 +170,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ rocblas \ && rm -rf /var/lib/apt/lists/* -# uv (pinned) manages Python 3.12 + resolves the luce + pflash +# uv (pinned) manages Python 3.12 + resolves the luce # workspace. Copied from the official image rather than `curl | sh`, so the # version is fixed and no remote installer script runs at build time. COPY --from=ghcr.io/astral-sh/uv:0.11.2 /uv /uvx /usr/local/bin/ @@ -185,7 +184,6 @@ ENV UV_PYTHON_INSTALL_DIR=/opt/uv/python \ WORKDIR /opt/lucebox-hub COPY --from=builder /src/pyproject.toml /src/uv.lock /src/README.md /opt/lucebox-hub/ -COPY --from=builder /src/optimizations/pflash /opt/lucebox-hub/optimizations/pflash COPY --from=builder /src/optimizations/megakernel/pyproject.toml \ /src/optimizations/megakernel/README.md \ /opt/lucebox-hub/optimizations/megakernel/ diff --git a/optimizations/README.md b/optimizations/README.md new file mode 100644 index 000000000..3334b71f5 --- /dev/null +++ b/optimizations/README.md @@ -0,0 +1,14 @@ +# Optimizations + +This directory holds write-ups, benchmark results, and standalone experiments for Lucebox's engine optimizations. + +**Production implementations live in [`../server/src/`](../server/src/)** (C++/CUDA/HIP inside `luce_server`) — not here. + +| Directory | Status | What's here | +|---|---|---| +| [`pflash/`](pflash/README.md) | Docs | Algorithm overview, results, and `luce_server --pflash` flags. Runtime lives in [`server/src/pflash/`](../server/src/pflash/) and [`server/src/server/pflash_unified.cpp`](../server/src/server/pflash_unified.cpp). | +| [`spark/`](spark/README.md) | Docs | Hot/cold MoE expert residency write-up, results, and `luce_server --spark` flags. Runtime lives in [`server/src/common/`](../server/src/common/), [`server/src/server/`](../server/src/server/), [`server/src/laguna/`](../server/src/laguna/), and [`server/src/qwen35moe/`](../server/src/qwen35moe/). | +| [`paged_attention/`](paged_attention/README.md) | Docs | Fixed-block K/V paging design and experiments for `luce_server --paged-attention`. | +| [`kvflash/`](kvflash/README.md) | Docs + live gate scripts | Bounded KV residency design, results, and manual `luce_server --kvflash` gate scripts. Runtime lives in `server/src/`. | +| [`image_gen/`](image_gen/README.md) | Docs + fetch/bench scripts | MOSS-Image docs, model fetcher (`fetch_models.sh`), and bench harness for `luce_server`. Runtime lives in [`server/src/moss_image/`](../server/src/moss_image/). | +| [`megakernel/`](megakernel/README.md) | Standalone CUDA extension | Fused single-kernel Qwen 3.5-0.8B PyTorch CUDA extension (built separately via `uv sync --extra megakernel`; not linked into `luce_server`). | diff --git a/optimizations/pflash/README.md b/optimizations/pflash/README.md index eda16a2f7..f8376731c 100644 --- a/optimizations/pflash/README.md +++ b/optimizations/pflash/README.md @@ -56,34 +56,20 @@ Decode after prefill: ~74 tok/s (dflash spec decode + DDTree). The pipeline is t ## Quick start -PFlash is the algorithm. The implementation lives in [`../../server/`](../../server/) as part of the luce daemon. The `optimizations/pflash/` directory in this repo only contains the Python tooling for **benchmarking** (NIAH case generation, bench harness around the daemon stdin protocol). Production deploys hit the luce daemon directly. +PFlash is the algorithm. The implementation lives in [`../../server/`](../../server/) as part of `luce_server`; production deploys run `luce_server` directly with no Python in the inference path. ```bash -# 1. from the repo root, install Python deps and build the server -uv sync +# 1. from the repo root, build luce_server git submodule update --init --recursive cmake -B server/build -S server -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_CUDA_ARCHITECTURES=86 -cmake --build server/build --target test_dflash -j +cmake --build server/build --target luce_server -j -# 2. fetch weights (target + spec-decode draft + drafter scorer) +# 2. fetch weights (target + spec-decode draft + drafter scorer + PFlash assets) uv run hf download unsloth/Qwen3.6-27B-GGUF Qwen3.6-27B-Q4_K_M.gguf --local-dir server/models/ -uv run hf download Qwen/Qwen3.5-0.8B model.safetensors tokenizer.json --local-dir server/models/drafter/ -uv run hf download z-lab/Qwen3.6-27B-DFlash model.safetensors --local-dir server/models/draft/ - -# 2b. convert the drafter (Qwen3.5-0.8B HF) to a BF16 GGUF for the C++ scorer. -# The submodule already vendors llama.cpp at deps/llama.cpp. -uv run python server/deps/llama.cpp/convert_hf_to_gguf.py server/models/drafter \ - --outtype bf16 --outfile server/models/Qwen3.5-0.8B-BF16.gguf - -# 3. generate NIAH cases + run head-to-head bench against the C++ daemon -uv run --directory optimizations/pflash python tests/niah_gen.py --n 1 --ctx 131072 --out /tmp/niah_128k.jsonl -uv run --directory optimizations/pflash python tests/bench_niah_cpp.py \ - --bin ../../server/build/test_dflash \ - --target ../../server/models/Qwen3.6-27B-Q4_K_M.gguf \ - --draft-spec ../../server/models/draft/model.safetensors \ - --drafter-gguf ../../server/models/Qwen3.5-0.8B-BF16.gguf \ - --cases /tmp/niah_128k.jsonl --keep-ratio 0.05 --n-gen 256 +uv run hf download unsloth/Qwen3.5-0.8B-GGUF Qwen3.5-0.8B-BF16.gguf --local-dir server/models/ +uv run hf download z-lab/Qwen3.6-27B-DFlash model.safetensors config.json --local-dir server/models/draft/ +uv run hf download Lucebox/pflash --local-dir server/models/pflash/ ``` ## OpenAI server flags @@ -92,50 +78,46 @@ For an OpenAI-compatible server with transparent compression on long prompts, ru | Flag | Choices / type | Default | Effect | |---|---|:---:|---| -| `--pflash` | `auto` / `on` / `off` | `auto` | Page long messages of at least `--prefill-threshold` droppable tokens. `auto` is on when `--prefill-drafter` and all four PFlash files (below) are given; `on` refuses to start without them. | -| `--prefill-threshold` | int (tokens) | `8192` | Droppable tokens a message needs to be paged; `0` pages every message. | +| `--pflash` | `auto` / `on` / `off` | `auto` | Page eligible regions once their combined droppable tokens reach `--prefill-threshold`. `auto` is on when `--prefill-drafter` and all four PFlash files (below) are given; `on` refuses to start without them. | +| `--prefill-threshold` | int (tokens) | `8192` | Aggregate droppable-token threshold across eligible regions (each region with at least `min(threshold, 2048)` droppable tokens); `0` pages every eligible region. | | `--prefill-keep-ratio` | float `(0, 1]` | release curve | Fraction of source tokens to keep. Without a ratio flag the release curve `8192:0.450 16384:0.350 32768:0.270 65536:0.260 120000:0.240` with the adaptive keep ratio applies. | -| `--prefill-drafter` | path to `.gguf` | required for PFlash | Drafter weights (Qwen3.5-0.8B BF16 GGUF). | +| `--prefill-drafter` | path to `.gguf` | required for PFlash | Drafter weights (published `Qwen3.5-0.8B-BF16.gguf`, checked against the PFlash asset SHA-256 contract). | -PFlash needs four files, all from [`Lucebox/pflash`](https://huggingface.co/Lucebox/pflash): the scoring head (`PFLASH_SCORING_HEAD_GGUF`), the segment and request probes (`PFLASH_SEGMENT_PROBE_GGUF`, `PFLASH_REQUEST_PROBE_GGUF`) and the segment reranker (`PFLASH_SEG_RERANKER_GGUF`); an unset probe or reranker path is looked up beside the head. Every unset PFlash setting takes the measured release profile; see [PFlash configuration](../../server/docs/PFLASH_CONFIGURATION.md#quick-launch). +PFlash needs four files, all from [`Lucebox/pflash`](https://huggingface.co/Lucebox/pflash): the scoring head (`PFLASH_SCORING_HEAD_GGUF`, `seg-scoring-head.gguf`), the segment and request probes (`PFLASH_SEGMENT_PROBE_GGUF`, `PFLASH_REQUEST_PROBE_GGUF`) and the segment reranker (`PFLASH_SEG_RERANKER_GGUF`); an unset probe or reranker path is looked up beside the head. Every unset PFlash setting takes the measured release profile; see [PFlash configuration](../../server/docs/PFLASH_CONFIGURATION.md#quick-launch). ```bash -PFLASH_SCORING_HEAD_GGUF=server/models/pflash/head.gguf \ -PFLASH_SEGMENT_PROBE_GGUF=server/models/pflash/segment-probe.gguf \ -PFLASH_REQUEST_PROBE_GGUF=server/models/pflash/request-probe.gguf \ -PFLASH_SEG_RERANKER_GGUF=server/models/pflash/seg-reranker.gguf \ +PFLASH_SCORING_HEAD_GGUF=server/models/pflash/seg-scoring-head.gguf \ ./server/build/luce_server server/models/Qwen3.6-27B-Q4_K_M.gguf \ - --draft server/models/draft/model.safetensors \ - --prefill-drafter server/models/Qwen3.5-0.8B-BF16.gguf + --draft server/models/draft/model.safetensors \ + --prefill-drafter server/models/Qwen3.5-0.8B-BF16.gguf \ + --pflash on ``` -PFlash is on because the drafter and the four files are given. A user message or tool output with fewer droppable tokens than the threshold is served as is; a longer one is paged, and the system prompt and tool definitions are always served whole. See the [server README](../../server/README.md#pflash) for how the view pages, recalls and continues a conversation. +`--pflash on` fails fast at startup if any of the four assets or drafter contracts is missing (with `--pflash auto`, the default, PFlash turns on automatically once they are present). Eligible regions with at least `min(--prefill-threshold, 2048)` droppable tokens are admitted individually once they reach `--prefill-threshold`, or in aggregate once the combined droppable tokens cross `--prefill-threshold` (for current-turn tool outputs, only the current turn's eligible tool outputs count toward that aggregate, so cold history does not force compression on a small active tool output). Shorter prompts are served as is, and the system prompt and tool definitions are always served whole. See the [server README](../../server/README.md#pflash) for how the view pages, recalls and continues a conversation. Validated end-to-end at 64K and 128K source on RTX 3090 (Qwen3.6-27B Q4_K_M target + Qwen3.5-DFlash draft + Qwen3-0.6B BF16 drafter). -## Daemon stdin protocol +## `test_dflash --daemon` stdin protocol -The dflash daemon runs persistently and accepts these commands on stdin (newline-delimited): +For low-level benchmarking, build the test daemon with `cmake --build server/build --target test_dflash -j` and launch `test_dflash --daemon --stream-fd=` (`luce_server` does not read stdin commands). It runs persistently, accepts newline-delimited commands on stdin, and writes int32 token-id streams (terminated by `-1`) to `--stream-fd`: | Command | Effect | |---|---| -| `compress ` | Drafter scores the prompt and emits the compressed token-id stream (terminated by `-1`). | -| `generate ` | Target spec-decode on the (already compressed) prompt. Streams committed token ids on stdout. | +| `compress ` | Drafter scores the prompt and emits the compressed token-id stream to `--stream-fd` (terminated by `-1`). | +| ` ` | Target spec-decode on the (already compressed) prompt. Streams committed token ids to `--stream-fd` (terminated by `-1`). | | `park draft` / `park target` / `park` | Free draft / target / both weights from VRAM. | | `unpark draft` / `unpark target` / `unpark` | Restore weights from disk to VRAM. | | `free drafter` | Release the spec-prefill drafter context (drafter weights + KV). | Typical flow at 128K on a 24 GB card: `park target` → `compress` → `free drafter` → `unpark target` → `unpark draft` → `generate` → `park draft`. -`pflash.dflash_client.DflashClient` is the Python wrapper around this protocol used by `tests/bench_niah_cpp.py`. - ## Runtime tunables -PFlash's required assets and operational settings are listed in [PFlash configuration](../../server/docs/PFLASH_CONFIGURATION.md). On the daemon process: +PFlash's required assets and operational settings are listed in [PFlash configuration](../../server/docs/PFLASH_CONFIGURATION.md). For direct `luce_server` launches, attention windowing is controlled by `--fa-window ` (default `0`, full attention on the compressed prompt). On `test_dflash` (and the container entrypoint, which translates `LUCE_FA_WINDOW` to `--fa-window`): | Env var | Default | Purpose | |---|:---:|---| -| `LUCE_FA_WINDOW` | `0` (set by the bench client) | Sliding window of the target's full-attention layers; `0` keeps full attention on the compressed prompt. Unset, `test_dflash` uses 2048. | +| `LUCE_FA_WINDOW` | `2048` (`test_dflash`) | Sliding window of the target's full-attention layers; set `0` for full attention on the compressed prompt. Ignored by direct `luce_server` launches (use `--fa-window`). | | `LUCE_KV_K` / `LUCE_KV_V` | (auto) | KV-cache quant types. `q4_0` / `q4_0` is the bench setting. `tq3_0` saves another ~4 GB at 128K. | The `LUCE_FP_*` FlashPrefill switches do not affect PFlash: the scorer does not run the FlashPrefill kernels. @@ -205,7 +187,7 @@ What we built: - **Single 24 GB GPU** target (RTX 3090 reference). On 32+ GB cards, drafter + target can coexist and the park/unpark dance disappears. - **Qwen3.6-27B Q4_K_M target + Qwen3.5-0.8B drafter** is the validated pair. Other targets/drafters need keep-ratio re-calibration. -- **Any target model.** The drafter scores the prompt on its own, so what it keeps does not depend on the model that serves it. A backend only says how it frees memory for the drafter and gets it back (`server/src/pflash/pflash_window.h`); loading, scoring and releasing the drafter are shared. Today: Qwen3.5/3.6 (`qwen35`, also layer-split), Qwen3 (`qwen3`), Qwen3.8-Flash (`qwen4exp`) and DeepSeek V4/V4.1 (`deepseek4`, `deepseek41`). Qwen3.8-Flash sizes its context to its GPUs, so with PFlash on it keeps the drafter's room free (its weights plus 56 KiB per context token) on whichever of its GPUs (target or expert device) the drafter shares, and never parks. +- **Supported target backends.** The in-process drafter scores the prompt on its own, and the server enables PFlash on backends that expose per-candidate scores (`pflash_gives_candidate_scores()`, plus a `server/src/pflash/pflash_window.h` memory window): Qwen3.5/3.6 (`qwen35`, also layer-split), Qwen3 (`qwen3`), Qwen3.8-Flash (`qwen4exp`), DeepSeek V4/V4.1 (`deepseek4`, `deepseek41`), and Inkling 2 (`inkling2`). Other backends (such as `laguna`) do not expose candidate scores and reject `--pflash on`. Qwen3.8-Flash sizes its context to its GPUs, so with PFlash on it keeps the drafter's room free (its weights plus 56 KiB per context token) on whichever of its GPUs (target or expert device) the drafter shares, and never parks. - **Concurrent serving** (`--max-concurrency > 1`) with PFlash is dense Qwen3.5 only: its scheduler scores prompts on a thread of its own while the other slots decode. Other models compress one request at a time, and the engine refuses PFlash with more than one slot (`--pflash auto` turns PFlash off instead). - **NIAH single-needle** is the only retrieval task validated end-to-end. Multi-doc QA, long-form code retrieval, etc. still TBD. @@ -238,8 +220,7 @@ defaults. ### Drafter selection: BF16 Qwen3.5-0.8B for compress PFlash compress benefits from a small, fast drafter. The validated -choice is **Qwen3.5-0.8B** in **BF16 safetensors** with ~5 attention -layers. The DFlash drafter for the same target works correctly +choice is **Qwen3.5-0.8B** in **BF16 GGUF** (`Qwen3.5-0.8B-BF16.gguf`). The DFlash drafter for the same target works correctly during decode-after-unpark but is heavier than ideal for compress. Practical guidance: @@ -285,7 +266,7 @@ caching artefacts. @software{luce_pflash_2026, title = {Luce PFlash: speculative prefill compression for long-context spec decode on consumer GPUs}, author = {Lucebox}, - url = {https://github.com/Luce-Org/lucebox-hub/tree/main/pflash}, + url = {https://github.com/Luce-Org/lucebox/tree/main/optimizations/pflash}, year = {2026} } diff --git a/optimizations/pflash/pflash/__init__.py b/optimizations/pflash/pflash/__init__.py deleted file mode 100644 index da9e8ae0c..000000000 --- a/optimizations/pflash/pflash/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -"""pflash, speculative-prefill harness around the luce C++/CUDA daemon. - -The daemon does the work — drafter forward, FlashPrefill scoring (BSA), and -spec-decode generation are all in-process C++/CUDA. This Python package is -just a thin client over the daemon's stdin/stdout protocol so reproduction -benches and external tooling can drive it. -""" -from .dflash_client import DflashClient -from . import config - -__version__ = "0.3.0" -__all__ = ["DflashClient", "config"] diff --git a/optimizations/pflash/pflash/config.py b/optimizations/pflash/pflash/config.py deleted file mode 100644 index 21d3c563c..000000000 --- a/optimizations/pflash/pflash/config.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Default env flags for the luce daemon when spawned by pflash.""" - -# The only daemon-side env flags pflash assumes. -LUCE_REQUIRED_ENV = { - "LUCE_FA_WINDOW": "0", # full attn on the (already compressed) prompt - "LUCE_KV_TQ3": "1", # 3-bit KV cache; saves ~4 GB at 128K -} diff --git a/optimizations/pflash/pflash/dflash_client.py b/optimizations/pflash/pflash/dflash_client.py deleted file mode 100644 index 5a858815d..000000000 --- a/optimizations/pflash/pflash/dflash_client.py +++ /dev/null @@ -1,340 +0,0 @@ -"""Subprocess client for the patched dflash daemon (with park/unpark commands).""" -from __future__ import annotations -import ctypes -import logging -import os -import struct -import subprocess -import sys -import tempfile -import threading -import time -from typing import Optional - -from . import config - -log = logging.getLogger(__name__) - -_READY_MARKERS = ( - "[daemon] ready", - "[qwen3-daemon] ready", - "[laguna-daemon] ready", - "[gemma4-daemon] ready", -) - - -def _query_nvidia_vram_mib() -> Optional[int]: - try: - out = subprocess.check_output( - ["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"], - stderr=subprocess.DEVNULL, timeout=5) - return int(out.decode().splitlines()[0]) - except (FileNotFoundError, subprocess.CalledProcessError, subprocess.TimeoutExpired, ValueError): - return None - - -def _hip_free_mib() -> int: - """Free GPU memory in MiB via hipMemGetInfo. - - Reliable on AMD unified-memory APUs (Strix Halo, Phoenix) where rocm-smi - only reports the small dedicated VRAM segment (~512 MB on gfx1151) rather - than the full shared-memory pool used by the GPU. Returns 0 on any error - so callers can treat 0 as "not available". - """ - try: - hip = ctypes.CDLL("libamdhip64.so") - free = ctypes.c_size_t(0) - total = ctypes.c_size_t(0) - hip.hipMemGetInfo(ctypes.byref(free), ctypes.byref(total)) - return int(free.value // (1024 * 1024)) - except Exception: - return 0 - - -class DflashClient: - def __init__(self, bin_path: str, target_path: str, draft_path: str, - max_ctx: int = 16384, ddtree_budget: int = 16, - *, - ddtree_temp: Optional[float] = None, - chain_seed: bool = True, - fa_window: Optional[int] = None, - kv_tq3: Optional[bool] = None, - boot_timeout_s: float = 60.0, - boot_vram_mib: int = 18000): - """Spawn the patched dflash daemon as a subprocess. - - Defaults for fa_window / kv_tq3 come from ``config.LUCE_REQUIRED_ENV`` - and are the only flags pflash relies on. Override per-call only when - you know what you're doing. - """ - self.bin_path = bin_path - self.target_path = target_path - self.draft_path = draft_path - self.max_ctx = max_ctx - self._ready_event = threading.Event() - self._stdout_tail: list[str] = [] - env_overrides = { - "LUCE_FA_WINDOW": str(0 if fa_window is None else fa_window), - "LUCE_KV_TQ3": "1" if (kv_tq3 if kv_tq3 is not None else True) else "0", - } - env = {**os.environ, **config.LUCE_REQUIRED_ENV, **env_overrides} - bin_dir = os.path.dirname(os.path.abspath(bin_path)) - if sys.platform == "win32": - # Windows uses PATH for DLL search rather than LD_LIBRARY_PATH. - path_extra = [os.path.join(bin_dir, "bin"), bin_dir] - env["PATH"] = os.pathsep.join( - path_extra + ([env["PATH"]] if env.get("PATH") else [])) - else: - ld_extra = [bin_dir, os.path.join(bin_dir, "bin")] - env["LD_LIBRARY_PATH"] = ":".join( - ld_extra + ([env["LD_LIBRARY_PATH"]] if env.get("LD_LIBRARY_PATH") else [])) - self.r_pipe: int = -1 - self.w_pipe: int = -1 - self.proc = None - self._stdout_thread = None - try: - self.r_pipe, self.w_pipe = os.pipe() - # subprocess.Popen pass_fds is POSIX-only. On Windows, mark the pipe - # write-end inheritable, convert it to a Win32 HANDLE, and pass that - # handle value as --stream-fd; the child inherits via close_fds=False. - if sys.platform == "win32": - import msvcrt - os.set_inheritable(self.w_pipe, True) - stream_fd_val = int(msvcrt.get_osfhandle(self.w_pipe)) - else: - stream_fd_val = self.w_pipe - cmd = [bin_path, target_path, draft_path, - "--daemon", "--fast-rollback", "--ddtree", - f"--ddtree-budget={ddtree_budget}", - f"--max-ctx={max_ctx}", - f"--stream-fd={stream_fd_val}"] - if ddtree_temp is not None: - cmd.append(f"--ddtree-temp={ddtree_temp}") - if not chain_seed: - cmd.append("--ddtree-no-chain-seed") - log.info("spawning dflash daemon: %s", " ".join(cmd)) - # Capture free-memory baseline before spawning so _wait_until_loaded can - # measure the delta on AMD unified-memory APUs (hipMemGetInfo approach). - self._initial_hip_free_mib: int = _hip_free_mib() - if sys.platform == "win32": - self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - close_fds=False, env=env) - else: - self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - pass_fds=(self.w_pipe,), env=env) - self._start_stdout_reader() - os.close(self.w_pipe) - self.w_pipe = -1 - self._wait_until_loaded(timeout=boot_timeout_s, vram_mib=boot_vram_mib) - # Park draft by default; user calls unpark when needed - self._send("park draft\n") - except Exception: - self.close() - raise - - def _start_stdout_reader(self): - def _reader(): - if self.proc is None or self.proc.stdout is None: - return - stdout = self.proc.stdout - mirror_stdout = True - try: - while True: - try: - raw = stdout.readline() - except (ValueError, OSError): - break - if not raw: - break - try: - line = raw.decode(errors="replace") - except AttributeError: - line = str(raw) - self._stdout_tail.append(line.rstrip()) - del self._stdout_tail[:-20] - if any(marker in line for marker in _READY_MARKERS): - self._ready_event.set() - if mirror_stdout: - try: - sys.stdout.write(line) - sys.stdout.flush() - except (BrokenPipeError, OSError, ValueError): - mirror_stdout = False - finally: - try: - stdout.close() - except Exception: - pass - - self._stdout_thread = threading.Thread( - target=_reader, name="dflash-daemon-stdout", daemon=True) - self._stdout_thread.start() - - def _read_vram_used_mib(self) -> Optional[int]: - """GPU memory allocated since daemon spawn, in MiB. - - Priority order: - 1. hipMemGetInfo delta — works on AMD unified-memory APUs (Strix Halo, - Phoenix) where rocm-smi only reports the tiny dedicated segment. - 2. rocm-smi — fallback for AMD discrete GPUs (reports total used VRAM). - 3. nvidia-smi — NVIDIA GPUs. - Returns None when no backend is available. - """ - # AMD UMA: hipMemGetInfo free-delta is the only reliable signal. - if self._initial_hip_free_mib > 0: - current = _hip_free_mib() - if current > 0: - delta = self._initial_hip_free_mib - current - if delta > 0: - return delta - # AMD discrete: rocm-smi total used (not delta). - try: - out = subprocess.check_output( - ["rocm-smi", "--showmeminfo", "vram", "--noheader"], - stderr=subprocess.DEVNULL, timeout=5) - for line in out.decode().splitlines(): - if "Used Memory" in line: - return int(line.split()[-1]) // (1024 * 1024) - except (FileNotFoundError, subprocess.CalledProcessError, - subprocess.TimeoutExpired, ValueError, StopIteration): - pass - # NVIDIA. - return _query_nvidia_vram_mib() - - def _wait_until_loaded(self, timeout: float = 60.0, vram_mib: int = 18000): - """Block until the daemon emits its explicit ready banner. - - The memory telemetry helpers are kept for diagnostics, but readiness is - driven by the daemon state rather than by GPU memory usage. This avoids - false timeouts when the first GPU does not host the target model. - """ - boot = time.time() - while time.time() - boot < timeout: - if self._ready_event.wait(timeout=0.1): - return - if self.proc.poll() is not None: - tail = "\n".join(self._stdout_tail[-10:]) - detail = f"\nLast daemon stdout:\n{tail}" if tail else "" - raise RuntimeError( - "dflash daemon exited before it emitted a ready banner. " - "Check the daemon's stderr." + detail) - time.sleep(0.9) - tail = "\n".join(self._stdout_tail[-10:]) - stdout_detail = f"\nLast daemon stdout:\n{tail}" if tail else "" - last_used = self._read_vram_used_mib() - memory_detail = ( - f" Last observed GPU memory signal: {last_used} MiB " - f"(legacy threshold was {vram_mib} MiB)." - if last_used is not None else "") - raise RuntimeError( - f"dflash daemon did not emit a ready banner within {timeout:.0f}s." - f"{memory_detail} Check the daemon's stderr." + stdout_detail) - - def _send(self, cmd: str): - self.proc.stdin.write(cmd.encode()) - self.proc.stdin.flush() - # Read until -1 sentinel - while True: - b = os.read(self.r_pipe, 4) - if not b or len(b) < 4: - break - if struct.unpack(" list[int]: - """C++ drafter score+compress via daemon. Returns compressed token ids. - - Daemon command: compress - """ - fd, path = tempfile.mkstemp(suffix=".bin") - with os.fdopen(fd, "wb") as f: - for t in prompt_ids: - f.write(struct.pack(" list[int]: - """Send prompt + n_gen request, return generated token ids.""" - fd, path = tempfile.mkstemp(suffix=".bin") - with os.fdopen(fd, "wb") as f: - for t in prompt_ids: - f.write(struct.pack("= 0: - try: - os.close(self.w_pipe) - except OSError: - pass - self.w_pipe = -1 - if self.r_pipe >= 0: - try: - os.close(self.r_pipe) - except OSError: - pass - self.r_pipe = -1 - if self.proc is not None: - try: - if self.proc.stdin: - self.proc.stdin.close() - except Exception: - pass - try: - try: - self.proc.wait(timeout=timeout) - except subprocess.TimeoutExpired: - self.proc.kill() - try: - self.proc.wait(timeout=timeout) - except Exception: - pass - finally: - if self._stdout_thread is not None and self._stdout_thread.is_alive(): - self._stdout_thread.join(timeout=timeout) - elif self._stdout_thread is None and self.proc.stdout: - try: - self.proc.stdout.close() - except Exception: - pass - - def __enter__(self) -> DflashClient: - return self - - def __exit__(self, exc_type, exc_val, exc_tb) -> None: - self.close() diff --git a/optimizations/pflash/pyproject.toml b/optimizations/pflash/pyproject.toml deleted file mode 100644 index bf7a263ce..000000000 --- a/optimizations/pflash/pyproject.toml +++ /dev/null @@ -1,34 +0,0 @@ -[project] -name = "pflash" -version = "0.3.0" -description = "Python client + bench harness for the lucebox dflash speculative-prefill daemon" -readme = "README.md" -requires-python = ">=3.10" -authors = [{name = "lucebox"}] -license = {text = "MIT"} -keywords = ["llm", "speculative-decoding", "prefill", "long-context", "qwen"] -classifiers = [ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: MIT License", - "Operating System :: POSIX :: Linux", - "Topic :: Scientific/Engineering :: Artificial Intelligence", -] -# Drafter scoring + spec decode happen inside the C++/CUDA daemon. The Python -# side only needs the HF tokenizers (one for the drafter vocab, one for the -# target vocab + chat template) to drive the bench harness. -dependencies = [ - "transformers>=4.50", -] - -[project.urls] -Homepage = "https://github.com/Luce-Org/lucebox-hub" -Source = "https://github.com/Luce-Org/lucebox-hub/tree/main/pflash" -Blog = "https://lucebox.com/blog/pflash" - -[build-system] -requires = ["setuptools>=68"] -build-backend = "setuptools.build_meta" - -[tool.setuptools.packages.find] -where = ["."] -include = ["pflash*"] diff --git a/optimizations/pflash/tests/bench_niah_cpp.py b/optimizations/pflash/tests/bench_niah_cpp.py deleted file mode 100644 index bd44c9892..000000000 --- a/optimizations/pflash/tests/bench_niah_cpp.py +++ /dev/null @@ -1,123 +0,0 @@ -"""C++-only NIAH bench: daemon compress + generate, no Python drafter.""" -import argparse, json, sys, time -from pathlib import Path -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from transformers import AutoTokenizer -from pflash.dflash_client import DflashClient - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("--cases", required=True) - ap.add_argument("--n", type=int, default=1) - ap.add_argument("--bin", default="/home/lucebox/lucebox-hub/server/build/test_dflash") - ap.add_argument("--target", default="/opt/lucebox/models/Qwen3.6-27B-Q4_K_M.gguf") - ap.add_argument("--draft-spec", default="/home/lucebox/lucebox-hub/server/models/draft/model.safetensors", - help="draft model used for spec decoding (NOT drafter scorer)") - ap.add_argument("--drafter-gguf", default="/home/lucebox/lucebox-hub/server/models/Qwen3.5-0.8B-BF16.gguf", - help="C++ drafter scorer GGUF (Qwen3.5-0.8B BF16)") - ap.add_argument("--drafter-arch", default="qwen35-0.8b", choices=["qwen35-0.8b"], - help="C++ drafter architecture selector") - ap.add_argument("--target-tokenizer", default="Qwen/Qwen3.6-27B") - ap.add_argument("--drafter-tokenizer", default="Qwen/Qwen3.5-0.8B") - ap.add_argument("--max-ctx", type=int, default=16384, - help="daemon KV cache max ctx; sized for compressed prompt+gen, NOT source") - ap.add_argument("--keep-ratio", type=float, default=0.020) - ap.add_argument("--n-gen", type=int, default=64) - ap.add_argument("--ddtree-budget", type=int, default=16) - ap.add_argument("--ddtree-temp", type=float, default=None, - help="Drafter softmax temperature; lower = sharper") - ap.add_argument("--no-chain-seed", action="store_true") - ap.add_argument("--fa-window", type=int, default=0) - ap.add_argument("--kv-tq3", type=int, choices=[0, 1], default=1, - help="3-bit KV cache; saves VRAM") - ap.add_argument("--auto-max-ctx", action="store_true", - help="Auto-size --max-ctx based on src tokens") - ap.add_argument("--no-thinking", action="store_true", - help="Pass enable_thinking=False to the target chat " - "template. Required for Qwen3.6: thinking mode " - "consumes n_gen budget on a chain-of-thought " - "rollout instead of answering, breaking NIAH " - "validation.") - args = ap.parse_args() - - target_tok = AutoTokenizer.from_pretrained(args.target_tokenizer) - drafter_tok = AutoTokenizer.from_pretrained(args.drafter_tokenizer) - with open(args.cases) as f: - cases = [json.loads(l) for l in f][:args.n] - - max_ctx = args.max_ctx - if args.auto_max_ctx: - if not cases: - raise ValueError("--auto-max-ctx requires at least one case in --cases") - first = cases[0] - src_tokens_est = len(drafter_tok(first["prompt"], return_tensors="pt")["input_ids"][0]) - expected_compressed = int(src_tokens_est * args.keep_ratio * 1.15) + 64 - needed = expected_compressed + args.n_gen + 512 - max_ctx = max(max_ctx, needed) - max_ctx = ((max_ctx + 1023) // 1024) * 1024 - print(f"[init] auto-max-ctx: src~{src_tokens_est}, compressed~{expected_compressed}, max_ctx={max_ctx}", flush=True) - - print(f"[init] spawning daemon: {args.bin}", flush=True) - dflash = DflashClient( - args.bin, args.target, args.draft_spec, - max_ctx=max_ctx, - ddtree_budget=args.ddtree_budget, - ddtree_temp=args.ddtree_temp, - chain_seed=not args.no_chain_seed, - fa_window=args.fa_window, - kv_tq3=bool(args.kv_tq3), - ) - - correct = 0 - for i, case in enumerate(cases): - prompt = case["prompt"] - # Drafter tokenizes prompt, daemon scores+compresses, returns drafter ids. - ids = drafter_tok(prompt, return_tensors="pt")["input_ids"][0].tolist() - S = len(ids) - print(f"[case {i}] src={S} keep={args.keep_ratio}", flush=True) - - t0 = time.time() - compressed_ids = dflash.compress(ids, args.keep_ratio, args.drafter_gguf, args.drafter_arch) - t_score = time.time() - t0 - comp = len(compressed_ids) - print(f"[case {i}] compressed={comp} ratio={S/max(comp,1):.1f}x score_s={t_score:.1f}", flush=True) - - # Decode compressed ids with DRAFTER tokenizer, re-encode with TARGET + chat template. - comp_text = drafter_tok.decode(compressed_ids, skip_special_tokens=True) - user_msg = comp_text + "\n\nAnswer the user question based on the above context." - chat_kwargs = {"tokenize": False, "add_generation_prompt": True} - if args.no_thinking: - chat_kwargs["enable_thinking"] = False - chat = target_tok.apply_chat_template( - [{"role": "user", "content": user_msg}], **chat_kwargs) - target_ids = target_tok(chat, return_tensors="pt")["input_ids"][0].tolist() - - # Free drafter (1.2GB), restore target+spec_draft for target gen. - dflash.free_drafter() - dflash.unpark_target() - dflash.unpark_draft() - - t0 = time.time() - out_ids = dflash.generate(target_ids, args.n_gen) - t_gen = time.time() - t0 - # Re-park for next iter (drafter scoring). - dflash.park_draft() - print(f"[case {i}] raw out_ids ({len(out_ids)}): {out_ids[:20]}", flush=True) - out_text = target_tok.decode(out_ids, skip_special_tokens=True) - out_text_keep = target_tok.decode(out_ids, skip_special_tokens=False) - print(f"[case {i}] out_with_special: {out_text_keep!r}", flush=True) - - ok = case["answer"] in out_text - if ok: - correct += 1 - ttft = t_score + t_gen # rough; gen includes ttft - print(f"[case {i}] gen_s={t_gen:.1f} ttft={ttft:.1f} ok={ok} ans={case['answer']}", flush=True) - print(f"[case {i}] out: {out_text!r}", flush=True) - - print(f"\naccuracy: {correct}/{len(cases)}", flush=True) - dflash.close() - - -if __name__ == "__main__": - main() diff --git a/optimizations/pflash/tests/niah_gen.py b/optimizations/pflash/tests/niah_gen.py deleted file mode 100644 index c307e5588..000000000 --- a/optimizations/pflash/tests/niah_gen.py +++ /dev/null @@ -1,140 +0,0 @@ -"""Generate NIAH single-needle test cases at any context size.""" -import argparse, json, os, random, sys -from transformers import AutoTokenizer - - -def _positive_int(s): - try: - v = int(s) - except ValueError: - raise argparse.ArgumentTypeError(f"not an integer: {s!r}") - if v <= 0: - raise argparse.ArgumentTypeError(f"must be positive, got {v}") - return v - -FILLER = ("The grass is green. The sky is blue. The sun is yellow. " - "Here we go. There and back again. ") -NEEDLE_TMPL = "The special magic {key} number is: {value}." -QUESTION_TMPL = "What is the special magic {key} number? Answer in one short sentence." - - -def gen_one(seed: int, target_tokens: int, tokenizer, tolerance: float = 0.005): - """Generate a NIAH case whose tokenized length is within `tolerance` of - `target_tokens` *and never exceeds it*, regardless of which tokenizer is - passed in. - - Strategy: binary-search the chars-per-token ratio against the actual - tokenizer until we land within tolerance, then hard-trim chars off the - filler if we still overshoot by even one token. Token counts include - special tokens (BOS etc) so the cap matches what downstream consumers - see when they tokenize the prompt with default settings. - - Raises ValueError if `target_tokens` is below the scaffold floor (the - fixed intro + needle + question alone exceed the budget). - """ - if target_tokens <= 0: - raise ValueError(f"target_tokens must be positive, got {target_tokens}") - rng = random.Random(seed) - key = "".join(rng.choices("abcdefghijklmnopqrstuvwxyz", k=8)) - value = "".join(rng.choices("0123456789", k=7)) - needle = NEEDLE_TMPL.format(key=key, value=value) - question = QUESTION_TMPL.format(key=key) - insert_frac = rng.uniform(0.25, 0.75) # capture once for determinism - - def build(target_chars: int) -> str: - target_chars = max(0, target_chars) - filler = (FILLER * (target_chars // len(FILLER) + 1))[:target_chars] - insert = int(target_chars * insert_frac) - body = filler[:insert] + " " + needle + " " + filler[insert:] - return ( - "Below is a long passage. Answer the question at the end based ONLY on information in the passage.\n\n" - f"{body}\n\nQuestion: {question}\nAnswer:" - ) - - def n_tokens(prompt: str) -> int: - # Default add_special_tokens=True matches what downstream consumers - # (bench_niah_cpp.py via tokenizer(prompt)) actually see, so the cap - # below correctly accounts for any BOS/EOS the tokenizer prepends. - return len(tokenizer.encode(prompt)) - - # Binary-search chars-per-token. Bounds [2.0, 6.0] cover every common - # tokenizer (Qwen ~3.7, Llama/Mistral ~4.0, GPT-2 BPE ~4.2, byte-level ~5+). - lo, hi = 2.0, 6.0 - target_chars = int(target_tokens * (lo + hi) / 2) - prompt = build(target_chars) - actual = n_tokens(prompt) - for _ in range(20): - if abs(actual - target_tokens) / target_tokens < tolerance: - break - if actual > target_tokens: - hi = (lo + hi) / 2 - else: - lo = (lo + hi) / 2 - target_chars = int(target_tokens * (lo + hi) / 2) - prompt = build(target_chars) - actual = n_tokens(prompt) - - # Hard-trim: shrink filler until actual <= target_tokens. Step by larger - # chunks first to keep the worst case bounded (~few re-tokenizations). - for step in (256, 64, 16, 1): - while actual > target_tokens and target_chars >= step: - target_chars -= step - prompt = build(target_chars) - actual = n_tokens(prompt) - - if actual > target_tokens: - # filler at zero and the fixed scaffold (intro + needle + question + - # any specials) alone exceeds target_tokens. Surface this clearly - # rather than returning an over-limit prompt. - raise ValueError( - f"target_tokens={target_tokens} is below the scaffold floor " - f"(empty filler + needle + question + specials = {actual} tokens). " - f"Pick a larger target." - ) - - return {"prompt": prompt, "answer": value, "key": key, "n_tokens": actual} - - -def main(): - ap = argparse.ArgumentParser() - # --n stays type=int so --n 0 keeps producing an empty JSONL (preserves - # prior CLI behavior). --ctx is positive-only because the convergence - # loop divides by it. - ap.add_argument("--n", type=int, default=10) - ap.add_argument("--ctx", type=_positive_int, default=8192) - ap.add_argument("--out", required=True) - ap.add_argument("--seed-base", type=int, default=42, - help="Base seed for case generation (default 42). " - "Vary this to produce different needle key/value " - "pairs without changing --n.") - # Default matches bench_niah_cpp.py's --drafter-tokenizer, since that is - # the tokenizer the downstream NIAH bench uses to size case["prompt"] - # for the drafter forward. Override for any other harness. - ap.add_argument("--tokenizer", default="Qwen/Qwen3.5-0.8B") - args = ap.parse_args() - tok = AutoTokenizer.from_pretrained(args.tokenizer) - - # Write to a sibling temp file and atomically rename on success. Avoids - # truncating an existing args.out when gen_one fails mid-run (e.g. on - # an impossibly small --ctx for case 0). - tmp_path = f"{args.out}.tmp.{os.getpid()}" - try: - with open(tmp_path, "w") as f: - for i in range(args.n): - try: - ex = gen_one(seed=args.seed_base + i, target_tokens=args.ctx, tokenizer=tok) - except ValueError as e: - sys.exit(f"[error] case {i}: {e}") - assert ex["n_tokens"] <= args.ctx, ( - f"case {i}: n_tokens={ex['n_tokens']} exceeds --ctx={args.ctx}") - f.write(json.dumps(ex) + "\n") - print(f" case {i}: ntok={ex['n_tokens']} key={ex['key']} ans={ex['answer']}") - os.replace(tmp_path, args.out) - finally: - if os.path.exists(tmp_path): - os.unlink(tmp_path) - print(f"saved {args.n} cases to {args.out}") - - -if __name__ == "__main__": - main() diff --git a/optimizations/pflash/tests/test_dflash_client.py b/optimizations/pflash/tests/test_dflash_client.py deleted file mode 100644 index 3c9bbc533..000000000 --- a/optimizations/pflash/tests/test_dflash_client.py +++ /dev/null @@ -1,270 +0,0 @@ -"""Tests for DflashClient lifecycle and resource cleanup.""" -from __future__ import annotations - -import os -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path -from unittest.mock import patch - -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from pflash.dflash_client import DflashClient - - -def create_mock_daemon(ready: bool = True, exit_code: int | None = None, - continuous_output: bool = False) -> str: - """Create a temporary Python executable that mocks the dflash daemon protocol.""" - script = tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) - if exit_code is not None: - body = f"""#!/usr/bin/env python3 -import sys -sys.exit({exit_code}) -""" - else: - chatter_code = """ -import threading, time -running = True -def chatter(): - i = 0 - while running: - try: - sys.stdout.write(f"chatter line {i}\\n") - sys.stdout.flush() - i += 1 - time.sleep(0.005) - except Exception: - break -threading.Thread(target=chatter, daemon=True).start() -""" if continuous_output else "running = False" - stop_chatter = "running = False\n" if continuous_output else "" - body = f"""#!/usr/bin/env python3 -import os, struct, sys -{chatter_code} - -stream_fd = None -for arg in sys.argv: - if arg.startswith("--stream-fd="): - stream_fd = int(arg.split("=", 1)[1]) - -if {ready}: - sys.stdout.write("[daemon] ready\\n") - sys.stdout.flush() - -while True: - line = sys.stdin.readline() - if not line: - {stop_chatter} break - if stream_fd is not None: - parts = line.strip().split() - if len(parts) == 2 and parts[1].isdigit(): - # generate request: simulate returning token 42 followed by -1 sentinel - os.write(stream_fd, struct.pack(" A 33B-total mixture-of-experts only fires ~8 of 256 experts per token, but a naive hot/cold offload still pays for it: pick the wrong experts to keep resident and you hit the CPU tier a third of the time. Spark exploits **activation sparsity** as a product: it calibrates the hot set from the traffic you actually serve, then a bounded GPU cache swaps the long tail in and out so cold-misses fall to ~zero, all inside a fixed VRAM budget. @@ -75,8 +74,7 @@ coarse-grain case Spark ships today. Single RTX 3090, Laguna-XS.2 Q4_K_M. Calibrated from a 333-chunk / ~171K-token corpus of real Claude Code sessions; cold-hit rates validated on 60 held-out -sessions. Decode tok/s reproduce with [`spark/bench.py`](spark/bench.py); full -methodology in [RESULTS.md](RESULTS.md). +sessions. Full methodology in [RESULTS.md](RESULTS.md). | Config (60% resident) | decode tok/s | % of all-GPU speed | cold-hit | VRAM | |---|---:|---:|---:|---:| @@ -131,81 +129,27 @@ auto-tunes from its own traffic: ```bash luce_server --spark # use the card, auto-size everything -luce_server --spark --spark-vram 14 # cap total VRAM at 14 GiB +luce_server --spark --spark-vram 14 # target ~14 GiB total VRAM ``` -The only knob is `--spark-vram `: the total VRAM Spark may use. From that -target it sizes everything itself. It fits the non-expert weights, the KV cache -and a safety margin, pins as many calibrated-hot experts as the rest allows, and -carves an auto-sized cache ring out of the budget (you never set a slot count). -Omit it and Spark sizes to the whole card. +The main knob is `--spark-vram `: a total VRAM sizing target for Spark's auto-budgeting. From that +target it estimates non-expert weights, KV cache, and overhead, pins as many calibrated-hot experts as the remaining budget allows, and +carves an auto-sized cache ring out of the budget (you don't need to set a slot count; passing an explicit `--spark-slots N` overrides the cache size and can exceed the target). +Omit `--spark-vram` and Spark sizes to the whole card. That one flag aside, `--spark`: - enables the **bounded expert cache** (auto-tunes the working set at serve time), - **auto-loads** a learned placement profile from `.gguf.spark.csv` if present, +- **bootstraps** a profile before opening HTTP on backends that support it (`laguna`, `qwen35moe`) by replaying up to 150 local Claude Code/Codex history chunks when no `.spark.csv` exists yet, - keeps **persisting** that profile after every request from live routing. -First boot starts uniform and warms the cache within a session; each restart -loads a better profile and starts warmer. No corpus, no CSV juggling, no env -vars. Verified on RTX 3090 for **both** Laguna-XS.2 and Qwen3.6-35B-A3B: +If no profile and no usable local history are found, first boot starts with uniform placement and warms the cache within a session; each restart +loads a better profile and starts warmer. No manual corpus or CSV juggling. Verified on RTX 3090 for **both** Laguna-XS.2 and Qwen3.6-35B-A3B: `--spark-vram 13`/`15` holds peak VRAM at 11.6/13.8 GiB, the profile is written and reloaded (`source=hotness:...`), and generation stays coherent under offload. (`--spark-slots N` forces an explicit cache size if you ever want to override the auto-sizing.) -The offline pipeline below is for **bootstrapping** a profile before first serve -(e.g. from your own Claude Code and Codex session history) and for -**evaluation**. It is optional. - -## Bootstrapping / eval pipeline - -The tooling here drives the luce daemon (`test_dflash`); build it from -[`../../server/`](../../server/) first. - -```bash -cd optimizations/spark -uv sync # tokenizers (+ gguf/torch optional extras) - -# 0. one tokenizer, extracted from the GGUF (gpt2 byte-level BPE) -python -m spark.tokenizer --gguf laguna-xs2-Q4_K_M.gguf --out laguna_tok.json - -# 1. corpus from your agent sessions, by session split. Pulls Claude Code -# (~/.claude/projects) and Codex (~/.codex/sessions) by default; --source -# claude|codex|both to pick. -python -m spark.extract_sessions --source both --out-dir ./corpus - -# 2. calibrate the placement profile (routing is placement-independent, so a -# high budget calibrates fast) -python -m spark.calibrate \ - --bin ../../server/build/test_dflash --gguf laguna-xs2-Q4_K_M.gguf \ - --tok laguna_tok.json --corpus corpus/train.jsonl --out-profile spark_profile.csv - -# 3. validate on held-out sessions: uniform vs calibrated vs + cache -python -m spark.validate --bin ../../server/build/test_dflash \ - --gguf laguna-xs2-Q4_K_M.gguf --tok laguna_tok.json \ - --corpus corpus/test.jsonl --budget-pct 60 # uniform -python -m spark.validate ... --budget-pct 60 --hotness spark_profile.csv # calibrated -python -m spark.validate ... --budget-pct 60 --hotness spark_profile.csv --cache-slots 32 -``` - -## Reproduce the decode numbers - -``` -python -m spark.bench --bin ../../server/build/test_dflash \ - --gguf laguna-xs2-Q4_K_M.gguf --tok laguna_tok.json \ - --hotness laguna-xs2-Q4_K_M.gguf.spark.csv --budget-pct 48 --cache-slots 32 -``` - -Reports steady-state decode tok/s and asserts the single-graph hybrid path is -token-for-token identical to all-GPU at full residency. On an RTX 3090, -laguna-xs2 Q4_K_M: all-GPU 119 tok/s, single-graph @100% 118.8 (128/128 exact), -Spark offload @~60% residency 99 tok/s (83% of all-GPU). This is the same -`LagunaBackend` decode path that `luce_server --spark` runs. - -Deploy: run the daemon with `LUCE_EXPERT_BUDGET_PCT=60 -LUCE_LAGUNA_HOTNESS=spark_profile.csv` and, for the cache, -`LUCE_LAGUNA_EXPERT_CACHE=1 LUCE_LAGUNA_CACHE_SLOTS=32`. - ## Engine knobs Placement uses the merged hybrid-offload engine; the cache + trace are the Spark @@ -214,7 +158,7 @@ engine additions. All on the daemon process. | Env var | Purpose | |---|---| | `LUCE_EXPERT_BUDGET_PCT` | hot-tier VRAM budget (% of experts resident) | -| `LUCE_LAGUNA_HOTNESS` | placement profile CSV from `spark.calibrate` | +| `LUCE_LAGUNA_HOTNESS` | placement profile CSV | | `LUCE_LAGUNA_NEXT_PLACEMENT_OUT` | accumulate + dump a routing profile (calibration) | | `LUCE_LAGUNA_EXPERT_CACHE` / `_CACHE_SLOTS` | enable the bounded cache + slots/layer | | `LUCE_LAGUNA_GPU_REMAP` | unified GPU FFN the cache serves through | @@ -249,7 +193,7 @@ What we built: @software{luce_spark_2026, title = {Luce Spark: traffic-calibrated hot/cold expert residency for MoE inference on consumer GPUs}, author = {Lucebox}, - url = {https://github.com/Luce-Org/lucebox-hub/tree/main/optimizations/spark}, + url = {https://github.com/Luce-Org/lucebox/tree/main/optimizations/spark}, year = {2026} } diff --git a/optimizations/spark/RESULTS.md b/optimizations/spark/RESULTS.md index d42a1bc14..41ee98c3e 100644 --- a/optimizations/spark/RESULTS.md +++ b/optimizations/spark/RESULTS.md @@ -10,7 +10,7 @@ Decode tok/s is single-stream. "Cold-hit rate" = fraction of the 8 routed experts/layer that land on the CPU (cold) tier per token. Sections 1-2 isolate the placement and cache levers on the per-layer decode path; the shipped default **single-graph fused decode** (section 4) lifts that operating point to **~100 -tok/s** (`spark/bench.py`, bit-identical to all-GPU at full residency). +tok/s** (measured with the historical `spark/bench.py` harness at commit `a0a071cb`, bit-identical to all-GPU at full residency). ## 1. Placement: calibration is the big lever @@ -97,14 +97,13 @@ fitted-from-traces predictor does not get there. Reaching it means relocating and fine-tuning the model's gate (Pre-gated MoE), for which these traces are the dataset. The placement + cache results above need no model change. -The table above trains with per-expert binary cross-entropy. recall@K is a -ranking metric, so `spark/train_pregate.py` now defaults to a ranking-aware -objective (`--loss listnet|ranknet`) that optimizes the *order* of the expert +The table above trained with per-expert binary cross-entropy. recall@K is a +ranking metric, so the historical research trainer (`spark/train_pregate.py`, +preserved in git history at commit `a0a071cb`) also tested ranking-aware +objectives (`--loss listnet|ranknet`) that optimize the *order* of the expert scores instead of each expert independently (ListNet, Cao et al. 2007; RankNet, -Burges et al. 2005; ranking-aware pre-gating, arXiv:2511.10676). `--loss all` -trains every objective on the same split and init and prints the recall@K -comparison. The ranking objective is the right one for top-K prefetch, but it -cannot supply the post-attention information the pre-attention input lacks, so it -does not move the **fundamental** cap — it tightens the surrogate, not the -ceiling. Re-measure on the full trace with `--loss all` to quantify the delta -over the BCE baseline. +Burges et al. 2005; ranking-aware pre-gating, arXiv:2511.10676), with `--loss all` +comparing every objective on the same split and init. The ranking objective is +the right one for top-K prefetch, but it cannot supply the post-attention +information the pre-attention input lacks, so it does not move the **fundamental** +cap — it tightens the surrogate, not the ceiling. diff --git a/optimizations/spark/pyproject.toml b/optimizations/spark/pyproject.toml deleted file mode 100644 index 6e140d927..000000000 --- a/optimizations/spark/pyproject.toml +++ /dev/null @@ -1,38 +0,0 @@ -[project] -name = "spark" -version = "0.1.0" -description = "Calibration + validation tooling for Luce Spark hot/cold expert residency" -readme = "README.md" -requires-python = ">=3.10" -authors = [{name = "lucebox"}] -license = {text = "Apache-2.0"} -keywords = ["llm", "mixture-of-experts", "offloading", "sparsity", "moe", "laguna"] -classifiers = [ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: Apache Software License", - "Operating System :: POSIX :: Linux", - "Topic :: Scientific/Engineering :: Artificial Intelligence", -] -# The hot/cold offload engine + bounded expert cache live in ../../server/ (C++/ -# CUDA). This package only drives the daemon: extract a corpus, tokenize, run -# calibration, validate. `gguf`/`torch` are optional (tokenizer extraction and -# the research pre-gate trainer). -dependencies = [ - "tokenizers>=0.15", -] - -[project.optional-dependencies] -tokenizer = ["gguf>=0.10", "numpy"] -pregate = ["torch", "numpy"] - -[project.urls] -Homepage = "https://github.com/Luce-Org/lucebox-hub" -Source = "https://github.com/Luce-Org/lucebox-hub/tree/main/optimizations/spark" - -[build-system] -requires = ["setuptools>=68"] -build-backend = "setuptools.build_meta" - -[tool.setuptools.packages.find] -where = ["."] -include = ["spark*"] diff --git a/optimizations/spark/spark/__init__.py b/optimizations/spark/spark/__init__.py deleted file mode 100644 index b5f8de565..000000000 --- a/optimizations/spark/spark/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Luce Spark: calibrated hot/cold residency for sparsely-activated models. - -Tooling (this package) runs outside the daemon: calibrate expert placement from -real traffic, validate, and (research) train a pre-gate predictor. The engine -that does the hot/cold offload + bounded expert cache lives in ../../server/. -""" -__version__ = "0.1.0" diff --git a/optimizations/spark/spark/_daemon.py b/optimizations/spark/spark/_daemon.py deleted file mode 100644 index e07cdad13..000000000 --- a/optimizations/spark/spark/_daemon.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python3 -"""Driver for the luce daemon stdin/stdout protocol with real timeouts. - -A blocking `proc.stdout.readline()` returns only on a new line or on EOF (daemon -death). If the daemon goes silent (stalls during model load, deadlocks, disk -stall) it returns neither, so a `time.time()` check placed after `readline()` -never runs and the caller hangs forever. That matters for unattended calibration -and validation runs. - -Here a reader thread pumps stdout lines into a queue, so the main loop waits with -`queue.get(timeout=...)`: a read can never outlive its deadline. (A `select()` on -the fd would be subtly wrong because data already pulled into Python's text -buffer is invisible to `select`; the reader thread does the blocking `readline` -itself, which handles buffering correctly.) -""" -import queue -import subprocess -import threading -import time - - -class DaemonTimeout(Exception): - """A stdout read exceeded its deadline (daemon alive but silent).""" - - -class Daemon: - def __init__(self, cmd, env, capture_stderr=False): - self.proc = subprocess.Popen( - cmd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if capture_stderr else subprocess.DEVNULL), - bufsize=1, universal_newlines=True) - self.stderr_lines = [] - self._q = queue.Queue() - threading.Thread(target=self._pump_stdout, daemon=True).start() - if capture_stderr: - threading.Thread(target=self._pump_stderr, daemon=True).start() - - def _pump_stdout(self): - for line in self.proc.stdout: - self._q.put(line) - self._q.put(None) # EOF sentinel - - def _pump_stderr(self): - for line in self.proc.stderr: - self.stderr_lines.append(line.rstrip()) - - def readline(self, timeout): - """Next stdout line (str), or None on EOF. Raises DaemonTimeout past `timeout` s.""" - try: - return self._q.get(timeout=max(0.0, timeout)) - except queue.Empty: - raise DaemonTimeout - - def send(self, cmd): - self.proc.stdin.write(cmd if cmd.endswith("\n") else cmd + "\n") - self.proc.stdin.flush() - - def wait_ready(self, banner="-daemon] ready", timeout=600, on_line=None): - """Block until the ready banner. Kills + raises SystemExit on timeout/death.""" - deadline = time.time() + timeout - while True: - try: - line = self.readline(deadline - time.time()) - except DaemonTimeout: - self.kill() - raise SystemExit(f"daemon did not become ready within {timeout}s (no output)") - if line is None: - raise SystemExit("daemon died before ready banner") - if on_line: - on_line(line) - if banner in line: - return - - def request(self, cmd, timeout=120): - """Send a command and wait for its `ok ...`/`err ...` reply. - - Returns the reply line, or None if the daemon died or stalled past - `timeout` (in which case the daemon is killed so the caller can stop).""" - try: - self.send(cmd) - except (BrokenPipeError, OSError): - return None - deadline = time.time() + timeout - while True: - try: - line = self.readline(deadline - time.time()) - except DaemonTimeout: - self.kill() - return None - if line is None: - return None - if line.startswith("ok ") or line.startswith("err "): - return line - - def kill(self): - try: - self.proc.kill() - except Exception: - pass - - def quit(self, timeout=20): - try: - self.send("quit") - self.proc.wait(timeout=timeout) - except Exception: - self.kill() diff --git a/optimizations/spark/spark/bench.py b/optimizations/spark/spark/bench.py deleted file mode 100644 index da35bd172..000000000 --- a/optimizations/spark/spark/bench.py +++ /dev/null @@ -1,135 +0,0 @@ -#!/usr/bin/env python3 -"""Reproduce the Luce Spark decode-throughput numbers. - -Drives the luce daemon (server/build/test_dflash) over a fixed prompt and -reports steady-state decode tok/s for three configs: - - 1. all-GPU (full residency) -> the speed ceiling - 2. single-graph @ 100% residency -> exercises the hybrid graph with - every expert resident; output must - match all-GPU token-for-token - 3. Spark offload (single-graph hybrid) -> pinned `--budget-pct` of experts + - a bounded GPU cache, the rest on CPU - -`decode_tok_s` is generated_tokens / decode_seconds (prefill excluded), the same -metric the daemon prints. The single-graph hybrid lives in LagunaBackend, which -also powers `luce_server --spark`, so these decode numbers carry over to the -server. - - python -m spark.bench \ - --bin ../../server/build/test_dflash \ - --gguf laguna-xs2-Q4_K_M.gguf --tok laguna_tok.json \ - --hotness laguna-xs2-Q4_K_M.gguf.spark.csv \ - --budget-pct 48 --cache-slots 32 -""" -import argparse -import os -import re -import struct -import sys - -from tokenizers import Tokenizer - -try: - from ._daemon import Daemon -except ImportError: # allow `python bench.py` - from _daemon import Daemon - -IN_BIN = "/tmp/spark_bench_in.bin" -OUT_BIN = "/tmp/spark_bench_out.bin" - - -def write_counted_i32(path, ids): - with open(path, "wb") as f: - f.write(struct.pack("= 0: - ids = [args.bos] + ids - write_counted_i32(IN_BIN, ids) - - base = dict(os.environ) - base["LUCE_IGNORE_EOS"] = "1" # fixed-length decode for a stable tok/s - - def cfg(**kw): - e = dict(base) - e.update(kw) - return e - - offload = dict(LUCE_LAGUNA_GPU_REMAP="1", LUCE_LAGUNA_EXPERT_CACHE="1", - LUCE_LAGUNA_CACHE_SLOTS=str(args.cache_slots)) - if args.hotness: - offload["LUCE_LAGUNA_HOTNESS"] = args.hotness - - total_pct = args.budget_pct + 100.0 * args.cache_slots / args.n_expert - print(f"prompt={args.prompt!r} n_gen={args.n_gen} bos={args.bos}") - print(f"offload: pinned {args.budget_pct}% + cache {args.cache_slots}/{args.n_expert} " - f"=> ~{total_pct:.0f}% total residency\n") - - tps_all, ref = measure(args.bin, args.gguf, cfg(), - args.n_gen, args.ready_timeout, args.gen_timeout) - print(f" all-GPU (full residency) {tps_all:6.1f} tok/s") - - tps_100, out_100 = measure(args.bin, args.gguf, - cfg(LUCE_EXPERT_BUDGET_PCT="100", **offload), - args.n_gen, args.ready_timeout, args.gen_timeout) - n = min(len(out_100), len(ref)) - match = sum(1 for x, y in zip(out_100, ref) if x == y) - exact = "EXACT" if match == n and n > 0 else "DIVERGED" - print(f" single-graph @100% (vs all-GPU) {tps_100:6.1f} tok/s {match}/{n} {exact}") - - tps_off, _ = measure(args.bin, args.gguf, - cfg(LUCE_EXPERT_BUDGET_PCT=str(args.budget_pct), **offload), - args.n_gen, args.ready_timeout, args.gen_timeout) - pct = 100.0 * tps_off / max(1e-9, tps_all) - print(f" Spark offload (single-graph) {tps_off:6.1f} tok/s {pct:.0f}% of all-GPU") - - ok = (match == n and n > 0) - print(f"\nresult: {'PASS' if ok else 'FAIL'} (single-graph @100% must match all-GPU token-for-token)") - sys.exit(0 if ok else 1) - - -if __name__ == "__main__": - main() diff --git a/optimizations/spark/spark/calibrate.py b/optimizations/spark/spark/calibrate.py deleted file mode 100644 index dae54b527..000000000 --- a/optimizations/spark/spark/calibrate.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python3 -"""Step 2 of Spark calibration: corpus -> hot/cold placement profile. - -Feeds each corpus chunk through the luce daemon in hybrid mode with -`LUCE_LAGUNA_NEXT_PLACEMENT_OUT` set, so per-(layer, expert) routing -frequencies accumulate across the whole corpus. The resulting CSV is the -placement profile: load it at serve time with `LUCE_LAGUNA_HOTNESS=` and -the greedy knapsack keeps the most-frequent experts resident. - -Routing is placement-independent, so calibrate at a high budget (fast, little -cold) regardless of the budget you deploy at. - - python -m spark.calibrate \ - --bin ../../server/build/test_dflash \ - --gguf laguna-xs2-Q4_K_M.gguf \ - --tok laguna_tok.json \ - --corpus corpus/train.jsonl --out-profile spark_profile.csv -""" -import argparse -import json -import os -import struct -import time -from pathlib import Path - -from tokenizers import Tokenizer - -try: - from ._daemon import Daemon -except ImportError: # allow direct `python calibrate.py` - from _daemon import Daemon - - -def write_counted_i32(path, ids): - with open(path, "wb") as f: - f.write(struct.pack(" " - f"{'SAVED ' + str(pr.stat().st_size) + 'B' if pr.exists() else 'PROFILE MISSING'}: {pr}", - flush=True) - - -if __name__ == "__main__": - main() diff --git a/optimizations/spark/spark/extract_sessions.py b/optimizations/spark/spark/extract_sessions.py deleted file mode 100644 index 2587e1d89..000000000 --- a/optimizations/spark/spark/extract_sessions.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python3 -"""Step 1 of Spark calibration: extract a text corpus from agent session logs. - -Spark calibrates expert placement on *representative traffic*, so the corpus -should be whatever the model actually serves. This reads agent transcripts from -Claude Code (`~/.claude/projects/*/*.jsonl`) and/or Codex -(`~/.codex/sessions/**/rollout-*.jsonl`), pulls the conversational text (user + -assistant, thinking, tool calls and results), and splits train / held-out by -session so validation never sees calibration data. - - python -m spark.extract_sessions --source both --out-dir ./corpus - -Produces corpus/train.jsonl (calibration) and corpus/test.jsonl (held-out), -one JSON-encoded text chunk per line. -""" -import argparse -import hashlib -import json -from pathlib import Path - - -def claude_text_from_session(path): - """Claude Code transcript (one JSON object per line) -> conversational text.""" - def blocks(content): - out = [] - if isinstance(content, str): - out.append(content) - elif isinstance(content, list): - for b in content: - if not isinstance(b, dict): - continue - t = b.get("type") - if t == "text" and b.get("text"): - out.append(b["text"]) - elif t == "thinking" and b.get("thinking"): - out.append(b["thinking"]) - elif t == "tool_use" and b.get("input") is not None: - out.append(json.dumps(b["input"])[:4000]) - elif t == "tool_result": - cc = b.get("content") - if isinstance(cc, str): - out.append(cc) - elif isinstance(cc, list): - for x in cc: - if isinstance(x, dict) and x.get("type") == "text": - out.append(x.get("text", "")) - return out - - out = [] - try: - for ln in Path(path).open(): - try: - o = json.loads(ln) - except json.JSONDecodeError: - continue - if o.get("type") in ("user", "assistant") and isinstance(o.get("message"), dict): - out += blocks(o["message"].get("content")) - except OSError: - return "" - return "\n".join(s for s in out if s) - - -def codex_text_from_session(path): - """Codex rollout (one JSON object per line) -> conversational text. - - Pulls user + assistant `response_item` content blocks. Skips the developer - role, which is the repeated system/permissions/skills boilerplate and would - over-weight the calibration toward instructions rather than real traffic.""" - out = [] - try: - for ln in Path(path).open(): - try: - o = json.loads(ln) - except json.JSONDecodeError: - continue - if o.get("type") != "response_item": - continue - p = o.get("payload", {}) - if p.get("role") not in ("user", "assistant"): - continue - c = p.get("content") - if isinstance(c, list): - for b in c: - if isinstance(b, dict) and b.get("type") in ("input_text", "output_text", "text") and b.get("text"): - out.append(b["text"]) - elif isinstance(c, str): - out.append(c) - except OSError: - return "" - return "\n".join(s for s in out if s) - - -def chunks_from_text(txt, size, min_size): - txt = txt.strip() - for i in range(0, len(txt), size): - c = txt[i:i + size] - if len(c) >= min_size: - yield c - - -def collect_sessions(args): - """[(session_file, parser_fn, source_tag), ...] from the enabled sources.""" - out = [] - if args.source in ("claude", "both"): - for f in sorted(Path(args.claude_dir).glob("*/*.jsonl")): - out.append((f, claude_text_from_session, "claude")) - if args.source in ("codex", "both"): - for f in sorted(Path(args.codex_dir).glob("**/rollout-*.jsonl")): - out.append((f, codex_text_from_session, "codex")) - return out - - -def main(): - ap = argparse.ArgumentParser(description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--source", choices=["claude", "codex", "both"], default="both") - ap.add_argument("--claude-dir", default=str(Path.home() / ".claude" / "projects"), - help="dir with /.jsonl transcripts") - ap.add_argument("--codex-dir", default=str(Path.home() / ".codex" / "sessions"), - help="dir with YYYY/MM/DD/rollout-*.jsonl rollouts") - ap.add_argument("--out-dir", default="./corpus") - ap.add_argument("--chunk-chars", type=int, default=2000) - ap.add_argument("--min-chars", type=int, default=400) - ap.add_argument("--per-session", type=int, default=4, help="chunks sampled per session") - ap.add_argument("--test-frac", type=int, default=5, help="1/N sessions held out (5 = 20%%)") - ap.add_argument("--train-cap", type=int, default=500) - ap.add_argument("--test-cap", type=int, default=60) - args = ap.parse_args() - - sessions = collect_sessions(args) - if not sessions: - raise SystemExit(f"no sessions found (source={args.source}; " - f"claude={args.claude_dir}, codex={args.codex_dir})") - - train, test = [], [] - per_source = {} - for f, parse, tag in sessions: - # split by session-path hash so a whole session is train xor test - bucket = test if int(hashlib.md5(str(f).encode()).hexdigest(), 16) % args.test_frac == 0 else train - txt = parse(f) - if not txt: - continue - sess = list(chunks_from_text(txt, args.chunk_chars, args.min_chars)) - if not sess: - continue - step = max(1, len(sess) // args.per_session) - picked = sess[::step][:args.per_session] - bucket.extend(picked) - per_source[tag] = per_source.get(tag, 0) + len(picked) - - out = Path(args.out_dir) - out.mkdir(parents=True, exist_ok=True) - - def write(name, items, cap): - items = items[:cap] - p = out / name - with p.open("w") as fo: - for c in items: - fo.write(json.dumps(c) + "\n") - nchar = sum(len(c) for c in items) - print(f"{p}: {len(items)} chunks, ~{nchar // 1000}K chars (~{nchar // 4000}K tok est)") - - write("train.jsonl", train, args.train_cap) - write("test.jsonl", test, args.test_cap) - print(f"sources: {dict(per_source)} over {len(sessions)} sessions " - f"({args.source}), 1/{args.test_frac} held out by session") - - -if __name__ == "__main__": - main() diff --git a/optimizations/spark/spark/tokenizer.py b/optimizations/spark/spark/tokenizer.py deleted file mode 100644 index 853eb9e0f..000000000 --- a/optimizations/spark/spark/tokenizer.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python3 -"""Extract a usable HF tokenizer from a GGUF (gpt2 byte-level BPE). - -The Spark tools tokenize corpus text with the *target model's own* tokenizer. -GGUFs embed the vocab + merges, so we can rebuild a `tokenizers` BPE without -needing the original HF repo. - - python -m spark.tokenizer --gguf laguna-xs2-Q4_K_M.gguf --out laguna_tok.json -""" -import argparse - -import numpy as np # noqa: F401 (gguf reader pulls it in) -from tokenizers import Tokenizer, decoders, models, pre_tokenizers - - -def extract(gguf_path: str, out_path: str): - import gguf - rd = gguf.GGUFReader(gguf_path) - f = rd.fields - - def list_str(fl): - return [bytes(fl.parts[d]).decode("utf-8", errors="replace") for d in fl.data] - - model = bytes(f["tokenizer.ggml.model"].parts[f["tokenizer.ggml.model"].data[0]]).decode() - if model != "gpt2": - raise SystemExit(f"only gpt2 byte-level BPE supported, gguf says model={model!r}") - - tokens = list_str(f["tokenizer.ggml.tokens"]) - merges = list_str(f["tokenizer.ggml.merges"]) if "tokenizer.ggml.merges" in f else [] - vocab = {t: i for i, t in enumerate(tokens)} - bpe = models.BPE(vocab=vocab, - merges=[tuple(m.split(" ", 1)) for m in merges if " " in m], - fuse_unk=False) - tk = Tokenizer(bpe) - tk.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=True) - tk.decoder = decoders.ByteLevel() - - # sanity: round-trip - probe = "def f(n):\n return n + 1\n" - if tk.decode(tk.encode(probe).ids).strip() != probe.strip(): - print("warning: tokenizer round-trip mismatch (continuing)") - - tk.save(out_path) - print(f"{out_path}: vocab={len(tokens)} merges={len(merges)}") - - -def main(): - ap = argparse.ArgumentParser(description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--gguf", required=True) - ap.add_argument("--out", default="tokenizer.json") - extract(**vars(ap.parse_args())) - - -if __name__ == "__main__": - main() diff --git a/optimizations/spark/spark/train_pregate.py b/optimizations/spark/spark/train_pregate.py deleted file mode 100644 index ba0abdd69..000000000 --- a/optimizations/spark/spark/train_pregate.py +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/env python3 -"""(Research) Train a per-layer pre-gate predictor from a routing trace. - -A pre-gate predicts a layer's selected experts from the *block input* hidden, -i.e. one step early, which is what you need to prefetch experts and fuse the -attention+FFN graphs (Pre-gated MoE, arXiv:2308.12066). - -Trains a predictor per layer from the trace captured by the engine -(`LUCE_LAGUNA_PREGATE_TRACE`, fixed-size records: int16 layer, int16 n_sel, -int32[8] selected, float32[n_embd] hidden) and reports recall@K: of the experts -a layer actually selects, how many are in the predicted top-K. High recall@K at -small K means prefetch+fusion is viable. - -Loss (`--loss`): recall@K is a ranking metric, so the predictor is trained with a -ranking-aware objective by default rather than per-expert binary cross-entropy. - - `listnet` listwise: cross-entropy between softmax(scores) and the normalized - selected-expert distribution (ListNet, Cao et al. 2007). - - `ranknet` pairwise logistic on every (selected, unselected) score pair, so - every selected expert is pushed above every unselected one (RankNet, Burges - et al. 2005). - - `bce` the original per-expert binary cross-entropy baseline. -A ranking objective optimizes the *order* of the expert scores, which is exactly -what top-K prefetch consumes; BCE optimizes each expert independently and is only -a surrogate for it (ranking-aware pre-gating, arXiv:2511.10676). `--loss all` -trains every objective on identical splits/init and prints a recall@K comparison. - -Result on Laguna-XS.2 (RTX 3090, Claude Code traces) with BCE: linear ~50% / MLP -~53% recall@8 -- a richer model barely helps, because the pre-gate sees the -pre-attention hidden while the router decides on the post-attention hidden. That -information gap caps a fitted predictor; a ranking loss aligns the objective with -recall@K but does not create information the input lacks, so the headroom over -BCE is bounded. Reaching high recall needs fine-tuning the model's gate, not a -bigger predictor or a different loss alone. Re-measure with `--loss all`; see -RESULTS.md. - - python -m spark.train_pregate --trace pregate_trace.bin --model mlp - python -m spark.train_pregate --trace pregate_trace.bin --loss all - python -m spark.train_pregate --self-test # synthetic, no trace/GPU -""" -import argparse - -import numpy as np - -LOSSES = ("bce", "listnet", "ranknet") - - -def build_net(model, n_embd, n_expert, dev): - import torch.nn as nn - if model == "linear": - return nn.Linear(n_embd, n_expert).to(dev) - return nn.Sequential(nn.Linear(n_embd, 512), nn.GELU(), nn.Linear(512, n_expert)).to(dev) - - -def loss_listnet(scores, target): - """Top-1 ListNet: CE between softmax(scores) and the normalized relevance.""" - import torch - tgt = target / target.sum(dim=1, keepdim=True).clamp(min=1e-9) - return -(tgt * torch.log_softmax(scores, dim=1)).sum(dim=1).mean() - - -def loss_ranknet(scores, target, sel): - """Pairwise RankNet logistic loss over (selected, unselected) score pairs. - - `sel` is the padded (N, 8) selected-expert index matrix (-1 = empty slot); - `target` is the (N, E) multi-hot of the same selection. - """ - import torch.nn.functional as F - valid = (sel >= 0).unsqueeze(2) # (N, P, 1) - pos_scores = scores.gather(1, sel.clamp(min=0)) # (N, P) - neg = (target == 0).unsqueeze(1) # (N, 1, E) - diff = scores.unsqueeze(1) - pos_scores.unsqueeze(2) # (N, P, E): s_neg - s_pos - weight = valid & neg # count only pos-vs-neg pairs - return (F.softplus(diff) * weight).sum() / weight.sum().clamp(min=1) - - -def step_loss(name, out, Ytr, Str): - import torch.nn as nn - if name == "bce": - return nn.functional.binary_cross_entropy_with_logits(out, Ytr) - if name == "listnet": - return loss_listnet(out, Ytr) - if name == "ranknet": - return loss_ranknet(out, Ytr, Str) - raise ValueError(name) - - -def recall_at_k(net, Xte, Yte, ks=(8, 16, 24)): - import torch - with torch.no_grad(): - order = torch.argsort(net(Xte), dim=1, descending=True) - den = Yte.sum(1).clamp(min=1) - return {k: (100 * (Yte.gather(1, order[:, :k]).sum(1) / den).mean()).item() for k in ks} - - -def train_eval(model, name, Xtr, Ytr, Str, Xte, Yte, n_expert, epochs, lr, seed): - import torch - torch.manual_seed(seed) - net = build_net(model, Xtr.shape[1], n_expert, Xtr.device) - opt = torch.optim.Adam(net.parameters(), lr=lr, weight_decay=1e-4) - for _ in range(epochs): - opt.zero_grad() - step_loss(name, net(Xtr), Ytr, Str).backward() - opt.step() - return recall_at_k(net, Xte, Yte) - - -def to_multihot(sel, n_expert, dev): - import torch - Y = torch.zeros(len(sel), n_expert, device=dev) - for j in range(sel.shape[1]): - c = torch.tensor(sel[:, j].astype(np.int64), device=dev) - m = c >= 0 - Y[torch.arange(len(sel), device=dev)[m], c[m]] = 1.0 - return Y - - -def report(model, agg): - for name in LOSSES: - d = agg.get(name) - if not d or not d[8]: - continue - print(f"=== {model} pre-gate recall@K [{name}] (held-out, mean over layers) ===") - for k in sorted(d): - print(f" recall@{k:2d}: {np.mean(d[k]):5.1f}% (worst layer {min(d[k]):.0f}%)") - - -def main(): - ap = argparse.ArgumentParser(description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--trace") - ap.add_argument("--n-embd", type=int, default=2048) - ap.add_argument("--n-expert", type=int, default=256) - ap.add_argument("--n-layer", type=int, default=40) - ap.add_argument("--model", choices=["linear", "mlp"], default="mlp") - ap.add_argument("--loss", choices=[*LOSSES, "all"], default="listnet") - ap.add_argument("--max-per-layer", type=int, default=5000) - ap.add_argument("--epochs", type=int, default=120) - ap.add_argument("--lr", type=float, default=1e-3) - ap.add_argument("--seed", type=int, default=0) - ap.add_argument("--self-test", action="store_true", - help="run a synthetic separable-data check (no trace/GPU needed)") - args = ap.parse_args() - - if args.self_test: - raise SystemExit(self_test(args)) - if not args.trace: - ap.error("--trace is required (or pass --self-test)") - - import torch - torch.manual_seed(args.seed) - H, E = args.n_embd, args.n_expert - losses = list(LOSSES) if args.loss == "all" else [args.loss] - dt = np.dtype([("layer", " 70.0 - print(f" {name:8s} recall@8={rec[8]:5.1f}% recall@16={rec[16]:5.1f}% " - f"{'PASS' if ok else 'FAIL'}") - if not ok: - failures.append(name) - print("self-test PASS" if not failures else f"self-test FAIL: {failures}") - return 1 if failures else 0 - - -if __name__ == "__main__": - main() diff --git a/optimizations/spark/spark/validate.py b/optimizations/spark/spark/validate.py deleted file mode 100644 index 865606716..000000000 --- a/optimizations/spark/spark/validate.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python3 -"""Step 3: validate a placement profile on HELD-OUT chunks. - -Drives the daemon over held-out corpus chunks and reports mean decode tok/s and -the cold-hit rate from the per-token profiler. Compare runs with/without -`--hotness` (uniform vs calibrated) and with/without the expert cache to see the -ladder in RESULTS.md. - - # all-GPU baseline - python -m spark.validate --bin ... --gguf ... --tok ... \ - --corpus corpus/test.jsonl --budget-pct 0 - - # calibrated 60% + bounded expert cache - python -m spark.validate --bin ... --gguf ... --tok ... \ - --corpus corpus/test.jsonl --budget-pct 60 \ - --hotness spark_profile.csv --cache-slots 32 -""" -import argparse -import json -import os -import re -import statistics -import struct -from pathlib import Path - -from tokenizers import Tokenizer - -try: - from ._daemon import Daemon -except ImportError: # allow direct `python validate.py` - from _daemon import Daemon - - -def write_counted_i32(path, ids): - with open(path, "wb") as f: - f.write(struct.pack(" 0: - env["LUCE_EXPERT_BUDGET_PCT"] = str(args.budget_pct) - if args.hotness: - env["LUCE_LAGUNA_HOTNESS"] = args.hotness - if args.cache_slots > 0: - env["LUCE_LAGUNA_GPU_REMAP"] = "1" - env["LUCE_LAGUNA_EXPERT_CACHE"] = "1" - env["LUCE_LAGUNA_CACHE_SLOTS"] = str(args.cache_slots) - - placement = [] - daemon = Daemon([args.bin, args.gguf, "--max-ctx", str(args.max_ctx)], env, capture_stderr=True) - daemon.wait_ready( - timeout=args.ready_timeout, - on_line=lambda l: placement.append(l.rstrip()) - if ("storage ready" in l or "placement result" in l) else None) - - pp = Path("/tmp/spark_val_chunk.bin") - op = Path("/tmp/spark_val_out.bin") - toks = [] - for c in chunks: - ids = tk.encode(c).ids[:args.max_tok] - if len(ids) < 8: - continue - write_counted_i32(pp, ids) - reply = daemon.request(f"generate {pp} {args.n_gen} {op}", timeout=args.gen_timeout) - if reply is None: - print("daemon stalled/closed; stopping early") - break - if reply.startswith("ok "): - m = re.search(r"decode_tok_s=([0-9.]+)", reply) - if m: - toks.append(float(m.group(1))) - - daemon.quit() - - for p in placement: - print("PLACEMENT:", p.strip()) - label = f"budget={args.budget_pct} hotness={'yes' if args.hotness else 'no'} cache={args.cache_slots}" - print(f"\n===== VALIDATION {label} =====") - if toks: - print(f"decode tok/s: mean={statistics.mean(toks):.1f} median={statistics.median(toks):.1f} " - f"over {len(toks)} chunks") - colds = [float(m.group(1)) for l in daemon.stderr_lines - for m in [re.search(r"cold_experts/tok=([0-9.]+)", l)] if m] - if colds: - print(f"cold_experts/tok: mean={statistics.mean(colds):.2f} max={max(colds):.2f}") - - -if __name__ == "__main__": - main() diff --git a/pyproject.toml b/pyproject.toml index fcbcac775..be213d76c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,6 @@ authors = [{ name = "Lucebox" }] dependencies = [ "luce", - "pflash", ] [project.optional-dependencies] @@ -27,7 +26,6 @@ include = ["harness/**/*.py", "scripts/**/*.py", "conftest.py", "server/test/pyt extend-exclude = [ "server/deps", "megakernel", - "pflash", ] [tool.ruff.lint] @@ -39,7 +37,7 @@ select = ["F", "I", "UP", "B"] [tool.pytest.ini_options] # Repo root on sys.path so tests can import harness/, server/ helpers. pythonpath = ["."] -testpaths = ["server/test/python", "harness", ".github/ci", "optimizations/pflash/tests"] +testpaths = ["server/test/python", "harness", ".github/ci"] addopts = "-ra --strict-markers" markers = [ "server: needs a running luce_server (use --base-url URL or --launch MODEL)", @@ -64,11 +62,10 @@ no-build-isolation-package = ["qwen35-megakernel-bf16"] [tool.uv.workspace] # Workspace members. Keeping the list to the packages that live in this # repo lets `uv lock --check` / `uv sync --frozen` pass. -members = ["server", "optimizations/megakernel", "optimizations/pflash"] +members = ["server", "optimizations/megakernel"] [tool.uv.sources] luce = { workspace = true } -pflash = { workspace = true } qwen35-megakernel-bf16 = { workspace = true } torch = { index = "pytorch-cu128" } diff --git a/server/RESULTS.md b/server/RESULTS.md index 9964909c8..4eb999f63 100644 --- a/server/RESULTS.md +++ b/server/RESULTS.md @@ -577,9 +577,10 @@ Draft: local Qwen3.6-27B DFlash safetensors + Qwen3-0.6B-BF16 PFlash drafter. Build: `cmake -B build-luce-sm120 -S . -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=120 -DLUCE_USER_CUDA_ARCHITECTURES=120 -DLUCE_ENABLE_BSA=ON` -Final ("V4") runtime config — driven via the `optimizations/pflash/tests/bench_niah_cpp.py` -CLI flags added in #90 plus daemon env vars (each bullet leads with the -exact interface): +Final ("V4") historical PFlash v1 runtime config — originally driven via the +now-removed `optimizations/pflash/tests/bench_niah_cpp.py` harness (preserved in +git history at commit `a0a071cb`, CLI flags added in #90) plus daemon env vars +(each bullet leads with the exact historical interface): - `--keep-ratio=0.05` (PFlash compression target ratio) - `LUCE_FP_USE_BSA=1` and `LUCE_FP_ALPHA=0.70` (BSA enabled, block-selection threshold; both are daemon env vars) @@ -589,8 +590,9 @@ exact interface): - `--n-gen=1024` Test set: 10 NIAH prompts at 117K tokens (margin under Qwen3.6-27B's 131K -native RoPE limit, generated with [`optimizations/pflash/tests/niah_gen.py`](../optimizations/pflash/tests/niah_gen.py) -at calibrated `char_per_tok`). +native RoPE limit, generated with the historical +`optimizations/pflash/tests/niah_gen.py` script at commit `a0a071cb` with +calibrated `char_per_tok`). ### RTX 5090 long-ctx headline diff --git a/server/docs/laguna_integration_plan.md b/server/docs/laguna_integration_plan.md index 6032c6b30..d0c241343 100644 --- a/server/docs/laguna_integration_plan.md +++ b/server/docs/laguna_integration_plan.md @@ -58,7 +58,7 @@ No libllama dependency in dflash runtime. Keep ggml-only stack. (libllama+LAGUNA - For Laguna arch, use `LagunaTargetCache` + `build_laguna_graph` instead of qwen35 equivalents - Adjust per-layer-head-count in attention buffer sizing - PFlash drafter call unchanged (drafter is Qwen3.5-0.8B regardless of target) - - Cross-tokenizer mapping (Qwen3 IDs → Laguna IDs): byte-level round-trip via existing optimizations/pflash/ Python module OR port to C++ helper + - Cross-tokenizer mapping (Qwen3 IDs → Laguna IDs): byte-level round-trip (implemented in [`server/scripts/laguna_pflash_niah.py`](../scripts/laguna_pflash_niah.py) for benchmarking) OR port to C++ helper ## Phasing diff --git a/server/src/common/concurrency/paged_kv_pool.h b/server/src/common/concurrency/paged_kv_pool.h index fda828748..07708834f 100644 --- a/server/src/common/concurrency/paged_kv_pool.h +++ b/server/src/common/concurrency/paged_kv_pool.h @@ -14,6 +14,7 @@ #pragma once +#include #include #include #include @@ -280,9 +281,10 @@ class PagedKvPool { // The number of consecutive physical blocks in `blocks` starting at index // `first` (each one past the previous), at most `block_count - first`. -inline size_t contiguous_block_run(const std::vector & blocks, - size_t first, size_t block_count) { - size_t run = 1; +inline std::size_t contiguous_block_run(const std::vector & blocks, + std::size_t first, + std::size_t block_count) { + std::size_t run = 1; while (first + run < block_count && (uint64_t)blocks[first + run] == (uint64_t)blocks[first + run - 1] + 1) { ++run; diff --git a/server/test/python/test_full_compress_cache.py b/server/test/python/test_full_compress_cache.py index db9d95339..a5e023456 100644 --- a/server/test/python/test_full_compress_cache.py +++ b/server/test/python/test_full_compress_cache.py @@ -42,11 +42,7 @@ def build_long_prompt(target_tokens: int, seed: int = 42) -> tuple[str, str]: Uses a coarse `target_tokens * 4.0` sizing — this script only needs a long, deterministic, mostly-filler prompt and does not care about exact - token counts (cf. pflash/tests/niah_gen.py, which is the canonical - NIAH generator with tokenizer-aware sizing and a hard <=target cap). - Keep the FILLER / NEEDLE / QUESTION text in rough sync with niah_gen.py - so a reader sees the same NIAH shape; full deduplication would require - moving the shared text into a package both files can import. + token counts. """ rng = random.Random(seed) key = "".join(rng.choices("abcdefghijklmnopqrstuvwxyz", k=8)) diff --git a/uv.lock b/uv.lock index a013bd67c..fe2f6b2f3 100644 --- a/uv.lock +++ b/uv.lock @@ -11,7 +11,6 @@ resolution-markers = [ members = [ "luce", "lucebox-hub", - "pflash", "qwen35-megakernel-bf16", ] @@ -467,7 +466,6 @@ version = "0.0.0" source = { virtual = "." } dependencies = [ { name = "luce" }, - { name = "pflash" }, ] [package.optional-dependencies] @@ -484,7 +482,6 @@ megakernel = [ requires-dist = [ { name = "luce", virtual = "server" }, { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.10,<2" }, - { name = "pflash", editable = "optimizations/pflash" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8" }, { name = "qwen35-megakernel-bf16", marker = "extra == 'megakernel'", editable = "optimizations/megakernel" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.14,<1" }, @@ -829,17 +826,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, ] -[[package]] -name = "pflash" -version = "0.3.0" -source = { editable = "optimizations/pflash" } -dependencies = [ - { name = "transformers" }, -] - -[package.metadata] -requires-dist = [{ name = "transformers", specifier = ">=4.50" }] - [[package]] name = "pluggy" version = "1.6.0" diff --git a/variables.md b/variables.md index a20dbb3a1..2d777662e 100644 --- a/variables.md +++ b/variables.md @@ -312,7 +312,6 @@ Untagged variables are operational tuning knobs. | `LUCE_BENCH_SEED` | 🧪 **test/bench** Benchmark RNG seed. | | `LUCE_CHUNK` | 🧪 **test/bench** Generic chunk-size knob (bench/scripts). | | `LUCE_HAS_CURL` | 🧪 **test/bench** Whether curl is available (scripts). | -| `LUCE_REQUIRED_ENV` | 🧪 **test/bench** Required-env assertion list (scripts). | | `LUCE_SERVER_VERSION` | 🧪 **test/bench** Reported server version (scripts). | ---