You write custom CUDA kernels to replace the pytorch operators in the given architecture to get speedups. 

    You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.


        Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is: 

        ``` 

        # 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
import torch.nn.functional as F


class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()

    def forward(self, a, b):
        return a + b


def get_inputs():
    # randomly generate input tensors based on the model architecture
    a = torch.randn(1, 128).cuda()
    b = torch.randn(1, 128).cuda()
    return [a, b]


def get_init_inputs():
    # randomly generate tensors required for initialization based on the model architecture
    return []

        ``` 

        The example new arch with custom CUDA kernels looks like this:
        ```
        # 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
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline

# Define the custom CUDA kernel for element-wise addition
elementwise_add_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>

__global__ void elementwise_add_kernel(const float* a, const float* b, float* out, int size) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < size) {
        out[idx] = a[idx] + b[idx];
    }
}

torch::Tensor elementwise_add_cuda(torch::Tensor a, torch::Tensor b) {
    auto size = a.numel();
    auto out = torch::zeros_like(a);

    const int block_size = 256;
    const int num_blocks = (size + block_size - 1) / block_size;

    elementwise_add_kernel<<<num_blocks, block_size>>>(a.data_ptr<float>(), b.data_ptr<float>(), out.data_ptr<float>(), size);

    return out;
}
"""

elementwise_add_cpp_source = (
    "torch::Tensor elementwise_add_cuda(torch::Tensor a, torch::Tensor b);"
)

# Compile the inline CUDA code for element-wise addition
elementwise_add = load_inline(
    name="elementwise_add",
    cpp_sources=elementwise_add_cpp_source,
    cuda_sources=elementwise_add_source,
    functions=["elementwise_add_cuda"],
    verbose=True,
    extra_cflags=[""],
    extra_ldflags=[""],
)


class ModelNew(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.elementwise_add = elementwise_add

    def forward(self, a, b):
        return self.elementwise_add.elementwise_add_cuda(a, b)

        ``` 

        
    You are given the following architecture: 

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

class Model(nn.Module):
    """
    Model that performs matrix multiplication, max pooling, sum, and scaling.
    """
    def __init__(self, in_features, out_features, kernel_size, scale_factor):
        super(Model, self).__init__()
        self.matmul = nn.Linear(in_features, out_features)
        self.max_pool = nn.MaxPool1d(kernel_size)
        self.scale_factor = scale_factor

    def forward(self, x):
        """
        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, in_features).

        Returns:
            torch.Tensor: Output tensor of shape (batch_size, out_features).
        """
        x = self.matmul(x)
        x = self.max_pool(x.unsqueeze(1)).squeeze(1)
        x = torch.sum(x, dim=1)
        x = x * self.scale_factor
        return x

batch_size = 128
in_features = 32768
out_features = 32768
kernel_size = 2
scale_factor = 0.5

def get_inputs():
    return [torch.rand(batch_size, in_features)]

def get_init_inputs():
    return [in_features, out_features, kernel_size, scale_factor]
    ```
    
Optimize the architecture named Model with custom CUDA operators! Name your optimized output architecture ModelNew. Output the new code in codeblocks. Please generate real code, NOT pseudocode, make sure the code compiles and is fully functional. Just output the new model code, no other text, and NO testing code! 



This is turn 4 of 6 for this task. Your previous solution (turn 3) was:
```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
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline

# Allow tensor-core math for any fp32 fallback matmuls.
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False

# The workload is dominated by a (batch x in) @ (in x out) GEMM whose fp16 weight
# matrix is ~2.1 GB, i.e. it is HBM-bandwidth-bound. With batch=128 the single-GEMM
# launch only creates ~128 thread blocks (barely over one wave on a 108-SM A100),
# leaving the memory system under-utilized in the tail. We therefore split the K
# dimension into 4 chunks issued as ONE strided-batched GEMM (4x the thread blocks,
# much better SM/HBM utilization), accumulating fp16 tensor-core products into fp32
# partials (no extra rounding vs. the plain fp16 GEMM). A fused kernel then adds the
# bias, reduces the chunk partials, applies max-pool(k=2), sums over features and
# scales -- reading the partials once and writing only `batch` floats.
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>
#include <cublas_v2.h>

#define THREADS 512

