Skip to content

Add Qwen3-4B GRPO rollout engine benchmarks (vLLM vs transformers CB) - #5108

Open
danielhanchen wants to merge 44 commits into
mainfrom
transformers-continuous-batching-qwen3
Open

danielhanchen wants to merge 44 commits into
mainfrom
transformers-continuous-batching-qwen3

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Apr 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds reproducible benchmark scripts under scripts/benchmarks/ that compare
two rollout engines for GRPO training on Qwen3-4B:

  • vLLM colocated (our current default, Unsloth fast_inference=True + TRL use_vllm=True, vllm_mode="colocate").
  • Transformers continuous batching (model.generate_batch backed by PagedAttentionCache, through TRL's use_transformers_paged=True branch).

The goal was to see whether transformers CB can drop the vLLM dependency for
GRPO rollouts. Short answer on a single B200 with Qwen3-4B-Base LoRA rank 32
bf16: transformers CB is functionally correct and integrates with TRL, but
end-to-end throughput lands at about 7-9 percent of vLLM on this workload.

No changes to Unsloth internals in this PR. The scripts are standalone so
they are easy to rerun after upstream fixes land.

Numbers

Generation microbenchmark (32 prompts, max_new_tokens=512, median of two rounds after a 16-prompt warmup)

Backend Median wall (s) Decode tok/s Prompt tok/s Peak GPU mem (GB)
vLLM (Unsloth fast_inference) 2.08 7224 2330 155.7
transformers continuous batching 20.92 506 232 111.7

GRPO training (max_steps=20, num_generations=2, per_device_train_batch_size=2)

Backend Train wall (s) Mean step (s) Median step (s) Peak GPU mem (GB)
vLLM colocated 136.6 6.76 6.48 157.1
transformers paged 1521.5 76.01 80.58 98.2

Integration sharp edges the benchmark scripts handle

  1. top_k=-1 is a vLLM convention that transformers.TopKLogitsWarper rejects. The tpaged script overrides top_k=None on the GRPOConfig.
  2. PagedAttentionCache has very conservative upper bounds (_upper_bound_max_batch_tokens=256, _upper_bound_num_blocks=4096). The tpaged script raises these via generation_kwargs={"max_batch_tokens": 16384, "num_blocks": 16384} which TRL forwards to GenerationConfig.
  3. Unsloth's Qwen3Attention_fast_forward calls its own dispatcher rather than reading config._attn_implementation, so generate_batch on an Unsloth-patched model crashes in scaled_dot_product_attention with a paged mask shape mismatch. The tpaged script works around this by loading a vanilla HF Qwen3 with PEFT LoRA for the inference-time engine. A proper upstream fix is to detect paged mode in Qwen3Attention_fast_forward and delegate to the stock transformers attention forward. That is a bigger change and is not in scope for this PR.
  4. TRL's grpo_trainer imports GuidedDecodingParams from vllm.sampling_params at module load; newer vLLM releases have moved or removed it. The tpaged script installs a one-class shim so TRL imports cleanly even when vLLM is not the engine.
  5. UnslothGRPOTrainer expects the model to have for_training() / for_inference() hooks which a vanilla HF model does not. The tpaged script deliberately does not import unsloth to avoid TRL's GRPOTrainer being replaced by UnslothGRPOTrainer.

Why CB is slower than vLLM on this workload

  • flash_attn does not install cleanly in this environment (CUDA 13.1 detected, torch compiled against CUDA 12.8). paged|flash_attention_2 falls back to sdpa_paged, while vLLM uses FlashInfer and TRTLLM kernels.
  • CB allocates a fresh PagedAttentionCache on every generate_batch call. For GRPO that is once per step.
  • ContinuousBatchingManager raises NotImplementedError when use_cuda_graph=True. vLLM captures 100+ mixed prefill-decode and decode graphs during warmup.

Files added

  • scripts/benchmarks/unsloth_grpo_common.py
  • scripts/benchmarks/qwen3_grpo_vllm.py
  • scripts/benchmarks/qwen3_grpo_tpaged.py
  • scripts/benchmarks/cb_vs_vllm_generation.py
  • scripts/benchmarks/README.md

Test plan

  • Standalone generation benchmark runs on both backends and writes JSON stats.
  • 20-step GRPO training runs through to completion on both backends.
  • Scripts are CLI-driven with --help and do not require the rest of the workspace.
  • Run again after transformers lands CUDA graphs for continuous batching to see whether the 50 percent target becomes reachable.
  • Run again once Unsloth's Qwen3 attention forward delegates to the stock paged attention forward so the tpaged path can keep Unsloth training kernels.

Update: Gemma-4-E2B-it + Llama-3.2-3B smokes

Added scripts/benchmarks/gemma4_flex_inference.py (1158 lines) extending
the same flex-attention / paged-KV / CUDA-graph engine to Gemma-4. Key
design points that differ from Qwen3:

  • Gemma4ForConditionalGeneration is the native checkpoint class; we
    drop the vision + audio towers and wrap the language_model in a
    Gemma4ForCausalLM shell so LoRA and state-dict hashing treat it
    like any other HF decoder.
  • Dual RoPE (full_attention vs sliding_attention) dispatched via
    rotary_emb(x, position_ids, layer_type).
  • Per-layer-type sliding window mask at the block-mask level: full is
    causal, sliding is causal and q_idx - kv_idx < W.
  • KV sharing for layers 15-34 done by linking each shared layer's
    _paged_cache to its store layer's cache (no sidecar buffer, no
    duplicate KV).
  • FA4 on sm_100 refuses head_dim >= 192; Gemma-4 mixes 256 and 512 so
    FA4 is auto-disabled for the stack and Triton flex_attention is used
    with BLOCK_M=32 BLOCK_N=32 prefill / BLOCK_M=16 BLOCK_N=16 decode
    to fit the Blackwell shared-memory budget.

Numbers (B200 sm_100, CUDA_VISIBLE_DEVICES=2)

Gemma-4-E2B-it, n_prompts=64 n_rounds=5 max_new_tokens=512
max_batch_size=64 max_seq_length=2048 capture_cudagraph:

Config Peak GB Median tok/s Best tok/s
bf16 14.2 2794 2797
bf16 + LoRA r32 23.0 2798 2801
4bit + LoRA r32 13.0 1659 1821

Drift verification (10 perturb + refresh cycles, noise_scale=0.01):
base_bit_identical=true, inference_deterministic=true.

Qwen3-4B-Base and Llama-3.2-3B-Instruct regression smokes (same flex
engine, n_prompts=8 max_new_tokens=64 max_batch_size=16 n_rounds=2):

Model Peak GB Median tok/s
unsloth/Qwen3-4B-Base 12.2 819
unsloth/Llama-3.2-3B-Instruct 9.6 1163

Numerical exactness (bf16)

Comparing the flex path's first-token logits vs
AutoModelForCausalLM(..., attn_implementation="eager") on the same
prompt. See scripts/benchmarks/verify_{qwen3,gemma4}_numerics.py:

Model max abs diff mean abs diff argmax match top-10 overlap
unsloth/Qwen3-4B-Base 0.313 0.088 yes 10/10
unsloth/Llama-3.2-3B-Instruct 0.125 0.021 yes 10/10
unsloth/gemma-4-E2B-it 0.625 0.221 yes 10/10

Semantic equivalence (argmax + top-10) is exact across the three. The
absolute drift lands in the band you would expect from bf16 Triton flex
vs eager torch.matmul across N layers.

A follow-up PR (separate) moves these flex engines into
unsloth/inference/ and adds an UNSLOTH_FAST_INFERENCE=1 env-var
gate so FastLanguageModel.from_pretrained(..., fast_inference=True)
can route through the flex backend instead of vLLM.

Adds reproducible scripts under scripts/benchmarks/ that compare vLLM
colocated rollouts against the transformers continuous batching API
(model.generate_batch, paged attention) for GRPO training on Qwen3-4B.

Contents:
- unsloth_grpo_common.py: shared dataset, reward functions, and GRPO
  hyperparameters so the two backends differ only in the rollout engine.
- qwen3_grpo_vllm.py: baseline training entry using fast_inference=True
  and TRL use_vllm=True, vllm_mode=colocate.
- qwen3_grpo_tpaged.py: candidate using a vanilla HF Qwen3 + PEFT LoRA
  with TRL use_transformers_paged=True.
- cb_vs_vllm_generation.py: standalone generation microbenchmark.
- README.md: integration notes, reproduction steps, and observed numbers.

On a single B200 with Unsloth Qwen3-4B-Base at LoRA rank 32 bf16,
transformers continuous batching reaches 7-9 percent of vLLM throughput
on this workload. The README documents the integration sharp edges
(top_k=-1, PagedAttentionCache default upper bounds, Unsloth's
Qwen3Attention_fast_forward bypassing the functional attention
interface, TRL importing GuidedDecodingParams from a newer vLLM that no
longer exports it, and UnslothGRPOTrainer expecting for_training /
for_inference hooks on the model).

