[Bug] apply_rotary_pos_emb: leaves output tails unwritten with partial rotation

Abierto Apto para principiantes
#5,156 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 2 días

@shotsan ya está trabajando en esto.

Desde el 18/11/2026.

  • #5165 de @shotsan — abierto

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
78/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python, pytorch

Línea de trabajo

Empieza por lmdeploy/pytorch/kernels/cuda/apply_rotary_pos_emb.py en las líneas del launcher enlazadas en el issue y luego inspecciona el rango de escritura de la salida del kernel y la llamada al backend CUDA con inplace=False. Ejecuta la reproducción proporcionada en el modo intérprete de Triton; se considera terminado cuando las salidas separadas de query y key copian las columnas de entrada posteriores al ancho de rotación y ninguna de las dos colas contiene NaNs.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Describe the bug

apply_rotary_pos_emb supports a rotation width smaller than the head width. If its output tensors are separate from the inputs, it leaves the remaining columns unwritten. The reproduction uses head width 64 and rotation width 32. It initializes the output buffers with NaN and uses an identity rotation. The first 32 columns are correct. All 256 query-tail elements and 128 key-tail elements remain NaN.

The launcher allocates outputs with torch.empty_like and selects half_size from the smaller rotation width. The kernel writes only the rotated columns. It never copies the tail from the inputs.

The default kernel call allocates separate outputs. The CUDA backend also reaches this case when inplace=False. Model calls that reuse the input buffers retain the original tail. The cited kernel lines are unchanged on main as of 2026-11-17.

Reproduce
import torch
from lmdeploy.pytorch.kernels.cuda.apply_rotary_pos_emb import apply_rotary_pos_emb

dev = "cuda" if torch.cuda.is_available() else "cpu"
torch.set_default_device(dev)
torch.manual_seed(0)
S, H, D, R = 4, 2, 64, 32
q = torch.randn(S, H, D, dtype=torch.float16)
k = torch.randn(S, 1, D, dtype=torch.float16)
cos = torch.ones(S, R, dtype=torch.float16)
sin = torch.zeros_like(cos)
qo, ko = torch.full_like(q, float("nan")), torch.full_like(k, float("nan"))
apply_rotary_pos_emb(q, k, cos, sin, qo, ko)
print("Rotated query columns equal input:", torch.equal(qo[..., :R], q[..., :R]))
print("Unwritten query tail elements:", torch.isnan(qo[..., R:]).sum().item())
print("Unwritten key tail elements:", torch.isnan(ko[..., R:]).sum().item())
print("Expected unwritten elements: 0; both outputs equal their inputs.")
assert torch.equal(qo, q) and torch.equal(ko, k), "Partial rotary embedding does not copy the output tail."

Output:

Rotated query columns equal input: True
Unwritten query tail elements: 256
Unwritten key tail elements: 128
Expected unwritten elements: 0; both outputs equal their inputs.
AssertionError: Partial rotary embedding does not copy the output tail.
Expected behavior

Columns after the rotation width must equal the input columns. With cos = 1 and sin = 0, both full outputs must equal their inputs. No output element must retain the NaN initialization.

Suggested fix

When the output does not alias the input, copy the columns after the rotation width into the output. Apply this to both query and key outputs, including the default allocations.

Versions / environment

Library commit: fc33f69. Source checked: 2026-11-17.
torch 2.14.1, triton 3.8.0.
Reproduced with Triton's interpreter mode (TRITON_INTERPRET=1).
The CUDA kernel has the same store range. It also leaves the tail unwritten when the output does not alias the input.

Lenguaje dominante
Python
Estrellas
8.2k
Forks
797
Merge medio
3 d 15 h
PR fusionados (30 d)
52

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de InternLM/lmdeploy

Todos los issues de InternLM/lmdeploy

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.