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 5 of 6 for this task. Your previous solution (turn 4) 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 os
# Enlarge the cuBLASLt workspace before the CUDA context is created so that
# cublasLt can select higher-performance algorithms (e.g. split-K). Harmless
# if the context already exists or the variable is unsupported.
os.environ.setdefault("CUBLASLT_WORKSPACE_SIZE", "131072")

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline

# TF32 tensor-core math is allowed for the FP32 matmul (matches PyTorch reference behavior).
try:
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
except Exception:
    pass

# ----------------------------------------------------------------------------
# Fully fused TF32 tensor-core kernel (requires sm_80+):
#   out[b] = scale * sum_j max( (x @ W^T + bias)[b, 2j], (x @ W^T + bias)[b, 2j+1] )
#
# Single pass: the [batch, out_features] product is never written to DRAM;
# the weights are streamed exactly once via cp.async double buffering and the
# max-pool(2) + sum + scale epilogue is fused into the mma accumulator drain.
# ----------------------------------------------------------------------------
_fused_gemm_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cstdint>

#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 800)
#define FUSED_GEMM_HAS_SM80 1
#else
#define FUSED_GEMM_HAS_SM80 0
#endif

namespace fused_gemm {

constexpr int BM = 128;      // full batch tile (M <= 128)
constexpr int BN = 128;      // output-feature tile per block
constexpr int BK = 32;       // k tile
constexpr int PAD = 4;
constexpr int STRIDE = BK + PAD;                 // 36 floats, 16B aligned rows
constexpr int STAGE_FLOATS = BM * STRIDE;
constexpr int SMEM_BYTES = 2 * 2 * STAGE_FLOATS * (int)sizeof(float);
constexpr int NTHREADS = 256;

__device__ __forceinline__ uint32_t smem_u32(const void* p) {
    return static_cast<uint32_t>(__cvta_generic_to_shared(p));
}

__device__ __forceinline__ void cp_async16(void* dst, const void* src) {
#if FUSED_GEMM_HAS_SM80
    asm volatile("cp.async.ca.shared.global [%0], [%1], 16;\n" ::
                 "r"(smem_u32(dst)), "l"(src));
#endif
}

__device__ __forceinline__ void cp_commit() {
#if FUSED_GEMM_HAS_SM80
    asm volatile("cp.async.commit_group;\n" ::);
#endif
}

__device__ __forceinline__ void cp_wait1() {
#if FUSED_GEMM_HAS_SM80
    asm volatile("cp.async.wait_group 1;\n" ::);
#endif
}

__device__ __forceinline__ void mma_tf32(float& d0, float& d1, float& d2, float& d3,
                                         float a0, float a1, float a2, float a3,
                                         float b0, float b1) {
#if FUSED_GEMM_HAS_SM80
    asm volatile(
        "mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 "
        "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
        : "+f"(d0), "+f"(d1), "+f"(d2), "+f"(d3)
        : "r"(__float_as_uint(a0)), "r"(__float_as_uint(a1)),
          "r"(__float_as_uint(a2)), "r"(__float_as_uint(a3)),
          "r"(__float_as_uint(b0)), "r"(__float_as_uint(b1)));
#endif
}

__global__ void __launch_bounds__(NTHREADS, 2)
fused_linear_maxpool_sum_kernel(const float* __restrict__ X,
                                const float* __restrict__ W,
                                const float* __restrict__ bias,
                                float* __restrict__ out,
                                int M, int N, int K, float scale) {
#if FUSED_GEMM_HAS_SM80
    extern __shared__ float smem[];
    float* As = smem;                       // 2 stages of [128][36]
    float* Bs = smem + 2 * STAGE_FLOATS;    // 2 stages of [128][36]

    const int tid = threadIdx.x;
    const int n0 = blockIdx.x * BN;
    const int nk = K / BK;
    const int mlim = M - 1;

    const int ld_row = tid >> 3;            // 0..31
    const int ld_k4 = (tid & 7) * 4;        // 0,4,...,28

    // Load one (A,B) k-tile into the given buffer (128 rows x 32 cols each).
    auto load_stage = [&](int ks, int buf) {
        const int koff = ks * BK + ld_k4;
        float* as = As + buf * STAGE_FLOATS + ld_row * STRIDE + ld_k4;
        float* bs = Bs + buf * STAGE_FLOATS + ld_row * STRIDE + ld_k4;
        #pragma unroll
        for (int i = 0; i < 4; ++i) {
            const int r = ld_row + i * 32;
            const float* xa = X + (int64_t)(r < M ? r : mlim) * K + koff;
            const float* wa = W + (int64_t)(n0 + r) * K + koff;
            cp_async16(as + i * 32 * STRIDE, xa);
            cp_async16(bs + i * 32 * STRIDE, wa);
        }
    };

    const int warp = tid >> 5;              // 0..7
    const int lane = tid & 31;
    const int gid = lane >> 2;              // 0..7
    const int tig = lane & 3;               // 0..3
    const int wrow = (warp & 3) * 32;       // warp tile row base (4 warp rows)
    const int wcol = (warp >> 2) * 64;      // warp tile col base (2 warp cols)

    float acc[2][4][4];                     // [m16 tile][n8 tile][c0..c3]
    #pragma unroll
    for (int i = 0; i < 2; ++i)
        #pragma unroll
        for (int j = 0; j < 4; ++j)
            #pragma unroll
            for (int e = 0; e < 4; ++e) acc[i][j][e] = 0.0f;

    load_stage(0, 0);
    cp_commit();

    for (int ks = 0; ks < nk; ++ks) {
        const int buf = ks & 1;
        if (ks + 1 < nk) {
            load_stage(ks + 1, buf ^ 1);
        }
        cp_commit();
        cp_wait1();
        __syncthreads();

        const float* as = As + buf * STAGE_FLOATS;
        const float* bs = Bs + buf * STAGE_FLOATS;

        #pragma unroll
        for (int kk = 0; kk < BK / 8; ++kk) {
            const int kb = kk * 8 + tig * 2;
            float av[2][4];
            float bv[4][2];
            #pragma unroll
            for (int i = 0; i < 2; ++i) {
                const int r = wrow + i * 16 + gid;
                const float2 lo = *reinterpret_cast<const float2*>(as + r * STRIDE + kb);
                const float2 hi = *reinterpret_cast<const float2*>(as + (r + 8) * STRIDE + kb);
                av[i][0] = lo.x; av[i][1] = lo.y;
                av[i][2] = hi.x; av[i][3] = hi.y;
            }
            #pragma unroll
            for (int j = 0; j < 4; ++j) {
                const int r = wcol + j * 16 + gid;
                const float2 blo = *reinterpret_cast<const float2*>(bs + r * STRIDE + kb);
                const float2 bhi = *reinterpret_cast<const float2*>(bs + (r + 8) * STRIDE + kb);
                bv[j][0] = blo.x; bv[j][1] = blo.y;
                bv[j][2] = bhi.x; bv[j][3] = bhi.y;
            }
            #pragma unroll
            for (int j = 0; j < 4; ++j) {
                const float2 b0v = *reinterpret_cast<const float2*>(bv[j]);
                const float2 b1v = *reinterpret_cast<const float2*>(bv[j] + 2);
                #pragma unroll
                for (int i = 0; i < 2; ++i) {
                    mma_tf32(acc[i][j][0], acc[i][j][1], acc[i][j][2], acc[i][j][3],
                             av[i][0], av[i][1], av[i][2], av[i][3], b0v.x, b0v.y);
                    mma_tf32(acc[i][j + 2][0], acc[i][j + 2][1], acc[i][j + 2][2], acc[i][j + 2][3],
                             av[i][0], av[i][1], av[i][2], av[i][3], b1v.x, b1v.y);
                }
            }
        }
        __syncthreads();
    }

    // Fused epilogue: + bias, max-pool over adjacent column pairs (c0,c1) and
    // (c2,c3), scale, and accumulate per-row partial sums with atomics.
    #pragma unroll
    for (int i = 0; i < 2; ++i) {
        float sum0 = 0.0f, sum1 = 0.0f;
        #pragma unroll
        for (int j = 0; j < 4; ++j) {
            const int col = n0 + wcol + j * 8 + tig * 2;
            const float2 bb = *reinterpret_cast<const float2*>(bias + col);
            sum0 += fmaxf(acc[i][j][0] + bb.x, acc[i][j][1] + bb.y);
            sum1 += fmaxf(acc[i][j][2] + bb.x, acc[i][j][3] + bb.y);
        }
        sum0 += __shfl_xor_sync(0xffffffffu, sum0, 1);
        sum0 += __shfl_xor_sync(0xffffffffu, sum0, 2);
        sum1 += __shfl_xor_sync(0xffffffffu, sum1, 1);
        sum1 += __shfl_xor_sync(0xffffffffu, sum1, 2);
        if (tig == 0) {
            const int r0 = wrow + i * 16 + gid;
            const int r1 = r0 + 8;
            if (r0 < M) atomicAdd(&out[r0], sum0 * scale);
            if (r1 < M) atomicAdd(&out[r1], sum1 * scale);
        }
    }
#endif
}

}  // namespace fused_gemm

