```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 that computes C = diag(A) @ B.
# Key insight: diag(A) @ B simply scales row i of B by A[i], turning an
# O(N^2 * M) matmul into an O(N * M) memory-bound elementwise scaling.
# The kernel uses vectorized float4 loads/stores when M is a multiple of 4.
diag_matmul_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>

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

__global__ void diag_matmul_kernel_scalar(
    const float* __restrict__ A,
    const float* __restrict__ B,
    float* __restrict__ C,
    int N,
    int M)
{
    int col = blockIdx.x * blockDim.x + threadIdx.x;
    if (col < M) {
        for (int row = blockIdx.y; row < N; row += gridDim.y) {
            float a = A[row];
            long long idx = (long long)row * M + col;
            C[idx] = a * 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");
    TORCH_CHECK(A.dim() == 1 && B.dim() == 2, "A must be 1D and B must be 2D");
    TORCH_CHECK(A.numel() == B.size(0), "Size mismatch between A and B");

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

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

    auto C = torch::empty_like(B_c);

    const int block_size = 256;
    const int max_grid_y = 65535;

    if (M % 4 == 0) {
        int64_t M4 = M / 4;
        dim3 grid((unsigned)((M4 + block_size - 1) / block_size),
                  (unsigned)std::min<int64_t>(N, max_grid_y));
        diag_matmul_kernel_vec4<<<grid, block_size>>>(
            A_c.data_ptr<float>(),
            reinterpret_cast<const float4*>(B_c.data_ptr<float>()),
            reinterpret_cast<float4*>(C.data_ptr<float>()),
            (int)N,
            (int)M4);
    } else {
        dim3 grid((unsigned)((M + block_size - 1) / block_size),
                  (unsigned)std::min<int64_t>(N, max_grid_y));
        diag_matmul_kernel_scalar<<<grid, block_size>>>(
            A_c.data_ptr<float>(),
            B_c.data_ptr<float>(),
            C.data_ptr<float>(),
            (int)N,
            (int)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", "--use_fast_math"],
)


class ModelNew(nn.Module):
    """
    Optimized model that computes C = diag(A) * B with a custom CUDA kernel.
    Instead of materializing the N x N diagonal matrix and performing a full
    matmul (O(N^2 * M)), it directly scales each row of B by the corresponding
    diagonal entry of A (O(N * M)), using 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):
            return self.diag_matmul.diag_matmul_cuda(A, B)
        # Fallback for CPU tensors or non-float32 dtypes
        return torch.diag(A) @ B
```