import torch
import triton
import triton.language as tl

@triton.jit
def matmul_kernel_fp8dot_final(
    A_ptr, B_ptr, A_SCALE_ptr, B_SCALE_ptr, C_ptr,
    M, N, K,
    stride_a_m_dim, stride_a_k_dim,
    stride_b_n_dim, stride_b_k_dim,
    stride_a_scale_m_dim, stride_a_scale_k_scaled_dim,
    stride_b_scale_n_scaled_dim, stride_b_scale_k_scaled_dim,
    stride_c_m_dim, stride_c_n_dim,
    BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, # For C-tile and A/B data tiles
    BLOCK_SIZE_K_COMMON: tl.constexpr, # Common K-dimension for dot product (A is M x K_COMMON, B_T is K_COMMON x N)
    A_B_SCALE_K_GRANULARITY: tl.constexpr, # K granularity for a_scale and b_scale (typically 128)
    B_SCALE_N_GRANULARITY: tl.constexpr  # N granularity for b_scale (typically 128)
):
    pid_m_abs = tl.program_id(0) # M-tile index: 0 to M/BLOCK_SIZE_M - 1
    pid_n_abs = tl.program_id(1) # N-tile index: 0 to N/BLOCK_SIZE_N - 1

    # Offsets for C tile. M is div by BM (64), N is div by BN (64). No C-tile boundary checks.
    offs_m_for_c_tile = pid_m_abs * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
    offs_n_for_c_tile = pid_n_abs * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)

    accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) # C-tile is BM x BN (64x64)

    # Base pointers for A and A_scale. M is div by BLOCK_SIZE_M (64).
    a_scale_load_ptrs_base = A_SCALE_ptr + offs_m_for_c_tile * stride_a_scale_m_dim
    a_tile_ptrs_base = A_ptr + offs_m_for_c_tile[:, None] * stride_a_m_dim # Shape (BM, 1)

    # K-dimension loop setup for data tiles. K is div by BLOCK_SIZE_K_COMMON (128).
    k_indices_common_tile = tl.arange(0, BLOCK_SIZE_K_COMMON) 
    
    for k_block_start in range(0, K, BLOCK_SIZE_K_COMMON): # Iterate by common K-block size (128)
        # K-scale index. A_B_SCALE_K_GRANULARITY is 128. BLOCK_SIZE_K_COMMON is 128.
        current_k_scale_idx = k_block_start // A_B_SCALE_K_GRANULARITY

        # Load A_SCALE (vector of size BLOCK_SIZE_M=64). No M-mask needed.
        a_scale_load_ptrs = a_scale_load_ptrs_base + current_k_scale_idx * stride_a_scale_k_scaled_dim
        a_scales_m_vector = tl.load(a_scale_load_ptrs, eviction_policy="evict_first")

        # B_SCALE indexing. B_SCALE_N_GRANULARITY is 128. BLOCK_SIZE_N for data is 64.
        b_scale_n_idx_for_tile = (pid_n_abs * BLOCK_SIZE_N) // B_SCALE_N_GRANULARITY
        
        b_scale_scalar_ptr = B_SCALE_ptr + (
            b_scale_n_idx_for_tile * stride_b_scale_n_scaled_dim +
            current_k_scale_idx * stride_b_scale_k_scaled_dim
        )
        b_scale_val = tl.load(b_scale_scalar_ptr, eviction_policy="evict_first")

        # Absolute K indices for the current common K-block
        k_indices_absolute = k_block_start + k_indices_common_tile # Shape (BLOCK_SIZE_K_COMMON=128)

        # Load A tile (BLOCK_SIZE_M x BLOCK_SIZE_K_COMMON = 64x128). No M or K masks.
        a_tile_ptrs = a_tile_ptrs_base + k_indices_absolute[None, :] * stride_a_k_dim
        a_block_fp8 = tl.load(a_tile_ptrs) # Shape (64, 128)

        # Load B tile for tl.dot(A_tile (64,128), B_tile_transposed (128,64)).
        # B is N x K (col-major). We need K_COMMON rows from B, and BLOCK_SIZE_N columns from B.
        # Pointers for B to load a (BLOCK_SIZE_K_COMMON x BLOCK_SIZE_N) tile.
        b_tile_ptrs = B_ptr + (
            k_indices_absolute[:, None] * stride_b_k_dim + 
            offs_n_for_c_tile[None, :] * stride_b_n_dim    
        )
        # This loads a block of B that is K_COMMON_elements x N_elements_in_tile.
        # Shape of loaded b_block_fp8_for_dot will be (BLOCK_SIZE_K_COMMON, BLOCK_SIZE_N) = (128, 64)
        b_block_fp8_for_dot = tl.load(b_tile_ptrs) # No N or K masks.
        
        # dot( (64,128), (128,64) ) -> (64,64)
        dot_output_f32 = tl.dot(a_block_fp8, b_block_fp8_for_dot, out_dtype=tl.float32, allow_tf32=False)
        
        scaled_dot_output = dot_output_f32 * a_scales_m_vector[:, None] * b_scale_val
        accumulator += scaled_dot_output

    # Store C tile (64x64). No M or N masks needed.
    c_tile_ptrs = C_ptr + (offs_m_for_c_tile[:, None] * stride_c_m_dim +
                           offs_n_for_c_tile[None, :] * stride_c_n_dim)
    tl.store(c_tile_ptrs, accumulator.to(tl.bfloat16))


