Back to Community & Earn Hub
Q&A Questionllms +150 pt Bounty

PyTorch 2.6 torch.compile + Triton: How to prevent recompilation storms when sequence lengths vary across agent loop turns?

@arjun_nair2417 hours ago 1461 views

We are running a custom inference wrapper on PyTorch 2.6 using torch.compile(model, mode="reduce-overhead") with custom Triton attention kernels.

The Recompilation Storm

During an autonomous agent trajectory, each turn appends tool outputs of unpredictable lengths (seq_len = 412 -> 893 -> 1,540 -> 2,311).

With TORCH_LOGS="recompiles" enabled, our logs flood with:

text
[dynamo] Recompiling function forward in model.py:142
  triggered by GuardFailure: L['input_ids'].size()[1] == 412 (got 893)
[dynamo] Recompiling function forward in model.py:142
  triggered by GuardFailure: L['input_ids'].size()[1] == 893 (got 1540)

Once cache_size_limit (default 8) is exceeded, PyTorch falls back to eager mode or stalls for 12–18 seconds compiling new Triton kernels + CUDA Graphs mid-request.

  1. Why does dynamic=True still trigger occasional recompilations on custom Triton @triton.jit kernels?
  2. What is the cleanest combination of mark_dynamic() and sequence bucketing to keep CUDA Graph capture fast and bounded?
1 Answers

Community Answers

@siddharth_rao Accepted Answer17 hours ago

The reason dynamic=True still triggers recompilations with custom Triton kernels and mode="reduce-overhead" is two-fold:

  1. mode="reduce-overhead" enables CUDA Graphs, which require exact static tensor memory addresses and shapes at replay time.
  2. Triton tl.constexpr arguments (like BLOCK_N or HEAD_DIM specializations) bake shape-dependent branches into PTX code if seq_len is passed as a constexpr or fails alignment checks.

Here is the production pattern to eliminate recompilation storms completely:


1. Power-of-2 Sequence Bucketing + mark_dynamic

Never feed arbitrary sequence lengths (412, 893, 1540) into a CUDA-Graphed compiled model. Pad your input_ids and attention_mask up to fixed power-of-2 buckets (512, 1024, 2048, 4096):

python
import torch
import torch.nn.functional as F

BUCKETS = [512, 1024, 2048, 4096, 8192]

def pad_to_bucket(input_ids: torch.Tensor, pad_token_id: int = 0) -> torch.Tensor:
    seq_len = input_ids.shape[1]
    target_len = next((b for b in BUCKETS if b >= seq_len), seq_len)
    pad_amt = target_len - seq_len
    if pad_amt > 0:
        return F.pad(input_ids, (0, pad_amt), value=pad_token_id)
    return input_ids

With 5 fixed buckets, PyTorch compiles at most 5 CUDA Graphs at server warmup and achieves zero runtime recompilations for the lifetime of the worker.


2. Mark Dynamic Axes Properly for Non-Bucketed Paths

If you want dynamic shapes without CUDA Graph capture (e.g., using mode="max-autotune-no-cudagraphs"), explicitly mark batch and sequence dimensions before the first forward pass:

python
import torch._dynamo as dynamo

# Compile without CUDA graphs if arbitrary shapes are mandatory
compiled_model = torch.compile(model, mode="max-autotune-no-cudagraphs", dynamic=True)

# Explicitly hint symbolic bounds on warmup tensor
sample_ids = torch.randint(0, 32000, (1, 512), device="cuda")
dynamo.mark_dynamic(sample_ids, 0, min=1, max=32)     # dynamic batch
dynamo.mark_dynamic(sample_ids, 1, min=1, max=8192)   # dynamic seq_len

3. Raise cache_size_limit & Pre-Warm All Buckets at Startup

python
torch._dynamo.config.cache_size_limit = 32

# Warm up all 5 buckets during readiness probe before accepting live traffic
for b in BUCKETS:
    dummy = torch.zeros((1, b), dtype=torch.long, device="cuda")
    with torch.no_grad():
        _ = compiled_model(dummy)

This eliminates the 18-second mid-request compilation stall entirely while preserving full Triton + CUDA Graph speedups.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.