Skip to content

fix: run on Windows: kernel checks for torch builds without FlashAttention or Triton; UTF-8 file I/O - #38

Merged
rkinas merged 3 commits into
rkinas:mainfrom
lukaszpodgorski-pl:fix/windows
Oct 22, 2026
Merged

rkinas merged 3 commits into
rkinas:mainfrom
lukaszpodgorski-pl:fix/windows

Conversation

@lukaszpodgorski-pl

@lukaszpodgorski-pl lukaszpodgorski-pl commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Running basal on Windows

On Windows 11 with an RTX 3090 and torch 2.13.0+cu130 (the cu128 index has no Windows wheel past 2.11.0),
pytest on 2.3.1 gave 12 failures from three causes. None of them is in the model code.

  1. torch varlen attention without FlashAttention. The Windows torch wheels are built without
    USE_FLASH_ATTENTION, so varlen_attn raises at the first call. torch_varlen_available reported it as
    available. It now checks torch.backends.cuda.is_flash_attention_available(), so --batches compact is
    refused with that reason before loading, like the other refusals.
  2. FlexAttention without Triton. Inductor builds the flex kernel with Triton, and Triton is not in the Windows
    wheels. A new attention_available("flex") checks for the triton package. gemma_fast_kernels uses it before
    picking flex on sm_120, and --gemma-attn flex / fa3 (fa3 runs flex in the global layers) are refused without
    it. test_sdpa_stride checks flex only where it runs.
  3. Text files in the locale code page. read_text() / write_text() / open() without encoding use cp1250
    on a Polish Windows, which garbled the Format 2 vectors and would do the same to tokenizer.json, question
    files, calibration files and the decision log. Every text-mode call in basal/ and tests/ now passes
    encoding="utf-8" (114 calls, binary modes untouched).

test_gemma_fast_kernels_by_gpu_class stubbed attention_available with one answer for every kernel. The stub
now answers for fa3 only.

Tests

  • Windows 11, RTX 3090, torch 2.13.0+cu130, Python 3.11: 687 passed, 32 skipped (before: 12 failed).
  • Not run on Linux or Hopper here. The new checks return None wherever FlashAttention and Triton are present, so
    those paths should be unchanged.

Summary by Sourcery

Improve Windows compatibility by validating optional attention backends before model loading and standardizing text I/O on UTF-8.

Bug Fixes:

  • Prevent unsupported compact varlen attention and Gemma FlexAttention configurations from failing at runtime by rejecting them early when FlashAttention or Triton is unavailable.
  • Ensure all basal and test text-file I/O uses UTF-8 so non-ASCII data is handled consistently across platforms, including Windows.

Enhancements:

  • Update attention capability detection and related tests to account for platform-specific FlashAttention and Triton availability.

Documentation:

  • Document the Windows compatibility fixes and migration guidance for files previously written with the system code page.

Tests:

  • Update coverage for unavailable attention backends and UTF-8 file handling.

…ntion or Triton; UTF-8 file I/O

- torch_varlen_available: refuse when torch is built without FlashAttention (the Windows wheels), instead of failing
  in varlen_attn at the first compact pass
- attention_available("flex"): FlexAttention needs Triton; gemma_fast_kernels and --gemma-attn flex / fa3 check it
- encoding="utf-8" on every text read_text / write_text / open in basal/ and tests/: on Windows the default is the
  locale code page (cp1250 here), which garbled tokenizer.json, question files, calibration files and the
  Format 2 vectors

Windows 11, RTX 3090, torch 2.13.0+cu130: 687 passed, 32 skipped (was 12 failed).
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR improves Windows compatibility by adding pre-load checks for FlashAttention and Triton-dependent attention paths, while making all text I/O explicitly UTF-8 to prevent locale-dependent corruption; tests are adjusted to cover unavailable kernels and platform-independent file handling.

Sequence diagram for pre-load attention dependency validation

