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 2 of 6 for this task. Your previous solution (turn 1) 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

# Fused kernel: max-pool (kernel_size=2, non-overlapping) + sum over features + scale.
# This turns three separate ops (each materializing intermediate tensors) into a
# single memory-bound pass over the matmul output that writes only `batch_size` floats.
# The GEMM itself stays on cuBLAS (F.linear), which is already optimal for this shape.
_fused_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>

#define THREADS 512

__device__ __forceinline__ double blockReduceSum(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
}

// Fast path: feature count divisible by 4 -> aligned float4 loads.
__global__ void maxpool2_sum_scale_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));
    }
    // Tail pair when num_pairs is odd.
    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 = blockReduceSum(acc);
    if (threadIdx.x == 0) out[row] = (float)(acc * (double)scale);
}

// Generic fallback for any feature count.
__global__ void maxpool2_sum_scale_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 = blockReduceSum(acc);
    if (threadIdx.x == 0) out[row] = (float)(acc * (double)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.scalar_type() == torch::kFloat32, "x must be float32");
    TORCH_CHECK(x.dim() == 2, "x must be 2D (batch, features)");
    TORCH_CHECK(kernel_size == 2, "only kernel_size == 2 is supported");

    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());
    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 ((cols & 3) == 0) {
        maxpool2_sum_scale_vec4_kernel<<<grid, block, 0, stream>>>(
            xc.data_ptr<float>(), out.data_ptr<float>(), cols, num_pairs, s);
    } else {
        maxpool2_sum_scale_scalar_kernel<<<grid, block, 0, stream>>>(
            xc.data_ptr<float>(), out.data_ptr<float>(), 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",
    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 stays on cuBLAS via F.linear (optimal for this shape).
      - max-pool(k=2) + sum + scale are fused into a single custom CUDA kernel
        that reads the GEMM output once and writes only `batch_size` floats,
        eliminating two 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

    def forward(self, x):
        x = F.linear(x, self.matmul.weight, self.matmul.bias)
        if x.is_cuda and x.dtype == torch.float32 and self.kernel_size == 2:
            return _fused_op.maxpool_sum_scale_cuda(
                x, self.kernel_size, float(self.scale_factor)
            )
        # Fallback (CPU / other dtypes / other kernel sizes): original ops.
        x = F.max_pool1d(x.unsqueeze(1), self.kernel_size).squeeze(1)
        x = torch.sum(x, dim=1)
        return x * self.scale_factor
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 16 ms; the PyTorch reference (with TF32 enabled) takes 3.44 ms; speedup 0.215x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| ampere_sgemm_128x64_tn | 15981.1 | 1 |
| maxpool2_sum_scale_vec4_kernel(float const*, float*, int, int, float) | 17.4 | 1 |

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.
