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, # n_scaled_dim is stride for 1st dim of b_scale
    stride_c_m_dim, stride_c_n_dim,
    BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr,
    BLOCK_SIZE_K: tl.constexpr # This is the K-dimension for the tiles in tl.dot
):
    # Program IDs identify the C-tile this specific program instance will compute
    pid_m_abs = tl.program_id(0) # Absolute M-tile index
    pid_n_abs = tl.program_id(1) # Absolute N-tile index

    # Offsets for the C tile that this program instance will compute
    offs_m_for_c_tile = pid_m_abs * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) # Shape (BLOCK_SIZE_M)
    offs_n_for_c_tile = pid_n_abs * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) # Shape (BLOCK_SIZE_N)

    # Boundary masks for M and N dimensions
    mask_m_dim = offs_m_for_c_tile < M    # Shape (BLOCK_SIZE_M)
    mask_n_dim = offs_n_for_c_tile < N    # Shape (BLOCK_SIZE_N)

    # Accumulator for the C tile, initialized to zeros. Operates in float32.
    accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)

    # Base pointers for A and A_scale, adjusted for the M-dimension part of the tile.
    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

    # K-dimension loop setup
    # The K-loop iterates over the K dimension of the matrices in chunks of BLOCK_SIZE_K.
    k_indices_range_for_tile = tl.arange(0, BLOCK_SIZE_K) # K-dimension of tiles loaded into SMEM
    
    for k_loop_iter_start in range(0, K, BLOCK_SIZE_K):
        # current_k_scale_idx: Index for the K-dimension of scale tensors.
        # Scale K-granularity is 128, BLOCK_SIZE_K for tiles is 128.
        current_k_scale_idx = k_loop_iter_start // 128 

        # Load A_SCALE
        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, mask=mask_m_dim, other=1.0, eviction_policy="evict_first")

        # Load B_SCALE
        b_scale_n_idx_for_tile = pid_n_abs # BLOCK_SIZE_N is 128, matches 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")

        # K indices for loading A and B tiles for the current K-loop iteration
        k_indices_for_load = k_loop_iter_start + k_indices_range_for_tile

        # Load A tile (BLOCK_SIZE_M x BLOCK_SIZE_K)
        a_tile_ptrs = a_tile_ptrs_base + k_indices_for_load[None, :] * stride_a_k_dim
        a_block_fp8 = tl.load(a_tile_ptrs, mask=mask_m_dim[:, None], other=0.0) # M-mask, K is full

        # Load B tile (transposed view for dot: BLOCK_SIZE_K x BLOCK_SIZE_N)
        b_tile_ptrs = B_ptr + (offs_n_for_c_tile[None, :] * stride_b_n_dim +
                               k_indices_for_load[:, None] * stride_b_k_dim)
        b_block_fp8_transposed = tl.load(b_tile_ptrs, mask=mask_n_dim[None, :], other=0.0) # N-mask, K is full
        
        dot_output_f32 = tl.dot(a_block_fp8, b_block_fp8_transposed, 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
    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)
    mask_c_store = mask_m_dim[:, None] & mask_n_dim[None, :]
    tl.store(c_tile_ptrs, accumulator.to(tl.bfloat16), mask=mask_c_store)

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 (v7 configuration) ---
    BLOCK_SIZE_M_val = 128
    BLOCK_SIZE_N_val = 128
    BLOCK_SIZE_K_val = 128 # This corresponds to the K dimension of the tiles in tl.dot
    
    # Grid calculation
    grid_m = triton.cdiv(M, BLOCK_SIZE_M_val)
    grid_n = triton.cdiv(N, BLOCK_SIZE_N_val)
    grid = (grid_m, grid_n)
    
    # --- Tuning Parameters (v7 configuration) ---
    num_warps_val = 8
    num_stages_val = 2

    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=BLOCK_SIZE_K_val, 
        num_warps=num_warps_val,
        num_stages=num_stages_val
    )
    return c
python eval.py benchmark /tmp/tmpkxpjinqz