sequenceDiagram
    participant CLI
    participant Backend as Backend_init
    participant Torch as torch.backends.cuda
    participant Runtime as importlib.util
    participant Model
    CLI->>Backend: __init__
    alt compact batches
        Backend->>Torch: is_flash_attention_available()
        Torch-->>Backend: unavailable
        Backend-->>CLI: ValueError compact_refused
    else Gemma flex or fa3
        Backend->>Runtime: find_spec(triton)
        Runtime-->>Backend: unavailable
        Backend-->>CLI: ValueError attention unavailable
    else dependencies available
        Backend->>Model: from_pretrained
        Model-->>Backend: loaded
    end
Loading

Flow diagram for Windows attention capability checks

flowchart TD
    Start["Start model initialization"] --> Compact{Compact batches enabled?}
    Compact -->|Yes| Flash["torch_varlen_available"]
    Flash --> FlashOK{FlashAttention available?}
    FlashOK -->|No| RefuseCompact["Refuse compact mode"]
    FlashOK -->|Yes| FlexMode{Gemma attention is flex or fa3?}
    Compact -->|No| FlexMode
    FlexMode -->|Yes| Triton["attention_available flex"]
    Triton --> TritonOK{Triton package available?}
    TritonOK -->|No| RefuseFlex["Refuse requested attention mode"]
    TritonOK -->|Yes| Load["Load model"]
    FlexMode -->|No| Load
Loading

File-Level Changes

Change Details Files
Add runtime capability gates for attention implementations so unsupported Windows torch configurations fail before model/tokenizer loading.
  • Require torch FlashAttention support before enabling compact varlen attention.
  • Detect Triton availability for FlexAttention and block Gemma 4 flex/fa3 configurations when absent.
  • Make Gemma fast-kernel selection return no fast configuration when FlexAttention is unavailable.
  • Update stride and kernel-selection tests for conditional FlexAttention support.
basal/engine.py
tests/test_compact_varlen.py
tests/test_sdpa_stride.py
tests/test_server.py
Standardize text file access on UTF-8 across application and test code.
  • Pass encoding="utf-8" to text reads and writes for JSON, JSONL, calibration, tokenizer, configuration, logs, and generated files.
  • Update test fixtures and assertions to use explicit UTF-8 encoding, preserving binary I/O behavior.
basal/bench.py
basal/calibrate.py
basal/engine.py
basal/examples/types_demo.py
basal/gemma4_graph.py
basal/gguf_export.py
basal/identity.py
basal/loadtest.py
basal/prompt.py
basal/run.py
basal/server.py
basal/synth.py
basal/think.py
basal/tpu.py
basal/viz.py
tests/test_calibrate.py
tests/test_calibrate2.py
tests/test_calibrate_gates.py
tests/test_calibrate_tasks.py
tests/test_calibration2.py
tests/test_calibration_orders.py
tests/test_compact_varlen.py
tests/test_context.py
tests/test_format2_vectors.py
tests/test_fp8.py
tests/test_gemma4_graph.py
tests/test_gguf.py
tests/test_gguf_export.py
tests/test_loadtest_determinism.py
tests/test_mlx.py
tests/test_prompt2.py
tests/test_server.py
tests/test_vllm.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 4 issues

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

## Individual Comments

### Comment 1
<location path="basal/engine.py" line_range="372-373" />
<code_context>
     if attention_available("fa3") is None:
         return "fa3"
-    if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] == 12:
+    if (torch.cuda.is_available() and torch.cuda.get_device_capability()[0] == 12
+            and attention_available("flex") is None):
         return "flex"
     return None
</code_context>
<issue_to_address>
**Automatic startup fails**

When a Hopper GPU has FA3 installed but Triton is absent and Gemma uses automatic fast or compiled selection, `gemma_fast_kernels()` returns `fa3` before checking FlexAttention availability, so `_gemma_init()` rejects it instead of selecting math and automatic Gemma startup fails.

Select `fa3` only when FlexAttention is available; otherwise fall back to the math kernel.

Also at `basal/engine.py:776-777`.
</issue_to_address>

