```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 the O(N^2 * M) matmul,
# reducing the work to a single memory-bandwidth-bound elementwise pass (O(N*M)).
diag_matmul_source = """
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>

// Scalar fallback kernel (handles any M).
__global__ void diag_matmul_scalar_kernel(const float* __restrict__ A,
                                          const float* __restrict__ B,
                                          float* __restrict__ C,
                                          long N, long M) {
    long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;
    long total = N * M;
    if (idx < total) {
        long row = idx / M;
        C[idx] = __ldg(A + row) * B[idx];
    }
}

// Vectorized kernel using 128-bit loads/stores (requires M % 4 == 0).
__global__ void diag_matmul_vec4_kernel(const float* __restrict__ A,
                                        const float* __restrict__ B,
                                        float* __restrict__ C,
                                        long N, long vecM) {
    long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;
    long total = N * vecM;
    if (idx < total) {
        long row = idx / vecM;
        float a = __ldg(A + row);
        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;
    }
}

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() == at::kFloat && B.scalar_type() == at::kFloat,
                "Inputs must be float32");
    TORCH_CHECK(B.dim() == 2, "B must be a 2D tensor");

    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 = at::empty_like(B_c);
    if (N == 0 || M == 0) {
        return C;
    }

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

    if ((M & 3) == 0) {
        const long vecM = M >> 2;
        const long total = N * vecM;
        const 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>(), C.data_ptr<float>(), N, vecM);
    } else {
        const long total = N * M;
        const long num_blocks = (total + block_size - 1) / block_size;
        diag_matmul_scalar_kernel<<<num_blocks, block_size, 0, stream>>>(
            A_c.data_ptr<float>(), B_c.data_ptr<float>(), C.data_ptr<float>(), N, M);
    }
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    return C;
}
"""

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

# Compile the inline CUDA extension.
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_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized version of Model that computes C = diag(A) @ B as a fused
    row-scaling CUDA kernel (C[i, j] = A[i] * B[i, j]) in FP32.
    """
    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 (e.g. CPU tensors): mathematically equivalent row scaling.
        return A.unsqueeze(-1) * B
```