__device__ __forceinline__ float blockReduceSumF(float val) {
    __shared__ float shared[32];
    const int lane = threadIdx.x & 31;
    const int wid  = threadIdx.x >> 5;
    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1)
        val += __shfl_down_sync(0xffffffffu, val, offset);
    if (lane == 0) shared[wid] = val;
    __syncthreads();
    const int nwarp = (blockDim.x + 31) >> 5;
    if (wid == 0) {
        val = (lane < nwarp) ? shared[lane] : 0.0f;
        #pragma unroll
        for (int offset = 16; offset > 0; offset >>= 1)
            val += __shfl_down_sync(0xffffffffu, val, offset);
    }
    return val;  // only thread 0 holds the block total
}

// P: (CHUNKS, rows, N) fp32 partial sums of the K-split GEMM.
// out[r] = scale * sum_j max(bias[2j]   + sum_c P[c,r,2j],
//                            bias[2j+1] + sum_c P[c,r,2j+1])
// One float4 covers two pool pairs. Requires N % 8 == 0.
template<int CHUNKS>
__global__ void partial_maxpool2_sum_scale_kernel(
    const float* __restrict__ P, const float* __restrict__ bias,
    float* __restrict__ out, const int rows, const long long N,
    const float scale)
{
    const int r = blockIdx.x;
    const long long row_off = (long long)r * N;
    const long long cstride = (long long)rows * N;
    const long long nv = N >> 2;
    const float4* __restrict__ b4 = reinterpret_cast<const float4*>(bias);

    float acc = 0.0f;
    for (long long i = threadIdx.x; i < nv; i += blockDim.x) {
        float4 y = b4[i];
        #pragma unroll
        for (int c = 0; c < CHUNKS; ++c) {
            const float4 v = *reinterpret_cast<const float4*>(
                P + (long long)c * cstride + row_off + (i << 2));
            y.x += v.x; y.y += v.y; y.z += v.z; y.w += v.w;
        }
        acc += fmaxf(y.x, y.y) + fmaxf(y.z, y.w);
    }
    acc = blockReduceSumF(acc);
    if (threadIdx.x == 0) out[r] = acc * scale;
}

