The reason dynamic=True still triggers recompilations with custom Triton kernels and mode="reduce-overhead" is two-fold:
mode="reduce-overhead" enables CUDA Graphs, which require exact static tensor memory addresses and shapes at replay time.
- 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):
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:
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
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.