```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 matrix-vector multiplication (C = A @ B).
# This operation is memory-bandwidth bound (A is M x K ~ 8GB of reads),
# so the kernel is optimized for maximum memory throughput:
#   * one thread block per output row (M = 2048 blocks -> plenty of parallelism)
#   * 128-bit (float4) vectorized, fully coalesced global loads
#   * 4-way unrolled main loop with 4 independent accumulators for high MLP
#   * warp-shuffle + shared-memory tree reduction (no atomics, single kernel)
matvec_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>

#define THREADS 256
#define NWARPS  (THREADS / 32)

__global__ void matvec_kernel(const float* __restrict__ A,
                              const float* __restrict__ B,
                              float* __restrict__ C,
                              int M, int K) {
    const int row = blockIdx.x;
    const float* __restrict__ Arow = A + (size_t)row * (size_t)K;

    const int k4 = K >> 2;  // number of float4 elements
    const float4* __restrict__ A4 = reinterpret_cast<const float4*>(Arow);
    const float4* __restrict__ B4 = reinterpret_cast<const float4*>(B);

    const int stride = blockDim.x;
    int i = threadIdx.x;

    // 4-way unrolled main loop with independent accumulators
    float s0 = 0.0f, s1 = 0.0f, s2 = 0.0f, s3 = 0.0f;
    for (; i + 3 * stride < k4; i += 4 * stride) {
        float4 a0 = A4[i];
        float4 a1 = A4[i + stride];
        float4 a2 = A4[i + 2 * stride];
        float4 a3 = A4[i + 3 * stride];
        float4 b0 = B4[i];
        float4 b1 = B4[i + stride];
        float4 b2 = B4[i + 2 * stride];
        float4 b3 = B4[i + 3 * stride];
        s0 += a0.x * b0.x + a0.y * b0.y + a0.z * b0.z + a0.w * b0.w;
        s1 += a1.x * b1.x + a1.y * b1.y + a1.z * b1.z + a1.w * b1.w;
        s2 += a2.x * b2.x + a2.y * b2.y + a2.z * b2.z + a2.w * b2.w;
        s3 += a3.x * b3.x + a3.y * b3.y + a3.z * b3.z + a3.w * b3.w;
    }
    for (; i < k4; i += stride) {
        float4 a = A4[i];
        float4 b = B4[i];
        s0 += a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
    }

    float sum = s0 + s1 + s2 + s3;

    // Scalar tail for K not divisible by 4 (not hit for K = 1048576)
    for (int j = (k4 << 2) + threadIdx.x; j < K; j += stride) {
        sum += Arow[j] * B[j];
    }

    // Warp-level reduction via shuffle
    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1) {
        sum += __shfl_down_sync(0xffffffffu, sum, offset);
    }

    // Cross-warp reduction via shared memory
    __shared__ float smem[NWARPS];
    const int lane = threadIdx.x & 31;
    const int wid  = threadIdx.x >> 5;
    if (lane == 0) smem[wid] = sum;
    __syncthreads();

    if (wid == 0) {
        sum = (lane < NWARPS) ? smem[lane] : 0.0f;
        #pragma unroll
        for (int offset = 16; offset > 0; offset >>= 1) {
            sum += __shfl_down_sync(0xffffffffu, sum, offset);
        }
        if (lane == 0) C[row] = sum;
    }
}

torch::Tensor matvec_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 tensors");

    auto Ac = A.contiguous();
    auto Bc = B.contiguous();

    const int M = (int)Ac.size(0);
    const int K = (int)Ac.size(1);

    auto C = torch::empty({M, 1}, Ac.options());

    dim3 grid(M);
    dim3 block(THREADS);
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    matvec_kernel<<<grid, block, 0, stream>>>(
        Ac.data_ptr<float>(),
        Bc.data_ptr<float>(),
        C.data_ptr<float>(),
        M, K);

    return C;
}
"""

matvec_cpp_source = "torch::Tensor matvec_cuda(torch::Tensor A, torch::Tensor B);"

# Compile the inline CUDA extension
_matvec_ext = load_inline(
    name="matvec_ext",
    cpp_sources=matvec_cpp_source,
    cuda_sources=matvec_cuda_source,
    functions=["matvec_cuda"],
    verbose=False,
    extra_cuda_cflags=["-O3", "--use_fast_math"],
)


class ModelNew(nn.Module):
    """
    Optimized model that performs matrix-vector multiplication (C = A * B)
    using a custom fused CUDA reduction kernel.
    """
    def __init__(self):
        super(ModelNew, self).__init__()

    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        return _matvec_ext.matvec_cuda(A, B)
```