Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Merge upstream main (0.1.32) into b70; Intel code kept out of shared files

maxfridbec9fd9cd1d328
diff --cc docs/INTEL.md
index 072b0ed20,000000000..e8939dbee
mode 100644,000000..100644
--- a/docs/INTEL.md
+++ b/docs/INTEL.md
@@@ -1,542 -1,0 +1,528 @@@
+# Strata on an Intel Arc
+
- Strata's engine is CUDA. On an Intel Arc there are two ways to run the same model behind the same Strata
- server (OpenAI and Anthropic APIs, streaming, tool calls, MCP, the web app all unchanged):
++Strata's engine is CUDA. On an Intel Arc it runs as **Strata's own engine, ported to SYCL** (`sycl/`, the
++section "The engine itself on Intel" below), behind the same Strata server: OpenAI and Anthropic APIs, streaming,
++tool calls, MCP and the web app all unchanged. llama.cpp's SYCL backend is the comparison point in the tables (it
++runs the same GGUF at about a third of the speed).
+
- - **Strata's own engine, ported to SYCL** (`sycl/`, the section "The engine itself on Intel" below). The
- default once it is built: setup.py picks it on an Intel card when `build-sycl-aot/strata` and the
- `strata-sycl-dev` image exist.
- - **llama.cpp's SYCL backend** (`--intel-engine llama`, or when the port is not built). Simpler to set
- up, about a third of the speed.
++Everything Intel-specific lives in `sycl/`; no shared file of upstream's is changed, so upstream merges stay clean.
++`sycl/setup_intel.py` and `sycl/serve/server_intel.py` wrap upstream's `setup.py` and `serve/server.py` from
++outside.
+
+Written for and measured on an **Arc Pro B70 (32 GB)** running the Coder (IQ1_M) on Ubuntu 24.04, in a
+PCIe 3.0 x8 slot (the card trains at Gen3 x8 there; it can do Gen5 x16).
+
+## What you get (2026-10-01)
+
+| | NVIDIA (Strata engine) | Intel Arc, Strata SYCL port | Intel Arc, llama.cpp |
+|---|---|---|---|
+| models | all four | the Coder IQ1_M; the original IQ2_XS too (experts beyond VRAM in the host mirror: 58-64 tok/s) | the Coder (fits VRAM) |
+| model files | the same GGUFs | the same GGUFs + a native pack | the same GGUFs |
+| where the model lives | experts in RAM, hot ones on the card | every expert in VRAM (`--stream-experts`: no host copy), shard 2's lookup table read from the SSD by row | all of shard 1 on the card, shard 2 paged from disk |
+| RAM needed | 32-64 GB | little (23 GB is fine) | little (23 GB is fine) |
+| decode, Coder IQ1_M | 44-51 tok/s on an RTX 5070 | **78.2 tok/s** (19-token prompt, 256 greedy tokens), **75.7** after a 2,184-token prompt, 59.5 after 128K, 48.7 after 256K; 48-72 through the API | 23-25 tok/s |
+| prompt reading | ~1,870 tok/s | **780 tok/s** at 2,184 tokens, 1,189 at 40K, 934 at 128K, 784 at 256K | ~150 tok/s (424 at 105K) |
+| speculative decoding (MTP) | yes | yes (the base checkpoint's draft layer; 70-85% of drafts accepted on code) | no |
+| images | yes | not yet | not yet |
+| context | up to 262K | 256K measured, 49 tok/s decode there (`--kv-resident`: the KV in pinned host memory, the attended window in VRAM) | 131K measured ceiling |
+
+Decode speed with speculative decoding depends on the text: code drafts well, prose less so (see "Speed depends
+on the text"). The SYCL numbers are greedy runs of the engine (as in "How to run it by hand" below, 256 new
+tokens) on engine 0.1.31-sycl (2026-10-01);
+"Decode round 2" below lists what each change bought.
+
+## Setup
+
- ./setup.sh
++Build the engine and its runtime image first ("How to build it" below), then:
+
- Setup notices the Arc (no `nvidia-smi`; an Intel GPU under the `xe` or `i915` driver in sysfs), says
- so, and takes the Intel path: no CUDA toolkit. With the SYCL port built it writes a `"strata"` config for it
- (see "Serving the port" below); otherwise, or with `--intel-engine llama`, it finds a `llama-server` and writes a
- config with a `"llama"` block and a start script. The rest of this section and the next two are that llama.cpp
- path.
++ python3 sycl/setup_intel.py [setup.py's options, e.g. --model IQ2_XS --context 32768 --port 8085]
+
- Where the `llama-server` comes from, in order:
++This is upstream's `setup.py`, run with the Intel steps swapped in (it imports setup.py and replaces those steps;
++setup.py itself is unchanged). The model choice, download, pack, tokenizer, MTP draft layer and the context and KV
++questions are setup's own. What changes:
+
- 1. `--llama-server PATH` - a llama.cpp you built yourself with `-DGGML_SYCL=ON` (needs oneAPI).
- 2. `llama-server` on PATH.
- 3. A container: `ghcr.io/snailium/llama.cpp-sycl-intel-b70/llama-sycl-b70:stable`, a community SYCL
- build for Battlemage (llama.cpp 0.4.1, IntelLLVM 2026.1, AOT for bmg-g31). Needs docker and the
- `render` and `video` groups. Setup writes `start-llama.sh`, which runs it with the GPU passed
- through and the right environment. The run script starts it when nothing is answering yet.
++- **GPU check:** the Arc is found in sysfs (vendor 8086 under `xe` or `i915`) and offered through setup's AMD
++ path. That is the path that builds locally and has no images.
++- **Engine step:** it uses the SYCL build (`build-sycl-aot/strata`, run in the `strata-sycl-dev` image by
++ `sycl/serve/strata-sycl.sh`) instead of compiling CUDA or HIP.
++- **RAM rule:** this does not apply. The CUDA engine keeps every expert in RAM; the port streams them from the
++ GGUF into VRAM (`--stream-experts`), so RAM only decides the KV streaming. `--check` lists what fits by VRAM.
++- **The config:** it uses the container's paths and `"backend": "sycl"`. The VRAM reserve is 1,024 MiB up to
++ 32K and 2,048 MiB with 4,096-token prompt chunks above that. KV streaming (`--kv-resident 32768`) is on from
++ 64K up when the RAM holds the KV. A `model_switcher` or `sampling` block from an earlier config is kept.
++ `run-<model>.sh` starts `sycl/serve/server_intel.py`.
+
- Then `run-<model>.sh` (or `./setup.sh` again) starts the model. First start of a 30 GB model: about
- two minutes.
++If a future `setup.py` drops a step this relies on, it stops with a message instead of writing a wrong config.
++The models, packs and checkout must sit under the folder `strata-sycl.sh` mounts at `/work` (the one above the
++checkout, or `STRATA_SYCL_ROOT`).
+
- Two flags worth knowing on a box that already runs things: `--port N` (the default 8080 is also what
- open-webui takes; the llama-server container gets N+1) and `--host 0.0.0.0` to reach it from other
- machines (the default binds localhost only, as upstream does).
-
- ## The config
-
- ```json
- {
- "engine": "llama",
- "tokenizer": ".../packs/coder-iq1_m/tokenizer",
- "llama": {
- "url": "http://127.0.0.1:8081",
- "model": ".../Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf",
- "start": ".../start-llama.sh",
- "image": "ghcr.io/snailium/llama.cpp-sycl-intel-b70/llama-sycl-b70:stable"
- }
- }
- ```
-
- `url` attaches to a running llama-server; `start` is run first if nothing answers there. A config
- with `"exe"` and `"args"` instead spawns a native binary directly. See `serve/engine_llama.py`.
++Then `run-<model>.sh` (or `sycl/setup_intel.py` again) starts the model. The first start of a 30 GB model
++takes about two minutes. `--port N` and `--host 0.0.0.0` work as in upstream's setup.
+
+## Things that matter on this GPU
+
+- **`SYCL_CACHE_PERSISTENT` must be 0.** The persistent JIT cache segfaults on Xe2 during the first
+ compile. The start script sets it; if you run llama-server by hand, do too.
+- **The whole model goes on the card** (`--n-gpu-layers 999`), except `per_layer_token_embd.weight`,
+ the single 28.8 GB tensor of shard 2. `--override-tensor per_layer_token_embd=CPU` keeps it in host
+ memory, mmapped and paged from the SSD by row, which is how the model's authors serve it. Host RSS
+ stays around 2 GB.
+- **Thinking.** The model reasons before it answers. Strata's web app has the setting; for an API
+ client, put `{"reasoning_effort": "none"}` in `strata-<model>.shared-settings.json` next to the
+ config, or send `chat_template_kwargs: {"enable_thinking": false}` per request. Without one of
+ those a short `max_tokens` is spent entirely inside the think block and the answer looks empty.
+- **`/health` says 503 while loading**; the server polls `/props` instead.
+
+## How much context fits
+
+The architecture keeps this small: only every fourth layer is full attention (12 of 48); the other
+36 are gated-delta-net layers with a fixed-size recurrent state that does not grow with context.
+Per token, the 12 attention layers keep 2 KV heads x 256 x (K + V) at q8_0, plus the
+sparse-attention indexer's keys. **Measured: about 20 KiB per token** (VRAM grows 0.6 GB per 32k
+of context with everything else unchanged).
+
+| context | VRAM in use, model loaded | headroom on 32 GB | status |
+|---|---|---|---|
+| 32,768 | 28.4 GB | 3.5 GB | measured, the default |
+| 65,536 | 29.0 GB | 2.9 GB | measured, loads |
+| 98,304 | 29.6 GB | 2.3 GB | measured, loads |
+| 131,072 | 30.3 GB | 1.5 GB | **measured, the practical ceiling**: a 104,798-token prompt (79% of the window) read in 247 s at 424 tok/s, then answered |
+| 163,840 | ~31.0 GB | ~0.9 GB | not attempted: under the 1.2 GB safety margin |
+| 262,144 | ~32.6 GB | none | **does not fit - asking for it took the host down** |
+
+**Do not ask for more than fits.** On this driver a GPU allocation past VRAM does not fail: the xe
+driver evicts buffers into host RAM, the kernel runs out of memory, and the machine livelocks until
+its hardware watchdog resets it. A 262K request did exactly that on 2026-09-29, and llama.cpp's own
+"failed to fit params" check fired too late to prevent it. Compute the KV size first and leave
+1.5 GB free.
+
+Prompt reading gets faster with size, because the work batches better: ~150 tok/s on a 2.7k-token
+prompt, 424 tok/s on a 105k-token one. So a full 128k window costs about five minutes to read,
+not fifteen.
+
+## The engine itself on Intel: the SYCL port (`sycl/`)
+
+Everything above runs the model through llama.cpp. This is the other half: Strata's own engine - the 50 CUDA
+kernels and the host code that drives them (streams, events, graph capture, pinned memory) - built for the
+Arc with oneAPI. It is a migration of the tree, not a new backend: the engine has no backend seam to slot
+into.
+
+**Layout.** `sycl/src` and `sycl/include` mirror the tree and hold only the files the port changes; the
+SYCL build (`sycl/CMakeLists.txt`) takes every other source from the original location. No upstream file
+is edited. `sycl/include/dpct/` is the vendored SYCLomatic helper library, so the port builds without the
+migration tool.
+
+**How it was made, so it can be redone.**
+
+1. `sycl/tools/Dockerfile` - the dev image: the llama.cpp SYCL image plus SYCLomatic (`dpct` 2025.3),
+ ninja, and the CUDA 12.8 headers that `sycl/tools/get-cuda-headers.sh` pulls out of NVIDIA's pip wheels
+ (dpct parses CUDA; it needs the headers, not the toolkit).
+2. `sycl/tools/migrate.sh` - writes a compilation database for the 86 CUDA-touching translation units and
+ runs dpct over them. 85 migrate; dpct reports no line it could not migrate, and about 1,400 advisory
+ notes.
+3. `sycl/tools/fixups.py` - what dpct got wrong or could not do, as an idempotent script with a reason per
+ item. The ones that mattered:
+ - CUDA's null stream means the default stream; dpct turned it into a null `sycl::queue*`. Every
+ stream cast now goes through `strata::q_of()` (`sycl/include/strata/sycl_queue.hpp`).
+ - `__ldg((const float*) p)` came out as `*p`, reading one byte of a float scale (two sites, s_gemv).
+ - `__fadd_rn(a, b ? c : d)` lost its parentheses (two sites).
+ - the ggml lookup tables were threaded through kernel parameters with the wrong table per template;
+ they are plain `static const` arrays read from device code, as ggml-sycl does.
+ - helper headers renamed since dpct 2025.3 (`entangle`, `chunked_partition`), graph introspection and
+ `cudaGraphUpload` (no SYCL equivalents), `%globaltimer` (the stage profiler reads zeros).
+4. `sycl/tools/build.sh` - configure + build with icpx inside the image. Two compiler flags are load-bearing:
+ `-fp-model=precise` (icpx defaults to a fast FP model) and `-cl-fp32-correctly-rounded-divide-sqrt`
+ for the device compiler - the Arc's fp32 divide is not correctly rounded by default (OpenCL allows
+ 2.5 ulp), and Strata's quantizers are byte-exact against ggml through `amax / 127`. Measured: without
+ it `quantize_act_parity` has 303k mismatches, with it none.
+
+**Where it stands (2026-09-29).** The whole tree builds and links: the `strata` binary and 22 kernel
+parity tests. On the B70, 19 of the 22 pass byte-for-byte or within their tolerances; the other three
+need model fixtures (`iq_parity`, `ple_parity`) or the tensor-core kernel below (`qsa_prompt_attn`).
+
+| parity test | result |
+|---|---|
+| bf16_gemv, cvec, dequant_s2, elementwise, gdn, gr, kv_q4, kv_q8, kv_stream, qsa, quantize_act, rope, router_top10, s2_gemv, s2_gemv_q8, s_gemv, s_gemv_q8k, sampler, shared_expert | pass |
+| iq_parity, ple_parity | need fixtures (a `logs/iq_fixture` directory, a Q2_0 shard) |
+| qsa_prompt_attn_parity | needs the tensor-core kernel (below) |
+| kv_hybrid_parity (0.1.27, hybrid K8V4 KV) | appends, gathers and attention pass; its last step is that same tensor-core kernel |
+
+**The engine end to end (2026-09-29, later the same day).** It generates. Prompt "Write a Python function
+that returns the n-th Fibonacci number", greedy, 64 tokens:
+
+> `<think>` The user wants a Python function that returns the n-th Fibonacci number. Let me consider the
+> options: 1. **Recursive approach** - Simple but O(2^n) time complexity, very slow for large n. 2.
+> **Iterative approach** - O(n) time, O(1) ...
+
+Measured on the same card, same 2,185-token prompt, 64 greedy tokens (AOT build, `--spec 2`,
+`--no-prefill-borrow`), against llama.cpp's SYCL build serving the same GGUF:
+
+| | llama.cpp SYCL | Strata SYCL port |
+|---|---|---|
+| prompt reading | 138-319 tok/s | **560 tok/s** (693 at 2,000 tokens, 180 at 300) |
+| decode, suffix drafter only (`--spec 2`) | 24.2-26.0 tok/s | 20.2-20.8 tok/s |
+| decode with the MTP draft layer (`--spec 4 --mtp`) | - | **42.7 tok/s** at the 2,185-token context (81% accepted, 2.9 tokens/round); 45.3 on a short prompt |
+
+Prompt reading is where Strata's design pays (oneMKL GEMM over dequantised experts, the whole model on
+the card). Decode is at ~80%: a speculative round costs ~53 ms whatever its size and the suffix drafter
+is accepted 9% of the time, so nearly every round yields one token; `--spec 4` (16.9 tok/s) was worse
+than `--spec 2` (20.8) for that reason. The kernels themselves run at 130-160 GB/s of weights on a card
+that streams 600 GB/s (`sycl/probe/bw.cpp`, incompressible data) - the same class llama.cpp reaches -
+and five variants of the hot Q6_K matvec (lanes per row, rows per warp, unroll, 16-byte loads, software
+pipelining; `mmvq_bench`) all landed in that band. The draft source was the lever: the base
+Qwen3.8-Flash-Next checkpoint's MTP layer (`tools/mtp_fetch.py fetch`, `mtp_pack.py --experts q2_0`,
+`mtp_rt.py`; 4.9 GB downloaded, 809 MiB of VRAM) drafts for the Coder fine-tune at 87% acceptance:
+3.4 tokens per 53 ms round, 45 tok/s, the same greedy tokens. The `mtp.cpp` path ran on the first try
+under the same flags.
+
+Without AOT the runtime JIT-compiles every kernel on first use, ~47 s the first time a process runs;
+`SYCL_CACHE_PERSISTENT=1 SYCL_CACHE_DIR=<dir>` keeps that across runs (15 MB).
+
+How to run it by hand (a greedy test run, the way every number in this section was measured; inside the
+`strata-sycl-dev` image, AOT build in `build-sycl-aot/`):
+
+```
+STRATA_VERIFY_DEVICE_PLAN=1 STRATA_VERIFY_NO_HOST=1 \
+build-sycl/strata --pack <iq pack> --native <shard1> --ple-gguf <shard2> \
+ --expert-profile data/expert-profile-coder.bin --expert-cache auto --stream-experts \
+ --prefill auto --spec 4 --spec-min-p 0.5 --max-context 8192 --tokens <ids> --max-new 64 --greedy
+```
+
+- `--stream-experts` (this port): no resident host copy of the experts; every one of the 12,288 goes from
+ the GGUF into the VRAM cache through a small staging ring (`GgufExpertSource`). Upstream needs 32 GB of
+ RAM for this model; with the flag the engine runs on 23 GiB.
+- `STRATA_VERIFY_DEVICE_PLAN=1`: the GPU plans each layer itself (upstream's E-6; off by default there).
+- `STRATA_VERIFY_NO_HOST=1` (this port): the host waits for the whole window graph instead of per-layer
+ rings. Only valid with every expert resident, which is the case on a 32 GB card.
+- `--no-prefill-borrow`: the prompt path must not lend expert slots (a lent expert is served from the host
+ behind a flag the GPU does not see reliably here; long prompts hung without it).
+
+What the port had to get right beyond compiling (each is an entry in `sycl/tools/fixups.py` or a flag):
+
+- **Host-mapped flags.** Strata's decode is a GPU/CPU handshake through host-mapped memory. `volatile`
+ device loads do not bypass the caches on Intel; system-scope atomics do, and they are the only thing
+ measured to work (`sycl/probe/doorbell.cpp`, six variants). Host-to-device visibility *during* a kernel
+ stays unreliable on this platform, which is why the all-resident path waits for the window instead.
+- **Bounded spins.** A device spin that never sees its flag is not a hang of one process: the xe driver
+ times the queue out and resets the GT node by node - a window graph has 2,400 - and the card stays
+ wedged until a reboot (twice). Every spin is capped (`kSpinMax`).
+- **32-lane sub-groups.** The kernels are written for warps; dpct pinned 134 of 289 launches, the rest
+ would run at Xe2's default 16 (`-fsycl-default-sub-group-size=32`).
+- **Synchronous copies.** `cudaMemcpy` blocks; dpct's default-queue `memcpy` did not wait. With the
+ streaming ring that filled the expert cache from overwritten buffers: non-deterministic residuals, NaN by
+ layer 5. Found with the per-layer residual ladder (`STRATA_VERIFY_DEBUG=1` prints R after every layer).
+- `native_expert_parity` hand-ported: the GPU native expert kernel matches ggml's float reference on real
+ IQ1_M rows (rel 1.1e-2, the same class as the CPU path).
+
+Profiling: `sycl/tools/Dockerfile.unitrace` builds the dev image with Intel's unitrace; `unitrace -d` around
+the engine plus `sycl/rank_kernels.py` gives device time per kernel. `mmvq_bench` and `native_expert_parity
+NATIVE_BENCH=1` time the two hot kernel families in isolation (warm the clocks first: a 5 ms run measures
+the ramp, not the kernel).
+
+**After the 0.1.25-0.1.27 merge (2026-09-30, same card, same flags, AOT).** Fibonacci prompt (19 tokens),
+64 greedy tokens: decode 46.5 tok/s (85% of drafts accepted). The 2,184-token prompt: 566 tok/s prompt,
+38.3 tok/s decode (77% accepted on that text); the draft layer's prompt pass is now upstream's batched one
+(38.6 ms for 2,184 tokens, from 105 ms for 19 before it). Parity: 19 of 22, byte-exact `quantize_act` back.
+
+**Speed work, 2026-09-30 (after the 0.1.27 merge).** What moved the numbers, measured on the B70 with the
+same prompts as above (outputs identical before and after each change):
+
+| change | effect |
+|---|---|
+| every window graph and the drafter's graphs captured at load (`STRATA_WARM_GRAPHS=0`: as before) | the first request no longer pays 250-290 ms of captures |
+| the commit graph left running while the drafter's round runs on its own queue (`Verifier::commit(wait=false)` + `commit_finish`) | decode 38.3 -> 43.0 tok/s at the 2,184-token context, 46.5 -> 49.8 short |
+| upstream 0.1.29 merged (GDN recurrence pipelining, the block-scores read, sampler) | 2,184-token prompt 765 -> 792 tok/s, decode at that context 43.1 -> 45.2 |
+| the draft layer's batched prompt pass takes prompts under 64 rows (it fell back to per-6-token graphs) | its prompt cost on 19 tokens 106 -> 16 ms |
+| one device module per kernel (`-fsycl-device-code-split=per_kernel`) | the first launch in the prompt path (the embedding gather) 245 -> 1 ms |
+| the expert dequant writes each thread's run of FP16 values as one vector store (it wrote them one 2-byte store at a time) | dequant per expert 0.085 -> 0.030 ms; prompt 496 -> 575 tok/s at 2,184 tokens, 720 -> 841 at 8,000 |
+| SWAR sign compare/subtract in the expert dots, a local-memory resident-plan kernel, a split-K fused down kernel (bit-identical to the single-token one) | parity-clean, no measurable decode change; kept |
+| the PLE row reader's default queue depth 16 -> 64 blocking O_DIRECT threads (`STRATA_IO_THREADS`; 128 and 256 change nothing: the drive tops out near 85k IOPS on the 27k random 4 KB reads a 2,184-token prompt needs) | the rows of that prompt 466 -> 330 ms |
+| a short first prompt chunk (`STRATA_PREFILL_FIRST`, default 256 tokens) so the GPU starts while the remaining rows are still being read | 2,184 tokens: 711 -> 765 tok/s, 8,000: 857 -> 986; time to first token about 150 ms less. The chunk boundary moves rounding in the expert GEMMs, so a long greedy continuation can diverge late (token 45 of 64 on the test prompt) |
+
+Draft policy sweep (2,184-token prompt, 128 tokens): windows of 6 (`--spec 4`) at 41.6-43.5 tok/s; `--spec 2`
+33.6, `--spec 6` 35-37; `--spec-min-p` 0.3-0.7 within noise. Profiles (unitrace, `strata-sycl-dev:metrics` with
+Intel's metrics libraries and `dev.xe.observation_paranoid=0`): the expert dot kernels are ALU-bound (77% XVE
+active), the dense projections memory-latency bound (92-128 GB/s at 84-93% occupancy), a decode round is 80-85%
+kernel time and ~5 us of launch gap per node over 2,400-2,600 nodes.
+
+**XMX.** oneMKL's FP16 GEMMs already run on the XMX units (30-60 TFLOP/s in `xmx_gemm_bench`); the prompt path is
+bound by the dequant that feeds them, not by the products. Two joint_matrix kernels were written and are correct
+but lose to the existing paths on this card, so both stay opt-in: `xmx_gemm_iq` (a fused dequant + GEMM straight
+from the quantized rows, 4-5x slower than dequant + oneMKL) and `qsa_prompt_attn_xmx` (the port of the mma.sync
+prompt attention; `qsa_prompt_attn_parity` passes at 1e-6 of scale, 3x slower than the FP32 fallback per chunk;
+`STRATA_PROMPT_ATTN_XMX=1`). Where the prompt time goes now (2,184 / 8,000 tokens): dequant 28% / 27%, GEMMs
+22% / 20%, the per-layer host grouping 9.5% / 9%, attention 7% / 14%, embeddings + PLE rows 13% / 5%.
+
+A trap worth knowing: with a native pack `--prefill-until N` does not feed the rest of the prompt through the
+token loop (it is skipped for native packs), so the tokens after N are dropped and the model free-runs. Compare
+output tokens between paths, never only timings.
+
+**An 80,000-token prompt (2026-09-30).** Where the time goes changes completely at this scale:
+
+- **The VRAM plan.** `--expert-cache auto` fills the card down to `--vram-reserve-mib` *before* the KV state
+ (about 1 GB in INT8 at 81,920 cells) and the prompt chunk buffers (about 2 GB at `--prefill 8192`) exist. With
+ the 1,536 MiB default that put 30.95 of the B70's 32.6 GB in use, the driver started migrating buffers and the
+ run never finished. `--max-context 81920 --kv int8 --vram-reserve-mib 3072 --prefill 4096` peaks at 28.8 GB.
+ (80k ids also exceed Linux's 128 KB single-argument limit: `--tokens-file`.)
+- **Streamed experts.** The reserve costs cache slots (10,348 of 12,288 at 3 GB), and the prompt path streams the
+ missing experts from the GGUF for every chunk. Two port bugs sat on this path and are fixed: the stream plan
+ held `GgufExpertSource::blob()` pointers across ~1,900 reads of a 512-slot ring (so blobs were overwritten
+ before they were copied: the 75 s / 1,065 tok/s measured first was computed partly with the wrong experts), and
+ the stream-all walk hangs on this card in its first large chunk (the copy engine stops on a barrier). The stager
+ threads now read the blobs themselves, and the port uses the per-layer routed-only walk (`STRATA_PREFILL_RING=8`
+ upstream, the port's default; `STRATA_PREFILL_STREAM_ALL=1` restores the other for debugging).
+- **Correct result: 80,000 tokens in 101 s = 790 tok/s.** GPU time: expert down GEMM 26.0 s, attention 15.4 s,
+ dequant 12.7 s, QSA block selection 9.3 s (0.2 s at 8k: it scans every block of the context per query), gate/up
+ GEMM 8.9 s, gather 6.1 s, the per-layer grouping sync 5.2 s, GDN recurrence 4.8 s. The PLE rows are free at this
+ scale (97.6% row-cache hits).
+- **Decode after such a prompt, and the fix.** Without lending cache slots to the prompt path (`--no-prefill-borrow`,
+ which the port used from the start) the reserve evicts ~1,900 experts for good and decode after the prompt runs at
+ 2 tok/s. Borrowing lends ~940 slots to the prompt path and refills them in about a second afterwards: 80,000
+ tokens in 75 s = **1,062 tok/s, decode 35-40 tok/s** after it, at `--vram-reserve-mib 2048 --prefill 4096`.
+ It costs ~1 s on short prompts (2,184 tokens: 610 vs 792 tok/s), so the port borrows by default only above a
+ 32K context (`--prefill-borrow` / `--no-prefill-borrow` decide explicitly).
+
+**Long contexts (2026-10-01, engine 0.1.31-sycl, setup's flags: `--kv-resident 32768 --vram-reserve-mib 2048
+--prefill 4096`, prompt-slot borrowing off - see the 0.1.31 merge below).** Same text repeated to length, then 256
+greedy tokens:
+
+| context | KV | prompt | decode after | peak VRAM | experts in the host mirror |
+|---|---|---|---|---|---|
+| 128K | int8 | 934 tok/s (137 s) | **59.5 tok/s** | 29.7 GB | 1,040 (2.0 GB) |
+| 128K | q4_0 | 887 tok/s (144 s) | 53.4 tok/s | 29.3 GB | 1,073 |
+| 128K | k8v4, KV in VRAM | **1,026 tok/s** (125 s) | 54.4 tok/s | 29.5 GB | 1,523 (2.9 GB) |
+| 256K | int8 | 784 tok/s (327 s) | **48.7 tok/s** | 29.7 GB | 1,288 (2.5 GB) |
+| 256K | q4_0 | 763 tok/s (336 s) | 43.2 tok/s | 29.6 GB | 1,188 |
+| 256K | k8v4, KV in VRAM | 838 tok/s (305 s) | 42.3 tok/s | 29.5 GB | 2,327 (4.5 GB) |
+
+Before the merge, with borrowing (every expert in VRAM): 128K int8 856 / 66.1, 256K int8 740 / 54.1 tok/s. Without
+borrowing the prompt buffers keep their own VRAM, ~1,000-2,300 experts move to the pinned host mirror (planned item
+2) and decode pays ~10-17% for reading them over PCIe; the prompt is 4-9% faster.
+
+KV streaming (`--kv-resident`) keeps the whole KV in pinned host memory and only the attended window in VRAM, so
+the KV pushes no experts out; setup.py turns it on from 64K up and keeps INT8 (the faster of the
+two at every size here). Without it the KV pushes experts out and decode after the prompt fell to 4-9 tok/s at
+128K-256K (2026-09-30). `--kv k8v4` does not support streaming yet: setup keeps its KV in VRAM, which pushes up to
+more experts out; those come from the pinned host mirror over PCIe (planned item 2), so decode holds at 42 tok/s at
+256K (it was 3.8 before the mirror). k8v4 reads prompts fastest (no streaming copies) and works through the FP32
+attention fallback (its dedicated prompt kernel is the XMX one below).
+
+**XMX prompt attention v2.** 64-cell chunks, vector-packed K^T and V, hi+lo Q in one accumulator per scale group,
+one accumulator update per chunk: 1.4-1.5x faster than v1 and correct in all modes (`qsa_prompt_attn_parity`,
+and `kv_hybrid_parity` passes completely with it), but still ~2x slower than the FP32 fallback (13.4 vs 5.5 ms per
+chunk, INT8, 32K context). This attention is gather-bound: each query position selects its own ~2,000 cells, so
+the K/V fetch dominates and only 12 of the 16 matrix rows are real heads. Opt-in: `STRATA_PROMPT_ATTN_XMX=1`
+(64-cell chunks, 120 KB of local memory) or `=32`.
+
+**XMX v2 in the full matrix, and why a grouped kernel is not next (2026-09-30).** With `STRATA_PROMPT_ATTN_XMX=1`
+(stage timing on, ~8-10% overhead) the long prompts run 23-33% slower than with the FP32 attention: 128K int8 666 vs
+960 tok/s, k8v4 596 vs 983; 256K k8v4 506 vs 752, int8 536 vs 718 (q4_0 does not use the XMX kernel). The obvious
+fix, gathering the union of neighbouring positions' cells once, depends on how much their selections overlap.
+Measured on the last chunk of an 80K prompt (first QSA layer, `STRATA_DUMP_SEL=<file>`): the union of 8 consecutive
+positions is 3.3x one position's 2,051 cells (16: 5.1x), and only 12% of a selection is shared by all 8. Grouping
+would cut the K/V gather to ~40% but multiply the arithmetic by 3-5x: at best 5-8 s of an 80K prompt. Not built.
+
+**Serving the port (2026-09-30).** `serve/server.py --engine strata` runs the SYCL engine unchanged through
+`sycl/serve/strata-sycl.sh`, an `exe` that starts the binary inside the oneAPI runtime image with the serve pipes
+attached (paths in the config's `args` are the container's, the data root mounted at `/work`). A config:
+
+```json
+{"engine": "strata", "exe": "<repo>/sycl/serve/strata-sycl.sh",
+ "args": ["--pack", "/work/pack", "--native", "<shard 1>", "--ple-gguf", "<shard 2>",
+ "--expert-profile", "data/expert-profile-coder.bin", "--expert-cache", "auto", "--stream-experts",
+ "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", "/work/mtp/rt",
+ "--max-context", "32768", "--kv", "int8", "--vram-reserve-mib", "1024"],
+ "sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "repetition_penalty": 1.05}, ...}
+```
+
+Measured through the OpenAI API with those sampling defaults: 36 tok/s decode on a first turn, 33 on a follow-up
+(which reuses the conversation's cached prompt), against 24-26 for llama.cpp on the same card. After the decode work
+(2026-10-01 build): 48-72 tok/s on a ~190-token answer, prompt included (the first request after a start is the slower
+one); 55-59 tok/s over 5,000-18,000-token answers on the 2026-09-30 build. The reserve matters:
+with `--stream-experts` there is no host copy of the experts, so any expert left out of VRAM is read from the SSD
+and computed on the CPU whenever it is routed. At 1,536 MiB the cache came up 128 experts short and decode fell to
+5-10 tok/s; 1,024 MiB fits all 12,288 with 2 GB of VRAM still free.
+
- **The Monitor tab on Intel.** `serve/telemetry.py` reads the Arc through sysfs (temperature, power and its cap,
- the PCIe link the card trained at) and, for load and VRAM, from `/run/gpustat.json`: xe reports those per client in
- `/proc/*/fdinfo`, which only root can read, so a small root sampler writes them (`tools/intel/gpustat.py`, install
- with its `gpustat.service` as its header says). A run config may also name a `model_switcher` (an RPC taking
- `{"mode": m}`) for a host that swaps models on one card: the web app then shows a Model menu.
++**The Monitor tab on Intel.** `sycl/serve/server_intel.py` is `serve/server.py` with two additions made at run
++time:
+
- `setup.py` writes this config by itself on an Intel card once the SYCL engine is built (`build-sycl-aot/strata`
- and the `strata-sycl-dev` image): a native pack, the MTP draft layer (from an existing `mtp-q2_0.gguf` without the
- 5 GB download), the container's paths, the reserve (1,024 MiB up to 32K, 2,048 with 4,096-token chunks above),
- INT8 KV with `--kv-resident 32768` from 64K up (when the RAM holds the KV), and the `sampling` block of an earlier
- config kept. `--intel-engine llama` keeps llama.cpp.
++- **GPU readings.** When NVML has no card, it plugs `sycl/serve/xe_telemetry.py` into `serve/telemetry.py`'s
++ `gpu_reader`. That reads the Arc through sysfs (temperature, power and its cap, the PCIe link the card
++ trained at). Load and VRAM come from `/run/gpustat.json`: xe reports them per client in `/proc/*/fdinfo`,
++ which only root can read, so a small root sampler writes them (`sycl/tools/gpustat.py`; install it with its
++ `gpustat.service` as its header says).
++- **A Model menu.** A run config may name a `model_switcher` (an RPC taking `{"mode": m}`) for a host that swaps
++ models on one card. The web app's header then gets a Model menu (`sycl/serve/web/switcher.js`, injected into
++ the page).
+
+**Speed depends on the text.** Decode with speculative decoding tracks how often the draft layer guesses right.
+The served engine at 32K context: 45-51 tok/s on the test prompt (continuing a Fibonacci function, 77-85%
+of drafts accepted), 30-39 tok/s on a chat answer with prose (55-72%); sampling and the repetition penalty cost
+nothing measurable. The engine used to abort at exit in serve mode (a queue wait in a destructor after the
+runtime's teardown began); it now exits directly once its requests are done.
+
+**Planned (2026-09-30), in order.** Ranked by payoff on this card; the first three were taken first.
+
+1. Expert dot products on XMX in integer mode: a decode window (up to 6 tokens) fits one INT8 DPAS (1-8 rows), the
+ i-quant grids decode to small integers, the activations are already INT8. Today: scalar dp4a, ALU-bound (77%).
+ **Parked**: three `joint_matrix` versions (opt-in `STRATA_EXPERT_XMX=1`, do not enable) were 1.4x and 2-3x slower
+ than dp4a, and the third (B filled in place with `joint_matrix_apply`) hung the GPU. At 1-6 rows the grid decode
+ and the packed-B layout cost more than the DPAS saves.
+2. Experts missing from VRAM read from pinned host memory over PCIe instead of the SSD (the 256K decode collapse).
+ **Done**: at start-up every expert without a VRAM slot is read into a pinned host mirror (`STRATA_MIRROR_MIB`, by
+ default free RAM less 4 GiB), and the device-built verify plan points the expert kernels straight at it. Before,
+ that plan dropped non-resident experts, so output with misses was wrong. Forced test (`--expert-cache 8000`,
+ 1,879 experts / 3.6 GiB out of VRAM): decode 2.6 -> 40.9 tok/s (full cache 43.3), prompt 451 -> 640 tok/s
+ (776), output tokens identical to the full-cache run. About 3.6 GiB of VRAM can go to context for ~6% of decode.
+3. KV streaming (`--kv-resident`) from 64K up: only the attended window of the KV in VRAM. **Done**: 256K decodes at
+ 31 tok/s (from 4-5).
+4. QSA block selection on XMX: every query against every pooled block, a dense product that grows with the context.
+5. The hot decode kernels re-tuned for Xe2's native 16-wide sub-groups (twice the registers per thread).
+ **Tried, no gain**: SIMD16 builds of the multi-column mmvq and the wide Q6_K kernel (`STRATA_MMVQ_SG`: 16 all,
+ 1 IQ4_XS only, 2 short outputs only; default 32). Alone (`mmvq_sg_bench`) SIMD16 is up to 1.45x faster on IQ4_XS
+ and 1.3x on the 640-row shared-expert projections, 10-25% slower on the large K-quant ones; in the engine no
+ setting beats SIMD32 beyond run-to-run noise (SIMD32 itself lands at 39 or 45 tok/s). Output tokens identical.
+ The same bench shows the real headroom: the dense decode kernels stream 100-280 GB/s of a 608 GB/s card
+ (Q6_K, the most common type, ~146 GB/s at 2-4 columns).
+ **Found and fixed: misaligned loads.** A Q6_K block is 210 bytes, so every block's `ql`/`qh` runs start only
+ 2-byte aligned, and the B70 splits a misaligned 16-byte load into pieces. The same weights repacked at a
+ 224-byte stride ran 2.3-4.7x faster (`q6k_align_bench`). Without changing the layout, the wide Q6_K kernel now
+ does two aligned 16-byte loads and a shift (`load16_a2`; both stay inside the block) and takes every Q6_K
+ shape and window width (it used to be gated to n_out >= 4096, 1-4 columns): 2560->10240 at 1/2/4/6 columns
+ 160/145/141/101 -> 493/432/331/273 GB/s, the 248K-row head 150 -> 407 GB/s at 1 column. Output tokens
+ identical. **Coder decode 44.9 -> 54 tok/s** (2k prompt, greedy). `STRATA_MMVQ_A2=0` restores the old path.
+ Still misaligned: IQ4_XS (136 B, 8-aligned, ~100 GB/s), IQ4_NL (18 B), Q8_0 (34 B); Q4_K/Q5_K are aligned
+ but use 4-byte loads in the multi kernel (230-280 GB/s).
+
+**Decode round 2 (2026-09-30), from a unitrace of 256 decoded tokens.** Each step measured on its own, 19-token prompt,
+256 tokens, two runs each, output tokens identical throughout:
+
+| | decode |
+|---|---|
+| after the Q6_K alignment fix | 53.9 tok/s |
+| + `resident_plan` grouping in parallel (thread 0 alone took 73 us per layer, ~3.5 ms a round) | 57.1 |
+| + the GR down kernel reads the activations directly (the 60 KB SLM tile per group capped occupancy) | 58.7 |
+| + wide 16-byte-load kernels for Q4_K, Q5_K, IQ4_XS (codebook in registers) | 62.6 |
+| + wide kernels for Q8_0 (MTP dense, shexp down of layer 0) and IQ4_NL (shexp down); Q6_K's activation loads aligned | 65.6 |
+| + the GR down projection sliced by columns (each group stages one 128-column slice of xn, 4 lanes per row) + a fixed-order reduce | 70.6 |
+| + IQ4_NL expert dots (the down projection in 39 of 48 layers): codebook in registers, weights as aligned 4-byte loads, bitwise the same ints (2026-10-01) | 76.1 |
+| + GR norm per (token, stream), bitwise the same; aligned weight loads in the IQ3_XXS/IQ3_S/IQ2_S gate/up dots | **77.9** |
+
+The last step changes the output: identical for 146 tokens, then a near-tie after a comma goes the other way (the new
+kernels sum in a different order). Q8_0 kernels 4-6x (189 -> 31 us at 2560 x 10240, 2 columns), IQ4_NL 640 -> 2560
+28 -> 6.6 us. The aligned-load helper only loads its second chunk when the address is unaligned, so it never reads a
+16-byte chunk without a needed byte and cannot cross a page at the end of an allocation. `STRATA_MMVQ_WIDE_32=0`
+restores the old Q8_0/IQ4_NL kernels. The sliced GR down kernel (GR read 108.6 -> 76.5 us at 6 tokens, sums equal to
+~1e-7) flips that near-tie back: its output is the original one. `STRATA_GR_DOWN_SLICED=0` restores the direct kernel.
+
+Kernel level: IQ4_XS 107 -> 323 GB/s at 2 columns (61 -> 212 at 6), Q4_K/Q5_K 1.3-1.6x; the GR read 135 -> 110 us at
+6 tokens (bitwise equal). Switches to the old paths: `STRATA_PLAN_PARALLEL=0`, `STRATA_GR_DOWN_DIRECT=0`,
+`STRATA_MMVQ_WIDE_K=0`. (`iq_parity` reports 10 "missing fixture" failures with and without the change: the oracle
+fixtures are not in the port's tree.)
+
+**Two-speed runs, explained (2026-09-30).** Identical greedy runs decode at either ~45 or ~39 tok/s. A per-gather
+trace of the PLE reader (`STRATA_PLE_TRACE=1`) shows the slow runs pay one 226 ms PLE read stall in the first
+decode round, after the window graphs are captured; every other read and round matches the fast runs. Prompt time
+plus decode time is the same in both modes (4.95-5.17 s): the stall lands either in the prompt's PLE wait or in the
+first decode round, so it is a once-per-process cost, not lost throughput. Ruled out: NVMe APST, the I/O scheduler
+(`none`), CPU starvation (93% idle during decode), I/O thread count. Compare runs on time to first token + decode.
+6. INT8 prompt GEMMs: experts dequantized to INT8, oneMKL/oneDNN INT8 on XMX (half the dequant bytes, 2x rate).
+7. Fewer graph nodes per decode round (~2,500 at ~5 us): norm+rope, scores+top-k, gate+quantize fused.
+8. Wider speculation (two draft branches per verify window): the kernels are latency-bound, so it is nearly free.
+9. A model bigger than VRAM: the original Qwen3.8-Flash-Next IQ2_XS (35.5 GB of experts; the same path suits Q2_0
+ and Swift 1.5) on the B70 with 23 GB of RAM. ~24 GB of experts in VRAM, the rest (~10-12 GB) in the pinned host
+ mirror the device plan reads over PCIe (item 2). The port has the IQ2_XS/IQ3_XXS/Q2_0 expert kernels. Open: whether
+ a 10+ GB pinned mirror fits beside everything else in 23 GB, and decode with that share of experts on a Gen3 x8
+ link (3.6 GB mirrored measured 40.9 tok/s; expect less). Needs the 68 GB download.
+ **Done (2026-10-01)**: shard 1 downloaded (39.2 GB; shard 2 is byte-identical to the Coder's, so a hard link),
+ a native pack (`tools/iq_pack.py`, 6 s), the original model's expert profile, the same MTP draft layer. 18,329 of
+ 24,576 experts in VRAM (24.6 GiB), 6,247 in the pinned host mirror (8.4 GiB, 9 s to fill), host RAM never below
+ 12 GB free. **Decode 50.8 tok/s** on the 19-token prompt and **60.6** after 2,184 tokens, prompt 549 tok/s;
+ coherent, correct answers on both. Q2_0 and Swift 1.5 (similar size) should behave the same; IQ3_XXS/IQ3_S
+ (43-50 GB of experts) would need 19-26 GB mirrored, more than 23 GB of RAM allows.
+
+**Keeping up with upstream.** A merge of upstream `main` into `b70` leaves the copies in `sycl/` behind
+wherever upstream touched a file they mirror. They are refreshed by re-migration, not by hand (done for
+0.1.25-0.1.27, 2026-09-30):
+
- 1. Merge upstream into `b70` and resolve `setup.py` (the Intel path lives beside upstream's AMD one).
++1. Merge upstream into `b70`. No shared file should conflict: the Intel code is all in `sycl/`. Then check that
++ `sycl/setup_intel.py --check` and `sycl/serve/server_intel.py --engine mock` still run against the new
++ setup.py and server.py.
+2. Migrate the *old* upstream tree (a `git archive` of the pre-merge commit) with `migrate.sh` into
+ `sycl-base`, and the merged tree into `sycl-new`; about 3 minutes each in the dev image.
+3. `sycl/tools/normalize.sh <dir> <commit>` on both: dpct's file names, the unchanged files, the
+ message serials, then `fixups.py`. Two runs of dpct on the same source now differ only in the kernel
+ name hashes it generates.
+4. For every file present in both: `git merge-file sycl/F sycl-base/F sycl-new/F`. Files upstream did not
+ change are left alone. Copies dpct never produced (`verify.cpp`, `mtp.cpp`, `remote_experts.cpp`
+ include no CUDA header directly) take upstream's diff by hand; new parity tests are copied in and
+ listed in `sycl/CMakeLists.txt`.
+5. A fixup whose pattern upstream changed shows up as a compile error (the PTX gate became an `#elif`
+ under upstream's `__HIPCC__` guard); extend the fixup, re-run it, rebuild.
+
+**The 0.1.31 merge (2026-10-01).** Upstream 0.1.29 -> 0.1.31 (132 commits) by the steps above: 45 migrated files
+changed for real (27 more only in dpct's kernel-name hashes), 38 conflicts resolved, verify.cpp/mtp.cpp/
+conversation_state.cpp ported by hand. A symbol audit (the port's feature identifiers counted before and after) is
+part of the procedure now: it caught a dropped mirror hook and four doorbell waits that had lost their spin bound
+(upstream renamed the loops; `fixups.py` covers both spellings). What the merge needed beyond conflicts:
+
+- **The expert kernels.** Upstream sends the i-quant experts to new multi kernels (one warp per row, 8 rows a
+ group); the port's grid is sized for its own kernels (8 lanes a row, 32 rows a group), so only a quarter of each
+ expert's rows were written and the output was end-of-text tokens. The port's kernels stay the default (they also
+ serve upstream's new Q4_K/Q5_K/Q5_1/Q8_0 experts); `STRATA_EXPERT_SPLIT=1` runs upstream's, with their grid.
+- **Prompt-slot borrowing hangs** in the first chunk of any prompt with it on (40K, 128K; GPU busy, no chunk ends)
+ since upstream's borrow rework. Off by default on SYCL (`--prefill-borrow` opts in); long prompts are faster
+ without it, decode after them ~10-17% slower (the table above). Open.
+- **Upstream's new tests found three dpct mistranslations from the first migration.** dpct writes `__fadd_rn(a, b)`
+ as `a + b` without parentheses, so `__fadd_rn(sum, c ? x : y)` became `sum + c ? x : y` (replaced, not added): in
+ the native QSA indexer's per-token pooled key (the decode path: blocks completed while generating got wrong
+ pooled keys; prompt blocks come from the batched kernel and were right), in the native QSA scores (an opt-in
+ path) and in the s2 activation rounding (every value 0; the Q2_0 s2 pack, unused here). Fixed, and `fixups.py`
+ now parenthesises. `qsa_parity`'s batch-vs-sequential test passes; decode output after long prompts changed.
+- **Upstream's new kernels against the port's on the B70** (decode tok/s, Coder 19 / 2,184-token prompts, IQ2_XS
+ 19): port defaults 78.1 / 75.7 / 58.6; `STRATA_EXPERT_SPLIT=1` 65.6-69.5 / 67.2 / 49.1 (-11 to -16%);
+ `STRATA_GR_V3=1` 73.2 / 72.4 (-4 to -6%). Both stay opt-in.
+- **Lanes per row of the port's expert kernels** (`STRATA_GU_LANES` / `STRATA_DOWN_LANES`, 4/8/16/32 at run time):
+ gate/up 8 or 16 x down 4 or 8 all decode in 37.7-38.6 ms per verify round (2 runs each, Coder, both prompts); tok/s
+ differences between them are draft acceptance (each split rounds differently). The default (8 / 8) stays.
+- **Speed after the merge:** Coder 78.2 / 75.7 tok/s (as before), IQ2_XS 58.6 / 64.2 (from 50.8 / 60.6).
+- **Still failing:** `iq_multi_parity` on IQ2_XS (type 17: the port's mmvq disagrees with the reference, old and new
+ kernel alike; no model here uses it), `s2_expert_grouped_parity` (the s2 path), `kv_hybrid_parity`'s last step
+ (needs the unported tensor-core prompt kernel). `ple_parity` and `native_expert_parity` need model files.
+
+**Not ported yet (2026-10-01).**
+
+- Three kernels carry inline PTX (`mma.sync` tensor-core matrix ops, `ldmatrix`, `cp.async`):
+ `qsa_prompt_attn`, `qsa_select`'s block scores, `native_qsa_score`. The SYCL build takes the "older card"
+ fallback the CUDA build uses below sm_80. `qsa_prompt_attn` also has an XMX version (`joint_matrix`, opt-in
+ `STRATA_PROMPT_ATTN_XMX=1`): correct, but slower than the fallback (see "XMX prompt attention v2").
+- The ggml MMQ prefill path (`moe_mmq.cu`) needs llama.cpp's ggml-cuda sources; not built.
+- AOT device code is what runs: `AOT=bmg-g31 BUILD_DIR=.../build-sycl-aot` (the JIT build costs ~47 s of
+ compiling on the first window).
+
+## Not done
+
+- Images, on both Intel engines. Strata's vision path encodes with `strata-vision` into embeddings the CUDA
+ engine reads; neither the SYCL port nor the llama.cpp config wires it yet.
+- Speculative decoding on the llama.cpp path (the GGUF carries no draft layer llama.cpp can use). The SYCL
+ port has it (MTP draft layer, `--mtp`).
+
+## Measured, 2026-10-01, Arc Pro B70, Coder IQ1_M, 32K context, INT8 KV: the SYCL port (engine 0.1.31-sycl)
+
+| | |
+|---|---|
+| decode | 78.2 tok/s on a 19-token prompt, 75.7 after a 2,184-token prompt (256 greedy tokens, MTP + suffix drafts) |
+| prompt | 780 tok/s on 2,184 tokens; 934 tok/s at 128K, 784 at 256K |
+| through the API | 48-72 tok/s on a ~190-token chat answer, prompt included (the first request after a start is the slower one) |
+| VRAM | all 12,288 experts resident, ~1.9 GB free with everything loaded (`--vram-reserve-mib 1024`) |
+| RAM | no host copy of the experts (`--stream-experts`) |
+
+## Measured, 2026-09-29, Arc Pro B70, Coder IQ1_M, 32K context, q8_0 KV: llama.cpp
+
+| | |
+|---|---|
+| load | ~100 s |
+| VRAM | 28.4 of 32 GB |
+| decode | 23-25 tok/s; GPU 92% busy at 165 W, CPU idle |
+| prefill | 149 tok/s on a 2,701-token prompt; 424 tok/s on a 104,798-token prompt at 131k context |
+| quality | correct code on every test; matches the NVIDIA path token for token in spirit, not measured |
diff --cc sycl/.gitignore
index 000000000,000000000..d73108ee7
new file mode 100644
--- /dev/null
+++ b/sycl/.gitignore
@@@ -1,0 -1,0 +1,4 @@@
++# dpct output that is not part of the port (tools/migrate.sh)
++dpct_report.*
++**/*.yaml
++migrate.log
diff --cc sycl/serve/server_intel.py
index 000000000,000000000..819a5c2c4
new file mode 100644
--- /dev/null
+++ b/sycl/serve/server_intel.py
@@@ -1,0 -1,0 +1,132 @@@
++"""serve/server.py for an Intel Arc: the same server, with the Intel pieces added from outside.
++
++ python sycl/serve/server_intel.py --engine strata --config strata-<model>.json --port 8080 [...]
++
++Every argument is serve/server.py's. Nothing in serve/ is edited (the SYCL port keeps out of the shared files so
++upstream merges stay clean); this wrapper adds, at run time:
++
++ - the Monitor tab's GPU readings on an Intel Arc (sycl/serve/xe_telemetry.py) when no NVIDIA card answers;
++ - a model menu in the web app's header, for a host that swaps models on one GPU: the config names the RPC that
++ does the swap as "model_switcher" (it takes {"mode": m} and answers {"mode", "up", "starting", "choices",
++ "urls"}); the menu offers the models served on this server's port. Without that key nothing changes.
++"""
++from __future__ import annotations
++
++import json
++import sys
++import urllib.parse
++import urllib.request
++from pathlib import Path
++
++HERE = Path(__file__).resolve().parent
++ROOT = HERE.parent.parent
++sys.path.insert(0, str(ROOT))
++sys.path.insert(0, str(HERE))
++
++import serve.server as S # noqa: E402
++import serve.telemetry as T # noqa: E402
++from xe_telemetry import _XeGpu # noqa: E402
++
++
++def install_xe_reader():
++ """telemetry.gpu_reader -> the xe reader when NVML has no card and an Intel Arc is there."""
++ orig = T.gpu_reader
++
++ def gpu_reader(index=0, amd=False):
++ g = orig(index, amd)
++ if g.ok():
++ return g
++ xe = _XeGpu(index)
++ return xe if xe.ok() else g
++
++ T.gpu_reader = gpu_reader
++
++
++def model_switcher(url: str, port, model, mode: str = "") -> dict:
++ """The host's model swapper: the models it serves on THIS port, which one holds the card, whether one is loading.
++ With `mode`, asks for that one first; this server is then usually the one stopped, so the web app waits for
++ /health to name the new model."""
++ try:
++ body = json.dumps({"mode": mode} if mode else {}).encode()
++ req = urllib.request.Request(url, body, {"Content-Type": "application/json"})
++ with urllib.request.urlopen(req, timeout=10) as r:
++ res = json.load(r)
++ st = res.get("result", res)
++ except (OSError, ValueError) as e:
++ return {"enabled": True, "error": f"the model switcher did not answer ({e})"}
++ urls = st.get("urls") or {}
++ mine = {k: v for k, v in (st.get("choices") or {}).items()
++ if not urls or str(urllib.parse.urlsplit(str(urls.get(k, ""))).port) == str(port)}
++ return {"enabled": True, "mode": st.get("mode"), "up": st.get("up"), "starting": st.get("starting"),
++ "choices": mine, "model": model}
++
++
++def install_switcher(argv):
++ """Wraps make_handler: GET/POST /switcher, the menu's script and style, and the index page that loads them."""
++ def arg(name, default=None):
++ return argv[argv.index(name) + 1] if name in argv and argv.index(name) + 1 < len(argv) else default
++
++ try:
++ cfg = json.loads(Path(arg("--config")).read_text(encoding="utf-8-sig")) if arg("--config") else {}
++ except (OSError, ValueError):
++ cfg = {}
++ url = cfg.get("model_switcher")
++ if not url:
++ return
++ port = arg("--port", "8080")
++ web = HERE / "web"
++ types = {".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8"}
++ make_handler = S.make_handler
++
++ def make(svc):
++ base = make_handler(svc)
++
++ class Handler(base):
++ def _send(self, body: bytes, ctype: str):
++ self.send_response(200)
++ self.send_header("Content-Type", ctype)
++ self.send_header("Cache-Control", "no-cache")
++ self.send_header("Content-Length", str(len(body)))
++ self.end_headers()
++ self.wfile.write(body)
++
++ def do_GET(self):
++ path = self.path.split("?")[0].rstrip("/")
++ if path == "/switcher":
++ if self._authorized():
++ self._json(200, model_switcher(url, port, svc.model))
++ return
++ if path.startswith("/sycl-web/"):
++ f = web / path[len("/sycl-web/"):]
++ if f.parent != web or f.suffix not in types or not f.is_file():
++ self._json(404, {"error": {"message": "not found"}})
++ return
++ self._send(f.read_bytes(), types[f.suffix])
++ return
++ if path == "":
++ page = (ROOT / "serve" / "web" / "index.html").read_text(encoding="utf-8")
++ page = page.replace("</head>", '<link rel="stylesheet" href="sycl-web/switcher.css">\n</head>', 1)
++ page = page.replace("</body>", '<script src="sycl-web/switcher.js"></script>\n</body>', 1)
++ self._send(page.encode("utf-8"), "text/html; charset=utf-8")
++ return
++ super().do_GET()
++
++ def do_POST(self):
++ path = self.path.split("?")[0].rstrip("/")
++ if path == "/switcher":
++ if not self._authorized():
++ return
++ req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
++ self._json(200, model_switcher(url, port, svc.model, str(req.get("mode") or "")))
++ return
++ super().do_POST()
++
++ return Handler
++
++ S.make_handler = make
++
++
++if __name__ == "__main__":
++ install_xe_reader()
++ install_switcher(sys.argv[1:])
++ sys.exit(S.main())
diff --cc sycl/serve/web/switcher.css
index 000000000,000000000..48a736fdf
new file mode 100644
--- /dev/null
+++ b/sycl/serve/web/switcher.css
@@@ -1,0 -1,0 +1,7 @@@
++/* the model menu (sycl/serve/server_intel.py: a host that swaps models, config model_switcher) */
++.model-switch{display:flex;align-items:center;gap:var(--st-s-2);font-size:var(--st-fs-sm);color:var(--st-ink-muted)}
++.model-switch[hidden]{display:none}
++.model-switch select{font:inherit;color:var(--st-ink);background:var(--st-surface-2);border:1px solid var(--st-line);
++ border-radius:var(--st-r-md);padding:4px 8px;max-width:340px}
++.model-switch select:focus{outline:2px solid var(--st-focus);outline-offset:1px}
++@media (max-width:640px){.model-switch__k,.model-switch__s{display:none}.model-switch select{max-width:150px}}
diff --cc sycl/serve/web/switcher.js
index 000000000,000000000..9096ab9a6
new file mode 100644
--- /dev/null
+++ b/sycl/serve/web/switcher.js
@@@ -1,0 -1,0 +1,60 @@@
++// The model menu (sycl/serve/server_intel.py): a host that swaps models on one GPU (config model_switcher) offers
++// the ones served on this port. Switching stops THIS server and starts the other on the same port, so the page
++// waits for /health to name the new model, then reloads. Uses app.js's headers().
++(() => {
++ const box = document.createElement("label");
++ box.className = "model-switch";
++ box.hidden = true;
++ box.title = "Which model is loaded. Only one fits on the GPU at a time: switching unloads this one and loads the other (about 2 minutes).";
++ box.innerHTML = '<span class="model-switch__k">Model</span><select aria-label="Model on the GPU"></select>' +
++ '<span class="model-switch__s" role="status"></span>';
++ const sel = box.querySelector("select"), status = box.querySelector(".model-switch__s");
++ document.querySelector(".st-header__spacer").after(box);
++ let switching = null;
++
++ async function load() {
++ let sw;
++ try { sw = await (await fetch("switcher", {headers: headers()})).json(); } catch (e) { return; }
++ const keys = Object.keys(sw.choices || {});
++ if (!sw.enabled || sw.error || keys.length < 2) { box.hidden = true; return; }
++ sel.replaceChildren(...keys.map((k) => {
++ const o = document.createElement("option");
++ o.value = k;
++ o.textContent = sw.choices[k].replace(/ \(Strata SYCL engine\)$/, "");
++ o.selected = k === (sw.starting || sw.mode);
++ return o;
++ }));
++ sel.disabled = !!sw.starting || !!switching;
++ status.textContent = sw.starting && !switching ? `loading ${sw.choices[sw.starting] || sw.starting}…` : "";
++ box.hidden = false;
++ }
++
++ sel.onchange = async () => {
++ const mode = sel.value, name = sel.selectedOptions[0].textContent;
++ if (!confirm(`Load ${name}? The current model is unloaded first; it takes about 2 minutes and stops any answer in progress.`)) {
++ load();
++ return;
++ }
++ let from = null;
++ try { from = (await (await fetch("health", {cache: "no-store"})).json()).model; } catch (e) { /* going down */ }
++ switching = {from, t0: Date.now()};
++ sel.disabled = true;
++ try {
++ await fetch("switcher", {method: "POST", headers: headers(true), body: JSON.stringify({mode})});
++ } catch (e) { /* this server may already be going down */ }
++ const wait = async () => {
++ try {
++ const h = await (await fetch("health", {cache: "no-store"})).json();
++ if (h.model && h.model !== switching.from) { location.reload(); return; }
++ } catch (e) { /* down while the models swap */ }
++ const s = Math.round((Date.now() - switching.t0) / 1000);
++ if (s > 360) { status.textContent = `${name} did not come up in 6 minutes`; switching = null; sel.disabled = false; return; }
++ status.textContent = `switching to ${name}… ${s} s`;
++ setTimeout(wait, 3000);
++ };
++ setTimeout(wait, 5000);
++ };
++
++ load();
++ setInterval(() => { if (!switching) load(); }, 15000); // a switch started elsewhere shows here too
++})();
diff --cc sycl/serve/xe_telemetry.py
index 000000000,000000000..3eb3b61ab
new file mode 100644
--- /dev/null
+++ b/sycl/serve/xe_telemetry.py
@@@ -1,0 -1,0 +1,103 @@@
++"""Intel Arc (xe driver) readings for the server's Monitor tab, in the shape of serve/telemetry.py's readers.
++
++Kept out of serve/telemetry.py so the SYCL port touches no shared file: sycl/serve/server_intel.py installs it as
++telemetry.gpu_reader when there is no NVIDIA card. Load and VRAM need root (xe's only VRAM accounting is per-client
++fdinfo), so they come from a root sampler's /run/gpustat.json (sycl/tools/gpustat.py); temperature, power and the
++PCIe link are read from sysfs, so they show without it.
++"""
++from __future__ import annotations
++
++import os
++import sys
++import time
++
++
++class _XeGpu:
++ """The Intel Arc readings in NVML's shape. Load and VRAM come from /run/gpustat.json (a root sampler: the only
++ VRAM accounting xe exposes is per-client fdinfo, readable by root only); temperature, power and the PCIe link are
++ read from sysfs too, so they show without the sampler."""
++ STAT = "/run/gpustat.json"
++
++ def __init__(self, index=0):
++ import glob
++ self.dev = None
++ for d in sorted(glob.glob("/sys/class/drm/card[0-9]*/device")):
++ try:
++ if open(f"{d}/vendor").read().strip() == "0x8086" and os.path.isdir(f"{d}/tile0"):
++ self.dev = os.path.realpath(d)
++ break
++ except OSError:
++ continue
++ self.hwmon = None
++ for n in glob.glob(f"{self.dev}/hwmon/hwmon*/name") if self.dev else []:
++ self.hwmon = os.path.dirname(n)
++ self._e = None # (t, card energy uJ) for power without the sampler
++
++ def ok(self):
++ return self.dev is not None and sys.platform.startswith("linux")
++
++ def name(self):
++ st = self._stat()
++ return (st or {}).get("name") or "Intel Arc GPU"
++
++ def _stat(self):
++ try:
++ import json
++ with open(self.STAT) as f:
++ st = json.load(f)
++ return st if time.time() - float(st.get("ts", 0)) < 15 else None
++ except (OSError, ValueError):
++ return None
++
++ def _rd(self, p):
++ try:
++ return open(p).read().strip()
++ except OSError:
++ return None
++
++ def _link(self):
++ """The link the card trained at: its own functions sit behind an internal x1 switch, so the first port up
++ the path wider than x1; the max is what card AND slot allow (the root port caps it)."""
++ gen = {"2.5": 1, "5.0": 2, "8.0": 3, "16.0": 4, "32.0": 5, "64.0": 6}
++ d, chain = self.dev, []
++ while d and d.startswith("/sys/devices/pci") and os.path.exists(f"{d}/current_link_speed"):
++ chain.append(d)
++ d = os.path.dirname(d)
++ for p in chain:
++ w = int(self._rd(f"{p}/current_link_width") or 0)
++ if w > 1:
++ g = lambda q, k: gen.get((self._rd(f"{q}/{k}_link_speed") or "").split(" ")[0])
++ card, slot = g(p, "max"), g(chain[-1], "max")
++ return g(p, "current"), min(x for x in (card, slot) if x) if (card or slot) else None, w
++ return None, None, None
++
++ def read(self):
++ out = {}
++ st = self._stat()
++ if st:
++ out["util"] = st.get("busy_pct")
++ if st.get("vram_used_mb") is not None:
++ out["mem_used"] = st["vram_used_mb"] * 2**20
++ out["mem_total"] = st.get("vram_total_mb", 0) * 2**20 or None
++ out["temp"] = st.get("temp_pkg")
++ out["power"] = st.get("power_w")
++ out["power_limit"] = st.get("power_cap_w")
++ out["vram_temp"] = st.get("temp_vram_max") or st.get("temp_vram")
++ if self.hwmon:
++ if out.get("temp") is None:
++ for lab in os.listdir(self.hwmon):
++ if lab.endswith("_label") and self._rd(f"{self.hwmon}/{lab}") == "pkg":
++ v = self._rd(f"{self.hwmon}/{lab[:-6]}_input")
++ out["temp"] = int(v) / 1000 if v else None
++ if out.get("power") is None:
++ e, t = self._rd(f"{self.hwmon}/energy1_input"), time.time()
++ if e and e.isdigit():
++ if self._e and t > self._e[0] and int(e) >= self._e[1]:
++ out["power"] = (int(e) - self._e[1]) / 1e6 / (t - self._e[0])
++ self._e = (t, int(e))
++ if out.get("power_limit") is None:
++ cap = self._rd(f"{self.hwmon}/power1_cap")
++ out["power_limit"] = int(cap) / 1e6 if cap and cap.isdigit() and int(cap) > 0 else None
++ out["pcie_gen"], out["pcie_gen_max"], out["pcie_width"] = self._link()
++ out["pcie_rx_mb"] = out["pcie_tx_mb"] = None # xe exposes no PCIe traffic counters
++ return out
diff --cc sycl/setup_intel.py
index 000000000,000000000..0b1e2f058
new file mode 100644
--- /dev/null
+++ b/sycl/setup_intel.py
@@@ -1,0 -1,0 +1,246 @@@
++"""setup.py for an Intel Arc: upstream's installer, steered onto the SYCL port from outside.
++
++ python sycl/setup_intel.py [setup.py's options]
++
++The SYCL port keeps out of the shared files (upstream merges stay clean), so this does not edit setup.py: it imports
++it and replaces the few steps that are NVIDIA/AMD-specific, then runs setup's own main(). Everything else - the
++model choice, the download, the pack, the tokenizer, the MTP draft layer, the context and KV questions - is
++setup.py's, unchanged. What is replaced:
++
++ - the GPU check: the Intel Arc is offered through setup's AMD path (the one that compiles locally and has no
++ images), named and sized from sysfs;
++ - the engine step: the SYCL build (build-sycl-aot/strata, run in the strata-sycl-dev image by
++ sycl/serve/strata-sycl.sh; docs/INTEL.md) instead of a CUDA/HIP build;
++ - the RAM rule: the CUDA engine keeps every expert in RAM, the SYCL port streams them from the GGUF into VRAM
++ (--stream-experts), so RAM only bounds the KV streaming;
++ - the config: the container's paths, the SYCL flags, backend "sycl"; the run script starts
++ sycl/serve/server_intel.py (serve/server.py plus the Intel Monitor readings and the model menu).
++
++When setup.py changes the steps this relies on, this stops with a message rather than writing a wrong config.
++"""
++from __future__ import annotations
++
++import atexit
++import json
++import os
++import re
++import shutil
++import subprocess
++import sys
++import tempfile
++from pathlib import Path
++
++ROOT = Path(__file__).resolve().parent.parent
++sys.path.insert(0, str(ROOT))
++import setup as S # noqa: E402
++
++SYCL_WRAPPER = ROOT / "sycl" / "serve" / "strata-sycl.sh"
++SYCL_IMAGE = "strata-sycl-dev"
++SERVER = ROOT / "sycl" / "serve" / "server_intel.py"
++MOUNT = Path(os.environ.get("STRATA_SYCL_ROOT") or ROOT.parent) # what strata-sycl.sh mounts at /work
++
++# Battlemage / Alchemist PCI device ids -> (name, VRAM GB). lspci's database lags new cards (an Arc Pro B70 reads
++# "Intel Corporation Device [8086:e223]"), so the sysfs id is the reliable signal and the name table is ours.
++INTEL_ARC = {"e223": ("Arc Pro B70", 32.0), "e221": ("Arc Pro B60", 24.0), "e20b": ("Arc B580", 12.0),
++ "e20c": ("Arc B570", 10.0), "e212": ("Arc B50", 16.0),
++ "56a0": ("Arc A770", 16.0), "56a1": ("Arc A750", 8.0), "56a2": ("Arc A580", 8.0),
++ "56a5": ("Arc A380", 6.0), "56a6": ("Arc A310", 4.0), "5690": ("Arc A770M", 16.0)}
++
++
++def intel_gpus():
++ """Intel discrete GPUs from sysfs: vendor 0x8086 under the xe or i915 driver, named by PCI device id. VRAM comes
++ from the id table, else from the size of the card's VRAM BAR."""
++ found = []
++ for card in sorted(Path("/sys/class/drm").glob("card[0-9]*")):
++ if "-" in card.name: # connectors (card0-DP-1) share the card's device
++ continue
++ dev = card / "device"
++ try:
++ vendor = (dev / "vendor").read_text().strip().lower()
++ devid = (dev / "device").read_text().strip().lower().replace("0x", "")
++ driver = os.path.basename(os.path.realpath(dev / "driver")) if (dev / "driver").exists() else ""
++ except OSError:
++ continue
++ if vendor != "0x8086" or driver not in ("xe", "i915"):
++ continue
++ name, vram = INTEL_ARC.get(devid, (None, 0.0))
++ if name is None:
++ if driver != "xe": # i915 without a known Arc id is an integrated GPU
++ continue
++ name = f"Intel GPU {devid} (xe)"
++ if not vram: # resource line 2 (BAR 2) is the VRAM aperture on xe cards
++ try:
++ start, end, _ = (dev / "resource").read_text().splitlines()[2].split()
++ vram = (int(end, 16) - int(start, 16) + 1) / 2**30
++ except (OSError, IndexError, ValueError):
++ vram = 0.0
++ found.append({"index": len(found), "name": f"Intel {name}", "vram_gb": vram, "arch": "xe", "driver": driver})
++ return found
++
++
++def sycl_engine():
++ """The SYCL build: (binary, why-not)."""
++ if S.WIN:
++ return None, "the SYCL port runs on Linux only"
++ exe = next((b for b in (ROOT / "build-sycl-aot" / "strata", ROOT / "build-sycl" / "strata") if b.exists()), None)
++ if exe is None:
++ return None, "it is not built (sycl/tools/build.sh; docs/INTEL.md)"
++ if not shutil.which("docker"):
++ return None, "docker is not installed (the engine runs in the oneAPI image)"
++ if subprocess.run(["docker", "image", "inspect", SYCL_IMAGE], capture_output=True).returncode != 0:
++ return None, f"the runtime image {SYCL_IMAGE} is missing (sycl/tools/Dockerfile)"
++ return exe, None
++
++
++def sycl_path(path) -> str:
++ """A host path as the engine's container sees it: the folder above the Strata checkout (or STRATA_SYCL_ROOT) is
++ mounted at /work."""
++ p, root = Path(path).resolve(), MOUNT.resolve()
++ try:
++ return "/work/" + p.relative_to(root).as_posix()
++ except ValueError:
++ S.fail(f"{p} is outside {root}, which the SYCL engine's container mounts",
++ f"keep the models and the data folder under {root} (--models-dir / --data-dir)")
++
++
++def sycl_version() -> str:
++ m = re.search(r"project\(\s*\S+\s+VERSION\s+([\d.]+)", (ROOT / "sycl" / "CMakeLists.txt").read_text())
++ return m.group(1) if m else "0"
++
++
++def flag(args, name):
++ return args[args.index(name) + 1] if name in args else None
++
++
++def drop(args, name, value=False):
++ while name in args:
++ i = args.index(name)
++ del args[i:i + 1 + int(value)]
++
++
++def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict) -> dict:
++ """setup's config (written for its HIP path) -> the SYCL port's: the container's paths, experts streamed from the
++ GGUF into VRAM (every expert must fit, so the VRAM reserve is the smallest that leaves the KV and the prompt
++ buffers room - docs/INTEL.md), KV streaming from 64K up when the RAM holds the KV (the B70 at 256K decodes at
++ 40+ tok/s with it, 4-9 without)."""
++ args = list(cfg["args"])
++ for f in ("--resident-experts", "--mmap-experts"): # setup's low-RAM mode is the CUDA engine's
++ drop(args, f)
++ drop(args, "--kv-resident", True) # decided below on the real RAM
++ for f in ("--pack", "--native", "--ple-gguf", "--expert-profile", "--mtp", "--control-vector-scaled"):
++ if f in args:
++ v = args[args.index(f) + 1]
++ path, _, scale = v.rpartition(":") if f == "--control-vector-scaled" else (v, "", "")
++ args[args.index(f) + 1] = sycl_path(path) + (f":{scale}" if scale else "")
++ ctx = int(flag(args, "--max-context") or 32768)
++ kv = flag(args, "--kv") or "int8"
++ kv_ram = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9
++ if kv != "k8v4" and ctx >= 65536 and ram >= kv_ram + 6:
++ args += ["--kv-resident", "32768"]
++ S.ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram:.1f} GB), every expert stays in VRAM")
++ drop(args, "--vram-reserve-mib", True)
++ args += ["--stream-experts", "--vram-reserve-mib", "1024" if ctx <= 32768 else "2048"]
++ if ctx > 32768: # long contexts: 4096-token chunks keep the prompt buffers small
++ drop(args, "--prefill", True)
++ args += ["--prefill", "4096"]
++ out = {k: v for k, v in cfg.items() if k not in ("lib_dirs", "env", "vision", "gpus")}
++ out.update({"backend": "sycl", "exe": str(SYCL_WRAPPER), "args": args, "sycl_root": str(MOUNT)})
++ env = {}
++ if exe != ROOT / "build-sycl-aot" / "strata":
++ env["STRATA_SYCL_BIN"] = str(exe.relative_to(ROOT))
++ if MOUNT.resolve() != ROOT.parent.resolve():
++ env["STRATA_SYCL_ROOT"] = str(MOUNT)
++ if env:
++ out["env"] = env
++ out.update(keep)
++ return out
++
++
++def install(argv) -> None:
++ intel = [] if S.WIN else intel_gpus()
++ if not intel:
++ S.fail("no Intel Arc found (an xe or i915 card in /sys/class/drm)", "on an NVIDIA or AMD card, run ./setup.sh")
++ exe, why = sycl_engine()
++ if exe is None:
++ S.fail(f"Strata's SYCL engine cannot be used: {why}", "docs/INTEL.md: build it, then run this again")
++ for name in ("gpus", "amd_gpus", "amd_problem", "hip_vision", "build_engine_hip", "hipblaslt_table", "ram_gb",
++ "write_run_script", "start", "say", "main"):
++ if not callable(getattr(S, name, None)):
++ S.fail(f"setup.py has no {name}() any more: sycl/setup_intel.py needs updating for this setup.py")
++
++ real_ram = S.ram_gb()
++ keep = {} # hand-set keys setup does not write: kept across a rerun
++ for p in ROOT.glob("strata-*.json"):
++ try:
++ c = json.loads(p.read_text(encoding="utf-8-sig"))
++ keep[p.name] = {k: c[k] for k in ("model_switcher", "sampling") if k in c}
++ except (OSError, ValueError):
++ pass
++ stub = Path(tempfile.mkdtemp(prefix="strata-sycl-")) # setup reads the engine's BUILD.json; the SYCL build has none
++ atexit.register(shutil.rmtree, stub, True)
++ (stub / "BUILD.json").write_text(json.dumps({"version": sycl_version(), "source": "local", "lib_dirs": []}))
++
++ say = S.say
++ fake_ram = max(real_ram, 1024.0)
++
++ def say_intel(msg=""):
++ """setup's words for its AMD path and its RAM rule, said for the Intel card."""
++ msg = str(msg).replace("(AMD, experimental: docs/AMD_HIP.md)", "(Intel Arc: the SYCL port, docs/INTEL.md)")
++ msg = msg.replace("Your AMD GPUs:", "Your Intel GPUs:").replace("just run ./setup.sh", "just run sycl/setup_intel.py")
++ msg = msg.replace(f"RAM: {fake_ram:.0f} GB", f"RAM: {real_ram:.0f} GB (the experts are streamed into VRAM)")
++ if re.match(r"\s+\S+\s+needs ~\d+ GB RAM:", msg): # --check's CUDA verdicts: replaced by the Intel one
++ m = msg.split()[0]
++ d = S.MODELS.get(m, {})
++ shard1 = d.get("download_gb", 0) - 28.8 # all but the per-layer lookup table (read from disk)
++ room = intel[0]["vram_gb"] - 3 + max(0.0, real_ram - 10) # VRAM, plus a pinned host mirror
++ msg = (f" {m:8s} ~{shard1:.0f} GB of weights: " +
++ ("fits in VRAM" if shard1 <= intel[0]["vram_gb"] - 1.5 else
++ "fits with part of its experts mirrored in RAM (slower)" if shard1 <= room else "does not fit"))
++ say(msg)
++ S.say = say_intel
++ S.gpus = lambda *a, **k: []
++ S.amd_gpus = lambda *a, **k: intel
++ S.amd_problem = lambda g: None
++ S.hip_vision = lambda asked: "none" # images are not wired on the SYCL port yet
++ S.build_engine_hip = lambda *a, **k: stub
++ S.hipblaslt_table = lambda *a, **k: None
++ S.ram_gb = lambda: fake_ram # the experts are in VRAM: setup's RAM rule does not apply
++
++ write = S.write_run_script
++
++ def write_run_script(model, cfg_path, port):
++ cfg = json.loads(Path(cfg_path).read_text(encoding="utf-8"))
++ cfg = to_sycl(cfg, exe, real_ram, keep.get(Path(cfg_path).name, {}))
++ Path(cfg_path).write_text(json.dumps(cfg, indent=1), encoding="utf-8")
++ script = write(model, cfg_path, port)
++ script.write_text(script.read_text().replace(str(ROOT / "serve" / "server.py"), str(SERVER)))
++ return script
++ S.write_run_script = write_run_script
++
++ start = S.start
++
++ def start_sycl(cfg_path, *a, **k):
++ cfg = json.loads(Path(cfg_path).read_text(encoding="utf-8-sig"))
++ if cfg.get("backend") != "sycl":
++ return start(cfg_path, *a, **k)
++ script = ROOT / f"run-{Path(cfg_path).stem[len('strata-'):]}.sh"
++ S.say(f"\nstarting {script.name} ...")
++ os.execv("/bin/sh", ["/bin/sh", str(script)])
++ S.start = start_sycl
++
++ sys.argv = [str(ROOT / "setup.py"), *argv]
++ if "--backend" not in argv:
++ sys.argv += ["--backend", "hip"]
++ if "--vision" not in argv:
++ sys.argv += ["--vision", "none"]
++ if "--low-ram" not in argv:
++ sys.argv += ["--low-ram", "off"]
++ sys.exit(S.main())
++
++
++if __name__ == "__main__":
++ try:
++ install(sys.argv[1:])
++ except KeyboardInterrupt:
++ S.say("\nstopped.")
++ sys.exit(1)
diff --cc sycl/tools/gpustat.py
index db80e637a,000000000..fa7a73abc
mode 100644,000000..100644
--- a/sycl/tools/gpustat.py
+++ b/sycl/tools/gpustat.py
@@@ -1,182 -1,0 +1,182 @@@
+#!/usr/bin/env python3
- """GPU telemetry sampler for an Intel Arc on the xe driver (runs as root: tools/intel/gpustat.service).
++"""GPU telemetry sampler for an Intel Arc on the xe driver (runs as root: sycl/tools/gpustat.service).
+Writes /run/gpustat.json every INTERVAL s; Strata's web app (serve/telemetry.py) shows it in the Monitor tab:
+ name, vram_used_mb / vram_total_mb (sum of drm-resident-vram0 over unique drm
+ clients from /proc/*/fdinfo - the only VRAM accounting xe exposes; root-only),
+ busy_pct (compute/render cycle deltas), temp_pkg/temp_vram (hwmon 'xe'),
+ power_w / pkg_power_w (energy counter deltas over a POWER_WINDOW s window: the counters update in
+ bursts, so a 3 s delta swings 0.6 <-> 48 W), power_cap_w, fan_rpm, freq_mhz, the PCIe link the card
+ trained at (the first upstream port wider than x1 - the card's own functions sit behind an internal
+ x1 switch), the hottest VRAM channel, and the host's 1-minute load. Device totals only.
+Without it the Monitor tab still shows temperature, power and the PCIe link (sysfs), but not load or VRAM: xe
+reports those per client in /proc/*/fdinfo, which only root can read.
- Install: sudo install -m 755 tools/intel/gpustat.py /usr/local/sbin/
- sudo install -m 644 tools/intel/gpustat.service /etc/systemd/system/ && sudo systemctl enable --now gpustat
++Install: sudo install -m 755 sycl/tools/gpustat.py /usr/local/sbin/
++ sudo install -m 644 sycl/tools/gpustat.service /etc/systemd/system/ && sudo systemctl enable --now gpustat
+Env: GPUSTAT_INTERVAL (s), GPUSTAT_POWER_WINDOW (s), GPUSTAT_PCI (the card, e.g. 0000:03:00.0; default the first
+Intel GPU on xe), GPUSTAT_VRAM_MB (the total; default the card's largest PCI BAR, which maps all of VRAM with
+resizable BAR - a little above what the runtime reports as usable).
+"""
+import collections, glob, json, os, subprocess, time
+
+OUT = "/run/gpustat.json"
+INTERVAL = float(os.environ.get("GPUSTAT_INTERVAL", "3")) # each sample scans /proc/*/fd; keep it modest
+NAMES = {"e223": "Intel(R) Arc(TM) Pro B70 Graphics"}
+
+
+def find_card():
+ """The first Intel GPU on the xe driver (it has tile*/gt*), as a PCI address."""
+ for d in sorted(glob.glob("/sys/class/drm/card[0-9]*/device")):
+ try:
+ if open(f"{d}/vendor").read().strip() == "0x8086" and glob.glob(f"{d}/tile*/gt*"):
+ return os.path.basename(os.path.realpath(d))
+ except OSError:
+ continue
+ return None
+
+
+PCI = os.environ.get("GPUSTAT_PCI") or find_card() or "0000:00:00.0"
+
+
+def vram_total_mb():
+ if os.environ.get("GPUSTAT_VRAM_MB"):
+ return int(os.environ["GPUSTAT_VRAM_MB"])
+ try: # with resizable BAR the largest BAR maps all of VRAM
+ sizes = [int(e, 16) - int(s, 16) + 1 for s, e, _ in
+ (l.split() for l in open(f"/sys/bus/pci/devices/{PCI}/resource") if l.strip())]
+ return max(sizes) // 2**20
+ except (OSError, ValueError):
+ return 0
+
+
+def card_name(dev_id):
+ if dev_id in NAMES:
+ return NAMES[dev_id]
+ try:
+ out = subprocess.run(["lspci", "-mm", "-s", PCI], capture_output=True, text=True, timeout=5).stdout
+ parts = [p.strip('"') for p in out.split('" "')]
+ if len(parts) >= 3 and parts[2]:
+ return parts[2]
+ except (OSError, subprocess.SubprocessError):
+ pass
+ return f"Intel GPU 8086:{dev_id}"
+
+
+TOTAL_MB = vram_total_mb()
+POWER_WINDOW = float(os.environ.get("GPUSTAT_POWER_WINDOW", "15"))
+GEN = {"2.5": 1, "5.0": 2, "8.0": 3, "16.0": 4, "32.0": 5, "64.0": 6}
+
+def pcie_link():
+ """The link the card trained at: walk up from the GPU function to the first port wider than x1."""
+ d = os.path.realpath(f"/sys/bus/pci/devices/{PCI}")
+ chain = []
+ while d.startswith("/sys/devices/pci") and os.path.exists(f"{d}/current_link_speed"):
+ chain.append(d); d = os.path.dirname(d)
+ def link(p, kind):
+ sp = (rd(f"{p}/{kind}_link_speed", "") or "").split(" ")[0]
+ return {"gen": GEN.get(sp), "gts": sp, "width": int(rd(f"{p}/{kind}_link_width", "0") or 0)}
+ for i, p in enumerate(chain):
+ cur = link(p, "current")
+ if cur["width"] > 1:
+ root = chain[-1] # the CPU's root port: what the slot can do
+ return {"cur": cur, "card_max": link(p, "max"), "slot_max": link(root, "max")}
+ return None
+
+def hwmon_dir():
+ for n in glob.glob("/sys/class/hwmon/hwmon*/name"):
+ if open(n).read().strip() == "xe":
+ return os.path.dirname(n)
+ return None
+
+def rd(p, default=None):
+ try:
+ return open(p).read().strip()
+ except Exception:
+ return default
+
+def hw_temps(h):
+ t = {}
+ for lab in glob.glob(f"{h}/temp*_label"):
+ name = rd(lab); v = rd(lab.replace("_label", "_input"))
+ if name and v: t[name] = int(v) / 1000
+ return t
+
+def clients():
+ """{client_id: {pid, comm, vram_kb, cycles, total_cycles}} across all processes."""
+ res = {}
+ for pdir in glob.glob("/proc/[0-9]*"):
+ try:
+ fds = os.listdir(f"{pdir}/fd")
+ except Exception:
+ continue
+ for fd in fds:
+ try:
+ if not os.readlink(f"{pdir}/fd/{fd}").startswith("/dev/dri/"):
+ continue
+ info = dict(l.split(":\t", 1) for l in open(f"{pdir}/fdinfo/{fd}").read().splitlines() if l.startswith("drm-"))
+ except Exception:
+ continue
+ cid = info.get("drm-client-id")
+ if not cid or cid in res:
+ continue
+ kb = lambda k: int(info.get(k, "0").split()[0] or 0)
+ cyc = max(kb("drm-cycles-rcs"), kb("drm-cycles-ccs"))
+ tot = max(kb("drm-total-cycles-rcs"), kb("drm-total-cycles-ccs"))
+ res[cid] = {"pid": int(pdir[6:]), "comm": rd(f"{pdir}/comm", "?"),
+ "cg": rd(f"{pdir}/cgroup", ""), "vram_kb": kb("drm-resident-vram0"), "cycles": cyc, "total": tot}
+ return res
+
+def main():
+ h = hwmon_dir()
+ dev_id = (rd(f"/sys/bus/pci/devices/{PCI}/device", "0x0") or "0x0")[2:]
+ name = card_name(dev_id)
+ prev = {}; t_prev = time.time()
+ ring = collections.deque() # (t, card uJ, pkg uJ) over the last POWER_WINDOW s
+ link = pcie_link(); link_t = time.time()
+ while True:
+ now = time.time(); dt = max(now - t_prev, 1e-3)
+ cl = clients()
+ busy = 0.0
+ for cid, c in cl.items():
+ p = prev.get(cid)
+ if p and c["total"] > p["total"]:
+ busy += (c["cycles"] - p["cycles"]) / (c["total"] - p["total"]) * 100
+ e = int(rd(f"{h}/energy1_input", "0") or 0) if h else 0
+ e2 = int(rd(f"{h}/energy2_input", "0") or 0) if h else 0
+ ring.append((now, e, e2))
+ while len(ring) > 2 and now - ring[1][0] >= POWER_WINDOW:
+ ring.popleft()
+ t0, ea, eb = ring[0]
+ span = now - t0
+ power = (e - ea) / 1e6 / span if span >= 2.5 and e >= ea else None
+ pkg_power = (e2 - eb) / 1e6 / span if span >= 2.5 and e2 >= eb else None
+ if now - link_t > 30: # the link can retrain (power saving, errors): re-read it
+ link = pcie_link(); link_t = now
+ temps = hw_temps(h) if h else {}
+ vram_ch = [v for k, v in temps.items() if k.startswith("vram_ch_")]
+ cap = rd(f"{h}/power1_cap") if h else None
+ used_mb = sum(c["vram_kb"] for c in cl.values()) // 1024
+ out = {
+ "name": name, "pci": PCI, "ts": now,
+ "vram_used_mb": used_mb, "vram_total_mb": TOTAL_MB,
+ "busy_pct": round(min(busy, 100), 1),
+ "temp_pkg": temps.get("pkg"), "temp_vram": temps.get("vram"),
+ "power_w": None if power is None else round(power, 1),
+ "pkg_power_w": None if pkg_power is None else round(pkg_power, 1),
+ "power_cap_w": round(int(cap) / 1e6) if cap and cap.isdigit() and int(cap) > 0 else None,
+ "temp_vram_max": max(vram_ch) if vram_ch else None,
+ "temp_pcie": temps.get("pcie"), "temp_mctrl": temps.get("mctrl"),
+ "pcie": link,
+ "host_load1": round(os.getloadavg()[0], 2), "host_cpus": os.cpu_count(),
+ "energy_j": round(e / 1e6, 1), # cumulative card energy (hwmon energy1 = "card", uJ)
+ "fan_rpm": int(rd(f"{h}/fan1_input", "0") or 0) if h else None,
+ "freq_mhz": int(rd(glob.glob(f"/sys/bus/pci/devices/{PCI}/tile0/gt0/freq0/act_freq")[0], "0") or 0)
+ if glob.glob(f"/sys/bus/pci/devices/{PCI}/tile0/gt0/freq0/act_freq") else None,
+ }
+ tmp = OUT + ".tmp"
+ with open(tmp, "w") as f: json.dump(out, f)
+ os.chmod(tmp, 0o644); os.replace(tmp, OUT)
+ prev, t_prev = cl, now
+ time.sleep(INTERVAL)
+
+if __name__ == "__main__":
+ main()
diff --cc sycl/tools/gpustat.service
index 707962803,000000000..707962803
mode 100644,000000..100644
--- a/sycl/tools/gpustat.service
+++ b/sycl/tools/gpustat.service
diff --cc sycl/tools/migrate.sh
index 6be754d85,000000000..44994eb86
mode 100755,000000..100755
--- a/sycl/tools/migrate.sh
+++ b/sycl/tools/migrate.sh
@@@ -1,45 -1,0 +1,47 @@@
+#!/usr/bin/env bash
+# CUDA -> SYCL migration of the Strata engine with SYCLomatic (dpct), run inside strata-sycl-dev.
+# sycl/migrate.sh [repo] [out] repo defaults to the Strata_B70 checkout beside this dir
+# Writes a compilation database first (there is no nvcc here, so CMake cannot make one), then migrates every
+# CUDA-touching source into <out> mirroring the tree. Files dpct leaves alone are not copied - the port's
+# CMake falls back to the original for those, so the diff against upstream stays the port itself.
+set -euo pipefail
+repo=${1:-/work/Strata_B70}
+out=${2:-$repo/sycl}
+hdr=${CUDA_HEADERS:-/cuda-headers/include}
+source /opt/intel/oneapi/setvars.sh >/dev/null 2>&1 || true
+export PATH=/opt/intel/oneapi/dpcpp-ct/latest/bin:$PATH
+cd "$repo"
+# the compilation database: every .cu plus every .cpp/.hpp that includes a CUDA header
- python3 - "$repo" "$hdr" <<'PY'
++db_dir=$(mktemp -d) # outside the checkout: nothing to ignore in git
++trap 'rm -rf "$db_dir"' EXIT
++python3 - "$repo" "$hdr" "$db_dir" <<'PY'
+import json, os, re, sys, subprocess
- repo, hdr = sys.argv[1], sys.argv[2]
++repo, hdr, db_dir = sys.argv[1], sys.argv[2], sys.argv[3]
+files = subprocess.check_output(["bash", "-c",
+ r"find src -name '*.cu'; grep -rl 'cuda_runtime\|cublas_v2\|cuda_fp16\|cuda\.h' src --include='*.cpp'"],
+ cwd=repo, text=True).split()
+db = []
+# not in this tree: the optional ggml MMQ prefill path needs llama.cpp's ggml-cuda sources, and one parity test needs
+# ggml-cpu.h. Both stay CUDA-only for now.
+skip = {"src/prefill/moe_mmq.cu", "src/prefill/ggml_cuda_host.cu", "src/kernels/native_expert_parity.cpp"}
+for f in sorted(set(files) - skip):
+ tool = "nvcc" if f.endswith(".cu") else "g++"
+ cmd = [tool, "-std=c++20", "-Iinclude", "-Ithird_party/ggml", "-I" + hdr, "-DSTRATA_VERSION=\"port\""]
+ if tool == "nvcc": cmd += ["--cuda-gpu-arch=sm_80", "-x", "cuda"]
+ cmd += ["-c", f, "-o", f + ".o"]
+ db.append({"directory": repo, "file": os.path.join(repo, f), "arguments": cmd})
- json.dump(db, open(os.path.join(repo, "compile_commands.json"), "w"), indent=1)
++json.dump(db, open(os.path.join(db_dir, "compile_commands.json"), "w"), indent=1)
+print(len(db), "translation units")
+PY
+mkdir -p "$out"
+# --use-experimental-features: graph (cudaGraph -> sycl_ext_oneapi_graph), matrix (mma -> joint_matrix)
+# --gen-helper-function: copy the dpct helper headers next to the output so the port builds without the tool
- dpct -p "$repo" --in-root="$repo" --out-root="$out" \
++dpct -p "$db_dir" --in-root="$repo" --out-root="$out" \
+ --cuda-include-path="$hdr" \
+ --use-experimental-features=graph,matrix,logical-group,masked-sub-group-operation,occupancy-calculation,free-function-queries,local-memory-kernel-scope-allocation,bindless_images,virtual_mem,root-group,non-uniform-groups \
+ --gen-helper-function --always-use-async-handler --sycl-named-lambda \
+ --enable-ctad --optimize-migration --assume-nd-range-dim=3 \
+ --report-type=all --report-file-prefix=dpct_report --report-format=csv \
- --stop-on-parse-err=false ${DPCT_EXTRA:-} 2>&1 | tee "$out/../sycl-migrate.log" | tail -40
++ --stop-on-parse-err=false ${DPCT_EXTRA:-} 2>&1 | tee "$out/migrate.log" | tail -40
+echo "MIGRATE EXIT ${PIPESTATUS[0]}"
+find "$out" -type f | wc -l