### Comment 2
<location path="basal/server.py" line_range="609" />
<code_context>
     tasks report automated: null), and the answers are marked unvalidated. An explicit --calibration file is not replaced."""
     cal = calibration_file(md, kind, path, quant, preset)
-    data = {} if off or not cal.exists() else json.loads(cal.read_text())
+    data = {} if off or not cal.exists() else json.loads(cal.read_text(encoding="utf-8"))
     fitted = calibration_orders(data)
     alt = cal.with_name(f"{cal.stem}.o{orders}{cal.suffix}")
</code_context>
<issue_to_address>
**Older Windows files fail to load**

When an existing Windows-generated calibration or saved question/input file contains non-ASCII text encoded with the prior locale code page, `load_calibration()` and `compared()` decode existing files as UTF-8, raising `UnicodeDecodeError` and stopping serving or recalibration.

Fall back to the prior locale encoding when decoding these existing files as UTF-8 fails.

Also at `basal/calibrate.py:935`, `basal/run.py:60`, `basal/bench.py:145`, `basal/identity.py:212`.
</issue_to_address>

### Comment 3
<location path="basal/server.py" line_range="776" />
<code_context>
         self.temps = self.cal.get("temperature_per_prim", {})
         self.soam = a.soam == "on"
-        self.log = open(a.log_decisions, "a", buffering=1) if a.log_decisions else None
+        self.log = open(a.log_decisions, "a", buffering=1, encoding="utf-8") if a.log_decisions else None
         self.letters = {}
         self.queue, self.max_batch, self.wait = asyncio.Queue(), a.max_batch, a.wait_ms / 1000
</code_context>
<issue_to_address>
**Appended logs mix encodings**

When a decision log from an earlier Windows version contains non-ASCII rows, `Server` appends UTF-8 JSON with `ensure_ascii=False` after the existing bytes, leaving earlier cp1250 rows unchanged. The JSONL file then has no consistent encoding, and UTF-8 readers fail on affected older rows.

Before appending, migrate an existing legacy-encoded log to UTF-8 or otherwise ensure the file is consistently encoded.
</issue_to_address>

### Comment 4
<location path="basal/engine.py" line_range="776" />
<code_context>
             merge = kernels != "math"
         if "fa3" in str(kernels) and attention_available("fa3"):
             raise ValueError(f"--gemma-attn {kernels}: {attention_available('fa3')}")
+        if kernels in ("flex", "fa3") and attention_available("flex"):  # fa3: flex in the global layers
+            raise ValueError(f"--gemma-attn {kernels}: {attention_available('flex')}")
         # the math kernel runs uncompiled in --mode fast too: the configuration its gate measured (E2, 20 Oct:
</code_context>
<issue_to_address>
**Flex refusal happens after model load**

When a Gemma model is started with `--gemma-attn flex` on a system without Triton and the model load exhausts available GPU memory, `GraphBackend.__init__` loads the tokenizer and moves the model to CUDA before `_gemma_init` reaches this Triton check. A large model can exhaust VRAM first, so startup fails with an OOM instead of the actionable unsupported-kernel error.

Check Flex availability before loading the tokenizer or model, and refuse the requested Gemma kernel there.
</issue_to_address>

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

Comment thread basal/engine.py Resolved
Comment thread basal/server.py Resolved
Comment thread basal/server.py
self.temps = self.cal.get("temperature_per_prim", {})
self.soam = a.soam == "on"
self.log = open(a.log_decisions, "a", buffering=1) if a.log_decisions else None
self.log = open(a.log_decisions, "a", buffering=1, encoding="utf-8") if a.log_decisions else None

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 · Appended logs mix encodings

When a decision log from an earlier Windows version contains non-ASCII rows, Server appends UTF-8 JSON with ensure_ascii=False after the existing bytes, leaving earlier cp1250 rows unchanged. The JSONL file then has no consistent encoding, and UTF-8 readers fail on affected older rows.

Before appending, migrate an existing legacy-encoded log to UTF-8 or otherwise ensure the file is consistently encoded.

Prompt for AI agents
In `basal/server.py` at line 776:

**Appended logs mix encodings**

When a decision log from an earlier Windows version contains non-ASCII rows, `Server` appends UTF-8 JSON with `ensure_ascii=False` after the existing bytes, leaving earlier cp1250 rows unchanged. The JSONL file then has no consistent encoding, and UTF-8 readers fail on affected older rows.

Before appending, migrate an existing legacy-encoded log to UTF-8 or otherwise ensure the file is consistently encoded.

Comment thread basal/engine.py Resolved
… fa3 before loading

Review of rkinas#38: auto picked fa3 on a Hopper with flash_attn_3 but no Triton (fa3 runs flex in the global layers), and an explicit flex / fa3 was refused only after the model was on the GPU.
@lukaszpodgorski-pl

Copy link
Copy Markdown
Contributor Author

Review follow-up (713b585):

  • Automatic startup fails / Flex refusal after model load: fixed. gemma_fast_kernels returns None without Triton (fa3 runs flex in the global layers), and --gemma-attn flex / fa3 is refused before the tokenizer and weights load, like --batches compact. Both have a test.
  • Older Windows files / appended logs mix encodings: not changing this. Before this PR basal on Windows read and wrote in the locale code page, so files shipped from Linux (tokenizer.json, calibrations) were the ones garbled. Guessing the encoding on read would bring that back. Files basal wrote on Windows with non-ASCII text need regenerating once; I can add a line to WHATS_NEW.

@lukaszpodgorski-pl

Copy link
Copy Markdown
Contributor Author

@sourcery-ai review

@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 1 issue

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

## Individual Comments

### Comment 1
<location path="basal/run.py" line_range="60" />
<code_context>

 async def run(a):
-    items = [json.loads(line) for line in Path(a.input).read_text().splitlines() if line.strip()]
+    items = [json.loads(line) for line in Path(a.input).read_text(encoding="utf-8").splitlines() if line.strip()]
     for i, it in enumerate(items):
         it.setdefault("id", i)
</code_context>
<issue_to_address>
**Legacy Windows data fails to load**

When an existing artifact contains non-ASCII text written by an earlier Windows release using a code page such as cp1250, `Path.read_text(encoding="utf-8")` raises `UnicodeDecodeError` on non-ASCII JSON or JSONL artifacts saved by an earlier Windows release using the locale encoding, so `basal-run` and `basal-bench` abort and the server cannot load that calibration file.

Provide a documented migration or an explicit legacy-encoding option for existing locale-encoded artifacts.

Also at `basal/bench.py:145`, `basal/server.py:609`.
</issue_to_address>

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

Comment thread basal/run.py Resolved
…8 text files and converting older Windows files
@lukaszpodgorski-pl

Copy link
Copy Markdown
Contributor Author

Legacy Windows files: documented in WHATS_NEW (2.3.2, not released yet) with a one-line conversion from the locale code page to UTF-8, checked on a cp1250 file.

@rkinas
rkinas merged commit c55c5df into rkinas:main Oct 22, 2026
1 check passed
rkinas added a commit that referenced this pull request Oct 22, 2026
…ent) and three test writes #38 missed; restore a line break in _gemma_init
@rkinas

rkinas commented Oct 22, 2026

Copy link
Copy Markdown
Owner

Thank you, Łukasz. Running basal on Windows was a real gap, and the change is careful: the new checks return None wherever FlashAttention and Triton are present, and no binary-mode open got an encoding.

2.3.2 was released before we could merge this, so the branch conflicted. We merged it on top of 2.3.2 and moved your WHATS_NEW entry under 2.3.3. We added one small commit on top:

  • 2.3.2 added two reads without encoding (recurrent_layers in engine.py, a helper in tests/test_recurrent.py);
  • three test writes still had none (test_calibrate.py, test_lean.py, test_server.py; ASCII only, so harmless);
  • in 713b585 a line break went missing in _gemma_init, so the next comment ended up on the raise line.

Checked on Linux, one H100: torch 2.11 and 2.13 both report FlashAttention, Triton is present, attention_available("flex") is None and gemma_fast_kernels() still picks fa3. basal-2.0-mini in --mode fast (compact rows with FA3, plain rows, and torch varlen rows on torch 2.13) and basal-omni-1.0-mini: the same start-up line and the same probabilities as 2.3.2 on 200 items alone and the same 200 in two option orders (max |Δp| 0). A mock over sm_80 to sm_120 gives the same kernels as before wherever Triton is installed. Tests: 708 passed, 0 failed.

On the Sourcery points: the start-up and load-order ones are fixed in 713b585. For older Windows files we agree with not guessing the encoding; your WHATS_NEW line covers the conversion.

It is in basal 2.3.3: https://github.com/rkinas/basal/releases/tag/v2.3.3. Thank you!

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