def custom_kernel(kernel_input_data: tuple) -> torch.Tensor:
    a, b, a_scale, b_scale, c = kernel_input_data

    M, K_orig = a.shape 
    N, K_check = b.shape
    K = K_orig 
    
    stride_a_m_dim = 1 
    stride_a_k_dim = M
    stride_b_n_dim = 1 
    stride_b_k_dim = N 
    
    stride_a_scale_m_dim = 1
    stride_a_scale_k_scaled_dim = M
    
    stride_b_scale_n_scaled_dim = 1 
    stride_b_scale_k_scaled_dim = b_scale.shape[0] if b_scale.nelement() > 0 else 1
    
    stride_c_m_dim = N 
    stride_c_n_dim = 1

    # --- Kernel Launch Parameters ---
    BLOCK_SIZE_M_val = 64   # M is div by 64
    BLOCK_SIZE_N_val = 64   # N is div by 64
    # BLOCK_SIZE_K_COMMON_val is the K dimension for the tiles A and B_T in matmul A @ B_T
    # A_tile: M_val x K_COMMON_val; B_T_tile: K_COMMON_val x N_val
    BLOCK_SIZE_K_COMMON_val = 128  # K is div by 128.
    
    A_B_SCALE_K_GRANULARITY_val = 128 # K granularity for scales
    B_SCALE_N_GRANULARITY_val = 128 # N granularity for b_scale

    # Grid calculation: M div by BM, N div by BN.
    grid_m = M // BLOCK_SIZE_M_val
    grid_n = N // BLOCK_SIZE_N_val
    grid = (grid_m, grid_n)
    
    # --- Tuning Parameters ---
    # Shared mem per stage for A(64x128) and B_T(128x64) tiles:
    # A tile: 64*128 = 8192 bytes. B_T tile: 128*64 = 8192 bytes. Total = 16384 bytes.
    # Max stages = floor(65536 / 16384) = 4.
    num_warps_val = 4  # For 64x64 C-tile. (64*64 C elements) / (4 warps * 64 threads/AMD_wave) = 16 elem/thread
    num_stages_val = 3 # Try 3 stages first, 4 is max. (16384 * 3 = 49152 bytes)

    matmul_kernel_fp8dot_final[grid](
        a, b, a_scale, b_scale, c,
        M, N, K, 
        stride_a_m_dim, stride_a_k_dim,
        stride_b_n_dim, stride_b_k_dim,
        stride_a_scale_m_dim, stride_a_scale_k_scaled_dim,
        stride_b_scale_n_scaled_dim, stride_b_scale_k_scaled_dim, 
        stride_c_m_dim, stride_c_n_dim,
        BLOCK_SIZE_M=BLOCK_SIZE_M_val,
        BLOCK_SIZE_N=BLOCK_SIZE_N_val,
        BLOCK_SIZE_K_COMMON=BLOCK_SIZE_K_COMMON_val,
        A_B_SCALE_K_GRANULARITY=A_B_SCALE_K_GRANULARITY_val,
        B_SCALE_N_GRANULARITY=B_SCALE_N_GRANULARITY_val,
        num_warps=num_warps_val,
        num_stages=num_stages_val
    )
    return c
python eval.py benchmark /tmp/tmp69ra7c6o