```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-scalar multiplication (C = A * s).
#
# The operator is purely DRAM-bandwidth bound, so the kernel is built to
# saturate memory bandwidth while adding as little per-call overhead as
# possible:
#   * 128-bit vectorized (float4) loads/stores, 4x unroll for MLP
#   * 32-bit addressing fast path (covers any realistic tensor) to cut
#     integer/address overhead vs int64 indexing
#   * compile-time constant block size / unroll (__launch_bounds__)
#   * plain cache behavior (streaming hints measured slower on this op)
#   * launch on the current CUDA stream (capture-safe), device guard
#   * minimal host-side work (no dispatcher round-trip for contiguous())
scalar_mul_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda_runtime.h>
#include <cstdint>

namespace {

constexpr int kBlock = 256;
constexpr int kUnroll = 4;

// 32-bit index fast path (n4 < 2^32 float4 elements = 64 GiB of data).
__global__ void __launch_bounds__(kBlock)
scalar_mul_vec4_kernel(const float4* __restrict__ A,
                       float4* __restrict__ C,
                       const float s,
                       const unsigned int n4) {
    const unsigned int base = blockIdx.x * (kBlock * kUnroll) + threadIdx.x;
    #pragma unroll
    for (int j = 0; j < kUnroll; ++j) {
        const unsigned int i = base + (unsigned int)j * kBlock;
        if (i < n4) {
            float4 v = A[i];
            v.x *= s;
            v.y *= s;
            v.z *= s;
            v.w *= s;
            C[i] = v;
        }
    }
}

// 64-bit fallback for gigantic tensors.
__global__ void __launch_bounds__(kBlock)
scalar_mul_vec4_kernel_64(const float4* __restrict__ A,
                          float4* __restrict__ C,
                          const float s,
                          const int64_t n4) {
    const int64_t base = (int64_t)blockIdx.x * (kBlock * kUnroll) + threadIdx.x;
    #pragma unroll
    for (int j = 0; j < kUnroll; ++j) {
        const int64_t i = base + (int64_t)j * kBlock;
        if (i < n4) {
            float4 v = A[i];
            v.x *= s;
            v.y *= s;
            v.z *= s;
            v.w *= s;
            C[i] = v;
        }
    }
}

// Handles the (n % 4) tail after the vectorized body.
__global__ void scalar_mul_tail_kernel(const float* __restrict__ A,
                                       float* __restrict__ C,
                                       const float s,
                                       const int64_t start,
                                       const int64_t n) {
    const int64_t idx = start + (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n) {
        C[idx] = A[idx] * s;
    }
}

// Generic fallback for misaligned pointers (e.g. odd-offset contiguous views).
__global__ void __launch_bounds__(kBlock)
scalar_mul_kernel(const float* __restrict__ A,
                  float* __restrict__ C,
                  const float s,
                  const int64_t n) {
    const int64_t stride = (int64_t)gridDim.x * kBlock;
    for (int64_t i = (int64_t)blockIdx.x * kBlock + threadIdx.x; i < n; i += stride) {
        C[i] = A[i] * s;
    }
}

}  // namespace

torch::Tensor scalar_mul_cuda(torch::Tensor A, double s) {
    TORCH_CHECK(A.is_cuda(), "A must be a CUDA tensor");
    TORCH_CHECK(A.scalar_type() == at::kFloat, "A must be float32");

    const c10::cuda::CUDAGuard device_guard(A.device());

    auto Ac = A.is_contiguous() ? A : A.contiguous();
    auto C = torch::empty_like(Ac);

    const int64_t n = Ac.numel();
    if (n == 0) {
        return C;
    }

    const float sf = static_cast<float>(s);
    const float* a_ptr = Ac.data_ptr<float>();
    float* c_ptr = C.data_ptr<float>();
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    const bool aligned =
        ((reinterpret_cast<uintptr_t>(a_ptr) & 0xF) == 0) &&
        ((reinterpret_cast<uintptr_t>(c_ptr) & 0xF) == 0);

    if (aligned) {
        const int64_t n4 = n >> 2;
        if (n4 > 0) {
            const int64_t per_block = (int64_t)kBlock * kUnroll;
            const int64_t blocks = (n4 + per_block - 1) / per_block;
            if (n4 <= (int64_t)0xFFFFFFFFu) {
                scalar_mul_vec4_kernel<<<(unsigned int)blocks, kBlock, 0, stream>>>(
                    reinterpret_cast<const float4*>(a_ptr),
                    reinterpret_cast<float4*>(c_ptr),
                    sf, (unsigned int)n4);
            } else {
                scalar_mul_vec4_kernel_64<<<(unsigned int)blocks, kBlock, 0, stream>>>(
                    reinterpret_cast<const float4*>(a_ptr),
                    reinterpret_cast<float4*>(c_ptr),
                    sf, n4);
            }
        }
        const int64_t rem = n & 3;
        if (rem > 0) {
            const int64_t start = n4 << 2;
            scalar_mul_tail_kernel<<<1, kBlock, 0, stream>>>(
                a_ptr, c_ptr, sf, start, n);
        }
    } else {
        const int64_t full_blocks = (n + kBlock - 1) / kBlock;
        const int64_t blocks = full_blocks < 8192 ? full_blocks : 8192;
        scalar_mul_kernel<<<(unsigned int)blocks, kBlock, 0, stream>>>(
            a_ptr, c_ptr, sf, n);
    }

    return C;
}
"""

scalar_mul_cpp_source = (
    "torch::Tensor scalar_mul_cuda(torch::Tensor A, double s);"
)

# Compile the inline CUDA extension
scalar_mul_ext = load_inline(
    name="scalar_mul_ext_v3",
    cpp_sources=scalar_mul_cpp_source,
    cuda_sources=scalar_mul_source,
    functions=["scalar_mul_cuda"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    extra_ldflags=[""],
)


class ModelNew(nn.Module):
    """
    Optimized model that performs matrix-scalar multiplication (C = A * s)
    using a custom vectorized CUDA kernel.
    """
    def __init__(self):
        super(ModelNew, self).__init__()
        self._fn = scalar_mul_ext.scalar_mul_cuda

    def forward(self, A: torch.Tensor, s: float) -> torch.Tensor:
        if A.is_cuda and A.dtype == torch.float32:
            return self._fn(A, float(s))
        # Fallback for non-CUDA / non-FP32 inputs
        return A * s
```