Part 1 of 1 in a series on local AI on Intel Panther Lake. This post covers a Qwen4-35B-A3B coding-agent server with 256K context on a Framework 13 Pro (Core Ultra X7 358H, Arc B390, 32 GB LPDDR5X) running Fedora 45.


Why again, and why this laptop

In the Lunar Lake series I ran a 7B reasoning model and a 1.5B completion model on an Intel Core Ultra 7 268V. It worked, and I ended up on a single Ollama container. Those models are fine for autocomplete and chat. They are not good enough to drive a coding agent that reads files, calls tools and keeps a long working context.

The new machine changes the budget:

CPU Intel Core Ultra X7 358H (Panther Lake, 16 cores)
GPU Arc B390 (Xe3), ~23 GiB device-local heap
Memory 32 GB LPDDR5X, ~30 GiB usable, shared between CPU and GPU
OS Fedora 45, podman, no NVIDIA, no CUDA

Unified memory is the interesting part. The GPU can address most of the RAM, so a model that would never fit in a discrete 8 or 12 GB card fits here. It also means the model, the KV cache, the browser and the IDE all compete for the same 30 GiB.

The model is Qwen4-35B-A3B: a mixture-of-experts model with 35B parameters in total and about 3B active per token. Decode speed depends on the active parameters, not the total, so a 35B model can decode at 25+ tokens/s on an iGPU. The catch is that all 35B parameters have to be resident in memory.

The goal: an OpenAI-compatible server on 127.0.0.1:8080 with a 256K context window, tuned for coding agents (opencode, pi and hermes), with the least memory it can get away with.

The model and the memory budget

I use Unsloth’s GGUF quants of Qwen4-35B-A3B, following their Qwen4 guide. Two 3-bit variants matter:

quant size on disk KLD vs BF16 (Unsloth)
UD-Q3_K_XL 29 GB 0.0569
UD-IQ3_XXS 27 GB 0.0760

Lower KLD means closer to the BF16 model. IQ3_XXS is a little further away, but it frees about 2 GiB.

Each quant is split into two shards. The second shard (11.5 GB) is the per-layer token embedding table, which Qwen4 calls the engram. It is a lookup table, not compute, so it doesn’t need to live on the GPU. It is byte-identical in both quants, so I hard-linked it instead of storing it twice. The server keeps it on the CPU side and memory-maps it:

-ot per_layer_token_embd=CPU --load-mode mmap --lazy-mode on

With mmap, pages are loaded on first touch and can be dropped under memory pressure. That matters a lot on a laptop where Firefox wants memory too.

Downloading 30 GB

This took longer than it should have. hf download was throttled per connection and stalled at around 15 GB. Xet (the newer Hugging Face transfer backend) did not help, and it could not reuse the partial files either.

What worked was plain aria2c with 16 connections straight from the resolve URL:

aria2c -x16 -s16 --conf-path=/path/to/private-aria2.conf \
  "https://huggingface.co/unsloth/Qwen4-35B-A3B-GGUF/resolve/main/<dir>/<file>.gguf"

The Hugging Face token lives in a systemd credential (~/.creds/hf-token.cred) and is passed through a private aria2 config, so it never shows up in shell history or ps. That took a ~36 MB/s crawl to ~100 MB/s.

Always verify. The LFS oid from the tree API is the SHA-256 of each file:

curl -s https://huggingface.co/api/models/unsloth/Qwen4-35B-A3B-GGUF/tree/main/UD-Q3_K_XL | jq -r '.[] | "\(.lfs.oid)  \(.path)"'
sha256sum Qwen4-35B-A3B-UD-Q3_K_XL-0000*-of-00002.gguf

Building llama.cpp twice

Without CUDA there are two realistic GPU backends for Intel: Vulkan and SYCL. I didn’t want to guess which was faster, so I built both from the same llama.cpp commit (8b8de44).

Vulkan is a normal host build. On Fedora it needed spirv-headers-devel and ccache beyond the usual toolchain:

cmake -B build -DGGML_VULKAN=ON -DCMAKE_BUILD_TYPE=Release -DGGML_CCACHE=ON
cmake --build build -j 12 --target llama-server llama-bench