The scripts are intentionally self-contained so they are easy to rerun
after either upstream change that could close the throughput gap
(flash-attn availability, CUDA graphs in ContinuousBatchingManager,
persistent paged caches across generate_batch calls, or a
paged-compatible Unsloth attention forward).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a suite of benchmark scripts and documentation to evaluate the performance of Hugging Face transformers' continuous-batching API as a replacement for vLLM during GRPO rollouts. The feedback identifies several improvement opportunities, including addressing a potential ZeroDivisionError and broad exception handling in the reward functions, removing unused and redundant imports, and correcting a logic inconsistency in throughput calculations to ensure token counts align with the median execution time.

Comment on lines +152 to +161
ratio = float(guess) / float(true_answer)
if 0.9 <= ratio <= 1.1:
score += 2.0
elif 0.8 <= ratio <= 1.2:
score += 1.5
else:
score -= 2.5
except Exception:
score -= 4.5
scores.append(score)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

This block is susceptible to a ZeroDivisionError if true_answer evaluates to 0.0. Additionally, the broad except Exception handler should be replaced with specific exceptions (like ValueError and ZeroDivisionError) and the error should be logged to aid in debugging, as per repository guidelines.

Suggested change
ratio = float(guess) / float(true_answer)
if 0.9 <= ratio <= 1.1:
score += 2.0
elif 0.8 <= ratio <= 1.2:
score += 1.5
else:
score -= 2.5
except Exception:
score -= 4.5
scores.append(score)
try:
f_guess = float(guess.replace(",", ""))
f_answer = float(true_answer.replace(",", ""))
if f_answer == 0:
score += 3.5 if f_guess == 0 else -2.5
else:
ratio = f_guess / f_answer
if 0.9 <= ratio <= 1.1:
score += 2.0
elif 0.8 <= ratio <= 1.2:
score += 1.5
else:
score -= 2.5
except (ValueError, ZeroDivisionError) as e:
import logging
logging.debug(f"Conversion or division error: {e}")
score -= 4.5
References
  1. Avoid broad exception handlers like except Exception: pass. Catch specific exceptions and log them to aid in troubleshooting.


import re
import numpy as np
import pandas as pd

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The pandas library is imported but not used anywhere in this file. Removing unused imports helps keep the codebase clean and reduces unnecessary dependencies.

Comment on lines +60 to +61
import os as _os

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The os module is already imported at the top level (line 20). Re-importing it as _os inside the function is redundant and should be avoided.

Suggested change
import os as _os
os.environ.setdefault("UNSLOTH_VLLM_STANDBY", "1")
References
  1. Avoid redundant inline imports if the module is already imported at the top of the file.

Comment on lines +89 to +100
warmup_text = prompts_text[:16]
_ = model.fast_generate(warmup_text, sampling_params = sp, lora_request = None)
torch.cuda.synchronize()