torch::Tensor fused_linear_maxpool_sum_cuda(torch::Tensor x, torch::Tensor w,
                                            torch::Tensor b, double scale) {
    TORCH_CHECK(x.is_cuda() && w.is_cuda() && b.is_cuda(), "CUDA tensors required");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32 &&
                w.scalar_type() == torch::kFloat32 &&
                b.scalar_type() == torch::kFloat32, "float32 required");
    auto xc = x.contiguous();
    auto wc = w.contiguous();
    auto bc = b.contiguous();
    const int M = (int)xc.size(0);
    const int K = (int)xc.size(1);
    const int N = (int)wc.size(0);
    TORCH_CHECK(wc.size(1) == K && bc.numel() == N, "shape mismatch");
    TORCH_CHECK(M <= fused_gemm::BM, "batch too large for fused kernel");
    TORCH_CHECK((N % fused_gemm::BN) == 0, "out_features must be multiple of 128");
    TORCH_CHECK((K % fused_gemm::BK) == 0, "in_features must be multiple of 32");

    auto out = torch::zeros({M}, xc.options());
    if (N == 0 || M == 0) {
        return out;
    }

    static int smem_configured = [] {
        cudaFuncSetAttribute(fused_gemm::fused_linear_maxpool_sum_kernel,
                             cudaFuncAttributeMaxDynamicSharedMemorySize,
                             fused_gemm::SMEM_BYTES);
        return 1;
    }();
    (void)smem_configured;

    dim3 grid(N / fused_gemm::BN);
    auto stream = at::cuda::getCurrentCUDAStream();
    fused_gemm::fused_linear_maxpool_sum_kernel
        <<<grid, fused_gemm::NTHREADS, fused_gemm::SMEM_BYTES, stream>>>(
            xc.data_ptr<float>(), wc.data_ptr<float>(), bc.data_ptr<float>(),
            out.data_ptr<float>(), M, N, K, (float)scale);
    return out;
}
"""

_fused_gemm_cpp_source = (
    "torch::Tensor fused_linear_maxpool_sum_cuda(torch::Tensor x, "
    "torch::Tensor w, torch::Tensor b, double scale);"
)

try:
    _fused_gemm = load_inline(
        name="fused_linear_maxpool_sum_gemm_v2",
        cpp_sources=_fused_gemm_cpp_source,
        cuda_sources=_fused_gemm_cuda_source,
        functions=["fused_linear_maxpool_sum_cuda"],
        verbose=False,
        extra_cuda_cflags=["-O3"],
    )
except Exception:
    _fused_gemm = None


class ModelNew(nn.Module):
    """
    Optimized model.

    Primary path: a single fused TF32 tensor-core CUDA kernel computing
    Linear -> MaxPool1d(2) -> sum -> scale in one pass (the full
    [batch, out_features] product never touches DRAM; the weight matrix is
    streamed exactly once).

    Fallback path: cuBLAS (TF32) linear + a fully vectorized (float4) fused
    max-pool/sum/scale epilogue.

    On the first eligible forward call both implementations are validated and
    timed against each other; the faster one is used permanently afterwards.
    Any shape/dtype the kernels do not support falls back to the reference
    PyTorch ops.
    """

    _plan_cache = {}

    def __init__(self, in_features, out_features, kernel_size, scale_factor):
        super(ModelNew, self).__init__()
        self.matmul = nn.Linear(in_features, out_features)
        self.max_pool = nn.MaxPool1d(kernel_size)
        self.kernel_size = kernel_size
        self.scale_factor = float(scale_factor)
        self.in_features = in_features
        self.out_features = out_features
        self._w_t = None

    # ------------------------------------------------------------------ paths
    def _reference(self, x):
        y = F.linear(x, self.matmul.weight, self.matmul.bias)
        y = self.max_pool(y.unsqueeze(1)).squeeze(1)
        y = torch.sum(y, dim=1)
        return y * self.scale_factor

    def _epilogue(self, y, yT=False):
        # out[b] = scale * sum_i max(y[b, 2i], y[b, 2i+1])
        v = y[0] if not yT else y[:, 0]
        w = y[1] if not yT else y[:, 1]
        m = torch.maximum(v, w)
        if not yT:
            y2 = y.view(y.size(0), -1, 2)
            m = torch.maximum(y2[..., 0], y2[..., 1])
        else:
            m = m.view(-1, y.size(1))
        return m.sum(dim=1 if not yT else 0) * self.scale_factor

    def _cublas(self, x):
        y = F.linear(x, self.matmul.weight, self.matmul.bias)
        y2 = y.view(y.size(0), y.size(1) // 2, 2)
        m = torch.maximum(y2[..., 0], y2[..., 1])
        return m.sum(dim=1) * self.scale_factor

    def _cublas_t(self, x):
        yT = torch.matmul(self.matmul.weight, x.t())
        y2 = yT.view(yT.size(0) // 2, 2, yT.size(1))
        m = torch.maximum(y2[:, 0, :], y2[:, 1, :])
        return m.sum(dim=0) * self.scale_factor

    def _fused(self, x):
        return _fused_gemm.fused_linear_maxpool_sum_cuda(
            x, self.matmul.weight, self.matmul.bias, self.scale_factor)

    # ------------------------------------------------------------- selection
    @staticmethod
    def _time_path(fn, x, reps=3):
        torch.cuda.synchronize()
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        start.record()
        for _ in range(reps):
            fn(x)
        end.record()
        torch.cuda.synchronize()
        return start.elapsed_time(end)

    def _select_plan(self, x):
        candidates = [self._cublas, self._cublas_t]
        if _fused_gemm is not None and torch.cuda.get_device_capability(x.device)[0] >= 8:
            candidates.append(self._fused)

        ref = self._cublas(x)
        best = self._cublas
        try:
            best_t = self._time_path(self._cublas, x)
        except Exception:
            best_t = float("inf")

        tol = 5e-2 * float(ref.abs().max().item()) + 1e-3
        for cand in candidates[1:]:
            try:
                out = cand(x)
                err = float((out - ref).abs().max().item())
                if not (bool(torch.isfinite(out).all().item()) and err <= tol):
                    continue
                t = self._time_path(cand, x)
                if t < best_t * 0.97:
                    best, best_t = cand, t
            except Exception:
                continue
        return best

    # --------------------------------------------------------------- forward
    def forward(self, x):
        eligible = (
            x.is_cuda and x.dtype == torch.float32
            and self.kernel_size == 2 and x.dim() == 2
            and x.size(0) <= 128 and x.size(0) > 0
            and (self.out_features % 128) == 0
            and (self.in_features % 32) == 0
            and self.matmul.weight.is_cuda
        )
        if not eligible:
            if x.is_cuda and x.dtype == torch.float32 and self.kernel_size == 2 \
                    and (self.out_features % 2) == 0:
                return self._cublas(x)
            return self._reference(x)

        key = (x.size(0), self.in_features, self.out_features,
               self.scale_factor, x.device.index)
        plan = ModelNew._plan_cache.get(key)
        if plan is None:
            try:
                plan = self._select_plan(x)
            except Exception:
                plan = self._cublas
            ModelNew._plan_cache[key] = plan
        return plan(x)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 3.42 ms; the PyTorch reference (with TF32 enabled) takes 3.44 ms; speedup 1.006x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| void cutlass::Kernel2<cutlass_80_tensorop_s1688gemm_256x128_32x3_tn_align4>(cutlass_80_ten | 3340.8 | 1 |
| void at::native::elementwise_kernel<128, 2, at::native::gpu_kernel_impl_nocast<at::native: | 14.6 | 1 |
| void at::native::reduce_kernel<512, 1, at::native::ReduceOp<float, at::native::func_wrappe | 8.4 | 1 |
| void at::native::vectorized_elementwise_kernel<4, at::native::AUnaryFunctor<float, float,  | 2.1 | 1 |
| Memset (Device) | 1.2 | 1 |

The fastest correct solution so far (1.015x 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

# TF32 tensor-core math is allowed for the FP32 matmul (matches PyTorch reference behavior).
try:
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
except Exception:
    pass

# Fused kernel: max-pool (kernel_size=2) + sum over features + scaling.
# For each batch row: out[b] = scale * sum_i max(x[b, 2i], x[b, 2i+1])
fused_maxpool_sum_scale_cuda_source = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <cstdint>

constexpr int BLOCK_SIZE = 256;

__global__ void maxpool_sum_scale_kernel(const float* __restrict__ x,
                                         float* __restrict__ out,
                                         int64_t out_features,
                                         float scale) {
    const int64_t row = blockIdx.x;
    const float* p = x + row * out_features;
    const int64_t num_pairs = out_features >> 1;

    float sum = 0.0f;

    if ((reinterpret_cast<uintptr_t>(p) & 0xF) == 0) {
        // 16-byte aligned: use vectorized float4 loads (2 pairs per load).
        const float4* p4 = reinterpret_cast<const float4*>(p);
        const int64_t num_vec = num_pairs >> 1;
        for (int64_t i = threadIdx.x; i < num_vec; i += BLOCK_SIZE) {
            float4 v = p4[i];
            sum += fmaxf(v.x, v.y) + fmaxf(v.z, v.w);
        }
        // Tail pair when the number of pairs is odd.
        if ((num_pairs & 1) && threadIdx.x == 0) {
            const int64_t i = num_pairs - 1;
            sum += fmaxf(p[2 * i], p[2 * i + 1]);
        }
    } else {
        for (int64_t i = threadIdx.x; i < num_pairs; i += BLOCK_SIZE) {
            sum += fmaxf(p[2 * i], p[2 * i + 1]);
        }
    }

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

    __shared__ float shared[BLOCK_SIZE / 32];
    const int lane = threadIdx.x & 31;
    const int wid  = threadIdx.x >> 5;
    if (lane == 0) {
        shared[wid] = sum;
    }
    __syncthreads();

    if (wid == 0) {
        sum = (lane < BLOCK_SIZE / 32) ? shared[lane] : 0.0f;
        #pragma unroll
        for (int offset = 16; offset > 0; offset >>= 1) {
            sum += __shfl_down_sync(0xffffffffu, sum, offset);
        }
        if (lane == 0) {
            out[row] = sum * scale;
        }
    }
}

torch::Tensor maxpool_sum_scale_cuda(torch::Tensor x, double scale) {
    TORCH_CHECK(x.is_cuda(), "x must be a CUDA tensor");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "x must be float32");
    auto xc = x.contiguous();
    const int64_t batch = xc.size(0);
    const int64_t out_features = xc.size(1);

    auto out = torch::empty({batch}, xc.options());

    dim3 grid(static_cast<unsigned int>(batch));
    maxpool_sum_scale_kernel<<<grid, BLOCK_SIZE>>>(
        xc.data_ptr<float>(),
        out.data_ptr<float>(),
        out_features,
        static_cast<float>(scale));

    return out;
}
"""

