Skip to content

feat: --mode strix, a basal-1.5 / basal-2.0 forward with Triton kernels for AMD Strix Halo (gfx1151) - #14

Merged
rkinas merged 5 commits into
rkinas:mainfrom
kardysm:strix-halo-perf
Oct 19, 2026
Merged

rkinas merged 5 commits into
rkinas:mainfrom
kardysm:strix-halo-perf

Conversation

@kardysm

@kardysm kardysm commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

(Benchmarking files are in separate PR I didn't file against this upstream - results below: github.com/kardysm/pull/3)

A profile of --mode gguf on the Radeon 8060S: every request is >=98.5% GPU decode at 16-19 useful TFLOPS; FFN matmuls take 47-69% of the GPU time (21-25 TFLOPS), flash attention up to 28.5% on long states (~11 TFLOPS), unfused bias / residual / SwiGLU passes ~15% (the model has biases on every linear layer). basal/strix.py (StrixHaloFastBackend) keeps the bf16 weights and replaces those kernels:

  • attention: Triton flash attention over the packed prefix trie, GQA-packed. The block mask becomes an interval per key (depth-first packing: key k is visible to query q iff k <= q < sub_end[k]); key blocks no query can see are skipped, fully visible ones run unmasked. ~20 TFLOPS at 6k tokens (AOTriton ~10)
  • FFN input: gate, up, biases and SwiGLU in one kernel, ~32 TFLOPS (F.linear + silu*up ~17)
  • qkv / o / down: Triton matmuls with the bias and residual add in the epilogue, tile configs per row count
  • RMSNorm and rotary kernels, the last layer for the readout rows only, all rows of a chunk one sequence (no padding, shapes or graphs), the GPU awaited by polling an event (ROCm's synchronize spins a core at 100%); rounding as the stock bf16 forward

Request matrix over HTTP against gguf, basal-1.5-4.5B: 1.12-1.75x (S 1 q 178 -> 159 ms, L 1 q 1.28 -> 0.74 s, XL 1 q 4.16 -> 2.73 s, XL 20 q 6.77 -> 4.57 s; 32 clients 7.7 -> 10.9/s); 144/144 decisions equal to an fp32 reference, 26/26 edge cases. basal-2.0-4.5B (same Llama shape) runs through it unchanged: 1.37-1.81x except one short question at a time (136 -> 144 ms, 0.94x); XL 20 q 5.25 -> 2.90 s, 32 clients 11.5 -> 19.0/s; 142/144 equal to fp32 (the other two are one 0.502 / 0.498 question), 26/26 edge cases. GTT 10.0 GiB, start-up 6-7 s.

Opt-in by name (--mode strix in basal-serve and basal-bench); every other mode and basal/engine.py are unchanged. Like GGUFBackend it runs its own run_shared, so it declares streams = False, inflight = 1 (no early readouts, one engine call at a time). Tests: tests/test_strix.py (kernels against their stock counterparts, the interval mask against the block mask, the backend against separate forwards).


basal-2.0-4.5B through --mode strix

basal-2.0-4.5B has the architecture of basal-1.5 (Llama, 60 layers, hidden 2048, GQA 16/2, biases) and runs through --mode strix unchanged. Against --mode gguf with basal-2.0-4.5B-Q8_0.gguf, interleaved A/B with both servers up (each shape sent to both engines in alternating order, median of 5 rounds; the script bench_ab.py is in #3), so thermal drift and the power limit hit both alike:

request prompt tokens gguf strix speed-up
S (≈100 tokens), 1 question 201 136 ms 144 ms 0.94×
S, 5 questions 1,508 277 ms 203 ms 1.37×
M (≈570), 1 question 669 397 ms 263 ms 1.51×
M, 10 questions 8,825 816 ms 464 ms 1.76×
L (≈2,000), 1 question 2,109 1.27 s 714 ms 1.77×
L, 5 questions 16,772 1.41 s 788 ms 1.79×
XL (≈6,000), 1 question 6,163 4.16 s 2.41 s 1.73×
XL, 5 questions 49,204 4.37 s 2.52 s 1.73×
XL, 20 questions 141,818 5.25 s 2.90 s 1.81×
single questions, 32 clients – 11.5/s 19.0/s 1.65×
  • Speed: faster than gguf on every shape except one short question at a time. The long-state gain is larger than with basal-1.5 (XL, 1 question: 1.70× in the matrix, 1.52× with 1.5). Each added question costs 12–28 ms (gguf 37–55 ms).
  • Answers: 142/144 decisions equal to the fp32 reference for both engines (strix mean |Δp| 0.0047, max 0.028; gguf 0.0064, 0.068). The two others are one question that fp32 puts at 0.502 / 0.498 and both engines the other way round. All 26 edge-case decisions equal fp32. strix and gguf differ on 4 of 188 matrix decisions, all multi-label yes/no on XL at 0.47–0.54.
  • Costs: start-up 6.2 s, 10.1 GiB GTT (gguf 3.3 s, 5.8 GiB).
  • basal-1.5 → 2.0: prompt format 2 reads one option order by default (1.5 read two), so requests carry about half the prompt tokens. With strix: S with 20 questions 1.08 s → 467 ms, XL with 20 questions 4.57 → 3.00 s, 32 clients 10.9 → 20.3/s.
  • The full request matrix, edge cases, fp32 reference and raw results are in Korpus prawdziwych polskich dokumentów (klauzule UOKiK, OWU) z odpowiedziami Jeva 1.13.0 #3. A one-engine-at-a-time matrix run agrees with the A/B within 5% except S with 1 question (an outlier: strix 231 ms there, 142–148 ms in every A/B round).

The numbers in the sections below were measured with basal-1.5-4.5B on #1 (981b354).

Summary

--mode strix is a basal forward written for AMD Strix Halo (Ryzen AI Max+ 395, Radeon 8060S, gfx1151), on basal-1.5; basal-2.0 runs through it unchanged. It keeps the bf16 weights and replaces the kernels that a profile showed to be slow on this GPU with Triton ones. On a request matrix with basal-1.5 it is 1.12–1.75× faster than --mode gguf and agrees with an fp32 reference on 144 of 144 decisions. With basal-2.0 it is 1.37–1.81× faster except for one short question at a time (0.94×), and agrees with fp32 on 142 of 144 (the other two are a 0.502 / 0.498 tie).

It is opt-in by name (basal-serve --mode strix, basal-bench --modes strix). Every other mode is unchanged: basal/engine.py is not touched, and server.py / bench.py only gain the dispatch for the new mode. The new module is basal/strix.py. It needs no new dependencies (Triton ships with PyTorch on ROCm) and adds no CLI flags.

Why: where --mode gguf spends its time

Every request is at least 98.5% GPU decode, at 16–19 useful TFLOPS whatever the size. GPU time by operation, from llama.cpp's Vulkan performance logger:

operation S, 1 q L, 1 q XL, 1 q XL, 20 q speed
FFN matmuls 69% 60% 51% 47% 21–25 TFLOPS
flash attention 2.5% 10% 23% 28.5% ~11 TFLOPS on long rows
element-wise (bias and residual adds, SwiGLU, norms) 16% 18% 15.5% 14.5% memory-bound, fp32
attention projections 12.5% 12.4% 10.4% 9.7% q / o 18, k / v 8–9 TFLOPS

The model has biases on every linear layer, and llama.cpp adds each one in a separate pass. This GPU sustains ~35–40 TFLOPS on matmuls. The CPU, weight bandwidth, clock ramp-up and llama.cpp's batch size are not limits.

What it does

kernel at ~6k tokens stock
attention over the packed prefix trie, GQA-packed ~20 TFLOPS AOTriton causal ~10
gate + up + biases + SwiGLU in one kernel ~32 TFLOPS F.linear + silu × up ~17
qkv / o / down with bias and residual in the epilogue, tile configs per row count o 2.4 ms / layer F.linear + add 3.7 ms
  • Attention mask. The block mask of a packed request (the state once, then every question and option order) becomes an interval per key. Depth-first packing puts each subtree in one contiguous range, so key k is visible to query q iff k ≤ q < sub_end[k]. Key blocks no query can see are skipped, and fully visible ones run without a mask. A packed row therefore costs what a causal row of the same length costs.
  • One sequence per chunk. Rows of several requests are separate trees in one sequence, so there is no padding, no captured shapes and no graphs. Requests over 16,384 tokens are bisected as in GraphBackend.
  • Smaller pieces: RMSNorm and rotary kernels, the last layer computed only for the readout rows, and the GPU awaited by polling an event (ROCm's synchronize spins a CPU core at 100%).
  • Rounding follows the stock bf16 forward step by step. The Hugging Face modules keep views of the fused q / k / v weights, so the evidence head still runs the stock model.

Results: request matrix over HTTP, p50

state 1 question 5 questions 20 questions
S (≈100 tokens) 178 → 159 ms (1.12×) 573 → 348 ms (1.65×) 1.79 → 1.08 s (1.66×)
M (≈570) 439 → 289 ms (1.52×) 817 → 480 ms (1.70×) 2.12 → 1.25 s (1.70×)
L (≈2,000) 1.28 s → 736 ms (1.74×) 1.73 → 1.09 s (1.59×) 3.22 → 2.12 s (1.52×)
XL (≈6,000) 4.16 → 2.73 s (1.52×) 4.78 → 3.28 s (1.46×) 6.77 → 4.57 s (1.48×)
  • Speed: fastest on all 20 shapes. --mode fast-nocompile as shipped is 2–12× slower than strix here, at 888 s start-up and 32 GiB.
  • Throughput, single questions over short states: 32 clients 7.7 → 10.9/s.
  • Answers: 144/144 decisions equal to fp32 (mean |Δp| 0.0042; gguf 143/144, 0.0067) and 26/26 edge cases.
  • Costs: 10.0 GiB GTT against 5.8 for gguf; start-up 6–7 s.

Full tables, method and raw results: #3 (docs/benchmarks/STRIX_HALO.md).

Limits

  • Long states stay below 2×. Their matmuls are 58 TFLOP at ~35 TFLOPS sustained, and under strix the package runs at its power limit (~160 W, then ~140 W after ~25 s), with the GPU at 2.15–2.33 GHz. A single XL forward on a cool GPU takes 2.37 s (1.76×).
  • One short question at a time is faster with gguf (141 vs 159 ms): the bf16 weights are 9 GB per forward, the Q8_0 file 5 GB.
  • Model shapes: Llama models with silu, a power-of-two hidden size, head size (at least 16) and number of query heads per kv head, projection widths that are multiples of the tile sizes, and RoPE whose frequencies do not depend on the sequence length (no dynamic, longrope); all checked at start-up with a message naming what does not fit. bf16 only.
  • Hardware: ROCm only (the kernels take AMD launch options; on CUDA the mode refuses at start-up). Tile configs were tuned on the 8060S, and the mode has not been run on other GPUs.

Tests

  • tests/test_strix.py, 29 cases:

    • every Triton kernel against its stock counterpart: attention against a dense masked softmax over rows of several requests (including readout-only queries), rotary (bit-identical), projections for every row-count config, FFN input and RMSNorm;
    • the interval mask against the block mask it replaces;
    • the backend on a tiny random Llama with biases against separate bf16 forwards: questions over one state, several requests in one sequence against the same request alone, chunking and bisection, determinism;
    • the start-up checks (refused shapes, RoPE types and non-ROCm builds), the backend under torch.use_deterministic_algorithms, and the warmup on a 64-token vocabulary;
    • the mode dispatch.

    It caught rows of a later request in one sequence turning into NaN, which is fixed.

  • Full suite on the 8060S, rebased onto 2.0.0: 521 passed, 20 skipped (MLX, and the media / mcp extras not installed, training-side code). tests/test_format2_vectors.py passes against the basal-2.0-4.5B tokenizer.

  • Engine 2.0.0 installed into a venv with llama-cpp-python (Vulkan): 511 passed, 19 skipped; tests/test_strix.py 18 passed.

  • Real model: on Run on Apple Silicon (MPS) #1, answers equal to the benchmarked basal-1.5 run (max |Δp| 0.000). basal-2.0-4.5B: request matrix, edge cases, fp32 reference and the A/B above.

Summary by Sourcery

Add an opt-in AMD Strix Halo inference mode that uses specialized Triton kernels to accelerate bf16 basal model serving without changing existing backends.

New Features:

  • Add an opt-in --mode strix backend for AMD Strix Halo systems, supporting basal-1.5 and basal-2.0 models with bf16 inference.
  • Expose Strix mode through serving and benchmarking CLIs, including deterministic execution support.

Enhancements:

  • Optimize Strix Halo inference with specialized Triton attention, feed-forward, projection, normalization, and rotary kernels while preserving existing modes.
  • Support packed request execution, readout-only final layers, request chunking, model compatibility checks, and ROCm-specific synchronization.

Documentation:

  • Document Strix Halo support, usage, compatibility limits, performance characteristics, and benchmark results.
  • Add benchmark tooling and recorded results for latency, throughput, accuracy, startup, and memory comparisons.

Tests:

  • Add comprehensive Strix backend tests covering Triton kernels, packed attention masks, model forwards, batching, chunking, determinism, validation, and mode dispatch.

…ls for AMD Strix Halo (gfx1151)

A profile of --mode gguf on the Radeon 8060S: every request is >=98.5% GPU decode at
16-19 useful TFLOPS; FFN matmuls take 47-69% of the GPU time (21-25 TFLOPS), flash
attention up to 28.5% on long states (~11 TFLOPS), unfused bias / residual / SwiGLU
passes ~15% (the model has biases on every linear layer). basal/strix.py
(StrixHaloFastBackend) keeps the bf16 weights and replaces those kernels:

- attention: Triton flash attention over the packed prefix trie, GQA-packed. The block
  mask becomes an interval per key (depth-first packing: key k is visible to query q
  iff k <= q < sub_end[k]); key blocks no query can see are skipped, fully visible ones
  run unmasked. ~20 TFLOPS at 6k tokens (AOTriton ~10)
- FFN input: gate, up, biases and SwiGLU in one kernel, ~32 TFLOPS (F.linear + silu*up ~17)
- qkv / o / down: Triton matmuls with the bias and residual add in the epilogue, tile
  configs per row count
- RMSNorm and rotary kernels, the last layer for the readout rows only, all rows of a
  chunk one sequence (no padding, shapes or graphs), the GPU awaited by polling an event
  (ROCm's synchronize spins a core at 100%); rounding as the stock bf16 forward

Request matrix over HTTP against gguf, basal-1.5-4.5B: 1.12-1.75x (S 1 q 178 -> 159 ms,
L 1 q 1.28 -> 0.74 s, XL 1 q 4.16 -> 2.73 s, XL 20 q 6.77 -> 4.57 s; 32 clients
7.7 -> 10.9/s); 144/144 decisions equal to an fp32 reference, 26/26 edge cases.
basal-2.0-4.5B (same Llama shape) runs through it unchanged: 1.37-1.81x except one
short question at a time (136 -> 144 ms, 0.94x); XL 20 q 5.25 -> 2.90 s, 32 clients
11.5 -> 19.0/s; 142/144 equal to fp32 (the other two are one 0.502 / 0.498 question),
26/26 edge cases. GTT 10.0 GiB, start-up 6-7 s.

Opt-in by name (--mode strix in basal-serve and basal-bench); every other mode and
basal/engine.py are unchanged. Like GGUFBackend it runs its own run_shared, so it
declares streams = False, inflight = 1 (no early readouts, one engine call at a time).
Tests: tests/test_strix.py (kernels against their stock counterparts, the interval mask
against the block mask, the backend against separate forwards).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces an opt-in --mode strix backend for AMD Strix Halo that retains bf16 model weights while replacing the main Llama forward-path bottlenecks with fused, Strix-tuned Triton kernels and interval-masked packed attention. The integration leaves existing modes untouched and is backed by GPU kernel, masking, packed-request, chunking, numerical-equivalence, determinism, and dispatch tests.

Sequence diagram for the Strix packed forward pass

sequenceDiagram
    participant Request
    participant Backend as StrixHaloFastBackend
    participant Triton as Triton kernels
    participant GPU as AMD_Strix_Halo_GPU

    Request->>Backend: run_shared(groups)
    Backend->>Backend: _chunks_tok(units)
    Backend->>Backend: _sub_end(pack, off)
    Backend->>Triton: _rmsnorm(h, w)
    Backend->>Triton: _linear(qkv, x, w, b)
    Backend->>Triton: _rope(qkv, pos)
    Backend->>Triton: _attn_fwd(q, k, v, sub, kmin, kmax)
    Backend->>Triton: _linear(o, a, wo, bo, h)
    Backend->>Triton: _swiglu_mm(x, wg, wu, bg, bu)
    Backend->>Triton: _linear(down, g, wd, bd, h)
    Triton->>GPU: Execute fused kernels
    Backend->>Backend: _wait()
    Backend-->>Request: Readout probabilities
Loading

Flow diagram for interval-masked packed attention

flowchart TD
    Pack["Pack request trees depth-first"] --> Bounds["_sub_end(pack, off)"]
    Bounds --> Intervals["Each key gets a visible interval"]
    Intervals --> Skip["Skip key blocks no query can see"]
    Intervals --> Full["Run fully visible blocks unmasked"]
    Intervals --> Mask["Apply interval mask to partial blocks"]
    Skip --> Attention["_attn_fwd"]
    Full --> Attention
    Mask --> Attention
    Attention --> Readout["Readout rows"]
Loading

File-Level Changes

Change Details Files
Adds an AMD Strix Halo-specific bf16 backend using fused Triton kernels for packed-trie attention and Llama projection/FFN operations.
  • Implements interval-based attention masking with GQA-packed flash attention and readout-only final-layer execution.
  • Fuses FFN projections, biases, and SwiGLU; fuses projection bias and residual epilogues; adds custom RMSNorm and rotary kernels.
  • Fuses q/k/v weights during initialization, preserves views for the stock evidence head, chunks or bisects oversized packed requests, and polls GPU events to avoid ROCm synchronization spinning.
  • Validates supported Llama model dimensions, activations, biases, bf16 dtype, and Strix-tuned launch configurations.
basal/strix.py
Integrates the new backend as an opt-in strix mode without changing existing engine modes.
  • Adds strix dispatch and CLI help text to benchmarking.
  • Adds strix mode registration and backend construction to serving.
  • Configures the backend for one in-flight call with no stream-based early readouts.
basal/bench.py
basal/server.py
Adds GPU-focused correctness and integration coverage for the fused backend.
  • Compares Triton attention, rotary, projections, FFN, and RMSNorm kernels with stock PyTorch/Hugging Face behavior.
  • Verifies interval masks match packed prefix-trie block masks and that packed, multi-request, chunked, bisected, and deterministic execution matches separate forwards.
  • Tests mode dispatch while confirming the existing GraphBackend packing remains unchanged.
tests/test_strix.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 8 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="basal/strix.py" line_range="338" />
<code_context>
+            xa, oa = x[a: a + step], o[a: a + step]
+            m = xa.shape[0]
+            c = next(c for lim, c in self.LINEAR[kind] if lim is None or m <= lim)
+            _linear[(triton.cdiv(m, c["BM"]) * (N // c["BN"]),)](xa, w, b, oa, oa, m, N, K, xa.stride(0), w.stride(0),
+                                                                 oa.stride(0), RES=r is not None, **c)
+        return o
</code_context>
<issue_to_address>
**Trailing QKV channels stay uninitialized**

When a Llama model passes startup checks but its fused QKV width is not divisible by the selected BN, `_linear` launches `N // c["BN"]` output tiles, so trailing QKV channels remain uninitialized and `_rope` and attention consume them, producing incorrect answers.

Round the output-tile count up, such as with `triton.cdiv(N, c["BN"])`, and mask out-of-range output columns in the kernel.

Also at `basal/strix.py:339`.
</issue_to_address>

### Comment 2
<location path="basal/strix.py" line_range="261" />
<code_context>
+                self.run_shared([(toks, [[30, 31], [30, 31]])])
+
+    def _oversize(self, pack, n):
+        return len(pack[0]) > self.TOKEN_BUDGET
+
+    def _chunks_tok(self, units):
</code_context>
<issue_to_address>
**Oversized prompts exceed the token budget**

When the model accepts a prompt longer than `TOKEN_BUDGET` and the request contains it as a single prompt, `GraphBackend._units` only bisects oversized packs with multiple prompts, and `_chunks_tok` admits the oversized unit by itself. `forward` allocates intermediates for the full prompt, which can exhaust GPU memory and fail the request.

Split oversized single-prompt units before chunking, or reject prompts that exceed the budget.

Also at `basal/strix.py:268`, `basal/strix.py:270`.
</issue_to_address>

### Comment 3
<location path="basal/strix.py" line_range="252-253" />
<code_context>
+        # rotary tables as the stock model computes them: fp32 angles, cos / sin scaled, then cast to bf16
+        rot = m.rotary_emb
+        pos = torch.arange(cfg.max_position_embeddings, device=self.dev, dtype=torch.float32)
+        ang = pos[:, None] * rot.inv_freq.float()[None, :]
+        self.cos = (ang.cos() * rot.attention_scaling).to(torch.bfloat16).contiguous()
+        self.sin = (ang.sin() * rot.attention_scaling).to(torch.bfloat16).contiguous()
+        if warm:  # compile every kernel once (Triton JIT), short and multi-block rows
</code_context>
<issue_to_address>
**Long-context answers use incorrect RoPE**

When the selected Llama config uses dynamic or position-dependent RoPE scaling and a request passes its scaling threshold, the startup code builds `self.cos` and `self.sin` from the initial `rot.inv_freq` and `attention_scaling`, and inference does not apply the rotary module's updated frequencies for the current sequence length. Long-context attention therefore produces predictions that differ from the model.

Compute or update the rotary tables using the scaling for the current sequence length, as the model's rotary module does.
</issue_to_address>

### Comment 4
<location path="basal/strix.py" line_range="225-226" />
<code_context>
+        self.H, self.KV = cfg.num_attention_heads, cfg.num_key_value_heads
+        self.D = getattr(cfg, "head_dim", None) or cfg.hidden_size // self.H
+        self.hidden, self.eps = cfg.hidden_size, cfg.rms_norm_eps
+        if self.D % 2 or self.hidden & (self.hidden - 1) or cfg.intermediate_size % 64 \
+                or self.hidden % 64 or cfg.hidden_act != "silu":
+            raise ValueError("--mode strix expects a Llama with silu, a power-of-two hidden size and an FFN size "
+                             "divisible by 64")
</code_context>
<issue_to_address>
**Accepted head shapes fail at runtime**

When a Llama model has an even, non-power-of-two head dimension or a non-power-of-two query-heads-per-KV-head ratio, the startup checks accept these shapes, but `_attn_fwd` or `_rope` passes a non-power-of-two extent to `tl.arange`; Triton kernel compilation fails and requests using the model fail.

Validate that both the head dimension and query-heads-per-KV-head ratio meet the power-of-two requirements before accepting the model.
</issue_to_address>

### Comment 5
<location path="basal/strix.py" line_range="324" />
<code_context>
+        N = wg.shape[0]
+        o = torch.empty(M, N, device=x.device, dtype=x.dtype)
+        c = next(c for lim, c in self.FFN if lim is None or M <= lim)
+        grid = (triton.cdiv(M, c["BM"]) * (N // c["BN"]),)
+        _swiglu_mm[grid](x, wg, wu, bg, bu, o, M, N, K, x.stride(0), wg.stride(0), o.stride(0), **c)
+        return o
</code_context>
<issue_to_address>
**Projection tail channels go unwritten**

When a Llama model passes the current startup checks but its fused QKV width is not divisible by the selected `BN`, `_linear` sizes its output grid with `N // BN`, but the startup checks do not require the fused QKV output width to be divisible by the selected tile width. For an accepted Llama shape such as hidden size 2048, 32 query heads, and 1 KV head, large row batches use `BN=128` with a 2176-wide QKV output, leaving the last 64 channels unwritten; rotary and attention then consume uninitialized values and predictions are wrong.

Use ceiling division and mask output-channel loads/stores in `_linear`, or reject configurations whose projection widths are not tile-divisible.
</issue_to_address>

### Comment 6
<location path="basal/server.py" line_range="71" />
<code_context>
     "mlx-q8": ("mlx", "q8", False),         # "mlx" with 8-bit weights made at load time (less memory, not faster)
     "mps": ("mps", None, False),            # Apple Silicon: PyTorch MPS + shared prefix, no graphs
     "gguf": ("gguf", None, False),          # llama.cpp in process on a GGUF file (--gguf; Metal, CUDA or CPU)
+    "strix": ("strix", None, False),       # AMD Strix Halo: Triton attention / FFN kernels, one sequence per chunk
     "ollama": ("ollama", None, False),      # Ollama with the GGUF exports (1.5); --ollama-url, --ollama-model
     "llamacpp": ("llamacpp", None, False),  # llama.cpp server with the GGUF exports (1.5); --llamacpp-url
</code_context>
<issue_to_address>
**Deterministic mode rejects Strix**

When the caller starts the server with `--mode strix --deterministic`, `--mode strix` maps to kind `strix`, so `Server.__init__` passes that kind to `deterministic_setup`, which rejects it before the backend loads. Callers cannot use the server's deterministic option with this in-process backend.

Add `strix` to the deterministic-kind allowlist if its kernels and readout path satisfy the deterministic contract.
</issue_to_address>

### Comment 7
<location path="basal/strix.py" line_range="257" />
<code_context>
+        self.sin = (ang.sin() * rot.attention_scaling).to(torch.bfloat16).contiguous()
+        if warm:  # compile every kernel once (Triton JIT), short and multi-block rows
+            for n in (300, 1100):
+                toks = [[1] + list(range(1000, 1000 + n)), [1] + list(range(1000, 1000 + n // 2)) + [7, 8]]
+                self.run_shared([(toks, [[30, 31], [30, 31]])])
+
</code_context>
<issue_to_address>
**Warmup fails on small vocabularies**

When the model vocabulary has fewer than 2100 entries and the backend uses its default `warm=True`, warmup sends token IDs from 1000 through 2099 to the embedding layer without checking the model vocabulary size. For a valid small-vocabulary Llama checkpoint, initialization raises an embedding/device error and the server cannot start in `strix` mode.

Generate warmup IDs bounded by the embedding vocabulary, or use a valid repeated token ID.
</issue_to_address>

### Comment 8
<location path="tests/test_strix.py" line_range="16" />
<code_context>
+from basal.engine import GraphBackend
+
+triton = pytest.importorskip("triton")
+gpu = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a ROCm (or CUDA) GPU and Triton")
+
+
</code_context>
<issue_to_address>
**CUDA test runs fail at FFN**

When triton is installed and the test runs on a CUDA GPU rather than a ROCm GPU, `test_ffn_and_norm_match_the_stock_layer` reaches `_ffn_in` at line 159, which launches the FFN kernel with the backend’s `waves_per_eu` setting. Triton’s CUDA backend does not accept that AMD-specific launch option, so the test errors during compilation instead of checking the output.

Restrict this marker to supported ROCm devices, or make the FFN launch omit `waves_per_eu` on CUDA before running these tests there.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/strix.py Resolved
Comment thread basal/strix.py
self.run_shared([(toks, [[30, 31], [30, 31]])])

def _oversize(self, pack, n):
return len(pack[0]) > self.TOKEN_BUDGET

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Oversized prompts exceed the token budget

When the model accepts a prompt longer than TOKEN_BUDGET and the request contains it as a single prompt, GraphBackend._units only bisects oversized packs with multiple prompts, and _chunks_tok admits the oversized unit by itself. forward allocates intermediates for the full prompt, which can exhaust GPU memory and fail the request.

Split oversized single-prompt units before chunking, or reject prompts that exceed the budget.

Also at basal/strix.py:268, basal/strix.py:270.

Prompt for AI agents
In `basal/strix.py` at line 261:

**Oversized prompts exceed the token budget**

When the model accepts a prompt longer than `TOKEN_BUDGET` and the request contains it as a single prompt, `GraphBackend._units` only bisects oversized packs with multiple prompts, and `_chunks_tok` admits the oversized unit by itself. `forward` allocates intermediates for the full prompt, which can exhaust GPU memory and fail the request.

Split oversized single-prompt units before chunking, or reject prompts that exceed the budget.

Also at `basal/strix.py:268`, `basal/strix.py:270`.

Comment thread basal/strix.py Resolved
Comment thread basal/strix.py Resolved
Comment thread basal/strix.py Resolved
Comment thread basal/server.py Resolved
Comment thread basal/strix.py Resolved
Comment thread tests/test_strix.py Resolved
kardysm and others added 3 commits October 16, 2026 08:10
… --deterministic; safe warmup

From the review of rkinas#14:

- StrixHaloFastBackend.unsupported(cfg) replaces the start-up shape check. Every
  tile config must divide its projection: the matmuls have no column or depth
  masks, so a qkv width that is not a multiple of 128 left its last columns
  unwritten. Head size and query heads per kv head must be powers of two
  (tl.arange; other shapes failed to compile), head size at least 16. RoPE
  types whose frequencies depend on the sequence length (dynamic, longrope)
  are refused, since the tables are computed once. basal-1.5 and basal-2.0
  pass unchanged.
- ROCm only: the kernels take AMD launch options (waves_per_eu). On CUDA the
  mode now refuses at start-up, and the GPU tests skip.
- --deterministic accepts strix. It already runs one request per forward, and
  the Triton kernels have no atomics or split-K, so an answer depends only on
  its own request. Tested under torch.use_deterministic_algorithms: identical
  answers, no refused op.
- Warmup token ids stay within the vocabulary and lengths within the context.
- Docstring: a single prompt over TOKEN_BUDGET runs alone in one forward, as
  in GraphBackend.

Tests: 11 new in tests/test_strix.py; suite 521 passed, 20 skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…WARE.md, SERVING.md

docs/benchmarks/STRIX_HALO.md: the gguf profile behind --mode strix, the request
matrix over HTTP (S/M/L/XL states x 1-20 questions, concurrency 1-64), edge cases and
an fp32 reference for gguf, strix and the shipped graph mode, with the method. The
scripts that produced it (bench_matrix.py, edge_check.py, report.py) and the raw
results (docs/benchmarks/results/) are next to it.

basal-1.5-4.5B against gguf: 1.12-1.75x (S 1 q 178 -> 159 ms, L 1 q 1.28 -> 0.74 s,
XL 1 q 4.16 -> 2.73 s, XL 20 q 6.77 -> 4.57 s; 32 clients 7.7 -> 10.9/s); 144/144
decisions equal to fp32, 26/26 edge cases. One client with short questions stays
faster on gguf (141 vs 159 ms). GTT 10.0 GiB, start-up 6-7 s.

Also: an "AMD Strix Halo" section in docs/HARDWARE.md, the strix row in the modes
table of docs/SERVING.md, and a pointer to STRIX_HALO.md in the basal/strix.py
docstring.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
basal-2.0-4.5B (engine 2.0.0, same Llama shape as 1.5) runs through --mode strix
unchanged. Request matrix + edge cases + fp32 reference, and an interleaved A/B of
both servers (new docs/benchmarks/bench_ab.py: each shape to both engines in
alternating order, median of 5 rounds; 32-client bursts), against --mode gguf with
basal-2.0-4.5B-Q8_0.gguf:

- S 1 q 136 -> 144 ms (0.94x, gguf stays faster for one short question),
  S 5 q 1.37x, M 1 q 1.51x, L 1 q 1.27 s -> 714 ms (1.77x), XL 1 q 4.16 -> 2.41 s
  (1.73x), XL 20 q 5.25 -> 2.90 s (1.81x); 32 clients 11.5 -> 19.0/s (1.65x)
- 142/144 decisions equal to fp32 for both engines; the two others are one
  question fp32 puts at 0.502 / 0.498. 26/26 edge-case decisions.
- start-up 6.2 s, 10.1 GiB GTT (gguf 3.3 s, 5.8 GiB)

Prompt format 2 reads one option order by default, so requests carry about half
the prompt tokens of basal-1.5: strix S 20 q 1.08 s -> 467 ms, XL 20 q 4.57 ->
3.00 s, 32 clients 10.9 -> 20.3/s. Raw results in docs/benchmarks/results/2.0/,
tables in STRIX_HALO.md (basal-1.5 sections unchanged) and HARDWARE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kardysm

kardysm commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed in cdd73ad, apart from (2):

  1. Trailing QKV channels (and 5, the same issue): fixed by refusing these shapes at start-up rather than masking the kernels, which keeps the measured kernels unchanged. StrixHaloFastBackend.unsupported(cfg) requires every tile config to divide its projection (qkv, o, down, gate / up). The example in (5) is in fact tile-divisible: 2176 = 17 × 128. A head size of 16 with 8 query heads over 1 kv head (160 columns) is refused with a message naming the projection.
  2. Oversized single prompts: kept as is. A single prompt cannot be bisected the way a packed row can, and GraphBackend also runs one past its largest graph as a single forward. The server keeps prompts within the model's context (32,768 for basal-2.0, 2 × TOKEN_BUDGET). At that length the activations are about 1.5 GB, and the attention kernel needs no length × length buffer. The class docstring now says this.
  3. Dynamic RoPE: dynamic and longrope (the types whose frequencies transformers updates per sequence length) are refused at start-up. basal uses default.
  4. Head shapes: confirmed on the GPU. A head size of 48 or 80 fails to compile, and so do 3 query heads per kv head. Both must now be powers of two (head size at least 16), checked at start-up.
  5. --deterministic: strix added to DETERMINISTIC_KINDS. With one request per forward, the chunking and tile choice depend only on that request, and the kernels have no atomics or split-K. Tested under torch.use_deterministic_algorithms(True): identical answers, no refused op, and torch.empty is then NaN-filled, so an unwritten output element would show.
  6. Warmup on small vocabularies: warmup ids are taken modulo the vocabulary, and lengths are capped by the context. A tiny model with 1,024 positions failed the same way.
  7. CUDA: the mode is ROCm only. It now refuses on non-ROCm builds with a clear message, and the GPU tests skip unless torch.version.hip is set.

Tests: 11 new cases in tests/test_strix.py (29 in total); full suite 521 passed, 20 skipped on the 8060S.

docs(strix): --mode strix benchmarks, HARDWARE.md and SERVING.md (stacked on #2)
@rkinas

rkinas commented Oct 18, 2026

Copy link
Copy Markdown
Owner

Thanks, impressive kernels and profile. We'd like --mode strix in as an experimental, community-maintained backend after 2.2.0. Please: (1) drop docs/benchmarks/results/** and the bench scripts (keep the summary in STRIX_HALO.md, link your fork for raw data); (2) rebase onto v2.2.0; (3) parity against the bf16 eager reference on ~2,000 rows; (4) CODEOWNERS for basal/strix.py and tests/test_strix.py.

@rkinas

rkinas commented Oct 18, 2026

Copy link
Copy Markdown
Owner

Ok. I am merging it now. It will be in 2.2. Than you for your contribution.

@rkinas
rkinas merged commit 54f89f0 into rkinas:main Oct 19, 2026
1 check passed
rkinas added a commit that referenced this pull request Oct 19, 2026
…the scripts in the author's fork

STRIX_HALO.md gets a Raw results section computed from the JSON of #14 (request matrix p50 per shape for gguf, strix, fast-nocompile and the fp32 reference, both models; start-up, GTT, agreement with fp32, edge cases, throughput at 1 / 32 clients; the basal-2.0 A/B), attributed to @kardysm, in place of the sections report.py generated from the same files. The latency, start-up and agreement figures elsewhere on the page agree with the files. Removed: docs/benchmarks/results/** (27 files) and bench_ab.py, bench_matrix.py, edge_check.py, report.py; nothing in basal/ or tests/ uses them; kardysm#3 has them.
rkinas added a commit that referenced this pull request Oct 19, 2026
One line per external contributor whose commits are in main or in 2.2, with what they added and the PR: Paweł Kiszczak (#4), Piotr Durlej (#8), Kuba Sołtys (#15), Michał Kardyś (#14); names from their GitHub profiles and commit authors. README and WHATS_NEW 2.2 list basal-export-gguf, --mode tpu and --mode strix; NOTICE names the contributors.
@rkinas

rkinas commented Oct 19, 2026

Copy link
Copy Markdown
Owner

Thank you, Michał! --mode strix is merged and ships in basal v2.2.0
(https://github.com/rkinas/basal/releases/tag/v2.2.0), marked experimental and community-maintained, with your commits
exactly as you wrote them. The profile of where gguf spends its time on the 8060S, the interval form of the trie mask
and a test for every kernel against its stock counterpart made this easy to review.

What we added on top:

  • merged it with the 2.2.0 engine and with --mode tpu (add TPU support for basal 2.0 #15), which touched the same lines of server.py and
    bench.py;
  • the raw benchmark JSON and the scripts stay in your fork: before removing docs/benchmarks/results/** and the four
    scripts from this repository, we summarised the JSON in docs/benchmarks/STRIX_HALO.md ("Raw results (summary)":
    latency per request shape, start-up, memory, agreement with fp32, the edge cases and the basal-2.0 A/B, all computed
    from your files and attributed to you). Your figures elsewhere on the page agree with the files. The page links
    docs(strix): --mode strix benchmarks, HARDWARE.md and SERVING.md (stacked on #2) kardysm/basal#3 for the scripts and the data, so please keep that branch around;
  • unsupported(cfg) now refuses any model type other than llama first: on the real basal-omni configs (Gemma 4) the
    check stopped with an AttributeError before it ran. One parametrize case added to tests/test_strix.py;
  • HARDWARE.md / SERVING.md: an "experimental, community-maintained" section that names you and says the numbers are
    your measurements (we have no Strix Halo to reproduce them), and that the mode covers the Llama-architecture
    basal-1.5 / basal-2.0 (your shape checks refuse the mini models; basal-omni is not supported). You are in the README's
    new "Contributors" section.

We could only run the CPU-side tests here (12 pass on Linux with Triton; the kernel tests need ROCm). If you have a
moment, a run of tests/test_strix.py on the 8060S at v2.2.0 would close the loop.

If you'd like, we'd be glad to list you in CODEOWNERS for basal/strix.py, tests/test_strix.py and
docs/benchmarks/STRIX_HALO.md, so that changes there come to you for review. Entirely optional: just say so here.

@kardysm

kardysm commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @rkinas ! 🙌

just to be sure, do these still hold despite merging?

Please: (1) drop docs/benchmarks/results/** and the bench scripts (keep the summary in STRIX_HALO.md, link your fork for raw data); (2) rebase onto v2.2.0; (3) parity against the bf16 eager reference on ~2,000 rows; (4) CODEOWNERS for basal/strix.py and tests/test_strix.py.

If so, I'll implement the feedback

kardysm pushed a commit to kardysm/basal that referenced this pull request Oct 19, 2026
Upstream 2.2.0 includes the strix backend (rkinas#14, merge 54f89f0)
plus the maintainer's follow-ups (Llama-only check, docs). The merged tree
equals upstream v2.2.0 exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
rkinas pushed a commit that referenced this pull request Nov 2, 2026
Triton compiles a kernel once per tile config and per class of each
integer argument (1, a multiple of 16, other), and the row count picks
both. The start-up warm-up ran two lengths only, so the first request
whose length was a multiple of 16 in a tile-config range waited for new
copies: in the request matrix the first timed pass of S with 1 question
(208 tokens) and of M with 2 (720 tokens), on both machines of #14 / #21.

The warm-up now runs the projections on zero rows of every range and
class (one row: the last row chunk of qkv / o, one readout row) and six
short forwards for attention and rotary (lengths other / multiple of 16
against readout rows 1 / other / 16). Kernels are unchanged.

basal-2.0 on the 8060S, request matrix: the old code compiled 18 copies
during the matrix (empty Triton cache: S-q1 pass 1 1.82 s against
0.18 s), now none. Start-up 8.8 s against 7.9 s with a filled Triton
cache, 18.7 against 13.8 s at the first start on a machine.

test_warmup_compiles_every_kernel_copy: no row count (20-5000 rows, 1-528
readout rows) compiles a kernel after the warm-up; it fails without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants