```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.
# Key insight: (diag(A) @ B)[i, j] == A[i] * B[i, j], so the O(N^2 * M) matmul
# (plus the O(N^2) memory for the dense diagonal matrix) can be replaced by a
# simple O(N * M) memory-bound row-scaling kernel with vectorized float4 access.
diag_matmul_cuda_source = """
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>

__global__ void diag_mul_vec4_kernel(const float* __restrict__ A,
                                     const float* __restrict__ B,
                                     float* __restrict__ C,
                                     const long N,
                                     const long M4) {
    const long col = (long)blockIdx.x * blockDim.x + threadIdx.x;
    if (col < M4) {
        for (long row = blockIdx.y; row < N; row += gridDim.y) {
            const float a = A[row];
            const long idx = row * M4 + col;
            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;
        }
    }
}

__global__ void diag_mul_scalar_kernel(const float* __restrict__ A,
                                       const float* __restrict__ B,
                                       float* __restrict__ C,
                                       const long N,
                                       const long M) {
    const long col = (long)blockIdx.x * blockDim.x + threadIdx.x;
    if (col < M) {
        for (long row = blockIdx.y; row < N; row += gridDim.y) {
            const long idx = 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(), "Inputs must be CUDA tensors");
    TORCH_CHECK(A.dim() == 1 && B.dim() == 2, "A must be 1D and B must be 2D");
    TORCH_CHECK(A.scalar_type() == torch::kFloat32 && B.scalar_type() == torch::kFloat32,
                "Only float32 tensors are supported by the custom kernel");

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

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

    auto C = torch::empty_like(B_c);

    if (N == 0 || M == 0) {
        return C;
    }

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

    if (M % 4 == 0) {
        const long M4 = M / 4;
        const long blocks_x = (M4 + block_size - 1) / block_size;
        const long blocks_y = N < max_grid_y ? N : max_grid_y;
        dim3 grid((unsigned int)blocks_x, (unsigned int)blocks_y);
        diag_mul_vec4_kernel<<<grid, block_size, 0, stream>>>(
            A_c.data_ptr<float>(), B_c.data_ptr<float>(), C.data_ptr<float>(), N, M4);
    } else {
        const long blocks_x = (M + block_size - 1) / block_size;
        const long blocks_y = N < max_grid_y ? N : max_grid_y;
        dim3 grid((unsigned int)blocks_x, (unsigned int)blocks_y);
        diag_mul_scalar_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);"
)

diag_matmul = load_inline(
    name="diag_matmul_ext",
    cpp_sources=diag_matmul_cpp_source,
    cuda_sources=diag_matmul_cuda_source,
    functions=["diag_matmul_cuda"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model that performs C = diag(A) * B with a custom fused CUDA
    kernel. Avoids materializing the N x N diagonal matrix and replaces the
    O(N^2 * M) matmul with an O(N * M) memory-bound row-scaling kernel.
    """
    def __init__(self):
        super(ModelNew, self).__init__()
        self.diag_matmul = diag_matmul

    def forward(self, A, B):
        if (A.is_cuda and B.is_cuda and A.dim() == 1 and B.dim() == 2
                and A.dtype == torch.float32 and B.dtype == torch.float32):
            return self.diag_matmul.diag_matmul_cuda(A, B)
        # Fallback path (mathematically identical to torch.diag(A) @ B)
        return A.unsqueeze(-1) * B
```