SYCL needs Intel’s oneAPI compiler (icpx 2026.2), which I don’t want on the host. llama.cpp ships a Dockerfile for it, so the SYCL build is a podman image:

podman build -f .devops/intel.Dockerfile --target server -t localhost/llama-sycl:latest .

The Dockerfile builds with -DGGML_SYCL=ON -DGGML_SYCL_F16=ON and dynamic backend libraries. Before spending hours on it, I ran a quick go/no-go check: does sycl-ls inside the container see the GPU? It lists the Arc B390 through Level Zero (Intel(R) Graphics [0xb082]) and through OpenCL, so yes.

Vulkan vs SYCL

llama-bench with UD-Q3_K_XL, q8_0 KV cache, FlashAttention on, on an idle desktop:

Vulkan SYCL
tg128 (decode) 24.8 24.6
tg128 @ 16K depth 20.7 22.6
pp512 (prompt) 541 355
pp512 @ 16K depth 165 515

All numbers are tokens/s. On an empty context Vulkan reads the prompt faster. But the @ d16384 rows measure speed with 16K tokens already in the context, and that is what a coding agent actually does: the system prompt, tool definitions and file contents are always there. At that depth SYCL processes prompts 3x faster and also decodes faster. SYCL wins, and the Vulkan build stays around as a fallback.

Fitting 256K: quant × KV cache × context

Long context costs memory in the KV cache. With 256K tokens the cache is big enough to matter, and there are two levers to pull: a smaller quant and a smaller cache type. I measured all the combinations on SYCL with the browser and IDE open and a ~16K-token prompt:

quant KV ctx free after load (GiB) needle found
UD-Q3_K_XL q8_0 256K 3.8 yes
UD-Q3_K_XL q8_0 512K 0.5 (+1.1 swap) yes
UD-Q3_K_XL q4_0 256K 5.5 yes
UD-Q3_K_XL q4_0 512K 2.4 yes
UD-Q3_K_XL q4_0 1M – GPU DEVICE_LOST at load
UD-IQ3_XXS q8_0 256K 7.3 yes
UD-IQ3_XXS q8_0 512K 2.6 yes
UD-IQ3_XXS q4_0 512K 5.9 yes
UD-IQ3_XXS q4_0 1M 0.4 (+0.8 swap) yes

“Needle found” means I buried a fact in the 16K prompt and the model retrieved it. It doesn’t prove long-context quality, but it shows the quantized cache isn’t broken. The throughput columns from this first matrix under-measured decode because the answers were only about 10 tokens long. Those numbers get redone below with a proper ~150-token answer.

Takeaways: the q4_0 KV cache saves more than the smaller quant does, and the two together are what make 1M possible at all.

MTP speculative decoding

Qwen4 ships with a multi-token-prediction head. llama.cpp can use it as a draft model for speculative decoding with no second model to load:

--spec-type draft-mtp --spec-draft-n-max 2

The model drafts up to two tokens, the main model verifies them in one pass, and accepted tokens come for free. On short prompts at 16K context, decode went from 23.9 to 32.1 tokens/s (+35%), with about 67% of draft tokens accepted. On the realistic 16K-token-prompt test:

config free GiB prompt t/s decode t/s
MTP off (warm) 5.6 196 21.9
MTP on 2.5 441 25.5

That is 2.25x faster prompt processing and ~16% faster decode, for about 3.1 GiB of extra memory. Thread count made no measurable difference in these runs.

One thing I noticed in practice: llama.cpp picked only 2 CPU threads on its own, and during agent sessions one core sat at 100%. That is expected on SYCL. The main thread drives the GPU, and SYCL lacks the fused MoE top-k op, so that step falls back to the CPU every layer. I set --threads 4 --threads-batch 4 through EXTRA_ARGS.

The OOM that picked the default

My first default was quality: UD-Q3_K_XL, q4_0 KV, 256K, MTP on. It benchmarked well (439 prompt / 26.4 decode, 5.2 GiB free). Then, in a real pi session at around 13K tokens of context, the kernel OOM-killed llama-server. Swap was full, the GPU was holding about 24 GB of shared RAM, and the browser, the IDE, pi and a couple of other sessions were open. systemd restarted it, but that is not a workflow.

