Repository navigation
fix: run on Windows: kernel checks for torch builds without FlashAttention or Triton; UTF-8 file I/O - #38
Conversation
…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).
Reviewer's GuideThe 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 validationsequenceDiagram
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
Flow diagram for Windows attention capability checksflowchart 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
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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>| 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 |
There was a problem hiding this comment.
🟡 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.… 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.
|
Review follow-up (713b585):
|
|
@sourcery-ai review |
There was a problem hiding this comment.
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>…8 text files and converting older Windows files
|
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. |
…ent) and three test writes #38 missed; restore a line break in _gemma_init
|
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:
Checked on Linux, one H100: torch 2.11 and 2.13 both report FlashAttention, Triton is present, 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! |
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),
pyteston 2.3.1 gave 12 failures from three causes. None of them is in the model code.USE_FLASH_ATTENTION, sovarlen_attnraises at the first call.torch_varlen_availablereported it asavailable. It now checks
torch.backends.cuda.is_flash_attention_available(), so--batches compactisrefused with that reason before loading, like the other refusals.
wheels. A new
attention_available("flex")checks for thetritonpackage.gemma_fast_kernelsuses it beforepicking flex on sm_120, and
--gemma-attn flex/fa3(fa3 runs flex in the global layers) are refused withoutit.
test_sdpa_stridechecks flex only where it runs.read_text()/write_text()/open()withoutencodinguse cp1250on a Polish Windows, which garbled the Format 2 vectors and would do the same to
tokenizer.json, questionfiles, calibration files and the decision log. Every text-mode call in
basal/andtests/now passesencoding="utf-8"(114 calls, binary modes untouched).test_gemma_fast_kernels_by_gpu_classstubbedattention_availablewith one answer for every kernel. The stubnow answers for fa3 only.
Tests
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:
Enhancements:
Documentation:
Tests: