```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

# diag(A) @ B is mathematically equivalent to scaling each row i of B by A[i],
# i.e. out[i, j] = A[i] * B[i, j]. This avoids materializing the N x N diagonal
# matrix and reduces the O(N^2 * M) matmul to an O(N * M) element-wise kernel.

diag_matmul_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>

__global__ void diag_matmul_kernel(const float* __restrict__ A,
                                   const float* __restrict__ B,
                                   float* __restrict__ out,
                                   int N, int M) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int total = N * M;
    if (idx < total) {
        int row = idx / M;
        out[idx] = A[row] * B[idx];
    }
}

// Vectorized version: each thread handles 4 contiguous floats (one float4).
__global__ void diag_matmul_vec4_kernel(const float* __restrict__ A,
                                        const float* __restrict__ B,
                                        float* __restrict__ out,
                                        int N, int M4) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int total = N * M4;
    if (idx < total) {
        int row = idx / M4;
        float a = A[row];
        float4 b = reinterpret_cast<const float4*>(B)[idx];
        float4 r;
        r.x = a * b.x;
        r.y = a * b.y;
        r.z = a * b.z;
        r.w = a * b.w;
        reinterpret_cast<float4*>(out)[idx] = r;
    }
}

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.size(0) == B.size(0), "Size mismatch between A and B");

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

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

    auto out = torch::empty_like(B_c);

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

    // Use the float4 vectorized path when rows are 16-byte aligned
    // (M divisible by 4 and base pointers aligned, which torch guarantees).
    if (M % 4 == 0) {
        const int M4 = M / 4;
        const int total = N * M4;
        const int 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, M4);
    } else {
        const int total = N * M;
        const int 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 = 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 model that performs C = diag(A) * B using a custom fused CUDA
    kernel that directly computes out[i, j] = A[i] * B[i, j] without
    materializing the diagonal matrix.
    """
    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 non-CUDA / non-float32 inputs
        return A.unsqueeze(1) * B
```