A benchmark with 5 GiB free is not the same as a laptop you are using. I switched the default to the IQ3_XXS variant, which has about 2 GiB more headroom (7.0 GiB free), and called it lean.

I also dropped my own rule of keeping 4 GiB free at all times. It excluded MTP, and the measured gain (2.25x prompt, +16% decode) was worth more than the margin. The real safety net is the lean weights plus mmap.

The result: the lean preset

UD-IQ3_XXS, q4_0 KV cache, 262144 context, MTP on, SYCL. It loads in about 2.5 to 3 minutes (132 s in the benchmark), leaves 7.0 GiB free with a 16K prompt, and runs at 336 tokens/s prompt, 26.4 tokens/s decode. The needle test passes.

All presets, measured the same way (16K-token prompt, ~150-token answer, SYCL, browser and IDE open):

preset quant KV ctx MTP free RAM prompt / decode t/s
512k UD-IQ3_XXS q4_0 512K on 2.5 GiB 441 / 25.5
lean (default) UD-IQ3_XXS q4_0 256K on 7.0 GiB 336 / 26.4
lean-128k UD-IQ3_XXS q4_0 128K on not measured not measured
quality UD-Q3_K_XL q4_0 256K on 5.2 GiB 439 / 26.4
quality-512k UD-Q3_K_XL q4_0 512K off (no room) 3.6 GiB 173 / 21.7
1m UD-IQ3_XXS q4_0 1M off (no room) 0.3 GiB, swaps 117 / 21.9

Free RAM readings vary by ±1-2 GiB with desktop activity.

Two notes on that table. First, the 1M preset exists because it can: the model loads, retrieves the needle and decodes at ~22 tokens/s, but it leaves 0.3 GiB free and grows swap by about 1.1 GiB. It is for occasional use. Second, the prompt speeds (336 for lean vs 441 for 512k) come from single runs on a busy desktop, so I wouldn’t read much into the difference. The column I trust is the headroom.

The server command

Everything goes through one launcher, ~/Projects/qwen4/scripts/qwen4-serve.sh. The core of it:

ARGS=(
  -m "$MODEL"
  --host 127.0.0.1 --port 8080
  --alias qwen4
  --jinja
  -ngl 99
  -ot per_layer_token_embd=CPU
  --load-mode mmap --lazy-mode on
  -c "$CTX" --parallel 1
  -fa on --cache-type-k "$KV_TYPE" --cache-type-v "$KV_TYPE"
)
  • --jinja uses the model’s own chat template. Tool calling and the reasoning controls depend on it.
  • -ngl 99 offloads every layer to the GPU. Combined with -ot, the engram stays on the CPU side.
  • -c is the context size and --parallel 1 gives all of it to a single slot. With more slots the context would be divided between them.
  • -fa on is FlashAttention. It is required for a quantized V cache.
  • --cache-type-k/v q4_0 is the 4-bit KV cache from the matrix above.
  • --alias qwen4 lets clients ask for any model name, since there is only one model loaded.

The sampling is set per profile, following Qwen’s recommendations:

think) ARGS+=(--reasoning on --reasoning-effort "$THINK_EFFORT"
              --temp 1.0 --top-p 0.95 --top-k 20 --min-p 0.0) ;;
fast)  ARGS+=(--reasoning off
              --temp 0.7 --top-p 0.8 --top-k 20 --min-p 0.0 --presence-penalty 1.5) ;;

On SYCL the whole thing runs inside the podman image:

exec podman run --rm --replace --name qwen4-sycl \
  --device /dev/dri --group-add keep-groups --security-opt label=disable \
  --network host -v "$ROOT/models:/models:ro" \
  localhost/llama-sycl:latest "${ARGS[@]}"

--device /dev/dri gives the container the GPU, --group-add keep-groups keeps my render group membership in rootless podman, label=disable avoids SELinux relabeling a 30 GB model directory, and the models are mounted read-only. The server binds to localhost only.

Presets are a small case table mapping a name to QUANT KV CTX MTP_OK. The last field forces MTP off for presets that don’t have the memory for it.

Reasoning modes, and a gotcha

