```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: C = diag(A) @ B is equivalent to scaling row i of B by A[i].
# This turns an O(N^2 * M) matmul into a purely memory-bound O(N * M) kernel.
diag_matmul_cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>

// Vectorized (float4) kernel used when M % 4 == 0 for max memory bandwidth.
__global__ void diag_matmul_vec4_kernel(const float* __restrict__ A,
                                        const float4* __restrict__ B,
                                        float4* __restrict__ C,
                                        long N, long M4) {
    long col = blockIdx.x * blockDim.x + threadIdx.x;
    if (col < M4) {
        for (long row = blockIdx.y; row < N; row += gridDim.y) {
            long idx = row * M4 + col;
            float4 b = B[idx];
            float a = A[row];
            float4 c;
            c.x = a * b.x;
            c.y = a * b.y;
            c.z = a * b.z;
            c.w = a * b.w;
            C[idx] = c;
        }
    }
}

// Generic scalar fallback kernel for any M.
__global__ void diag_matmul_kernel(const float* __restrict__ A,
                                   const float* __restrict__ B,
                                   float* __restrict__ C,
                                   long N, long M) {
    long col = blockIdx.x * blockDim.x + threadIdx.x;
    if (col < M) {
        for (long row = blockIdx.y; row < N; row += gridDim.y) {
            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.scalar_type() == torch::kFloat32 && B.scalar_type() == torch::kFloat32,
                "Inputs must be float32");

    auto A_c = A.contiguous();
    auto B_c = B.contiguous();
    auto C = torch::empty_like(B_c);

    long N = A_c.numel();
    long M = B_c.size(1);
    if (N == 0 || M == 0) {
        return C;
    }

    const int block_size = 256;
    const long max_grid_y = 65535;
    long grid_y = N < max_grid_y ? N : max_grid_y;

    if (M % 4 == 0) {
        long M4 = M / 4;
        dim3 grid((unsigned int)((M4 + block_size - 1) / block_size), (unsigned int)grid_y);
        diag_matmul_vec4_kernel<<<grid, block_size>>>(
            A_c.data_ptr<float>(),
            reinterpret_cast<const float4*>(B_c.data_ptr<float>()),
            reinterpret_cast<float4*>(C.data_ptr<float>()),
            N, M4);
    } else {
        dim3 grid((unsigned int)((M + block_size - 1) / block_size), (unsigned int)grid_y);
        diag_matmul_kernel<<<grid, block_size>>>(
            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_custom",
    cpp_sources=diag_matmul_cpp_source,
    cuda_sources=diag_matmul_cuda_source,
    functions=["diag_matmul_cuda"],
    verbose=True,
    extra_cflags=[""],
    extra_ldflags=[""],
)


class ModelNew(nn.Module):
    """
    Optimized model that performs C = diag(A) * B with a custom CUDA kernel.
    Since diag(A) @ B simply scales each row i of B by A[i], the O(N^2 * M)
    dense matmul is replaced by a memory-bound O(N * M) row-scaling kernel
    with vectorized float4 memory access.
    """
    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.dtype == torch.float32
                and B.dtype == torch.float32 and A.dim() == 1 and B.dim() == 2):
            return self.diag_matmul.diag_matmul_cuda(A, B)
        # Fallback for non-CUDA / non-float32 inputs
        return A.unsqueeze(1) * B
```