Apply rotary embeddings using interleaved (even/odd) decomposition. One program per row. Each row has head_dim elements. x1 = even-indexed elements (0, 2, 4, ...) x2 = odd-indexed elements (1, 3, 5, ...) out[2i] = x1[i] * cos[i] - x2[i] * sin[i] out[2i+1] = x1[i] * sin[
(
X_ptr,
COS_ptr,
SIN_ptr,
OUT_ptr,
seq_len,
head_dim,
stride_x_row,
stride_cos_row,
stride_sin_row,
stride_out_row,
half_dim,
BLOCK_SIZE: tl.constexpr,
)
| 23 | |
| 24 | @triton.jit |
| 25 | def rotary_embedding_kernel( |
| 26 | X_ptr, |
| 27 | COS_ptr, |
| 28 | SIN_ptr, |
| 29 | OUT_ptr, |
| 30 | seq_len, |
| 31 | head_dim, |
| 32 | stride_x_row, |
| 33 | stride_cos_row, |
| 34 | stride_sin_row, |
| 35 | stride_out_row, |
| 36 | half_dim, |
| 37 | BLOCK_SIZE: tl.constexpr, |
| 38 | ): |
| 39 | """ |
| 40 | Apply rotary embeddings using interleaved (even/odd) decomposition. |
| 41 | |
| 42 | One program per row. Each row has head_dim elements. |
| 43 | x1 = even-indexed elements (0, 2, 4, ...) |
| 44 | x2 = odd-indexed elements (1, 3, 5, ...) |
| 45 | |
| 46 | out[2i] = x1[i] * cos[i] - x2[i] * sin[i] |
| 47 | out[2i+1] = x1[i] * sin[i] + x2[i] * cos[i] |
| 48 | """ |
| 49 | row_idx = tl.program_id(0) |
| 50 | |
| 51 | col_offsets = tl.arange(0, BLOCK_SIZE) |
| 52 | mask_half = col_offsets < half_dim |
| 53 | |
| 54 | # Compute pointers to even-indexed (x1) and odd-indexed (x2) elements |
| 55 | # even indices: 0, 2, 4, ... => col_offsets * 2 |
| 56 | # odd indices: 1, 3, 5, ... => col_offsets * 2 + 1 |
| 57 | x_row_base = X_ptr + row_idx * stride_x_row |
| 58 | x1 = tl.load(x_row_base + col_offsets * 2, mask=mask_half, other=0.0).to(tl.float32) |
| 59 | x2 = tl.load(x_row_base + col_offsets * 2 + 1, mask=mask_half, other=0.0).to(tl.float32) |
| 60 | |
| 61 | # Load cos and sin (shape [n_rows, half_dim]) |
| 62 | cos = tl.load(COS_ptr + row_idx * stride_cos_row + col_offsets, mask=mask_half, other=1.0).to(tl.float32) |
| 63 | sin = tl.load(SIN_ptr + row_idx * stride_sin_row + col_offsets, mask=mask_half, other=0.0).to(tl.float32) |
| 64 | |
| 65 | # Apply rotation |
| 66 | rx1 = x1 * cos - x2 * sin |
| 67 | rx2 = x1 * sin + x2 * cos |
| 68 | |
| 69 | # Store results interleaved: out[2i] = rx1[i], out[2i+1] = rx2[i] |
| 70 | out_row_base = OUT_ptr + row_idx * stride_out_row |
| 71 | tl.store(out_row_base + col_offsets * 2, rx1, mask=mask_half) |
| 72 | tl.store(out_row_base + col_offsets * 2 + 1, rx2, mask=mask_half) |
| 73 | |
| 74 | |
| 75 | def kernel_fn( |
nothing calls this directly
no outgoing calls
no test coverage detected