One server serves both modes, and clients choose per request through chat_template_kwargs, so there is no need to restart anything:

mode request sampling
think (default) reasoning_effort: low (or high / xhigh) temp 1.0, top_p 0.95, top_k 20
fast reasoning_effort: "off" and enable_thinking: false temp 0.7, top_p 0.8, top_k 20, presence 1.5

To turn reasoning off you have to send both keys. reasoning_effort: off alone makes the chat template raise Conflicting thinking settings, and the top-level OpenAI reasoning_effort: "off" alone still lets the model think. The template also accepts only xhigh, high, low and off. There is no medium, and the server answers HTTP 400 if a client sends it.

Does more thinking help? I ran three small coding tasks (an off-by-one bug, a SemVer regex, a SQL “second-highest” query) at low and high:

effort total time notes
low 104 s (includes ~40 s first-request warm-up) correct answers
high 106 s no better: the SQL could return duplicate rows on ties, and the regex asserts called an undefined parse()

The default is low.

Running it: systemd and a small CLI

One systemd user template unit, one instance per preset:

[Unit]
Description=Qwen4-35B-A3B llama.cpp server, preset %i, on 127.0.0.1:8080
After=network.target

[Service]
Type=exec
ExecStart=%h/Projects/qwen4/scripts/qwen4-serve.sh think %i
ExecStopPost=-/usr/bin/podman rm -f --ignore qwen4-sycl
Restart=on-failure
RestartSec=5
TimeoutStopSec=30

[Install]
WantedBy=default.target

ExecStopPost removes the container so a stopped service never leaves a stale GPU process behind. The unit is not enabled at boot: the server holds ~23 GiB, and I only want that when I’m working.

A thin wrapper called qwen4 makes it pleasant:

qwen4 start              # default preset 'lean'
qwen4 start 512k         # a different preset for this session
qwen4 status             # running preset, health, free memory
qwen4 logs               # follow the server log
qwen4 stop               # give the ~23 GiB back

qwen4 start <preset> also rewrites the context limit in each agent’s config (opencode limit.context, pi contextWindow, hermes context_length) to match the preset. Agents compact their history based on their own idea of the window, so if they think they have 256K and the server was started with 128K, they hit the wall instead of compacting. Set SYNC_AGENTS=0 to turn it off.

The settings live in ~/.config/qwen4/env:

BACKEND=sycl          # sycl (benchmark winner) | vulkan
PRESET=lean           # quality | lean | lean-128k | 512k | quality-512k | 1m
THINK_EFFORT=low      # reasoning effort for the server default (xhigh | high | low | off)
MTP=1                 # MTP speculative decoding: +16-35% decode, 2.25x prompt, costs ~3.1 GiB (set 0 to free RAM)
SYNC_AGENTS=1         # qwen4 start sets opencode/pi/hermes context limits to the preset ctx (0 = leave them alone)
THREADS=4             # CPU threads for generation + batch (llama.cpp auto-picked 2)
EXTRA_ARGS="--threads $THREADS --threads-batch $THREADS"

Wiring the agents

All three agents speak the OpenAI API, so each one needs a provider entry. The interesting part is mapping their reasoning controls onto chat_template_kwargs.

opencode (~/.config/opencode/opencode.json) defines the default (think, low) and variants for the other modes. -m qwen4/qwen4#fast selects fast:

"models": {
  "qwen4": {
    "reasoning": true,
    "interleaved": { "field": "reasoning_content" },
    "limit": { "context": 262144, "output": 16384 },
    "options": {
      "temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0,
      "chat_template_kwargs": { "reasoning_effort": "low" }
    },
    "variants": {
      "high": { "chat_template_kwargs": { "reasoning_effort": "high" } },
      "fast": {
        "temperature": 0.7, "top_p": 0.8, "presence_penalty": 1.5,
        "chat_template_kwargs": { "reasoning_effort": "off", "enable_thinking": false }
      }
    }
  }
}

pi maps its thinking levels onto the template: --model qwen4-local/qwen4:low or :off, with per-level sampling in samplingParamsByThinkingLevel. hermes has two custom providers, qwen4-think and qwen4-fast, switched with /model custom:qwen4-fast. The full configs are in the appendix.

Validating it