// Strided-batched GEMM computing, for each K-chunk c:
//   P[c] = x_half[:, c*k:(c+1)*k] @ w_half[:, c*k:(c+1)*k]^T
// with fp16 inputs (tensor cores) and fp32 accumulation/output.
// Column-major view: C(N x b) = opT(w_chunk)(N x k) * x_chunk(k x b).
torch::Tensor chunked_linear_fp16in_fp32out(torch::Tensor w, torch::Tensor x,
                                            int64_t chunks) {
    TORCH_CHECK(w.is_cuda() && x.is_cuda(), "inputs must be CUDA");
    TORCH_CHECK(w.scalar_type() == torch::kFloat16, "w must be fp16");
    TORCH_CHECK(x.scalar_type() == torch::kFloat16, "x must be fp16");
    TORCH_CHECK(w.dim() == 2 && x.dim() == 2, "w and x must be 2D");
    TORCH_CHECK(w.is_contiguous() && x.is_contiguous(),
                "w and x must be contiguous");
    const int64_t N  = w.size(0);
    const int64_t in = w.size(1);
    const int64_t b  = x.size(0);
    TORCH_CHECK(x.size(1) == in, "feature dim mismatch");
    TORCH_CHECK(in % chunks == 0, "in_features must be divisible by chunks");
    const int64_t k = in / chunks;

    auto P = torch::empty({chunks, b, N}, x.options().dtype(torch::kFloat32));
    if (b == 0 || N == 0) return P;

    cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    C10_CUBLAS_CHECK(cublasSetStream(handle, stream));
    C10_CUBLAS_CHECK(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH));

    const float alpha = 1.0f, beta = 0.0f;
    C10_CUBLAS_CHECK(cublasGemmStridedBatchedEx(
        handle, CUBLAS_OP_T, CUBLAS_OP_N,
        (int)N, (int)b, (int)k,
        &alpha,
        w.data_ptr(), CUDA_R_16F, (int)in, (long long)k,
        x.data_ptr(), CUDA_R_16F, (int)in, (long long)k,
        &beta,
        P.data_ptr(), CUDA_R_32F, (int)N, (long long)(b * N),
        (int)chunks,
        CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
    return P;
}

torch::Tensor partial_maxpool2_sum_scale(torch::Tensor P, torch::Tensor bias,
                                         double scale) {
    TORCH_CHECK(P.is_cuda() && P.dim() == 3, "P must be a 3D CUDA tensor");
    TORCH_CHECK(P.scalar_type() == torch::kFloat32, "P must be fp32");
    TORCH_CHECK(bias.is_cuda() && bias.dim() == 1, "bias must be 1D CUDA");
    TORCH_CHECK(bias.scalar_type() == torch::kFloat32, "bias must be fp32");
    auto Pc = P.contiguous();
    auto bc = bias.contiguous();
    const int chunks = Pc.size(0);
    const int rows   = Pc.size(1);
    const int64_t N  = Pc.size(2);
    TORCH_CHECK(bc.size(0) == N, "bias size mismatch");
    TORCH_CHECK(N % 8 == 0, "N must be a multiple of 8");

    auto out = torch::empty({rows}, Pc.options());
    if (rows == 0) return out;
    if (N == 0) { out.zero_(); return out; }

    const dim3 grid(rows);
    const dim3 block(THREADS);
    const float s = (float)scale;
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    const float* p  = Pc.data_ptr<float>();
    const float* bi = bc.data_ptr<float>();
    float* o = out.data_ptr<float>();

    switch (chunks) {
        case 1:
            partial_maxpool2_sum_scale_kernel<1><<<grid, block, 0, stream>>>(
                p, bi, o, rows, N, s); break;
        case 2:
            partial_maxpool2_sum_scale_kernel<2><<<grid, block, 0, stream>>>(
                p, bi, o, rows, N, s); break;
        case 4:
            partial_maxpool2_sum_scale_kernel<4><<<grid, block, 0, stream>>>(
                p, bi, o, rows, N, s); break;
        case 8:
            partial_maxpool2_sum_scale_kernel<8><<<grid, block, 0, stream>>>(
                p, bi, o, rows, N, s); break;
        default:
            TORCH_CHECK(false, "unsupported chunk count");
    }
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return out;
}
"""

_cpp_src = (
    "torch::Tensor chunked_linear_fp16in_fp32out(torch::Tensor w, torch::Tensor x, int64_t chunks);\n"
    "torch::Tensor partial_maxpool2_sum_scale(torch::Tensor P, torch::Tensor bias, double scale);"
)

_ext = load_inline(
    name="chunked_linear_maxpool_sum_scale_v3",
    cpp_sources=_cpp_src,
    cuda_sources=_cuda_src,
    functions=["chunked_linear_fp16in_fp32out", "partial_maxpool2_sum_scale"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
    extra_ldflags=["-lcublas"],
)


class ModelNew(nn.Module):
    """
    Optimized model:
      - Weights are cast once to fp16 and cached; the linear layer runs on tensor
        cores via a K-split strided-batched GEMM (4 chunks) with fp32 accumulation,
        which exposes ~4x more thread blocks than a single GEMM at batch=128 and
        keeps the HBM saturated (the kernel is weight-bandwidth-bound).
      - Chunk partial reduction + bias add + max-pool(k=2) + feature sum + scaling
        are fused into a single custom CUDA kernel with fp32 accumulation.
    """
    def __init__(self, in_features, out_features, kernel_size, scale_factor):
        super(ModelNew, self).__init__()
        self.matmul = nn.Linear(in_features, out_features)
        self.kernel_size = kernel_size
        self.scale_factor = scale_factor
        self._w_half = None

    def forward(self, x):
        w = self.matmul.weight
        b = self.matmul.bias
        if (x.is_cuda and x.dtype == torch.float32 and b is not None
                and self.kernel_size == 2
                and w.size(1) % 32 == 0 and w.size(0) % 8 == 0):
            if self._w_half is None or self._w_half.device != w.device:
                self._w_half = w.detach().half()
            xh = x.half()
            if not xh.is_contiguous():
                xh = xh.contiguous()
            partials = _ext.chunked_linear_fp16in_fp32out(self._w_half, xh, 4)
            return _ext.partial_maxpool2_sum_scale(
                partials, b.detach(), float(self.scale_factor)
            )
        # Fallback (CPU / other dtypes / unsupported shapes): original ops.
        y = F.linear(x, w, b)
        y = F.max_pool1d(y.unsqueeze(1), self.kernel_size).squeeze(1)
        y = torch.sum(y, dim=1)
        return y * self.scale_factor
```
Result of evaluating it:
The solution failed to compile. Error output:
```
RuntimeError: Error building extension 'chunked_linear_maxpool_sum_scale_v3': [1/3] /opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/bin/nvcc -MD -MF cuda.cuda.o.d -DTORCH_EXTENSION_NAME=chunked_linear_maxpool_sum_scale_v3 -DTORCH_API_INCLUDE_EXTENSION_H -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include/torch/csrc/api/include -isystem /opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/include -isystem /usr/include/python3.12 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_80,code=sm_80 --compiler-options '-fPIC' -O3 -std=c++20 -c /srv/jobs/1791506174337334997-1221082-0/build/chunked_linear_maxpool_sum_scale_v3/cuda.cu -o cuda.cuda.o 
FAILED: [code=2] cuda.cuda.o 
/opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/bin/nvcc -MD -MF cuda.cuda.o.d -DTORCH_EXTENSION_NAME=chunked_linear_maxpool_sum_scale_v3 -DTORCH_API_INCLUDE_EXTENSION_H -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include/torch/csrc/api/include -isystem /opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/include -isystem /usr/include/python3.12 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_80,code=sm_80 --compiler-options '-fPIC' -O3 -std=c++20 -c /srv/jobs/1791506174337334997-1221082-0/build/chunked_linear_maxpool_sum_scale_v3/cuda.cu -o cuda.cuda.o 
/srv/jobs/1791506174337334997-1221082-0/build/chunked_linear_maxpool_sum_scale_v3/cuda.cu(87): error: identifier "C10_CUBLAS_CHECK" is undefined
      C10_CUBLAS_CHECK(
      ^

1 error detected in the compilation of "/srv/jobs/1791506174337334997-1221082-0/build/chunked_linear_maxpool_sum_scale_v3/cuda.cu".
[2/3] c++ -MMD -MF main.o.d -DTORCH_EXTENSION_NAME=chunked_linear_maxpool_sum_scale_v3 -DTORCH_API_INCLUDE_EXTENSION_H -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include/torch/csrc/api/include -isystem /opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/include -isystem /usr/include/python3.12 -fPIC -std=c++20 -c /srv/jobs/1791506174337334997-1221082-0/build/chunked_linear_maxpool_sum_scale_v3/main.cpp -o main.o 
ninja: build stopped: subcommand failed.

```

The fastest correct solution so far (1.593x speedup) is:
```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
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline

# Allow tensor-core math for any fp32 fallback matmuls.
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
# Keep fp16 GEMM reductions in fp32 for accuracy.
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False

# Fused kernel: max-pool (kernel_size=2, non-overlapping) + sum over features + scale.
# Supports fp32 and fp16 inputs (fp16 lets the GEMM run on tensor cores at 2x TF32
# throughput; accumulation inside this kernel is fp32).
_fused_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>

#define THREADS 512

__device__ __forceinline__ double blockReduceSumD(double val) {
    __shared__ double shared[32];
    const int lane = threadIdx.x & 31;
    const int wid  = threadIdx.x >> 5;
    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1)
        val += __shfl_down_sync(0xffffffffu, val, offset);
    if (lane == 0) shared[wid] = val;
    __syncthreads();
    const int nwarp = (blockDim.x + 31) >> 5;
    if (wid == 0) {
        val = (lane < nwarp) ? shared[lane] : 0.0;
        #pragma unroll
        for (int offset = 16; offset > 0; offset >>= 1)
            val += __shfl_down_sync(0xffffffffu, val, offset);
    }
    return val;  // only thread 0 holds the block total
}

__device__ __forceinline__ float blockReduceSumF(float val) {
    __shared__ float shared[32];
    const int lane = threadIdx.x & 31;
    const int wid  = threadIdx.x >> 5;
    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1)
        val += __shfl_down_sync(0xffffffffu, val, offset);
    if (lane == 0) shared[wid] = val;
    __syncthreads();
    const int nwarp = (blockDim.x + 31) >> 5;
    if (wid == 0) {
        val = (lane < nwarp) ? shared[lane] : 0.0f;
        #pragma unroll
        for (int offset = 16; offset > 0; offset >>= 1)
            val += __shfl_down_sync(0xffffffffu, val, offset);
    }
    return val;  // only thread 0 holds the block total
}

// -------- fp32 paths --------
__global__ void maxpool2_sum_scale_f32_vec4_kernel(
    const float* __restrict__ x, float* __restrict__ out,
    const int row_stride, const int num_pairs, const float scale)
{
    const int row = blockIdx.x;
    const float4* __restrict__ p =
        reinterpret_cast<const float4*>(x + (long long)row * row_stride);
    const int n4 = num_pairs >> 1;
    double acc = 0.0;
    for (int i = threadIdx.x; i < n4; i += blockDim.x) {
        float4 v = p[i];
        acc += (double)(fmaxf(v.x, v.y) + fmaxf(v.z, v.w));
    }
    if ((num_pairs & 1) && threadIdx.x == 0) {
        const float* sp = x + (long long)row * row_stride
                          + (long long)(num_pairs - 1) * 2;
        acc += (double)fmaxf(sp[0], sp[1]);
    }
    acc = blockReduceSumD(acc);
    if (threadIdx.x == 0) out[row] = (float)(acc * (double)scale);
}

__global__ void maxpool2_sum_scale_f32_scalar_kernel(
    const float* __restrict__ x, float* __restrict__ out,
    const int row_stride, const int num_pairs, const float scale)
{
    const int row = blockIdx.x;
    const float* __restrict__ p = x + (long long)row * row_stride;
    double acc = 0.0;
    for (int i = threadIdx.x; i < num_pairs; i += blockDim.x) {
        acc += (double)fmaxf(p[2 * i], p[2 * i + 1]);
    }
    acc = blockReduceSumD(acc);
    if (threadIdx.x == 0) out[row] = (float)(acc * (double)scale);
}

// -------- fp16 paths (fp32 accumulation) --------
// Vectorized: one float4 load = 8 halfs = 4 pool pairs.
__global__ void maxpool2_sum_scale_f16_vec8_kernel(
    const __half* __restrict__ x, float* __restrict__ out,
    const int row_stride, const int num_pairs, const float scale)
{
    const int row = blockIdx.x;
    const __half* __restrict__ base = x + (long long)row * row_stride;
    const float4* __restrict__ p = reinterpret_cast<const float4*>(base);
    const int n8 = num_pairs >> 2;  // groups of 4 pairs

    float acc = 0.0f;
    for (int i = threadIdx.x; i < n8; i += blockDim.x) {
        float4 raw = p[i];
        const __half2* h = reinterpret_cast<const __half2*>(&raw);
        float2 a = __half22float2(h[0]);
        float2 b = __half22float2(h[1]);
        float2 c = __half22float2(h[2]);
        float2 d = __half22float2(h[3]);
        acc += fmaxf(a.x, a.y) + fmaxf(b.x, b.y)
             + fmaxf(c.x, c.y) + fmaxf(d.x, d.y);
    }
    // Remaining pairs (fewer than 4).
    for (int i = (n8 << 2) + threadIdx.x; i < num_pairs; i += blockDim.x) {
        acc += fmaxf(__half2float(base[2 * i]), __half2float(base[2 * i + 1]));
    }
    acc = blockReduceSumF(acc);
    if (threadIdx.x == 0) out[row] = acc * scale;
}

__global__ void maxpool2_sum_scale_f16_scalar_kernel(
    const __half* __restrict__ x, float* __restrict__ out,
    const int row_stride, const int num_pairs, const float scale)
{
    const int row = blockIdx.x;
    const __half* __restrict__ p = x + (long long)row * row_stride;
    float acc = 0.0f;
    for (int i = threadIdx.x; i < num_pairs; i += blockDim.x) {
        acc += fmaxf(__half2float(p[2 * i]), __half2float(p[2 * i + 1]));
    }
    acc = blockReduceSumF(acc);
    if (threadIdx.x == 0) out[row] = acc * scale;
}

torch::Tensor maxpool_sum_scale_cuda(torch::Tensor x, int64_t kernel_size, double scale) {
    TORCH_CHECK(x.is_cuda(), "x must be a CUDA tensor");
    TORCH_CHECK(x.dim() == 2, "x must be 2D (batch, features)");
    TORCH_CHECK(kernel_size == 2, "only kernel_size == 2 is supported");
    const auto st = x.scalar_type();
    TORCH_CHECK(st == torch::kFloat32 || st == torch::kFloat16,
                "x must be float32 or float16");

    auto xc = x.contiguous();
    const int rows = xc.size(0);
    const int cols = xc.size(1);
    const int num_pairs = cols / 2;

    auto out = torch::empty({rows}, xc.options().dtype(torch::kFloat32));
    if (rows == 0) return out;
    if (num_pairs == 0) { out.zero_(); return out; }

    const dim3 grid(rows);
    const dim3 block(THREADS);
    const float s = (float)scale;
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    if (st == torch::kFloat32) {
        const float* xp = xc.data_ptr<float>();
        float* op = out.data_ptr<float>();
        if ((cols & 3) == 0) {
            maxpool2_sum_scale_f32_vec4_kernel<<<grid, block, 0, stream>>>(
                xp, op, cols, num_pairs, s);
        } else {
            maxpool2_sum_scale_f32_scalar_kernel<<<grid, block, 0, stream>>>(
                xp, op, cols, num_pairs, s);
        }
    } else {
        const __half* xp =
            reinterpret_cast<const __half*>(xc.data_ptr<at::Half>());
        float* op = out.data_ptr<float>();
        // vec8 path needs each row 16B-aligned: row_stride multiple of 8.
        if ((cols & 7) == 0) {
            maxpool2_sum_scale_f16_vec8_kernel<<<grid, block, 0, stream>>>(
                xp, op, cols, num_pairs, s);
        } else {
            maxpool2_sum_scale_f16_scalar_kernel<<<grid, block, 0, stream>>>(
                xp, op, cols, num_pairs, s);
        }
    }
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return out;
}
"""

_fused_cpp_source = (
    "torch::Tensor maxpool_sum_scale_cuda(torch::Tensor x, int64_t kernel_size, double scale);"
)

_fused_op = load_inline(
    name="maxpool_sum_scale_fused_v2",
    cpp_sources=_fused_cpp_source,
    cuda_sources=_fused_cuda_source,
    functions=["maxpool_sum_scale_cuda"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model:
      - GEMM + bias runs in fp16 on tensor cores (cuBLAS via F.linear), which is
        ~2x the throughput of the TF32 reference on Ampere. The fp16 weight/bias
        are cast once and cached.
      - max-pool(k=2) + sum + scale are fused into a single custom CUDA kernel
        (fp32 accumulation) that reads the GEMM output once and writes only
        `batch_size` floats, eliminating intermediate tensor materializations.
    """
    def __init__(self, in_features, out_features, kernel_size, scale_factor):
        super(ModelNew, self).__init__()
        self.matmul = nn.Linear(in_features, out_features)
        self.kernel_size = kernel_size
        self.scale_factor = scale_factor
        self._w_half = None
        self._b_half = None

    def forward(self, x):
        if x.is_cuda and x.dtype == torch.float32 and self.kernel_size == 2:
            w = self.matmul.weight
            if self._w_half is None or self._w_half.device != w.device:
                self._w_half = w.detach().half()
                b = self.matmul.bias
                self._b_half = b.detach().half() if b is not None else None
            y = F.linear(x.half(), self._w_half, self._b_half)
            return _fused_op.maxpool_sum_scale_cuda(
                y, self.kernel_size, float(self.scale_factor)
            )
        # Fallback (CPU / other dtypes / other kernel sizes): original ops.
        x = F.linear(x, self.matmul.weight, self.matmul.bias)
        x = F.max_pool1d(x.unsqueeze(1), self.kernel_size).squeeze(1)
        x = torch.sum(x, dim=1)
        return x * self.scale_factor
```

Write an improved complete ModelNew: fix any error, and if the solution is already correct, make it faster. Output the new code in one ```python codeblock. Just the model code, no other text, and NO testing code.
