```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 just a row-wise scaling: C[i, j] = A[i] * B[i, j].
# This avoids materializing the N x N diagonal matrix and avoids the
# O(N^2 * M) matmul entirely, reducing the op to a single memory-bound
# elementwise pass over B.
diag_matmul_source = """
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>

// Vectorized kernel (used when M % 4 == 0): each thread handles 4
// consecutive elements of a row via a single float4 load/store.
__global__ void diag_matmul_vec4_kernel(const float* __restrict__ A,
                                        const float* __restrict__ B,
                                        float* __restrict__ C,
                                        int N, int M) {
    const int M4 = M >> 2;
    const int col4 = blockIdx.x * blockDim.x + threadIdx.x;
    if (col4 < M4) {
        for (int row = blockIdx.y; row < N; row += gridDim.y) {
            const float a = A[row];
            const long idx = ((long)row * M4 + col4) << 2;
            const float4 b = *reinterpret_cast<const float4*>(B + idx);
            float4 c;
            c.x = a * b.x;
            c.y = a * b.y;
            c.z = a * b.z;
            c.w = a * b.w;
            *reinterpret_cast<float4*>(C + idx) = c;
        }
    }
}

// Generic scalar kernel: one thread per output element.
__global__ void diag_matmul_kernel(const float* __restrict__ A,
                                   const float* __restrict__ B,
                                   float* __restrict__ C,
                                   int N, int M) {
    const int col = blockIdx.x * blockDim.x + threadIdx.x;
    if (col < M) {
        for (int row = blockIdx.y; row < N; row += gridDim.y) {
            const long idx = (long)row * M + col;
            C[idx] = A[row] * B[idx];
        }
    }
}

torch::Tensor diag_matmul_cuda(torch::Tensor A, torch::Tensor B) {
    TORCH_CHECK(A.is_cuda() && B.is_cuda(), "A and B must be CUDA tensors");
    TORCH_CHECK(A.dim() == 1, "A must be a 1D tensor");
    TORCH_CHECK(B.dim() == 2, "B must be a 2D tensor");
    TORCH_CHECK(A.size(0) == B.size(0), "Length of A must equal rows of B");
    TORCH_CHECK(A.scalar_type() == torch::kFloat32 &&
                B.scalar_type() == torch::kFloat32,
                "Only float32 tensors are supported");

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

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

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

    const int block_size = 256;
    const int max_grid_y = 65535;
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    if ((M & 3) == 0) {
        const int M4 = M >> 2;
        dim3 grid((M4 + block_size - 1) / block_size,
                  N < max_grid_y ? N : max_grid_y);
        diag_matmul_vec4_kernel<<<grid, block_size, 0, stream>>>(
            A_c.data_ptr<float>(), B_c.data_ptr<float>(),
            C.data_ptr<float>(), N, M);
    } else {
        dim3 grid((M + block_size - 1) / block_size,
                  N < max_grid_y ? N : max_grid_y);
        diag_matmul_kernel<<<grid, block_size, 0, stream>>>(
            A_c.data_ptr<float>(), B_c.data_ptr<float>(),
            C.data_ptr<float>(), N, M);
    }

    return C;
}
"""

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

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


class ModelNew(nn.Module):
    """
    Optimized model that performs C = diag(A) * B with a custom CUDA kernel.

    Replaces the explicit diagonal-matrix construction and dense matmul with a
    single fused row-scaling kernel: C[i, j] = A[i] * B[i, j].
    """
    def __init__(self):
        super(ModelNew, self).__init__()
        self.diag_matmul = diag_matmul

    def forward(self, A, B):
        return self.diag_matmul.diag_matmul_cuda(A, B)
```