After every llama.cpp update I run a small gate script against the live server. It checks that tool calls come back as proper tool_calls in both streaming and non-streaming mode, that any model name is accepted, that reasoning is present in think mode and absent with reasoning off, and that medium is rejected.

It passes, with one honest footnote: the “reasoning present at low effort” check once failed on a trivial prompt because the model skipped thinking, and a re-test showed reasoning deltas as expected. I treat that as a flaky check, not a broken server.

For reliability under agents I also fired the same tool-calling request six times per mode: 6/6 valid tool calls with reasoning off (1.9 s average per request) and with low (2.2 s). All three agents, opencode, pi and hermes, passed a smoke test that reads a file through a tool and answers.

Trade-offs

  • Fidelity. IQ3_XXS is a bit further from BF16 than Q3_K_XL (KLD 0.076 vs 0.057). For agentic coding I haven’t seen it matter, but I haven’t done a proper evaluation either. The quality preset is one command away.
  • Context. 256K is the sweet spot for my memory. 512K works and 1M technically works, but both cost most of the headroom.
  • The CPU fallback. SYCL lacks the fused MoE top-k op, so decode is partly bound by one CPU core. Vulkan doesn’t do better at depth, so I live with it.
  • Re-benchmark after updates. llama.cpp moves quickly, and the Vulkan/SYCL winner can change. bench-backends.sh and the gate script are there for that.
  • No fine-tuning. The tooling for that is NVIDIA-only, so this stays an inference setup.

The result is a 35B-class model with a 256K window that runs at around 26 tokens/s on a thin laptop, offline, and can be started and stopped like any other service.

Appendix: full listings

The scripts and configs as they run on my machine.

scripts/qwen4-serve.sh

#!/usr/bin/env bash
# Launch Qwen4-35B-A3B (llama.cpp) on the Intel Arc B390.
# Usage: qwen4-serve.sh [think|fast] [preset]      (defaults: think, $PRESET from env file)
# Settings: ~/.config/qwen4/env   Presets: see `qwen4 presets` / bench/results.md
set -euo pipefail

PROFILE="${1:-think}"
ROOT="$HOME/Projects/qwen4"
ENV_FILE="${QWEN4_ENV:-$HOME/.config/qwen4/env}"
[[ -f "$ENV_FILE" ]] && source "$ENV_FILE"

PRESET="${2:-${PRESET_OVERRIDE:-${PRESET:-quality}}}"

# name -> "QUANT KV_TYPE CTX MTP_OK"   (benchmarked on SYCL with browser+IDE open, 2026-12-05)
# MTP_OK=0: preset too tight for MTP (~3.1 GiB extra); MTP is forced off for it.
preset_spec() {
  case "$1" in
    512k)         echo "UD-IQ3_XXS q4_0 524288 1"  ;;  # MTP on: 2.5 GiB free, 441 pp / 25.5 tg
    1m)           echo "UD-IQ3_XXS q4_0 1048576 0" ;;  # 0.3 GiB free, swaps, 117 pp / 21.9 tg
    lean)         echo "UD-IQ3_XXS q4_0 262144 1"  ;;  # MTP on: 7.0 GiB free, 336 pp / 26.4 tg
    lean-128k)    echo "UD-IQ3_XXS q4_0 131072 1"  ;;  # MTP on: est. ~9 GiB free (not yet measured)
    quality)      echo "UD-Q3_K_XL q4_0 262144 1"  ;;  # MTP on: 5.2 GiB free, 439 pp / 26.4 tg
    quality-512k) echo "UD-Q3_K_XL q4_0 524288 0"  ;;  # 3.6 GiB free, 173 pp / 21.7 tg
    *) return 1 ;;
  esac
}
spec=$(preset_spec "$PRESET") || { echo "unknown preset '$PRESET' (quality lean lean-128k 512k quality-512k 1m)" >&2; exit 2; }
read -r P_QUANT P_KV P_CTX P_MTP_OK <<<"$spec"

# `qwen4-serve.sh --print-ctx <preset>`: print the preset's context size and exit (used by `qwen4 start`)
if [[ "$PROFILE" == "--print-ctx" ]]; then echo "${CTX_OVERRIDE:-$P_CTX}"; exit 0; fi

