from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl @triton.jit def _rope_interleaved( out, x, cos, sin, ): head_start = tl.program_id(0) * 8 pos = tl.program_id(1) offsets = tl.arange(0, 8 * 128) x_offsets = pos * 24 * 128 + head_start * 128 + offsets values = tl.load(x + x_offsets, cache_modifier=".cg") pairs = tl.reshape(values, (8 * 64, 2)) even, odd = tl.split(pairs) even = tl.reshape(even, (8, 64)).to(tl.float32) odd = tl.reshape(odd, (8, 64)).to(tl.float32) freq = tl.arange(0, 64) c = tl.load(cos + pos * 64 + freq).to(tl.float32) s = tl.load(sin + pos * 64 + freq).to(tl.float32) out_even = even * c - odd * s out_odd = odd * c + even * s result = tl.reshape(tl.join(out_even, out_odd), (8 * 128,)) tl.store(out + x_offsets, result, cache_modifier=".cs") class DiffusionRoPE(nn.Module): def __init__(self, is_neox_style: bool = False) -> None: super().__init__() self.interleaved = not is_neox_style def forward( self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, ) -> torch.Tensor: if cos.dim() == 3: cos = cos[0] sin = sin[0] # Captured diffusion shapes use the interleaved, full 128-wide layout. assert self.interleaved assert x.shape[0] == 1 and x.shape[2:] == (24, 128) assert cos.shape[-1] == 64 output = torch.empty_like(x) grid = (3, x.shape[1]) _rope_interleaved[grid]( output, x, cos, sin, num_warps=2, ) return output