```python
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline

# Custom CUDA kernel for C = diag(A) @ B.
# Mathematically this is row-wise scaling: C[i, j] = A[i] * B[i, j].
# This avoids materializing the N x N diagonal matrix and the O(N^2 * M)
# matmul, reducing the work to a single memory-bandwidth-bound streaming
# pass (read B once, write C once).
#
# Optimizations over a naive elementwise kernel:
#   * 2D grid: blockIdx.x directly selects the row, so no expensive 64-bit
#     integer division is needed to recover the row index.
#   * 128-bit vectorized loads/stores (float4) with 4x unrolling so each
#     thread has 4 independent 16-byte transactions in flight (64 B of
#     memory-level parallelism per thread), which saturates DRAM bandwidth.
#   * Streaming cache hints on both loads (__ldcs) and stores (__stcs):
#     B and C are each touched exactly once, so evict-first policy keeps
#     L2 behavior clean for this pure streaming workload.
#   * A templated "even" path removes all bounds checks when the row
#     length is an exact multiple of the block tile (true for 4096 x 4096).
#   * __launch_bounds__ to cap register pressure and guarantee occupancy.
diag_matmul_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>

#define BLOCK_SIZE 256
#define UNROLL 4
#define MAX_GRID_Y 65535

// Vectorized kernel: requires M % 4 == 0. One block-row per matrix row.
template <bool EVEN>
__global__ void __launch_bounds__(BLOCK_SIZE)
diag_matmul_vec4_kernel(const float* __restrict__ A,
                        const float* __restrict__ B,
                        float* __restrict__ C,
                        const int vecM) {
    const long row = blockIdx.x;
    const float a = __ldg(A + row);
    const long offset = row * (long)vecM;
    const float4* Brow = reinterpret_cast<const float4*>(B) + offset;
    float4* Crow = reinterpret_cast<float4*>(C) + offset;

    const int base = blockIdx.y * (BLOCK_SIZE * UNROLL) + threadIdx.x;
    #pragma unroll
    for (int k = 0; k < UNROLL; ++k) {
        const int i = base + k * BLOCK_SIZE;
        if (EVEN || i < vecM) {
            const float4 b = __ldcs(Brow + i);
            float4 c;
            c.x = a * b.x;
            c.y = a * b.y;
            c.z = a * b.z;
            c.w = a * b.w;
            __stcs(Crow + i, c);
        }
    }
}

// Scalar grid-stride fallback kernel (handles any M).
__global__ void __launch_bounds__(BLOCK_SIZE)
diag_matmul_scalar_kernel(const float* __restrict__ A,
                          const float* __restrict__ B,
                          float* __restrict__ C,
                          const long M) {
    const long row = blockIdx.x;
    const float a = __ldg(A + row);
    const long offset = row * M;
    const float* Brow = B + offset;
    float* Crow = C + offset;
    const long stride = (long)gridDim.y * BLOCK_SIZE;
    for (long i = (long)blockIdx.y * BLOCK_SIZE + threadIdx.x; i < M; i += stride) {
        __stcs(Crow + i, __ldcs(Brow + i) * a);
    }
}

torch::Tensor diag_matmul_cuda(torch::Tensor A, torch::Tensor B) {
    TORCH_CHECK(A.is_cuda() && B.is_cuda(), "Inputs must be CUDA tensors");
    TORCH_CHECK(A.scalar_type() == at::kFloat && B.scalar_type() == at::kFloat,
                "Inputs must be float32");
    TORCH_CHECK(B.dim() == 2, "B must be a 2D tensor");
    TORCH_CHECK(A.numel() == B.size(0),
                "A must have exactly B.size(0) elements");

    auto A_c = A.contiguous();
    auto B_c = B.contiguous();

    const long N = B_c.size(0);
    const long M = B_c.size(1);

    auto C = at::empty_like(B_c);
    if (N == 0 || M == 0) {
        return C;
    }

    const float* a_ptr = A_c.data_ptr<float>();
    const float* b_ptr = B_c.data_ptr<float>();
    float* c_ptr = C.data_ptr<float>();

    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    const dim3 block(BLOCK_SIZE);

    const long vecM = M >> 2;
    const long tiles = (vecM + BLOCK_SIZE * UNROLL - 1) / (BLOCK_SIZE * UNROLL);
    if ((M & 3) == 0 && tiles <= MAX_GRID_Y && vecM <= 0x7fffffffL) {
        const dim3 grid((unsigned)N, (unsigned)tiles);
        if (tiles * (BLOCK_SIZE * UNROLL) == vecM) {
            diag_matmul_vec4_kernel<true><<<grid, block, 0, stream>>>(
                a_ptr, b_ptr, c_ptr, (int)vecM);
        } else {
            diag_matmul_vec4_kernel<false><<<grid, block, 0, stream>>>(
                a_ptr, b_ptr, c_ptr, (int)vecM);
        }
    } else {
        long yblocks = (M + BLOCK_SIZE - 1) / BLOCK_SIZE;
        if (yblocks > MAX_GRID_Y) yblocks = MAX_GRID_Y;
        const dim3 grid((unsigned)N, (unsigned)yblocks);
        diag_matmul_scalar_kernel<<<grid, block, 0, stream>>>(
            a_ptr, b_ptr, c_ptr, M);
    }
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    return C;
}
"""

diag_matmul_cpp_source = (
    "torch::Tensor diag_matmul_cuda(torch::Tensor A, torch::Tensor B);"
)

# Compile the inline CUDA extension.
diag_matmul = load_inline(
    name="diag_matmul_v3",
    cpp_sources=diag_matmul_cpp_source,
    cuda_sources=diag_matmul_source,
    functions=["diag_matmul_cuda"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized version of Model that computes C = diag(A) @ B as a fused
    row-scaling CUDA kernel (C[i, j] = A[i] * B[i, j]) in FP32.
    """
    def __init__(self):
        super(ModelNew, self).__init__()
        self._fn = diag_matmul.diag_matmul_cuda

    def forward(self, A, B):
        if (A.is_cuda and B.is_cuda and A.dim() == 1 and B.dim() == 2
                and A.dtype is torch.float32 and B.dtype is torch.float32):
            return self._fn(A, B)
        # Fallbacks (CPU tensors, other dtypes, or unexpected ranks),
        # mathematically equivalent to torch.diag(A) @ B.
        if A.dim() <= 1:
            return A.unsqueeze(-1) * B
        return torch.diag(A) @ B
```