# precedence: *_OVERRIDE (bench scripts) > preset
BACKEND="${BACKEND_OVERRIDE:-${BACKEND:-sycl}}"
QUANT="${QUANT_OVERRIDE:-$P_QUANT}"
KV_TYPE="${KV_TYPE_OVERRIDE:-$P_KV}"
CTX="${CTX_OVERRIDE:-$P_CTX}"
MTP="${MTP_OVERRIDE:-${MTP:-0}}"
if [[ -z "${MTP_OVERRIDE:-}" && "$P_MTP_OK" == "0" && "$MTP" == "1" ]]; then
  echo "qwen4: MTP disabled for preset '$PRESET' (not enough memory)" >&2; MTP=0
fi
THINK_EFFORT="${THINK_EFFORT:-low}"
PORT="${PORT:-8080}"
HOST="${HOST:-127.0.0.1}"
MODEL_REL="Qwen4-35B-A3B-GGUF/$QUANT/Qwen4-35B-A3B-$QUANT-00001-of-00002.gguf"

case "$BACKEND" in
  vulkan) MODEL="$ROOT/models/$MODEL_REL" ;;
  sycl)   MODEL="/models/$MODEL_REL" ;;
  *) echo "BACKEND must be vulkan or sycl (got '$BACKEND')" >&2; exit 2 ;;
esac
[[ -f "$ROOT/models/$MODEL_REL" ]] || { echo "model file missing: $ROOT/models/$MODEL_REL" >&2; exit 2; }

ARGS=(
  -m "$MODEL"
  --host "$HOST" --port "$PORT"
  --alias qwen4
  --jinja
  -ngl 99
  -ot per_layer_token_embd=CPU   # engram stays on CPU / SSD
  --load-mode mmap --lazy-mode on
  -c "$CTX" --parallel 1
  -fa on --cache-type-k "$KV_TYPE" --cache-type-v "$KV_TYPE"
)

case "$PROFILE" in
  think) ARGS+=(--reasoning on --reasoning-effort "$THINK_EFFORT"
                --temp 1.0 --top-p 0.95 --top-k 20 --min-p 0.0) ;;
  fast)  ARGS+=(--reasoning off
                --temp 0.7 --top-p 0.8 --top-k 20 --min-p 0.0 --presence-penalty 1.5) ;;
  *) echo "profile must be think or fast (got '$PROFILE')" >&2; exit 2 ;;
esac

[[ "$MTP" == "1" ]] && ARGS+=(--spec-type draft-mtp --spec-draft-n-max 2)
[[ -n "${EXTRA_ARGS:-}" ]] && read -ra _extra <<<"$EXTRA_ARGS" && ARGS+=("${_extra[@]}")

echo "qwen4: preset=$PRESET backend=$BACKEND quant=$QUANT kv=$KV_TYPE ctx=$CTX profile=$PROFILE mtp=$MTP effort=$THINK_EFFORT" >&2

if [[ "$BACKEND" == "vulkan" ]]; then
  exec "$ROOT/llama.cpp/build/bin/llama-server" "${ARGS[@]}"
else
  exec podman run --rm --replace --name qwen4-sycl \
    --device /dev/dri --group-add keep-groups --security-opt label=disable \
    --network host -v "$ROOT/models:/models:ro" \
    localhost/llama-sycl:latest "${ARGS[@]}"
fi

scripts/qwen4