fused_maxpool_sum_scale_cpp_source = (
    "torch::Tensor maxpool_sum_scale_cuda(torch::Tensor x, double scale);"
)

fused_maxpool_sum_scale = load_inline(
    name="fused_maxpool_sum_scale",
    cpp_sources=fused_maxpool_sum_scale_cpp_source,
    cuda_sources=fused_maxpool_sum_scale_cuda_source,
    functions=["maxpool_sum_scale_cuda"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model: cuBLAS (TF32) linear layer + a single fused CUDA kernel
    performing max-pool (kernel_size=2), feature sum and scaling in one pass.
    """

    def __init__(self, in_features, out_features, kernel_size, scale_factor):
        super(ModelNew, self).__init__()
        self.matmul = nn.Linear(in_features, out_features)
        self.max_pool = nn.MaxPool1d(kernel_size)
        self.kernel_size = kernel_size
        self.scale_factor = scale_factor
        self.fused_op = fused_maxpool_sum_scale

    def forward(self, x):
        x = F.linear(x, self.matmul.weight, self.matmul.bias)
        if self.kernel_size == 2 and x.is_cuda and x.dtype == torch.float32:
            return self.fused_op.maxpool_sum_scale_cuda(
                x, float(self.scale_factor))
        # Generic fallback (reference path).
        x = self.max_pool(x.unsqueeze(1)).squeeze(1)
        x = torch.sum(x, dim=1)
        x = x * self.scale_factor
        return x
```

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.


Precision rule: the timed forward must compute in FP32 (TF32 tensor-core math is allowed, as in the PyTorch reference). Do not cast inputs, weights or intermediate results to float16 or bfloat16 and do not call half-precision kernels in forward().
