```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 row-wise scaling
# out[i, j] = A[i] * B[i, j], which avoids materializing the N x N diagonal
# matrix and the expensive O(N^2 * M) matmul, reducing it to O(N * M).
diag_matmul_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>

// Vectorized kernel: each thread handles 4 consecutive elements (float4).
__global__ void diag_matmul_vec4_kernel(const float* __restrict__ A,
                                        const float* __restrict__ B,
                                        float* __restrict__ out,
                                        int N, int M) {
    int vec_per_row = M >> 2;
    long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
    long long total = (long long)N * vec_per_row;
    if (idx < total) {
        int row = (int)(idx / vec_per_row);
        float a = A[row];
        float4 b = reinterpret_cast<const float4*>(B)[idx];
        float4 o;
        o.x = a * b.x;
        o.y = a * b.y;
        o.z = a * b.z;
        o.w = a * b.w;
        reinterpret_cast<float4*>(out)[idx] = o;
    }
}

// Fallback elementwise kernel for the case where M is not divisible by 4.
__global__ void diag_matmul_kernel(const float* __restrict__ A,
                                   const float* __restrict__ B,
                                   float* __restrict__ out,
                                   int N, int M) {
    long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
    long long total = (long long)N * M;
    if (idx < total) {
        int row = (int)(idx / M);
        out[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();

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

    auto out = torch::empty_like(B_c);

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

    if ((M & 3) == 0) {
        long long total = (long long)N * (M >> 2);
        long long num_blocks = (total + block_size - 1) / block_size;
        diag_matmul_vec4_kernel<<<num_blocks, block_size, 0, stream>>>(
            A_c.data_ptr<float>(), B_c.data_ptr<float>(),
            out.data_ptr<float>(), N, M);
    } else {
        long long total = (long long)N * M;
        long long num_blocks = (total + block_size - 1) / block_size;
        diag_matmul_kernel<<<num_blocks, block_size, 0, stream>>>(
            A_c.data_ptr<float>(), B_c.data_ptr<float>(),
            out.data_ptr<float>(), N, M);
    }

    return out;
}
"""

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

diag_matmul_op = load_inline(
    name="diag_matmul",
    cpp_sources=diag_matmul_cpp_source,
    cuda_sources=diag_matmul_source,
    functions=["diag_matmul_cuda"],
    verbose=True,
    extra_cflags=[""],
    extra_cuda_cflags=["-O3"],
    extra_ldflags=[""],
)


class ModelNew(nn.Module):
    """
    Optimized model that computes C = diag(A) * B via a fused custom CUDA
    kernel that directly scales each row of B by the corresponding diagonal
    entry of A, avoiding explicit construction of the diagonal matrix and
    the full O(N^2 * M) matrix multiplication.
    """
    def __init__(self):
        super(ModelNew, self).__init__()
        self.diag_matmul = diag_matmul_op

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