#!/usr/bin/env bash
# qwen4 — manage the local Qwen4 server (one preset at a time, 127.0.0.1:8080)
#   qwen4 start [preset]   stop any running preset, start this one (default: PRESET from env file)
#                          also sets opencode/pi/hermes context limits to the preset's ctx (SYNC_AGENTS=0 in env to skip)
#   qwen4 stop             stop the server
#   qwen4 restart          restart the running preset
#   qwen4 status           show running preset, memory, health
#   qwen4 logs             follow the server log
#   qwen4 presets          list presets
set -euo pipefail
ENV_FILE="$HOME/.config/qwen4/env"
default_preset() { (source "$ENV_FILE" 2>/dev/null; echo "${PRESET:-quality}"); }
SERVE="$HOME/Projects/qwen4/scripts/qwen4-serve.sh"
# Rewrite the agents' context limits (opencode, pi, hermes) to $1 tokens. Only numeric values of these keys change.
sync_agents() {
  local ctx="$1" f changed=()
  f="$HOME/.config/opencode/opencode.json"
  [[ -f "$f" ]] && grep -qE '"context": *[0-9]+' "$f" && ! grep -qE "\"context\": *$ctx\b" "$f" \
    && sed -i -E "s/(\"context\": *)[0-9]+/\1$ctx/" "$f" && changed+=(opencode)
  f="$HOME/.pi/agent/models.json"
  [[ -f "$f" ]] && grep -qE '"contextWindow": *[0-9]+' "$f" && ! grep -qE "\"contextWindow\": *$ctx\b" "$f" \
    && sed -i -E "s/(\"contextWindow\": *)[0-9]+/\1$ctx/" "$f" && changed+=(pi)
  f="$HOME/.hermes/config.yaml"
  [[ -f "$f" ]] && grep -qE 'context_length: *[0-9]+' "$f" && grep -E 'context_length: *[0-9]+' "$f" | grep -vqE "context_length: *$ctx\b" \
    && sed -i -E "s/(context_length: *)[0-9]+/\1$ctx/" "$f" && changed+=(hermes)
  if ((${#changed[@]})); then echo "agent context set to $ctx tokens: ${changed[*]} (restart running agent sessions to pick it up)"
  else echo "agent context already $ctx tokens"; fi
}
running() { systemctl --user list-units --type=service --state=active,activating --no-legend 'qwen4@*' 2>/dev/null | awk '{print $1}'; }

case "${1:-status}" in
  start)
    p="${2:-$(default_preset)}"
    ctx=$("$SERVE" --print-ctx "$p") || exit 2   # unknown preset -> error before stopping anything
    [[ "$( (source "$ENV_FILE" 2>/dev/null; echo "${SYNC_AGENTS:-1}") )" == 0 ]] || sync_agents "$ctx"
    for u in $(running); do systemctl --user stop "$u"; done
    systemctl --user start "qwen4@$p.service"
    echo "starting preset '$p' ... (qwen4 logs to follow, qwen4 status to check)"
    for _ in $(seq 1 90); do
      curl -sf http://127.0.0.1:8080/health >/dev/null && { echo "ready on http://127.0.0.1:8080/v1"; exit 0; }
      systemctl --user is-active -q "qwen4@$p.service" || { echo "failed to start; see: qwen4 logs" >&2; exit 1; }
      sleep 2
    done
    echo "still loading; check: qwen4 status" ;;
  stop)    for u in $(running); do systemctl --user stop "$u"; done; echo stopped ;;
  restart) u=$(running | head -1); [[ -n "$u" ]] && systemctl --user restart "$u" && echo "restarted $u" || echo "nothing running" ;;
  status)
    u=$(running | head -1)
    echo "unit:   ${u:-none}"
    echo "health: $(curl -sf http://127.0.0.1:8080/health 2>/dev/null || echo down)"
    awk '/^MemAvailable/{printf "memory: %.1f GiB available\n", $2/1048576}' /proc/meminfo ;;
  logs)    u=$(running | head -1); journalctl --user -f -u "${u:-qwen4@*}" ;;
  presets)
    cat <<'EOF'
preset         quant        kv    ctx    MTP  free RAM*  prompt / decode t/s*
512k           UD-IQ3_XXS   q4_0  512K   on   2.5 GiB    441 / 25.5
lean           UD-IQ3_XXS   q4_0  256K   on   7.0 GiB    336 / 26.4   (default)
lean-128k      UD-IQ3_XXS   q4_0  128K   on   TBD        TBD           more headroom, same weights
quality        UD-Q3_K_XL   q4_0  256K   on   5.2 GiB    439 / 26.4   higher-fidelity weights
quality-512k   UD-Q3_K_XL   q4_0  512K   off  3.6 GiB    173 / 21.7   higher-fidelity, no room for MTP
1m             UD-IQ3_XXS   q4_0  1M     off  0.3 GiB    117 / 21.9   swaps (+1.1 GiB); occasional use only
* SYCL, browser+IDE open, 16K-token prompt (bench/results.md)
EOF
    echo "configured default: $(default_preset)" ;;
  *) sed -n '2,9p' "$0"; exit 2 ;;
