Skip to content

fix(kernels): int64 index offsets in SWITCH LoRA expand (int32 overflow on large intermediate_size, granite-4.1-30b) - #161

Open
thinkahead wants to merge 2 commits into
generative-computing:mainfrom
thinkahead:fix/switch-kernel-int64-overflow
Open

thinkahead wants to merge 2 commits into
generative-computing:mainfrom
thinkahead:fix/switch-kernel-int64-overflow

Conversation

@thinkahead

@thinkahead thinkahead commented Nov 1, 2026 •

Copy link
Copy Markdown

What

Fixes an int32 index overflow in the SWITCH fused-LoRA expand kernels that causes a CUDA illegal memory access when serving a composed adapter on large-intermediate_size bases (granite-4.1-30b).

Fixes #160.

Why

The expand kernels address x_ext as m * stride_xe_m + col, computed in int32. On granite-4.1-30b the shared-MLP gate/up row width is 2 × 32768 + shrink columns ≈ 65.5k, so once a forward pass reaches about 32.8k tokens (a large prefill or vLLM's profiling run), m * stride_xe_m passes 2³¹ and the kernel loads from a wrapped address:

switch_lora_kernel.py _accum_slice_delta / _switch_lora_expand_kernel
RuntimeError: Triton Error [CUDA]: an illegal memory access was encountered

granite-4.1-8b (intermediate_size 12800, row width ≈ 25.6k) would need about 83.8k tokens in one forward, which is why only the 30B class crashes. The trigger is intermediate_size × tokens per forward, not hidden_size (8B and 30B are both 4096) or layer count.

The packed lora_B offset lb_off_r + a·N·r + n·r + k is a much smaller term: it only passes 2³¹ when Σ(NA_r · r) > 2³¹ / N (32,768 at N = 65,536, e.g. 64 adapters at rank 512 on one module), which no realistic checkpoint reaches. The casts below cover it anyway.

How

Promote the index tensor operands to int64 (m_range/n_range/h_range and r16..r512 via .to(tl.int64)) in _switch_lora_expand_kernel, _accum_slice_delta, _switch_lora_expand_swiglu_kernel and _switch_lora_shrink_expand_kernel. Every pointer sum includes one of these, so the whole offset is 64-bit. Results are unchanged on shapes that already fit int32. A comment in the kernel records which term overflows, so a later cleanup does not drop the m_range casts.

Tests

tests/unit/test_switch_kernel_int64_offsets.py (GPU, needs ~7 GB free, skipped otherwise) runs switch_lora_expand and switch_lora_expand_swiglu at the 30B gate/up width with a last row-tile past the int32 limit, and checks the first and last tiles against a torch reference.

Validation

On H200:

  • granite-4.1-3b: load + generate unchanged — no regression on the common (int32-fitting) path.
  • granite-4.1-30b: loads and generates where it previously hit the illegal memory access.
  • A 12-domain 30B eval sweep then completed with zero illegal-memory failures.

Notes

  • tl.int64(x) is not callable (it's a dtype) — the cast is tensor.to(tl.int64).
  • int64 index math adds a few integer instructions per load; it should be negligible next to tl.dot, but the adapter benchmark should confirm there is no decode/switching speedup regression on small models.

@yairallouche

Copy link
Copy Markdown
Collaborator

Thanks for tracking this down and for the clear write-up. The fix is good: moving the index math to int64 resolves the 30B crash, and we'd like to merge it. Before we do, we have two small requests.

1. Root cause in the description

We think the overflow comes from the x_ext row offset, not from the packed lora_B offset. The lora_B offset maxes out at about N · Σ(NA_r · r). For 30B gate/up (N = 65,536), it only passes 2³¹ when Σ(NA_r · r) > 32,768, which means something like 64 adapters at rank 512 on a single module. A normal checkpoint never gets close.

The term that does overflow is m_range * stride_xe_m. The x_ext row width for 30B gate/up is about 65.5k, so the product passes 2³¹ once a forward pass reaches about 32.8k tokens. That would happen in a large prefill or in vLLM's profiling run. For 8B (row width about 25.6k), the threshold is about 83.8k tokens, which would explain why 8B doesn't crash.

Your patch already casts m_range, so the code is correct. Could you:

That way a later cleanup won't drop the m_range casts because they look unnecessary. If you're seeing something different on your side, for example a much smaller batch, please let us know.

2. Regression test

Could you add a GPU test that runs the expand kernel with M × row_width > 2³¹? For example, about 33k tokens × the 30B gate/up width (bf16 x_ext, about 4.3 GB) fits on one H100/H200. The test only needs to check that the kernel doesn't crash and that one row near the end matches a torch reference. It can go next to tests/vllm/test_swiglu_activation_equivalence.py or tests/unit/test_switched_lora_linear.py.

Alternative

If you don't have time for either, that's fine. Just say so here, and we'll open a follow-up issue for the test and the doc fix and handle them ourselves. In that case we'll merge this PR as it is after our GPU test suite and benchmark pass.

Thanks again!

@yairallouche

Copy link
Copy Markdown
Collaborator

/gpu-test

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

✅ GPU tests passed — vllm26

3177 passed, 80 skipped, 169 deselected, 21 warnings in 3856.81s (1:04:16)

Commit: 3044b268c36bfdae4e0d88826b7fd1230c210b1f
Full run & artifact log

Last 40 log lines
  <frozen importlib._bootstrap>:488: DeprecationWarning: builtin type SwigPyPacked has no __module__ attribute

<frozen importlib._bootstrap>:488
  <frozen importlib._bootstrap>:488: DeprecationWarning: builtin type SwigPyObject has no __module__ attribute

.venv/lib/python3.12/site-packages/torch/jit/_script.py:365: 14 warnings
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/torch/jit/_script.py:365: DeprecationWarning: `torch.jit.script_method` is deprecated. Please switch to `torch.compile` or `torch.export`.
    warnings.warn(

tests/composer/test_compose_e2e.py:117
  /tmp/granite-switch/tests/composer/test_compose_e2e.py:117: PytestUnknownMarkWarning: Unknown pytest.mark.xdist_group - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html
    @pytest.mark.xdist_group("compose_e2e")

tests/composer/test_multi_audio_compose_e2e.py:132
  /tmp/granite-switch/tests/composer/test_multi_audio_compose_e2e.py:132: PytestUnknownMarkWarning: Unknown pytest.mark.xdist_group - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html
    @pytest.mark.xdist_group("multi_audio_compose_e2e")

tests/composer/test_multi_audio_compose_e2e.py:138
  /tmp/granite-switch/tests/composer/test_multi_audio_compose_e2e.py:138: PytestUnknownMarkWarning: Unknown pytest.mark.xdist_group - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html
    @pytest.mark.xdist_group("multi_audio_compose_e2e")

tests/composer/test_multi_audio_compose_e2e.py:249
  /tmp/granite-switch/tests/composer/test_multi_audio_compose_e2e.py:249: PytestUnknownMarkWarning: Unknown pytest.mark.xdist_group - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html
    @pytest.mark.xdist_group("multi_audio_compose_e2e")

tests/composer/test_upstream_files.py:232
  /tmp/granite-switch/tests/composer/test_upstream_files.py:232: PytestUnknownMarkWarning: Unknown pytest.mark.xdist_group - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html
    @pytest.mark.xdist_group("upstream_build_e2e")

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
== 3177 passed, 80 skipped, 169 deselected, 21 warnings in 3856.81s (1:04:16) ==
sys:1: DeprecationWarning: builtin type swigvarlink has no __module__ attribute
[rank0]:[W1122 16:38:10.732579487 ProcessGroupNCCL.cpp:1575] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator())
===== ALL GPU TESTS PASSED =====
[16:38:16] <job> Succeeded
[16:38:19] verified: found success sentinel in pod log
[16:38:19] cleanup: deleting <job> (exit=0)
<job> "<job>" deleted

Verdict: PASSED

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

❌ GPU tests failed — vllm30

1 failed, 2856 passed, 75 skipped, 23 warnings in 14162.50s (3:56:02) — plus 4 nested failure(s) in child pytest processes

Commit: c3c1a3b9f0278fc2180e75fadc0bd2f6f6200feb
Full run & artifact log

Last 40 log lines
    @pytest.mark.xdist_group("upstream_build_e2e")

tests/unit/test_asr.py::TestMonoAndResample::test_resample_real_vllm_backend[8000-16000]
tests/unit/test_asr.py::TestMonoAndResample::test_resample_real_vllm_backend[44100-16000]
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/torch/backends/mkldnn/__init__.py:96: UserWarning: TF32 acceleration on top of oneDNN is available for Intel GPUs. The current Torch version does not have Intel GPU Support. (Triggered internally at /__w/pytorch/pytorch/aten/src/ATen/Context.cpp:265.)
    torch._C._set_onednn_allow_tf32(_allow_tf32)

tests/integration/test_hf_to_vllm_weights.py::TestMultiSwitchForwardEquivalence::test_forward_logit_equivalence
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/flashinfer/cute_dsl/availability.py:135: DeprecationWarning: Arch from arch.py is deprecated. Use Arch from enums.py instead.
    from cutlass.base_dsl.arch import Arch

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
=========================== short test summary info ============================
FAILED ::test_asr_ctc_default_gpu.py::<isolated-subprocess> - Isolated module...
==== 1 failed, 2856 passed, 75 skipped, 23 warnings in 14162.50s (3:56:02) =====
sys:1: DeprecationWarning: builtin type swigvarlink has no __module__ attribute
[rank0]:[W1122 14:08:13.792758847 ProcessGroupNCCL.cpp:1624] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator())
FATAL pytest failed
[14:08:31] <job> Failed
[14:08:33] --- post-mortem: why the job ended (status and events only) ---
[14:08:33] <job> status:
  QuotaReserved=True Resuming: Suspend is false
  ResourcesDeployed=True Resuming: Suspend is false
  PodsReady=True SufficientPodsReady: 1 pods running; 0 pods succeeded
  Unhealthy=False Resuming: Suspend is false
[14:08:34] pod <job> phase and conditions:
  phase=Failed
  Initialized=True : 
  Ready=False PodFailed: 
  ContainersReady=False PodFailed: 
  PodScheduled=True : 
[14:08:35] pod <job> container states:
  pytorch: ready=false restarts=0 state={"terminated":{"containerID":"cri-o://e220c974721bbdbfb59567303dcbe3448e9e84fadf4888d668dc5f1f09551e8e","exitCode":1,"finishedAt":"2026-11-22T14:08:15Z","reason":"Error","startedAt":"2026-11-22T10:10:27Z"}}
[14:08:35] kubelet events for <job>:
TIME   TYPE   REASON   MESSAGE
[14:08:36] --- end post-mortem ---
[14:08:36] cleanup: deleting <job> (exit=1)
<job> "<job>" deleted

Verdict: FAILED — 1 failed, 2856 passed, 75 skipped, 23 warnings in 14162.50s (3:56:02) — plus 4 nested failure(s) in child pytest processes

@yairallouche

Copy link
Copy Markdown
Collaborator

/gpu-test

2 similar comments
@yairallouche

Copy link
Copy Markdown
Collaborator

/gpu-test

@yairallouche

Copy link
Copy Markdown
Collaborator

/gpu-test

@aviv1ron1

Copy link
Copy Markdown
Collaborator

@yairallouche please note this branch is old, it does not have the new tests from pr 167- thats why it takes nearly 4 hours to run tests, @thinkahead you should probably pull latest from main to get the short tests - you need it anyway to make the branch mergeable

thinkahead and others added 2 commits November 22, 2026 10:15
…2 overflow on large intermediate_size

The SWITCH fused-LoRA expand kernels compute the packed lora_B element
offset as `lb_off_X + a*(N*X) + rX + n_range*X`. These index expressions
were int32, so with a large `N` (= intermediate_size) the offset exceeds
2^31 and the kernel issues an out-of-bounds load:

    switch_lora_kernel.py _accum_slice_delta / _switch_lora_expand_kernel
    RuntimeError: Triton Error [CUDA]: an illegal memory access was encountered

This reproduces on granite-4.1-30b (intermediate_size=32768) for any
composed adapter at inference time; compose succeeds, the crash is on the
first forward. granite-4.1-3b and -8b (intermediate_size 12800) stay under
the int32 limit, which is why only the 30B class is affected. The trigger
is intermediate_size, not hidden_size (both 8B and 30B are 4096) or layer
count.

Fix: promote the index tensor operands to int64 so the whole offset
arithmetic is 64-bit — `n_range`/`h_range`/`m_range` and the per-tier
`r16..r512` ranges via `.to(tl.int64)` — across the three LBPACK kernels
(`_switch_lora_expand_kernel`, `_accum_slice_delta`,
`_switch_lora_shrink_expand_kernel`). The `lb_off_*` scalars stay Python
ints; promotion happens because a tensor operand in each sum is now int64.
(Note: `tl.int64(x)` is not callable — the cast must be `tensor.to(tl.int64)`.)

Validated on BlueVela (H200): granite-4.1-3b load+generate unchanged (no
regression on the common path), and granite-4.1-30b now loads and
generates where it previously hit the illegal memory access; a 12-domain
30B eval sweep then ran with zero illegal-memory failures.

Signed-off-by: Alexei Karve <[email protected]>
…ion test

The int64 casts fix generative-computing#160, but the term that actually outgrows int32 is the
x_ext row offset m * stride_xe_m, not the packed lora_B offset: on
granite-4.1-30b the gate/up row width is ~65.5k, so a forward of ~32.8k
tokens passes 2^31. The lora_B offset only gets there with
sum(NA_r * r) > 2^31 / N, which no realistic checkpoint reaches. Say so in
the kernel, so a later cleanup does not drop the m_range casts.

The new GPU test drives switch_lora_expand and switch_lora_expand_swiglu at
the 30B gate/up width with a last row-tile past the int32 limit, and checks
the first and last tiles against a torch reference. It needs ~7 GB of free
GPU memory and skips otherwise.

Signed-off-by: yairallouche <[email protected]>
Signed-off-by: Alexei Karve <[email protected]>
@thinkahead
thinkahead force-pushed the fix/switch-kernel-int64-overflow branch from c3c1a3b to 3044b26 Compare November 22, 2026 15:17
@thinkahead

Copy link
Copy Markdown
Author

Rebased onto latest main (now at 3b53f62) and force-pushed — head is now 3044b26. This pulls in the release-test tier from #167, so the GPU run gets the short tests instead of the ~4-hour suite, and the branch is now conflict-free / mergeable. The earlier ASR failure (test_asr_ctc_default_gpu.py) came from the stale base and is unrelated to the kernel change. Ready for another /gpu-test whenever convenient. Thanks @yairallouche!

@aviv1ron1

Copy link
Copy Markdown
Collaborator

/gpu-test

@github-actions

Copy link
Copy Markdown

✅ GPU tests passed — vllm32

3176 passed, 81 skipped, 169 deselected, 40 warnings in 5963.62s (1:39:23)

Commit: 3044b268c36bfdae4e0d88826b7fd1230c210b1f
Full run & artifact log

Last 40 log lines
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/flashinfer/gemm/kernels/grouped_gemm_masked_blackwell.py:2391: DeprecationWarning: cutlass.utils.LayoutEnum is deprecated; use cutlass.tensor_utils.LayoutEnum instead. It will be removed in a future release.
    c_layout: utils.LayoutEnum,

tests/vllm/test_probe_capture_safety.py::test_sr_pipeline_stack_partitions_post_attention_metadata
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/flashinfer/gemm/kernels/cute_dsl/low_latency_blockscaled_gemm.py:102: DeprecationWarning: cutlass.utils.smem_allocator.get_smem_capacity_in_bytes is deprecated; use cutlass.memory.get_smem_capacity_in_bytes instead. It will be removed in a future release.
    _SMEM_CAPACITY_BYTES = cutlass.utils.get_smem_capacity_in_bytes("sm_100")

tests/vllm/test_probe_capture_safety.py::test_sr_pipeline_stack_partitions_post_attention_metadata
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/flashinfer/gemm/kernels/grouped_gemm_masked_rubin.py:215: DeprecationWarning: cutlass.utils.LayoutEnum is deprecated; use cutlass.tensor_utils.LayoutEnum instead. It will be removed in a future release.
    c_layout: utils.LayoutEnum,

tests/vllm/test_probe_capture_safety.py::test_sr_pipeline_stack_partitions_post_attention_metadata
tests/vllm/test_probe_capture_safety.py::test_sr_pipeline_stack_partitions_post_attention_metadata
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/flashinfer/gdn_kernels/blackwell/gated_delta_net_chunked.py:95: DeprecationWarning: cutlass.utils.TensorMapUpdateMode is deprecated; use cutlass.tensor_utils.TensorMapUpdateMode instead. It will be removed in a future release.
    from cutlass.utils import TensorMapManager, TensorMapUpdateMode

tests/vllm/test_probe_capture_safety.py::test_sr_pipeline_stack_partitions_post_attention_metadata
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/flashinfer/gdn_kernels/delta_rule_dsl/collective_store_tma.py:6: DeprecationWarning: cutlass.utils.tensormap_manager.TensorMapUpdateMode is deprecated; use cutlass.tensor_utils.TensorMapUpdateMode instead. It will be removed in a future release.
    from cutlass.utils.tensormap_manager import TensorMapManager, TensorMapUpdateMode

tests/vllm/test_probe_capture_safety.py::test_sr_pipeline_stack_partitions_post_attention_metadata
tests/vllm/test_probe_capture_safety.py::test_sr_pipeline_stack_partitions_post_attention_metadata
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/flashinfer/gdn_kernels/blackwell/gated_delta_net_cp_prefill.py:55: DeprecationWarning: cutlass.utils.TensorMapUpdateMode is deprecated; use cutlass.tensor_utils.TensorMapUpdateMode instead. It will be removed in a future release.
    from cutlass.utils import TensorMapManager, TensorMapUpdateMode

tests/vllm/test_probe_capture_safety.py::test_sr_pipeline_stack_partitions_post_attention_metadata
  /tmp/granite-switch/.venv/lib/python3.12/site-packages/flashinfer/cute_dsl/availability.py:136: DeprecationWarning: Arch from arch.py is deprecated. Use Arch from enums.py instead.
    from cutlass.base_dsl.arch import Arch

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
== 3176 passed, 81 skipped, 169 deselected, 40 warnings in 5963.62s (1:39:23) ==
sys:1: DeprecationWarning: builtin type swigvarlink has no __module__ attribute
[rank0]:[W1122 17:11:54.453956650 ProcessGroupNCCL.cpp:1624] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator())
===== ALL GPU TESTS PASSED =====
[17:12:13] <job> Succeeded
[17:12:16] verified: found success sentinel in pod log
[17:12:16] cleanup: deleting <job> (exit=0)
<job> "<job>" deleted

Verdict: PASSED

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SWITCH LoRA kernel: int32 index overflow -> CUDA illegal memory access on large intermediate_size (granite-4.1-30b)

3 participants