[BUG] phi3 _rotary_kernel reads Cos/Sin out of bounds whenever head_dim is not a power of two
Summary
The phi3 rotary kernel sizes its head-dimension block as BLOCK_DMODEL = triton.next_power_of_2(head_dim // 2). When head_dim // 2 is not a power of two the top lanes are padding, and every q/k load and store in the kernel masks them with dim_range0 < rot_dim — except the four Cos/Sin loads, whose masks cover only the sequence axis. Those padding lanes read Cos[s, rot_dim..BLOCK_DMODEL): past the end of every row of the exactly-sized (seq_len, head_dim // 2) cos/sin tensors the model code allocates, and past the end of the allocation on the last token.
Phi-3-mini (hidden_size=3072, 32 heads) has head_dim = 96, so rot_dim = 48 and BLOCK_DMODEL = 64: 16 of every 64 lanes read out of bounds, on every layer of every forward pass. Power-of-two head dims (128) are unaffected. The overrun is numerically silent — the values those lanes would produce are masked out of the stores — so no output comparison can see it; it is a memory-safety defect that can fault at an allocation boundary and is exactly what compute-sanitizer flags. (The q0 load three lines above the permalink shows the guard the Cos/Sin loads are missing; the K half repeats the pattern at lines 120-121.)
https://github.com/ModelTC/lightllm/blob/2c27b814e67e07dcd863d0da225b30f7cb1b4fa2/lightllm/models/phi3/triton_kernel/rotary_emb.py#L72-L73
The kernel was added in #433.
Steps to reproduce
Values match the rotary law before and after the fix (the repro asserts this); the bug itself is visible under the sanitizer, with PYTORCH_NO_CUDA_MEMORY_CACHING=1 so the caching allocator's slack does not absorb the overrun:
compute-sanitizer --tool memcheck python repro.py # repro.py in the PR
========= Invalid __global__ read of size 16 bytes
at _rotary_kernel ... lightllm/models/phi3/triton_kernel/rotary_emb.py:72
========= ERROR SUMMARY: 16 errors
head_dim=96, rot_dim=48, cos/sin allocated (T, 48) exactly as LlamaTpPartModel._cos_cached + torch.index_select produce them; after adding the dim guard, ERROR SUMMARY: 0 errors and outputs bit-identical.
Expected behavior
All loads mask the head-dimension padding lanes, as the kernel's q/k loads and stores already do.
Environment
- lightllm commit 2c27b814 (main)
- NVIDIA L40S (sm_89), driver CUDA 12.4
- torch 2.6.0+cu124, triton 3.2.0, Python 3.10
Re-checked against current main (fb1ebf0f): rotary_emb.py has not changed since this was filed, and the out-of-bounds reads still reproduce under compute-sanitizer --tool memcheck at the same line (rotary_emb.py:72). The PR still applies cleanly on top of the current main.