esac

opencode.json

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "qwen4": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Qwen4 (local llama.cpp)",
      "options": {
        "baseURL": "http://127.0.0.1:8080/v1",
        "apiKey": "none"
      },
      "models": {
        "qwen4": {
          "name": "Qwen4-35B-A3B (local)",
          "reasoning": true,
          "interleaved": {
            "field": "reasoning_content"
          },
          "limit": {
            "context": 262144,
            "output": 16384
          },
          "options": {
            "temperature": 1.0,
            "top_p": 0.95,
            "top_k": 20,
            "min_p": 0.0,
            "chat_template_kwargs": {
              "reasoning_effort": "low"
            }
          },
          "variants": {
            "high": {
              "chat_template_kwargs": {
                "reasoning_effort": "high"
              }
            },
            "fast": {
              "temperature": 0.7,
              "top_p": 0.8,
              "presence_penalty": 1.5,
              "chat_template_kwargs": {
                "reasoning_effort": "off",
                "enable_thinking": false
              }
            }
          }
        }
      }
    }
  }
}

pi models.json

{
  "$schema": "https://pi.dev/schemas/models.schema.json",
  "providers": {
    "qwen4-local": {
      "baseUrl": "http://127.0.0.1:8080/v1",
      "api": "openai-completions",
      "apiKey": "none",
      "models": [
        {
          "id": "qwen4",
          "name": "Qwen4-35B-A3B (local)",
          "reasoning": true,
          "thinkingLevelMap": {
            "off": "off",
            "minimal": null,
            "low": "low",
            "medium": null,
            "high": "high",
            "xhigh": "xhigh"
          },
          "contextWindow": 262144,
          "maxTokens": 16384,
          "cost": {
            "input": 0,
            "output": 0,
            "cacheRead": 0,
            "cacheWrite": 0
          },
          "samplingParams": {
            "top_k": 20,
            "min_p": 0.0
          },
          "samplingParamsByThinkingLevel": {
            "off": {
              "temperature": 0.7,
              "top_p": 0.8,
              "presence_penalty": 1.5
            },
            "low": {
              "temperature": 1.0,
              "top_p": 0.95,
              "presence_penalty": 0.0
            },
            "high": {
              "temperature": 1.0,
              "top_p": 0.95,
              "presence_penalty": 0.0
            },
            "xhigh": {
              "temperature": 1.0,
              "top_p": 0.95,
              "presence_penalty": 0.0
            }
          },
          "compat": {
            "thinkingFormat": "chat-template",
            "chatTemplateKwargs": {
              "reasoning_effort": {
                "$var": "thinking.effort"
              },
              "enable_thinking": {
                "$var": "thinking.enabled"
              }
            },
            "supportsDeveloperRole": false,
            "supportsReasoningEffort": false
          }
        }
      ]
    }
  }
}

hermes config.yaml

# Qwen4 local server (llama.cpp on 127.0.0.1:8080).
# Switch profile in hermes with: /model custom:qwen4-fast  (or qwen4-think)
model:
  provider: custom:qwen4-think
  default: qwen4-think
  base_url: http://127.0.0.1:8080/v1
  context_length: 262144

agent:
  reasoning_effort: low   # template accepts xhigh/high/low/off only (no "medium")

custom_providers:
  - name: qwen4-think
    base_url: http://127.0.0.1:8080/v1
    api_key: none
    model: qwen4-think
    context_length: 262144
    extra_body:
      reasoning_effort: low
      temperature: 1.0
      top_p: 0.95
      top_k: 20
      min_p: 0.0
  - name: qwen4-fast
    base_url: http://127.0.0.1:8080/v1
    api_key: none
    model: qwen4-fast
    context_length: 262144
    extra_body:
      reasoning_effort: "off"
      chat_template_kwargs:
        reasoning_effort: "off"
        enable_thinking: false
      temperature: 0.7
      top_p: 0.8
      top_k: 20
      min_p: 0.0
      presence_penalty: 1.5