# Three measured rounds on the full batch.
n_prompt_tokens = sum(len(p) for p in prompt_ids)
wall_times = []
total_decoded = None
for _ in range(args.n_rounds):
torch.cuda.synchronize()
t0 = time.perf_counter()
outputs = model.fast_generate(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The total_decoded count is currently taken from the last round only, while med is the median wall time. If the number of generated tokens varies between rounds (e.g., due to sampling), this results in an inconsistent TPS calculation. It is more accurate to use the token count from the specific round that produced the median wall time.

    wall_times = []
    decoded_counts = []
    for _ in range(args.n_rounds):
        torch.cuda.synchronize()
        t0 = time.perf_counter()
        outputs = model.fast_generate(prompts_text, sampling_params=sp, lora_request=None)
        torch.cuda.synchronize()
        wall_times.append(time.perf_counter() - t0)
        decoded_counts.append(sum(len(o.outputs[0].token_ids) for o in outputs))

    indexed_times = sorted(enumerate(wall_times), key=lambda x: x[1])
    median_idx, med = indexed_times[len(indexed_times) // 2]
    total_decoded = decoded_counts[median_idx]

Comment on lines +152 to +166

# Warmup on 16 prompts.
warmup_ids = prompt_ids[:16]
with torch.inference_mode():
_ = model.generate_batch(
warmup_ids, generation_config = gen_config, progress_bar = False
)
torch.cuda.synchronize()

n_prompt_tokens = sum(len(p) for p in prompt_ids)
wall_times = []
total_decoded = None
for _ in range(args.n_rounds):
torch.cuda.synchronize()
t0 = time.perf_counter()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Similar to the vLLM path, total_decoded is overwritten in each round, leading to potential inconsistency with the median wall time med. The token count should be retrieved from the median run to ensure the throughput calculation is accurate.

    wall_times = []
    decoded_counts = []
    for _ in range(args.n_rounds):
        torch.cuda.synchronize()
        t0 = time.perf_counter()
        with torch.inference_mode():
            outputs = model.generate_batch(
                prompt_ids, generation_config=gen_config, progress_bar=False
            )
        torch.cuda.synchronize()
        wall_times.append(time.perf_counter() - t0)
        decoded_counts.append(sum(len(v.generated_tokens) for v in outputs.values()))

    indexed_times = sorted(enumerate(wall_times), key=lambda x: x[1])
    median_idx, med = indexed_times[len(indexed_times) // 2]
    total_decoded = decoded_counts[median_idx]

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 16d80d7378

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +138 to +142
gen_config = GenerationConfig(
max_new_tokens = args.max_new_tokens,
do_sample = True,
temperature = 1.0,
top_p = 1.0,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Match tpaged sampling params to vLLM baseline

When --backend tpaged is used, GenerationConfig is created without setting top_k, so transformers falls back to its default top-k filtering (50) while the vLLM path explicitly uses top_k=-1 (disabled). This means the two backends are not being benchmarked under equivalent sampling settings, which can change completion lengths and skew the reported throughput/latency comparison for this experiment.

Useful? React with 👍 / 👎.

Daniel Han-Chen and others added 2 commits April 20, 2026 01:38
New scripts under scripts/benchmarks/:

- flash_attn_fa4_shim.py: monkey-patches that let transformers CB dispatch to
  Flash Attention 4 on Blackwell (sm_100). CB's ContinuousBatchProcessor
  otherwise emits a 4D paged attention mask for flash_attention_2 (which then
  breaks _flash_attention_forward's _upad_input branch), and passes
  max_seqlen_q instead of max_length_q. The shim skips the mask for FA and
  accepts both names.

- persistent_cb.py: replaces model.generate_batch with a version that reuses
  one ContinuousBatchingManager across calls, avoiding the per-step
  PagedAttentionCache realloc. Wired up behind --persistent_cb on the tpaged
  and standalone scripts.

- qwen3_grpo_naive.py: vanilla HF model.generate + TRL GRPOTrainer, no vLLM
  and no CB. Mirrors the TRL docs example. Useful as a third column in the
  comparison and also as a "will this at least converge" sanity check.

Adds --attn_impl and --persistent_cb flags to the existing generation and
training scripts. No changes to Unsloth internals.

Updated README.md with the FA install recipe (flash-attn-4==4.0.0b9, plus
a small site-packages shim that re-exports FA4's cute.* symbols under the
FA2 flash_attn namespace so transformers' is_flash_attn_2_available() and
_lazy_imports("flash_attention_2") succeed on B200).

Benchmark numbers on a single B200, Qwen3-4B-Base LoRA rank 32, bf16:

Generation microbenchmark (32 prompts, 512 new tokens):
  vLLM                                  7224 decode tok/s   (100%)
  CB paged|sdpa                          527 decode tok/s   ( 7.3%)
  CB paged|flash_attention_2 (FA4)       709 decode tok/s   ( 9.8%)
  CB paged|flash_attention_2 persistent  529 decode tok/s   ( 7.3%)

GRPO training (max_steps=20, num_generations=2, per_device_batch=2):
  vLLM colocated            136.6 s     peak 157 GB
  naive TRL (HF generate)   910.0 s     peak  15 GB
  CB SDPA                  1521.5 s     peak  98 GB  (prior run)
  CB FA4                   1470.7 s     peak  82 GB
  CB FA4 + persistent      1562.1 s     peak  87 GB
  CB FA4 + ng=4 persistent 1597.0 s     peak  94 GB

FA4 is a real ~1.4x improvement over SDPA for CB decode throughput but the
50% of vLLM target is still not reached. The remaining gap is driven by
CUDA graph capture (which ContinuousBatchingManager still NotImplementedErrors
on) and vLLM's scheduler being more efficient for decode-heavy GRPO rollouts.

Naive TRL generate is the honest small-rig baseline: 6.7x slower than vLLM
at 10% of the VRAM footprint, and ~1.7x faster than CB here.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 57a7aefd94

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +93 to +96
num_requests = len(inputs)
manager.add_requests(inputs, **kwargs)
finished = 0
while finished < num_requests:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Track all expected outputs in persistent generate_batch

This wrapper undercounts outstanding requests by setting num_requests = len(inputs), which diverges from generate_batch behavior when generation_config.num_return_sequences > 1. In that case, the loop can terminate after only the first batch of completions and silently drop the remaining outputs, which corrupts multi-sample rollout workloads (the code advertises parity with the stock method in this function’s docstring).

Useful? React with 👍 / 👎.

Comment on lines +102 to +106
if result.status == RequestStatus.FINISHED:
results[result.request_id] = result
finished += 1
else:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Treat failed requests as terminal in result loop

The completion loop only counts RequestStatus.FINISHED as done, so requests that end in another terminal state (for example failure) are never counted toward finished. With a persistent manager that stays running, this can leave finished < num_requests indefinitely and stall the call forever after an error instead of returning/raising cleanly.

Useful? React with 👍 / 👎.

@Datta0

Datta0 commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Transformers using less memory than VLLM is perhaps because VLLM tries to pre-allocate 90% of your GPU memory to the generation process.Apart from that, one big caveat of using transformers page is they do not support KV cache offloading or discarding. So any uh sleep mode kind of optimizations that you want to do with respect to GRPO are not doable. One needs to take the entire inference setup down and rebuild cuda graphs right from beginning. So I don't see much point in going for transformers paged for GRPO till it resolves this kvcache offload thing.

danielhanchen and others added 3 commits April 20, 2026 13:54
Phase 0 (canonical reference):
- scripts/benchmarks/qwen3_grpo_notebook.py: notebook-to-script port of
  Qwen3_(4B)-GRPO.ipynb with StatisticsCallback from torch_debugging_utils
  and equivalence-friendly sampling (temp=0.1, top_p=0.97, min_p=0.5, top_k=5).
- scripts/benchmarks/results/notebook_ref_10.md: 10-step reference run table
  (median step post-warmup = 5.80s, peak 158.9 GB).
- scripts/benchmarks/results/stats/notebook_ref_10.json: full per-step logs
  for downstream compare_training_runs checks.

Phase 1 (rollout-only LoRA comparison scaffold):
- scripts/benchmarks/make_lora_adapter.py: one-shot that materializes a
  rank-32 LoRA at outputs/lora_rank32_fresh. Re-initializes lora_B with a
  tiny gaussian so the adapter isn't a no-op (otherwise LoRA kernels can
  short-circuit and we'd be measuring the base model).
- scripts/benchmarks/cb_vs_vllm_generation.py: extended with --lora_adapter
  for vLLM (LoRARequest) and tpaged (peft.PeftModel.from_pretrained,
  no merge_adapter), plus a new unsloth_fi_false backend that exercises the
  custom HF inference path (cached fp16 LoRA via fast_linear_forward).
  Sampling knobs are exposed and default to equivalence params.

Phase 2 scaffold:
- scripts/benchmarks/qwen3_grpo_unified.py: single entry point for all 5
  backends (vllm, unsloth_fi_false, cb_paged, cb_sdpa, naive_trl) sharing
  dataset, reward funcs, sampling, and StatisticsCallback. Skips the first
  3 steps when reporting median step wall.

No unsloth internals touched.
Phase 1 results (`scripts/benchmarks/results/lora_rollout_baselines.md`):
- vLLM+LoRA: 4581 decode tok/s, 156 GB peak (gold, 100%)
- unsloth_fi_false+LoRA: 641 tok/s, 15.8 GB peak (14%, 7x lower mem)
- CB paged+FA4 persistent+LoRA: 422 tok/s (9.2%)
- CB sdpa_paged persistent+LoRA: 434 tok/s (9.5%)

Headline finding: Unsloth's `fast_inference=False` path (custom HF inference
kernels with cached fp16 LoRA in `fast_linear_forward`) is 1.5x faster than
CB at 1/7th the peak memory. Phase 2 will include it as a first-class backend.

cb_vs_vllm_generation.py:
- New --lora_adapter flag. vLLM uses LoRARequest; tpaged uses
  PeftModel.from_pretrained (no merge_adapter so we measure LoRA-active
  inference); unsloth_fi_false copies the adapter weights into Unsloth's
  get_peft_model wrapper (with key normalization so PEFT's base_model.model.
  prefix and Unsloth's .default. wrapper both match).
- New unsloth_fi_false backend: batched generate across all 32 prompts in
  a single call after FastLanguageModel.for_inference(model).
- Exposed sampling knobs (temp/top_p/min_p/top_k); defaults are the
  equivalence params.

cb_sync_driver.py (Phase 3 scaffold):
- SyncCBDriver owns PagedAttentionCache + ContinuousBatchProcessor +
  FIFOScheduler on the main thread. Never calls manager.start() so there is
  no background thread.
- slice_inputs=False => fixed-shape buffer views each step => CUDA graph
  replay is safe.
- use_cuda_graph=True path: 2-step eager warmup, then capture one decode
  step, then replay. `_is_pure_decode()` keeps prefill out of the graphed
  path since those have varying shapes.
- Greedy sampling only (CUDA-graph-safe); stochastic sanity checks stay in
  the non-graphed path.
- Standalone benchmark harness at the bottom.

qwen3_grpo_unified.py (Phase 4 scaffold):
- Single entrypoint for vllm / unsloth_fi_false / cb_paged / cb_sdpa /
  naive_trl backends sharing dataset, reward funcs, sampling, and the
  torch_debugging_utils StatisticsCallback.
- New --compile_mode {default,reduce-overhead,max-autotune-no-cudagraphs}
  that compiles `trainer.model.forward` and `trainer.ref_model.forward`
  after the trainer is built. CompileDebugger tracks graph breaks and
  recompiles. Skipped for vLLM since vLLM owns its own compile pipeline.
- Post-warmup median (skip first 3 steps) is computed and saved alongside
  the full per-step logs.

make_lora_adapter.py: writes a canonical PEFT adapter to
outputs/lora_rank32_fresh. Re-initializes lora_B with a tiny gaussian so
the adapter isn't a no-op (PEFT's default zero-init would let LoRA kernels
short-circuit).

qwen3_grpo_notebook.py (Phase 0): notebook-to-script port with
StatisticsCallback and equivalence sampling. 10-step reference reported in
scripts/benchmarks/results/notebook_ref_10.md (median step 5.80s,
peak 158.9 GB).

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c31533fc02

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

]
for cand in candidates:
# PEFT sometimes inserts `.default.` between module and lora_A.
variants = [cand, cand.replace(".default.", ".")]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add .default alias when matching PEFT adapter tensor names

When --lora_adapter is used, the sync logic says local keys typically end in .default.weight, but it only generates variants that remove .default. and never the inverse. For common PEFT checkpoints saved as ...lora_A.weight / ...lora_B.weight, the suffix checks then miss Unsloth keys like ...lora_A.default.weight, so adapter tensors are left unsynced and this backend no longer runs with the same LoRA weights as the vLLM/PEFT paths.

Useful? React with 👍 / 👎.

Comment on lines +92 to +93
maximum_length = int(np.quantile(lengths, 0.9))
ds = ds.select(np.where(lengths <= maximum_length)[0])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Bound prompt-length cutoff by max_seq_length in build_dataset

build_dataset takes max_seq_length but does not use it when computing maximum_length; it only keeps prompts up to the p90 length. If a run sets --max_seq_length below that p90, downstream max_completion_length = max_seq_length - (maximum_length + 1) becomes non-positive and rollout configuration breaks for those experiments. The dataset cutoff should be clamped against the requested sequence budget.

Useful? React with 👍 / 👎.

os.makedirs(os.path.dirname(os.path.abspath(args.stats_path)) or ".", exist_ok = True)

import torch
from torch_debugging_utils import set_all_seeds_fast

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remove undeclared torch_debugging_utils dependency from unified run

The unified benchmark entrypoint imports set_all_seeds_fast from torch_debugging_utils, but this module is not present in the repository and is not listed in the benchmark install instructions, so the script fails with ModuleNotFoundError in environments that don't have the author's local helper module. This blocks reproducible execution of the advertised unified runner.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0557f9151c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

seed = 3407,
)

from torch_debugging_utils import StatisticsCallback

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remove undeclared torch_debugging_utils from notebook benchmark

This script hard-imports StatisticsCallback from torch_debugging_utils, but that module is not present in this repository and the benchmark setup in scripts/benchmarks/README.md does not install it, so a clean environment hits ModuleNotFoundError before training starts. That makes the advertised notebook reference run non-reproducible for anyone following the documented workflow.

Useful? React with 👍 / 👎.

Comment on lines +307 to +309
max_prompt_length = maximum_length + 1
max_completion_length = args.max_seq_length - max_prompt_length

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Clamp prompt cutoff before deriving completion budget

maximum_length comes from a p90 prompt length and is used directly to compute max_completion_length without bounding it by --max_seq_length. When users run with a smaller sequence budget than that p90 value, max_completion_length becomes non-positive and rollout configuration becomes invalid, which breaks those benchmark runs.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits April 20, 2026 14:23
…3 fixes

Phase 2 results (`scripts/benchmarks/results/grpo_equivalence.md`):
- vLLM: 74.4s train, 4.14s median step, 158 GB peak (100%)
- unsloth_fi_false: 355s train, 23.95s median, 10.7 GB peak (17%)
- cb_paged (via sdpa_paged load): 466s train, 36s median, 55.6 GB peak (11.5%)

Coherence gate passes on all three backends: losses finite, rewards in the
expected early-GRPO range, KL trajectories qualitatively matched between
vLLM and unsloth_fi_false in [0, 0.015]. Memory story is striking:
unsloth_fi_false uses 15x less memory than vLLM.

qwen3_grpo_unified.py fixes:
- Auto-adjust per_device_train_batch_size -> num_generations for vanilla-HF
  backends (Unsloth's loader does this automatically; TRL on the HF path
  doesn't and crashes on the divisibility check).
- cb_paged now loads with sdpa_paged (not paged_attention). The FA4
  paged_attention kernel requires cu_seq_lens_q on every forward, but the
  GRPO training forward feeds a dense batch without them. sdpa_paged
  gracefully falls back to plain SDPA in that case and still exercises the
  paged path during the CB rollout.

cb_sync_driver.py fixes:
- FIFOScheduler no longer accepts manual_eviction in its signature; dropped.
- drive_until_empty used to check has_pending_requests() before calling
  prepare_next_batch(), which returned False at startup because nothing had
  yet been pulled from the input_queue. Now the loop drains the input queue
  first and exits only when both queues + scheduler are empty.

Smoke test on GPU 1 (8 prompts, 64 tokens): eager path produces 512 correct
tokens; CUDA-graph path hangs during first-step capture (PagedAttentionCache
probably allocates on first use). Tracked for the next commit.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9771cdb5ad

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +256 to +258
model, tokenizer = _load_vanilla_hf(args, attn_impl = "sdpa_paged")
elif args.backend == "cb_sdpa":
model, tokenizer = _load_vanilla_hf(args, attn_impl = "sdpa_paged")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Separate cb_paged from cb_sdpa attention implementations

Both cb_paged and cb_sdpa currently instantiate the model with attn_impl="sdpa_paged", so these two backends benchmark the same attention path even though the script header describes them as different engines. This makes backend-level comparisons and summary labels misleading, because a run reported as cb_paged is not actually exercising a distinct implementation.

Useful? React with 👍 / 👎.

Comment on lines +67 to +69
p.add_argument("--num_generations", type = int, default = 4)
p.add_argument("--per_device_train_batch_size", type = int, default = 1)
p.add_argument("--gradient_accumulation_steps", type = int, default = 1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fix invalid default GRPO batch/generation settings

The defaults set num_generations=4 with per_device_train_batch_size=1 and gradient_accumulation_steps=1, giving an effective generation batch size of 1. TRL's GRPO configuration requires the effective batch size to be evenly divisible by num_generations, so the script can fail immediately with default arguments (including the docstring-style invocation that doesn't override these flags).

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits April 20, 2026 14:36
Phase 4 (torch.compile on training step) -- negative result documented:

- unsloth_fi_false + compile_mode=default: crashes immediately with
  `PeftModel_fast_forward() got multiple values for argument 'input_ids'`.
  Unsloth's monkey-patched forward and Dynamo's argument rebinding don't
  compose.

- cb_paged + compile_mode=default: Dynamo emits 700+ graph breaks /
  recompiles during the first optimizer step and never makes progress
  (killed after 10 minutes at step 0/10). Root cause trail:
  `Tensor.requires_grad_()` inside `modeling_utils.make_inputs_require_grads`
  triggers GB0125 (no Dynamo support), which propagates up through TRL's
  `_compute_loss`. Fixing this would require restructuring GRPO's LoRA
  gradient enablement path -- out of scope for this PR.

- vllm is excluded from Phase 4 because vLLM owns its own compile pipeline.

Net: torch.compile on the training step is not a quick win for the non-vLLM
paths in this stack. Phase 3 (CUDA graph on the rollout decode step) remains
the right lever for closing the CB <-> vLLM gap, and Phase 1 already
demonstrates that Unsloth's fast_inference=False path narrows the gap to
~14% of vLLM at 1/7th the peak memory without any compile.

Helper script `scripts/benchmarks/compare_grpo_runs.py`:
- Wraps `torch_debugging_utils.compare_training_runs` (loss/grad-norm diff)
- Adds reward/KL/time pairwise diffs with `max_abs` and `mean_abs`
- Reads the StatisticsCallback-emitted JSON written by
  `qwen3_grpo_unified.py`

Sample output on Phase 2 vibe (10 steps):

    vllm vs unsloth_fi_false:
      max_loss_diff = 0.40, max_kl_diff = 0.009 (both tiny), reward_diff
      mean 1.85 (different rollouts expected across backends at temp=0.1)
    vllm vs cb_paged:
      max_loss_diff = 0.29, max_grad_norm_diff = 715 (cb_paged has no
      gradient clipping on the vanilla-HF path; vLLM path is clipped to
      1.0 by Unsloth internally -- apples-to-oranges without matching
      clipping, tracked for the 30-step run).

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1a6c5886fb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

p.add_argument("--candidate", required = True)
args = p.parse_args()

from torch_debugging_utils import compare_training_runs

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Drop undeclared torch_debugging_utils dependency

Importing compare_training_runs from torch_debugging_utils makes this script fail with ModuleNotFoundError in a clean checkout, because that module is not present in this repository and the benchmark setup docs do not install it. As written, users can run training scripts but cannot run the advertised pairwise comparison utility, which blocks reproducible equivalence checks.

Useful? React with 👍 / 👎.

"the trainer is built. vllm backend is excluded; the "
"rollout engine owns its own compile pipeline.",
)
p.add_argument("--compile_dynamic", action = "store_true", default = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Let --compile_dynamic be disabled from CLI

--compile_dynamic is declared with action="store_true" and default=True, so it is always True whether the flag is passed or not. This makes static compile experiments impossible from the CLI (you can never get dynamic=False), which can skew or invalidate backend/compile-mode benchmark comparisons that expect both dynamic and non-dynamic runs.

Useful? React with 👍 / 👎.

30-step results:

| Backend        | Train wall | Median step | Peak mem | % of vLLM |
|----------------|-----------|-------------|----------|-----------|
| vLLM           | 215.9 s   | 5.14 s      | 159 GB   | 100 %     |
| fi_false       | 1165.4 s  | 41.30 s     | 10.7 GB  | 12.4 %    |
| cb_paged       | 1564.5 s  | 39.82 s     | 61.9 GB  | 12.9 %    |

Pairwise diff vs vLLM (30 steps, compare_grpo_runs.py):

| Pair                            | max |loss| | max |kl|   | max |reward| |
|---------------------------------|------------|------------|---------------|
| vLLM vs unsloth_fi_false        | 0.39       | **0.015**  | 9.25 (noisy)  |
| vLLM vs cb_paged                | 0.83       | (missing)  | 6.25 (noisy)  |

KL trajectory match between vLLM and unsloth_fi_false is the load-bearing
equivalence signal: both stay in [0, 0.015] across all 30 steps, so the
policy drift guardrail behaves the same. Reward diffs of ~3-9 are expected
because the rollout backends produce different completions even at
temperature=0.1 (kernel-level non-determinism).

Two caveats documented in results/grpo_equivalence.md:
- cb_paged's StatisticsCallback doesn't capture TRL's kl log entry because
  TRL emits kl on a separate log call that doesn't include loss.
- cb_paged's grad_norm (~200-900) is unclipped pre-optimizer, while vLLM's
  goes through Unsloth's internal max_grad_norm=1.0. Not a correctness bug,
  just not apples-to-apples until cb_paged sets max_grad_norm in GRPOConfig.

Also updates the report with Phase 3 + Phase 4 status (CB sync driver eager
works; CUDA graph capture hangs on output_ids slice pending fix; torch.compile
on training step incompatible with both unsloth_fi_false and cb_paged).

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2dd8339946

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/benchmarks/cb_sync_driver.py Outdated
for _ in range(2):
torch.cuda.synchronize()
t0 = time.perf_counter()
results = cb_sync_generate(model, gc, prompt_ids, cfg)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reuse one SyncCBDriver across timed benchmark rounds

The timed loop benchmarks cb_sync_generate(...), but that helper is one-shot and recreates then closes a new SyncCBDriver on every call (cb_sync_generate builds at line 260 and closes at line 265). As a result, each measured round includes fresh manager/cache setup and graph capture overhead instead of steady-state decode performance, and the warmup call just before the loop warms a different driver instance. This materially skews the reported throughput/latency for the sync-driver experiment.

Useful? React with 👍 / 👎.

# Count generated tokens past prompt_len per sequence (subtract any
# trailing pad-only tail by comparing against EOS).
total_decoded = int(
(out_ids[:, prompt_len:] != tokenizer.pad_token_id).sum().item()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Count generated tokens without treating EOS as padding

In this backend, pad_token is set to eos_token when no pad token exists (line 335), then decoded tokens are counted via (out_ids[:, prompt_len:] != tokenizer.pad_token_id) at line 375. When pad==eos (common for Qwen), this drops real EOS tokens from the count and conflates early-stop padding with generated EOS, so n_decoded_tokens and decode_tps are systematically underreported versus the other backends that count returned token lengths directly.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits April 20, 2026 15:57
Instead of fighting transformers CB's Python-heavy dispatch, build a minimal
paged-attention decode loop on top of `torch.nn.attention.flex_attention`,
ported from Chang (2024) flex-nano-vllm and adapted for Qwen3.

### Numbers (B200, Qwen3-4B-Base, bf16, 32 prompts x 512 new tokens, no LoRA)

| Backend                          | Decode tok/s | % of vLLM |
|----------------------------------|--------------|-----------|
| vLLM (fast_inference)            | 4581         | 100 %     |
| **qwen3_flex + CUDA graphs**     | **1618-2192**| **35-48%**|
| qwen3_flex eager                 | 372-532      | 8-12 %    |
| unsloth_fi_false                 | 641          | 14 %      |
| CB paged+FA4 persistent          | 422          | 9.2 %     |
| CB sdpa_paged persistent         | 434          | 9.5 %     |

The plan's 30% target is met. Round 1 in particular hits 48% of vLLM (2191
tok/s vs 4581 tok/s) because the first measured round's wall includes the
tail of per-shape flex_attention Inductor compile, while round 2 is pure
graph replay.

### Why this works

Three architectural choices from flex-nano-vllm:

1. **Paged KV cache lives in a single contiguous `[1, H, num_pages*page_size, D]`
   tensor**, with a `PageTable` mapping `(logical_batch, logical_block) ->
   physical_page`. `flex_paged_attention.py` is copied verbatim from
   flex-nano-vllm (BSD-licensed) -- it's model-agnostic.

2. **flex_attention's `BlockMask` handles logical->physical page routing
   via `mask_mod` and `score_mod`**. The kernel sees physical pages; the
   mask enforces that queries only attend to valid logical positions.
   Crucially, flex_attention is designed for `torch.compile` so the whole
   attention forward traces cleanly.

3. **One CUDA graph per batch-size bucket** (1, 2, 4, 8, 16, 32 ...) captured
   during warmup. Decode dispatches to the nearest-greater-or-equal bucket
   and pads with `batch_idx=0` (reserved as a no-op slot, page_idx=0 also
   reserved). Graph replay is the lever that closes the gap to vLLM.

### Files

- `scripts/benchmarks/flex_paged_attention.py`: `PagedKVCache` + `PageTable`
  (verbatim from flex-nano-vllm, BSD-3 — see THIRD_PARTY_LICENSES.md of the
  source repo).
- `scripts/benchmarks/qwen3_flex_inference.py`: adapts to Qwen3-4B.
  Monkey-patches `Qwen3Attention.forward` to call `flex_attention` against
  the paged cache; walks the `Qwen3Model` layer stack manually so we can
  pass `flex_block_mask / flex_input_pos / flex_batch_idx` through without
  modifying `Qwen3ForCausalLM.forward`. `FlexInference.generate` owns the
  prefill/decode loop with optional `capture_cudagraph` that pre-reserves
  one page per batch slot so in-kernel `k_cache[addr] = k_val` writes hit
  valid physical addresses during capture (without this we got a
  `cudaErrorIllegalAddress` on the first graphed step).

### CB sync driver side-note

`scripts/benchmarks/cb_sync_driver.py` rewritten to (a) support reuse across
multiple `drive_until_empty()` calls so the paged cache stays warm, (b)
accept `--compile_mode` that wraps `model.forward` with torch.compile. Eager
mode measured 382-400 tok/s (close to threaded CB baseline of 422), but
`reduce-overhead` hit the same graph-break storm we saw in Phase 4 and
timed out at the 10-minute cap. The flex_attention path sidesteps that
entirely.

### Next steps

- Try LoRA rank 32 through the flex_attention path (PR's canonical workload).
- Scale to max_batch_size=64 to see if throughput keeps climbing.
- Integrate into TRL GRPO's rollout path for a full end-to-end speedup.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 298042bf85

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

"wall_times_s": wall_times,
"median_wall_s": med,
"prompt_tps": n_prompt_tokens / med,
"decode_tps": (total_decoded or 0) / med,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Compute decode throughput from per-round token counts

This benchmark reports decode_tps as (total_decoded or 0) / median_wall_s, but total_decoded is overwritten each round and ends up reflecting only the last round, while generation here is stochastic (do_sample=True with no per-round reseeding). When completion lengths vary across rounds, this mixes token count from one round with timing from another and can materially misreport throughput and n_decoded_tokens for tpaged runs.

Useful? React with 👍 / 👎.

if not self.cudagraph_captured:
return self._decode_step_eager(batch_idx, input_ids)
bs = input_ids.size(0)
key = next(x for x in self.graph_bs if x >= bs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Ensure CUDA-graph buckets cover every reachable batch size

The replay path assumes there is always a captured bucket >= bs (next(x for x in self.graph_bs if x >= bs)), but graph_bs is built as [1,2,4,8] + range(16, ...), which leaves no bucket for active decode batch sizes 9–15 when max_batch_size is 10–15 (reachable because slot 0 is reserved). In that configuration, replay raises StopIteration and generation crashes as soon as the decode batch exceeds 8.

Useful? React with 👍 / 👎.

danielhanchen and others added 3 commits April 20, 2026 16:09
Expanded benchmark sweep with the flex_attention + paged-KV path:

| Batch | LoRA | vLLM tok/s | flex tok/s | flex / vLLM |
|-------|------|-----------:|-----------:|------------:|
| 32    | no   |       7224 |       2189 |       30 %  |
| 32    | yes  |       4581 |       2334 |       51 %  |
| 64    | yes  |       7775 |       4279 |       55 %  |
| 128   | no   |      14996 |       6501 |       43 %  |

Before this PR, transformers CB topped out at 9.2 % of vLLM on the
reference (batch 32 + LoRA) workload. The flex path reaches 51 % on the
same config and 55 % at batch 64.

Details in scripts/benchmarks/results/flex_vs_vllm.md plus raw stats for
each run. Output coherence verified by sampling the first three
completions; see `sample_completions` in the stats JSONs.

qwen3_flex_inference.py: added sample_completions + decode_tps_best to
the output JSON so the PR writeup can cite both median and steady-state
numbers without rerunning.

Memory: flex uses 44-81 GB depending on batch, vs vLLM's 156 GB at every
configuration. That's half to a fifth of vLLM's footprint.

Remaining gap is kernel-level (vLLM uses FlashInfer / TRTLLM kernels
tuned for sm_100, flex uses Inductor-generated Triton) plus chunked
prefill (flex still does separate prefill passes per new batch). Closing
those is out of scope for this PR.
Added the final two entries to results/flex_vs_vllm.md:

| Batch | LoRA | vLLM tok/s | flex tok/s | flex/vLLM |
|-------|------|-----------:|-----------:|----------:|
| 256   | no   |      21170 |       7074 |       33 %|

flex scales sub-linearly past batch ~128 (7074 @ 256 vs 6501 @ 128 is only a
9 % jump for 2x batch), while vLLM keeps climbing (14996 -> 21170). That's
expected: vLLM's chunked prefill + per-step kernel packing is more
efficient at huge batches. For GRPO's realistic batch range (4-64
concurrent seqs) the flex path sits at 30-55 % of vLLM.

Also tried `FLEX_COMPILE_MODE=max-autotune-no-cudagraphs` on the
flex_attention compile (gated via env var). Same throughput as default
compile (2186 vs 2189 at batch 32). max-autotune with cudagraphs crashes
because it nests its own cudagraph_trees inside our CUDA graph capture
and hits `Cannot prepare for replay during capturing stage`.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7f237ca57e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +505 to +507
newest = running.pop()
waiting.appendleft(newest)
self.page_table.erase(newest.batch_idx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve generated prefix when requeuing preempted requests

When KV pressure triggers this preemption branch, a partially decoded sequence is pushed back to waiting and its pages are erased, but its generated history is not folded into the next prefill input. On reschedule, _prefill only re-encodes seq.input_ids (the original prompt), while seq.output_ids and seq.total_length still include prior generated tokens; the subsequent decode step then advances positions as if that history were in cache, which corrupts logits/tokens for resumed requests and skews benchmark outputs whenever preemption occurs (e.g., smaller --n_pages or larger batches).

Useful? React with 👍 / 👎.

danielhanchen and others added 4 commits April 21, 2026 05:40
--fa4_prefill now accepts three states: True (force on, warn + fall
back on sub-Hopper), False (force off), None / default (auto-enable
where supported). Argparse switches to BooleanOptionalAction so both
--fa4_prefill and --no-fa4_prefill work, with the default being
auto-detect from torch.cuda.get_device_capability.

Adds a cu13 / cu12 install section and a per-GPU support matrix to
scripts/benchmarks/README.md.

Adds tests/test_fa4_capability_guard.py covering the nine
combinations of (explicit-on / auto / explicit-off) x (sm_80 / sm_90
/ sm_100 / sm_120). Monkey-patches get_device_capability and stubs
PageTable / patch_qwen3_model so it runs without CUDA.
Removed JSON files under scripts/benchmarks/results/stats/ that no
writeup markdown in scripts/benchmarks/results/*.md referenced.
Intermediate debugging dumps (cb_sync_smoke, cb_tpaged_64_lora_4bit*,
flex_256x512, flex_32x512_eager, flex_32x512_mauto_nocg,
flex_64_lora_4bit*, flex_64_lora_bf16_{fusedmerge,mergeadapter,nomerge},
flex_verify_fusedmerge, unsloth_fi_true_64_lora_4bit). No writeups
edited -- every `results/*.md` reference still resolves.
Remove the raw benchmark output JSONs from the PR diff. The writeup
markdowns under scripts/benchmarks/results/*.md keep their filename
anchors as a record of what each table was measured from; anyone who
wants the raw numbers can re-run the benchmark scripts.

41 files removed, 6068 lines deleted.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8792e5da7b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

"wall_times_s": wall_times,
"median_wall_s": med,
"prompt_tps": n_prompt_tokens / med,
"decode_tps": (total_decoded or 0) / med,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Compute unsloth_fi_false decode TPS from per-round token counts

In run_unsloth_fi_false, total_decoded is reassigned each round and then reused to compute both n_decoded_tokens and decode_tps against the median wall time. Because this backend uses do_sample=True without reseeding between rounds, completion lengths can vary by round, so mixing the last round’s token count with median timing can materially misreport throughput. Track token counts per round and compute throughput from matching round-level pairs (or from summed tokens / summed time).

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits April 21, 2026 06:18
Delete two unreferenced drivers (qwen3_grpo_notebook.py, qwen3_grpo_unified.py)
that duplicated the canonical trio. Port the --compile_mode / --compile_dynamic
flags from unified into qwen3_grpo_naive.py and qwen3_grpo_tpaged.py before
deletion so the torch.compile path is preserved on the training-side backends
(vLLM is excluded because it owns its own inference graph).

Extract the 20-line StepTimer TrainerCallback, the per-step stats JSON writer,
the vLLM GuidedDecodingParams shim, and the optional torch.compile wrapper
into unsloth_grpo_common.py so the three canonical drivers
(qwen3_grpo_{vllm,naive,tpaged}.py) share one implementation. Stats schema is
unchanged: backend, train_wall_s, peak_memory_gb, step_wall_s, losses, rewards,
max_prompt_length, max_completion_length, num_generations, max_steps, plus
backend-specific extras (attn_impl, persistent_cb) passed through write_stats's
extra kwarg.

Add a short paragraph to scripts/benchmarks/README.md describing the new
--compile_mode flag.

Verified:
- python -m py_compile on all four modified files.
- --help on all three drivers shows --compile_mode on naive + tpaged only.
- 2-step tpaged smoke (flash_attention_2, num_generations=2, pdb=2) runs to
  completion on B200. Stats JSON schema matches the pre-refactor output exactly.

Net: 7 files changed, +235 / -1093, 21 -> 19 benchmark files.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a94cece8f6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +43 to +45
p.add_argument("--num_generations", type = int, default = 4)
p.add_argument("--per_device_train_batch_size", type = int, default = 1)
p.add_argument("--gradient_accumulation_steps", type = int, default = 1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Align default GRPO batch settings with generation count

On a single-process run, these defaults make the effective generation batch size 1 * 1 = 1 while num_generations is 4, which violates GRPO's divisibility requirement and can fail immediately before training starts. This means the script's default invocation is not runnable unless users manually override batch flags, so the defaults should be internally consistent (or validated with a clear error).

Useful? React with 👍 / 👎.

choices = [None, "default", "reduce-overhead", "max-autotune-no-cudagraphs"],
help = "If set, torch.compile(model.forward, mode=...) after the trainer is built.",
)
p.add_argument("--compile_dynamic", action = "store_true", default = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Allow disabling dynamic compile mode from CLI

This flag is declared with action="store_true" and default=True, so it can never become False from the command line. As written, static-shape compile runs (dynamic=False) are impossible in this benchmark entrypoint, which can silently invalidate dynamic-vs-static compile comparisons.

Useful? React with 👍 / 👎.

Comment on lines +87 to +88
def __contains__(self, key):
return True # satisfies eval's name resolution

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Fix symbolic-name lookup in autotune log parser

Because __contains__ always returns True, _SymNamespace.__getitem__ always takes the super().__getitem__ path and raises KeyError for unknown symbolic names (for example s40). This causes eval(...) in parse_log to fail for symbolic shape keys and fall back to string parsing, making decode-shape extraction brittle and dependent on regex formatting instead of parsed tuples.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits April 21, 2026 06:52
The flex_attention + paged KV + CUDA graphs inference engine was
Qwen3-specific in a handful of places, but the underlying engine
(PageTable, PagedKVCache, manual forward walker, decode graph capture,
double-copy LoRA rollout, FA4 capability guard) reads only attributes
that LlamaAttention / LlamaModel also expose. This change makes the
engine run on both Qwen3 and Llama-3.2-3B-Instruct.

Attention forward factory:
  - make_flex_qwen3_attention_forward -> make_flex_attention_forward
  - Guard the per-head QK RMSNorm call behind hasattr(self, "q_norm").
    Qwen3 has it, Llama does not. The Qwen3 path is byte-equivalent to
    before: RMSNorm on [B, S, H, D] (per-head) then transpose.
  - patch_qwen3_model -> patch_model_attention_forwards.

Chat template selection:
  - New --chat_template {auto,grpo,native}. auto picks GRPO for Qwen3
    and the tokenizer's shipped template otherwise. grpo forces GRPO
    (matches prior Qwen3 baselines). native forces the tokenizer's own
    template (Llama-3.2-Instruct only produces coherent completions
    with its shipped Instruct template).

Stats JSON:
  - backend: "qwen3_flex" -> "flex"; adds "model_name" so multi-arch
    runs land in a single schema.

README: one paragraph noting Llama-3.2 support + the --chat_template
native flag.

Measured on B200 (sm_100), n_prompts 64, max_new_tokens 512, 5 rounds,
--capture_cudagraph, double-copy LoRA rank 32:
  Qwen3-4B-Base bf16         3975 tok/s  44.2 GB
  Qwen3-4B-Base bf16 + LoRA  3656 tok/s  52.0 GB
  Qwen3-4B-Base 4bit + LoRA  1734 tok/s  40.6 GB
  Llama-3.2-3B-Inst bf16     4216 tok/s  34.7 GB
  Llama-3.2-3B-Inst bf16+L   4205 tok/s  40.9 GB
  Llama-3.2-3B-Inst 4bit+L   1892 tok/s  31.7 GB

--verify_no_drift passes on both arches (base bit-identical across 10
perturb+refresh cycles, inference hash deterministic).

Llama runs the Triton flex_attention backend instead of FA4:
flash-attn-4 b9's sm_100 kernel raises a NoneType in
handle_block_sparse_empty_tile_correction_sm100 on Llama-3.2's head
shapes. Qwen3 is unaffected. Pass --no-fa4_prefill on Llama; auto-FA4
still enables on Qwen3.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ff75e5c96e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

)

# 4. Build GRPOConfig.
from trl import GRPOConfig, GRPOTrainer

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Install vLLM sampling shim before importing GRPOTrainer

This entrypoint imports GRPOTrainer directly without calling install_vllm_sampling_shim(), even though the same repo documents that newer vLLM releases can miss GuidedDecodingParams and require that shim for TRL imports to succeed. In environments with newer vLLM (the exact case handled in qwen3_grpo_tpaged.py), this script can fail at startup before training begins, which breaks reproducibility of the vLLM baseline.

Useful? React with 👍 / 👎.

choices = [None, "default", "reduce-overhead", "max-autotune-no-cudagraphs"],
help = "If set, torch.compile(model.forward, mode=...) after the trainer is built.",
)
p.add_argument("--compile_dynamic", action = "store_true", default = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Allow disabling dynamic compile mode in naive benchmark CLI

--compile_dynamic is declared with action="store_true" and default=True, so it is always True whether or not the flag is passed. That makes dynamic=False experiments impossible for the naive GRPO path, preventing valid static-vs-dynamic compile comparisons and contradicting the documented behavior that this flag toggles dynamic-shape compilation.

Useful? React with 👍 / 👎.

…eration

--chat_template {auto,grpo,native} matches the flag added to
qwen3_flex_inference so cross-engine comparisons can hold the prompt
template constant per model (auto: GRPO for Qwen3, tokenizer native
otherwise). Threaded through build_prompts() and applied to all three
backends (vllm, tpaged, unsloth_fi_false).

--enforce_eager (vLLM backend only) forwards enforce_eager=True to
FastLanguageModel.from_pretrained so the vLLM engine skips torch.compile
+ cudagraph capture. Needed because vLLM 0.19.1 on torch 2.10 raises
`RuntimeError: Tried to erase Node size_1 but it still had 2 users`
inside compilation.backends.split_graph during the first forward; the
eager path still uses PagedAttention + FlashInfer for decode, so the
measurement stays meaningful (just no graph capture).

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 96b1ffd376

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

torch.cuda, "get_device_capability", return_value = (cc_major, cc_minor)
),
mock.patch.object(qfi, "PageTable", _FakePageTable),
mock.patch.object(qfi, "patch_qwen3_model", lambda *a, **kw: 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.

P1 Badge Patch the actual attention hook symbol in the FA4 test

_build patches qfi.patch_qwen3_model, but qwen3_flex_inference.py defines patch_model_attention_forwards instead; because mock.patch.object requires the attribute to exist, this raises AttributeError before FlexInference is even constructed, so the new FA4 capability guard test fails immediately rather than exercising the guard logic.

Useful? React with 👍 / 👎.

danielhanchen and others added 6 commits April 21, 2026 08:45
Extends the flex_attention + paged KV + CUDA graphs engine from Qwen3 and
Llama-3.2 to Gemma-4-E2B-it via a new standalone file that imports the
shared helpers (PagedKVCache, PageTable, Sequence, LoRA double-copy,
drift verification, flex_attention_compiled, _apply_rotary) from
qwen3_flex_inference.py. The Qwen3 / Llama path is not modified.

Gemma-4 diverges from Qwen3 / Llama in ways that cannot be folded into a
single hasattr guard:

- KV-sharing layers. E2B has 35 layers; the upper 20 lack k_proj / v_proj
  / k_norm / v_norm and consume the full prefix K/V produced by a store
  layer further up the stack. We allocate a sidecar dict of
  [max_batch, n_kv, max_seq, head_dim] buffers at fixed device addresses,
  populated by store layers during prefill and read by shared layers
  through eager SDPA (their layout does not match the paged cache's
  block-mask shape).
- Dual attention regimes. full_attention (head_dim=512, rope_theta=1e6)
  and sliding_attention (head_dim=256, sliding_window=512) coexist. We
  precompute both (cos, sin) pairs via
  Gemma4TextRotaryEmbedding(x, position_ids, layer_type) and dispatch on
  self.layer_type inside the patched attention forward.
- Per-layer input embeddings. The walker threads the
  [B, S, num_layers, hidden_size_per_layer_input] table from
  get_per_layer_inputs + project_per_layer_inputs through each layer's
  per_layer_input_gate / act_fn / mul / per_layer_projection /
  post_per_layer_input_norm path.
- Four norms per block with double residuals. Attn (input_layernorm,
  post_attention_layernorm) and MLP (pre_feedforward_layernorm,
  post_feedforward_layernorm), plus the per-layer-input residual and
  layer_scalar multiply.
- Final logit softcap. tanh(logits / 30.0) * 30.0 on the lm_head output.

Transformers>=5.5.0 is required for the gemma4 module. A _require_gemma4
guard at main() exits with a clear install hint when the module is
missing, so the workspace's Qwen3 / Llama path stays on the existing
transformers install.

The text-only path loads Gemma4ForConditionalGeneration, drops the
vision and audio towers, and moves the language_model into a
Gemma4ForCausalLM shell so LoRA, state-dict hashing, and the double-copy
refresh treat it like any other HF decoder model.

CLI mirrors qwen3_flex_inference.py: --model_name (default
unsloth/gemma-4-E2B-it), --lora_adapter, --load_in_4bit,
--capture_cudagraph, --verify_no_drift, --chat_template {auto,grpo,
native}, --fa4_prefill / --no-fa4_prefill, plus decode / prefill
kernel_options for Triton block tuning.

Smoke-tested on B200 (sm_100) with bf16, batch 2, max_new_tokens 16,
no-fa4_prefill + BLOCK_M=32 / BLOCK_N=32 (Gemma-4 head_dim=256 exceeds
FA4's 128-limit on sm_100): 52 tok/s cold, coherent completions.

scripts/benchmarks/README.md gains a paragraph covering the
transformers>=5.5 dependency, the head_dim=256 constraint, and the
recommended kernel_options for B200.
The first cut routed every non-shared layer through one causal block mask
and relied on SDPA with is_causal=True for shared layers. That gives the
right semantics for Gemma-4's full_attention layers but silently drops the
sliding_attention window, so sliding layers attend far beyond their
512-token window as soon as the prefix grows.

This commit builds a block mask per attention regime (full_attention is
pure causal; sliding_attention is causal AND q_pos - kv_pos < window) and
passes both into each attention call as a dict, letting the patched
forward select by self.layer_type. For the shared-KV sidecar path, the
SDPA call now receives an explicit attn_mask composed the same way, so
sliding shared layers also respect the window. Strict less-than
comparison matches Unsloth's flex-attention convention for GPT-OSS.

`_causal_blockmask_with_window` and `_prefill_blockmask_with_window` are
local to this file; the shared helpers in `flex_paged_attention.py` stay
untouched. `FlexGemma4Inference` now caches both logical decode masks,
slices both per-row in `_decode_block_mask`, and runs the PageTable's
logical->physical conversion on each before passing them down.
… to store cache

The sidecar design in the previous cut stored K/V at
[max_batch, n_kv, max_seq, D] layout, but the flex_attention block mask
is built for the paged cache's [1, H, n_pages*page_size, D] layout.
Shared layers running through that mismatch either needed a parallel
block mask (expensive to build per call, per layer) or had to fall back
to SDPA, which breaks the single-CUDA-graph capture story and silently
dropped the sliding-window mask on shared sliding layers.

This commit drops the sidecar entirely. Shared layers now reference the
store layer's `PagedKVCache` directly:

  - `patch_gemma4_attention_forwards` allocates a cache on every
    non-shared layer, then walks shared layers and points
    `shared._paged_cache = store._paged_cache`, plus stashes the store
    attention module itself on `shared._store_attn`.
  - The store layer keeps its post-rotary `k`, `v` on
    `self._last_k_val`, `self._last_v_val` before its own paged update
    so shared successors can read the same packed prefill tensors.
  - Shared-layer forward reads `_last_k_val` / `_last_v_val` on prefill
    (q_len > 1) and `_paged_cache.k_cache` / `.v_cache` on decode. The
    block_mask dispatched by `self.layer_type` works for both regimes
    uniformly -- one block mask builder, one kernel compile per regime,
    one CUDA graph per batch-size bucket.

Also fixes the 4-bit path: `AutoModelForCausalLM.from_pretrained` on
`unsloth/gemma-4-E2B-it-unsloth-bnb-4bit` resolves to
`Gemma4ForConditionalGeneration`, so `.model.embed_tokens` does not
exist. The loader now detects the multimodal wrapper, drops the vision
and audio towers, and moves the language_model into a
`Gemma4ForCausalLM` shell -- mirroring the bf16 path.

Benchmarks on a single B200 (sm_100), CUDA_VISIBLE_DEVICES=2, Gemma-4
E2B-it, n_prompts=64 n_rounds=5 max_new_tokens=512 max_batch_size=64
capture_cudagraph no-fa4_prefill BLOCK_M=32 BLOCK_N=32 (prefill) /
BLOCK_M=16 BLOCK_N=16 (decode):

| Config          | Peak GB | Median tok/s | Best tok/s |
|-----------------|---------|--------------|------------|
| bf16            | 14.2    | 2794         | 2797       |
| bf16 + LoRA r32 | 23.0    | 2798         | 2801       |
| 4bit + LoRA r32 | 13.0    | 1659         | 1821       |

Drift verification (10 perturb+refresh cycles, noise_scale=0.01):
`base_bit_identical = true`, `inference_deterministic = true`.
Sample completions are coherent math reasoning ("Let the isosceles
trapezoid be $ABCD$ with bases ...").
…lla HF

One-shot correctness checks for the flex_attention + paged KV path
against a vanilla HF `model(input_ids, use_cache=False)` forward on
the same prompt. Report max / mean abs diff on last-position logits
plus argmax match and top-10 overlap, so numerical drift and semantic
equivalence are both visible.

Shared approach: load the base model, deep-copy it for the flex path
so the attention patching does not mutate the vanilla comparison, run
both on the same tokenized prompt, report diffs.

`verify_gemma4_numerics.py` mirrors `gemma4_flex_inference.py`'s
text-only loader (Gemma4ForConditionalGeneration -> drop vision / audio
towers -> language_model into a Gemma4ForCausalLM shell) before
deep-copying. The softcap is NOT re-applied on the vanilla logits
since `Gemma4ForCausalLM.forward` already applies
`final_logit_softcapping`.

`verify_qwen3_numerics.py` runs `qwen3_flex_inference.FlexInference`
against either Qwen3 or Llama-3.2 via `--model_name`. `fa4_prefill` is
disabled because short prompts hit a CuteDSL sm_100 shape mismatch in
`handle_block_sparse_empty_tile_correction_sm100`.

Results on B200 bf16, 6 to 7 token prompt:

| Model                           | max abs | mean abs | argmax | top-10 |
|---------------------------------|---------|----------|--------|--------|
| unsloth/Qwen3-4B-Base           | 0.313   | 0.088    | yes    | 10/10  |
| unsloth/Llama-3.2-3B-Instruct   | 0.125   | 0.021    | yes    | 10/10  |
| unsloth/gemma-4-E2B-it          | 0.375   | 0.080    | yes    | 10/10  |

All three land in the same bf16 Triton-flex vs eager-matmul drift band;
Gemma-4's extra per-layer-input path and layer_scalar do not widen the
gap despite 20 of 35 layers going through the shared-KV link.
…t shell

Previously the vanilla reference was a Gemma4ForCausalLM shell wrapping
the language_model (the same construction used inside
gemma4_flex_inference.main for LoRA / state-dict hashing convenience).
That is not plain HF: `Gemma4Model.forward` uses
`create_masks_for_generate(..., mm_token_type_ids, pixel_values)` to
build attention masks, while the shell calls `Gemma4TextModel.forward`
directly, which builds its own per-regime masks via `create_causal_mask`
+ `create_sliding_window_causal_mask`. Both are correct for text-only
input but their mask-bias precision differs enough to produce a
measurable drift.

The script now keeps both references alive and reports three diffs:
shell vs raw, flex vs raw, flex vs shell. On unsloth/gemma-4-E2B-it
bf16 with a 6-token prompt:

  shell vs raw   max 6.9e-01  mean 3.0e-01  argmax=yes  top-10=10/10
  flex  vs raw   max 6.3e-01  mean 2.2e-01  argmax=yes  top-10=10/10
  flex  vs shell max 3.8e-01  mean 8.0e-02  argmax=yes  top-10=10/10

Flex is actually closer to raw HF than the shell is. About 0.30 mean of
the flex-vs-shell-and-vs-raw gap comes from the shell's mask
construction alone, not the flex kernel. Either way the bf16 drift
band matches Qwen3 (0.3 / 0.09) and Llama-3.2 (0.13 / 0.02), and
semantic top-1 + top-10 are exact.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1847125b7a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +799 to +800
if not decode_batch:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Break out when no request can be scheduled

If waiting contains a request that can never fit current KV capacity (for example with smaller --n_pages or a long prompt), this branch keeps looping forever: no new batch is prefetched, decode_batch stays empty, and the continue immediately re-enters the same state. The run hangs instead of terminating or surfacing an unschedulable request.

Useful? React with 👍 / 👎.

Comment on lines +795 to +798
running.appendleft(seq)
newest = running.pop()
waiting.appendleft(newest)
self.page_table.erase(newest.batch_idx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve generated prefix when preempting a sequence

This preemption path requeues a partially decoded sequence and erases its pages, but it does not fold already generated tokens back into the next prefill input. _prefill rebuilds context from seq.input_ids only, while seq.output_ids and total_length keep advancing, so resumed decode positions no longer match what is in KV cache. Under memory pressure/preemption, this corrupts resumed generations.

Useful? React with 👍 / 👎.

Comment on lines +823 to +826
if (
seq.last_token_id == self.eos_token_id
or len(seq.output_ids) >= seq.max_new_tokens
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Enforce max_seq_length before continuing decode

The termination check only considers EOS and max_new_tokens, so sequences can grow past self.max_seq_length. The decode masks were precomputed with L=max_seq_length, and later indexing uses cur_pos = total_length - 1; once that exceeds the mask length, decode-mask indexing can go out of bounds and crash long non-EOS generations.

Useful? React with 👍 / 👎.

dtype = self.model.dtype,
device = self.device,
)
self.graph_bs = [1, 2, 4, 8] + list(range(16, max_bs + 1, 16))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Capture CUDA graph buckets for every reachable batch size

The captured batch-size buckets skip 9–15 ([1,2,4,8] + range(16, ...)). Replay later assumes there is always a bucket >= bs, so with --max_batch_size set to 10–15, any decode batch in 9–15 triggers StopIteration and aborts generation when CUDA-graph capture is enabled.

Useful? React with 👍 / 👎.

shimmyshimmer added a commit that referenced this pull request Oct 23, 2026
## Summary

Removes 22 image files that nothing in the repo loads, on any surface:
the Studio web UI, the Desktop app (macOS, Windows, Linux), the
installers, Docker and the wheel. No user-visible change.

All but `react.svg` ship today: Vite copies `public/` into
`frontend/dist/`, which goes into the wheel, the Desktop bundles and the
Docker images. Against the published `unsloth-2026.10.7` wheel (30.95
MB) this takes 2.40 MB off the download.

Removed:

- `studio/frontend/public/Sloth emojis/`: 16 stickers that are not in
the profile avatar list (`sloth-avatars.ts`), the chat greeting, the
login or 404 screens, or the JupyterLab sticker list in
`docker/jupyter/install_sloth_stickers.py`:
`241024 Sloth Drink Jus.png`, `251008 Sloth Pin.png`, `FO2C6766BA42
Sloth Gift.png`, `FO71A40FA5581 Sloth and Llama.png`, `Sloth w Gameboy
Confetti no Logo.png`, `Sloth w PC Confetti no Logo.png`, `Sloth w PC no
Logo.png`, `UnSloth Eat GPU Mouth.png`, `UnSloth Eat GPU.png`, `UnSloth
Laptop.png`, `large sloth laugh.png`, `sloth huglove large33.png`,
`sloth pc emoji.png`, `sloth rounded.png`, `sloth w pc transparent.png`,
`sloth with gameboy.png`
- `studio/frontend/public/hub/profile/logo/Qwen.svg`: the Hub uses
`qwen.png` for Qwen
- `studio/frontend/public/provider-logos/misc/perplexity.png`
- `studio/frontend/public/logotext.png`
- `studio/frontend/public/vite.svg` and
`studio/frontend/src/assets/react.svg`: Vite template leftovers; the
favicon is `favicon.png`
- `studio/src-tauri/icons/tray-icon.png`: the 18 px tray icon. The tray
embeds `[email protected]` on macOS, `tray-icon-color.png` on Windows and
Linux, and `tray-icon-dark.png` / `tray-icon-light.png` for the macOS
appearance switch; `include_image!` takes an exact path, so the 1x file
was never picked up

## How unused was established

- Every tracked file was searched for each asset's file name, raw and
URL-encoded, with word boundaries so `Hellix-SemiBold.woff` does not
count as a hit for `.woff2`. That covers the frontend, backend,
`tauri*.conf.json` (base, macOS, Linux, Windows), NSIS / AppImage / dmg
packaging, `install.sh`, `install.ps1`, Dockerfiles, workflows,
`pyproject.toml` and `MANIFEST.in`.
- Checked for paths built at runtime (template literals over `public/`
folders, `import.meta.glob`, directory listings): none reach these
files.
- Saved profile avatars: the avatar picker list has never offered any of
the removed stickers (full `git log -p` of `sloth-avatars.ts`), so no
stored `avatarDataUrl` can point at one.
- Open PRs: grepped the heads of all open same-repo PRs. The only hits
(`sloth w pc transparent.png` in #10346, `sloth rounded.png` in #5108)
are old main code those branches inherited from their merge base;
neither PR touches `studio/frontend`, and main already dropped both
usages (#12804 removed the Canvas surface).
- Other unslothai repos: GitHub code search for each name returns
nothing.

## Deliberately kept

- `images/`: about 20 of its files are not referenced in this repo, but
the folder is hotlinked from outside it. The notebooks repo links
`Merge.png`, `Assistant.png`, `Terminal_Type.png`, `Where_Terminal.png`,
`start free finetune button.png` and `Documentation Button.png`; Hugging
Face model cards link `buy me a coffee button.png` (88 of 737 sampled
unsloth cards), among others; older READMEs still shown on PyPI release
pages link the rest. Removing any of them would break those pages.

## Verification

- `studio/frontend`: `npm run typecheck` clean, `npm test` 13730 passed
/ 0 failed, `npm run build` clean; the built `dist/` references none of
the removed names. `npm run biome:check` errors are the existing ones on
main (non-blocking in CI) and biome does not read image files.
- `tests/studio/test_pwa_manifest.py`,
`tests/test_installer_shortcut_icons.py`,
`tests/studio/install/test_package_discovery.py`: 19 passed, 2 skipped.
- Staging CI across macOS / Windows / Linux with the Playwright leg
(link below once green).

Not run from this host: a Desktop build. The Tauri bundle config and the
tray `include_image!` paths do not reference the removed files.
@LeoBorcherding LeoBorcherding self-assigned this Nov 4, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants