import math
from dataclasses import dataclass
import torch
from torch import nn
import torch.nn.functional as F
from task import input_t, output_t


class RoPE:
    def __init__(self, d_model: int, device="cuda"):
        self.d_model = d_model
        theta = 10000 ** (
            -torch.arange(0, d_model // 2, dtype=torch.bfloat16, device=device) / (d_model // 2)
        )
        self.theta = theta

    def rotate_half(self, x: torch.Tensor) -> torch.Tensor:
        x1, x2 = x.chunk(2, dim=-1)
        return torch.cat((-x2, x1), dim=-1)

    def forward(self, x: torch.Tensor, start_pos: int = 0) -> torch.Tensor:
        seq_len = x.size(-2)
        seq_idx = torch.arange(
            start_pos, start_pos + seq_len, device=x.device, dtype=torch.bfloat16
        )
        idx_theta = torch.einsum("s,d->sd", seq_idx, self.theta)
        idx_theta2 = torch.cat([idx_theta, idx_theta], dim=-1)
        cos = idx_theta2.cos()
        sin = idx_theta2.sin()
        return x * cos + self.rotate_half(x) * sin


class KVCache(nn.Module):
    def __init__(self, kv_cache_shape: tuple) -> None:
        super().__init__()
        self.register_buffer(
            "data", torch.zeros(kv_cache_shape, dtype=torch.bfloat16, device="cuda")
        )
        self.seq_len = 0
        self.zero()

    def zero(self) -> None:
        self.data.zero_()

    def get_data(self) -> torch.Tensor:
        return self.data

    def forward(self, c_kv: torch.Tensor) -> torch.Tensor:
        assert self.seq_len + c_kv.size(1) <= self.data.size(1), "KV Cache Exceeded"
        self.data = self.data.to(c_kv.dtype)
        self.data[:, self.seq_len : self.seq_len + c_kv.size(1), :] = c_kv
        self.seq_len += c_kv.size(1)
        return self.data[:, : self.seq_len], self.seq_len


@dataclass
class Config:
    batch_size: int
    dim: int
    n_heads: int
    q_lora_rank: int
    kv_lora_rank: int
    qk_nope_head_dim: int
    qk_rope_head_dim: int
    v_head_dim: int
    seq_len: int
    max_seq_len: int
    kv_cache_shape: tuple
    Q_proj_down_weight: torch.Tensor
    Q_proj_up_weight: torch.Tensor
    KV_proj_down_weight: torch.Tensor
    KV_proj_up_weight: torch.Tensor
    wo_weight: torch.Tensor


def mla_forward(x: torch.Tensor, kv_cache: KVCache, config: Config) -> torch.Tensor:
    # seq_len = 1 always here
    batch_size, seq_len, model_dim = x.size()

    # Create RoPE instances (lightweight, no nn.Module overhead)
    q_rope = RoPE(config.qk_rope_head_dim)
    k_rope = RoPE(config.qk_rope_head_dim)

    ################################################################################
    #                 Step 1: Handle down-projection + KV cache                    #
    ################################################################################
    q_lora = F.linear(x, config.Q_proj_down_weight)
    kv_lora = F.linear(x, config.KV_proj_down_weight)
    kv_lora, kv_len = kv_cache(kv_lora)
    query_pos = kv_len - 1

    ################################################################################
    #                  Step 2: Up-project and prepare NoPE + RoPE                  #
    ################################################################################
    # Handle queries Q first
    q_nope_and_rope = F.linear(q_lora, config.Q_proj_up_weight).view(
        batch_size, seq_len, config.n_heads, config.qk_nope_head_dim + config.qk_rope_head_dim
    )
    q_nope, q_rope_tensor = torch.split(
        q_nope_and_rope, [config.qk_nope_head_dim, config.qk_rope_head_dim], dim=-1
    )

    # Handle keys and values K/V. V does not need RoPE
    kv_nope, k_rope_tensor = torch.split(
        kv_lora, [config.kv_lora_rank, config.qk_rope_head_dim], dim=-1
    )
    kv_nope = F.linear(kv_nope, config.KV_proj_up_weight).view(
        batch_size, kv_len, config.n_heads, config.qk_nope_head_dim + config.v_head_dim
    )
    k_nope, v = torch.split(kv_nope, [config.qk_nope_head_dim, config.v_head_dim], dim=-1)

    ################################################################################
    #                    Step 3: Handle RoPE Stream                                #
    ################################################################################
    # Compute RoPE for queries and combine with no-RoPE part
    q_rope_tensor = q_rope_tensor.permute(0, 2, 1, 3)  # bs x n_heads x seq_len x rope_head_dim
    q_rope_tensor = q_rope.forward(q_rope_tensor, start_pos=query_pos)
    q_nope = q_nope.permute(0, 2, 1, 3)  # bs x n_heads x seq_len x nope_head_dim
    q = torch.concat([q_nope, q_rope_tensor], dim=-1)

    # Compute RoPE for keys and combine with no-RoPE part
    k_rope_tensor = k_rope_tensor[:, None, :, :]
    k_rope_tensor = k_rope.forward(k_rope_tensor).expand(-1, config.n_heads, -1, -1)
    k_nope = k_nope.permute(0, 2, 1, 3)  # bs x n_heads x kv_len x nope_head_dim
    k = torch.concat([k_nope, k_rope_tensor], dim=-1)

    ################################################################################
    #                        Compute Multi-head Attention                          #
    ################################################################################
    v = v.permute(0, 2, 1, 3)  # bs x n_heads x kv_len x v_head_dim
    scores = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(
        config.qk_rope_head_dim + config.qk_nope_head_dim
    )
    attn = F.softmax(scores, dim=-1).to(torch.bfloat16)
    y = torch.matmul(attn, v).view(batch_size, 1, -1)
    y = F.linear(y, config.wo_weight)
    return y, kv_cache.get_data()


# entry point for evaluation
def custom_kernel(data: input_t) -> output_t:
    # via generate_input
    config, x, kv_cache = data
    output, kv_cache = mla_forward(x, kv_cache, config)
    return output, kv_cache

python eval.py benchmark /tmp/tmp2d0o6bd8
Buff name: data, shape: torch.Size([128, 8192, 576])
Buff name: data, shape: torch.Size([128, 8192, 576])
