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
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline

_cpp_source = r"""
#include <torch/extension.h>

torch::Tensor pool_sum_scale_cuda(
    torch::Tensor x, int64_t kernel_size, double scale);
"""

_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>

__device__ __forceinline__ float max_nan(float a, float b) {
    return (isnan(a) || isnan(b)) ? CUDART_NAN_F : fmaxf(a, b);
}

__device__ __forceinline__ float warp_sum(float value) {
    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1) {
        value += __shfl_down_sync(0xffffffff, value, offset);
    }
    return value;
}

template<bool PAIRS>
__global__ void pool_sum_scale_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    int64_t columns,
    int64_t kernel_size,
    float scale
) {
    const int tid = threadIdx.x;
    const int64_t row = blockIdx.x;
    const float* row_input = input + row * columns;
    const int64_t pooled_columns = columns / kernel_size;

    float sum = 0.0f;

    if (PAIRS) {
        const float2* pairs = reinterpret_cast<const float2*>(row_input);
        for (int64_t i = tid; i < pooled_columns; i += blockDim.x) {
            const float2 values = pairs[i];
            sum += max_nan(values.x, values.y);
        }
    } else {
        for (int64_t i = tid; i < pooled_columns; i += blockDim.x) {
            const float* window = row_input + i * kernel_size;
            float maximum = -CUDART_INF_F;
            for (int64_t j = 0; j < kernel_size; ++j) {
                maximum = max_nan(maximum, window[j]);
            }
            sum += maximum;
        }
    }

    sum = warp_sum(sum);

    __shared__ float warp_sums[8];
    const int lane = tid & 31;
    const int warp = tid >> 5;

    if (lane == 0) {
        warp_sums[warp] = sum;
    }
    __syncthreads();

    if (warp == 0) {
        sum = lane < 8 ? warp_sums[lane] : 0.0f;
        sum = warp_sum(sum);
        if (lane == 0) {
            output[row] = sum * scale;
        }
    }
}

torch::Tensor pool_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() == at::kFloat, "x must be float32");
    TORCH_CHECK(x.dim() == 2 && x.is_contiguous(),
                "x must be a contiguous matrix");
    TORCH_CHECK(kernel_size > 0 && x.size(1) >= kernel_size,
                "invalid pooling kernel size");

    const c10::cuda::CUDAGuard device_guard(x.device());
    auto output = torch::empty({x.size(0)}, x.options());

    if (x.size(0) == 0) {
        return output;
    }

    const auto stream = at::cuda::getCurrentCUDAStream();
    const dim3 blocks(static_cast<unsigned int>(x.size(0)));
    constexpr int threads = 256;

    if (kernel_size == 2 && x.size(1) % 2 == 0) {
        pool_sum_scale_kernel<true><<<blocks, threads, 0, stream>>>(
            x.data_ptr<float>(), output.data_ptr<float>(),
            x.size(1), kernel_size, static_cast<float>(scale));
    } else {
        pool_sum_scale_kernel<false><<<blocks, threads, 0, stream>>>(
            x.data_ptr<float>(), output.data_ptr<float>(),
            x.size(1), kernel_size, static_cast<float>(scale));
    }

    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}
"""

_fused_ops = load_inline(
    name="fused_maxpool_sum_scale_cuda_v1",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["pool_sum_scale_cuda"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    verbose=False,
)


class ModelNew(nn.Module):
    def __init__(self, in_features, out_features, kernel_size, scale_factor):
        super().__init__()
        self.matmul = nn.Linear(in_features, out_features)
        self.max_pool = nn.MaxPool1d(kernel_size)
        self.kernel_size = (
            kernel_size[0] if isinstance(kernel_size, tuple) else kernel_size
        )
        self.scale_factor = scale_factor

    def forward(self, x):
        x = self.matmul(x)

        if (
            x.is_cuda
            and x.dtype == torch.float32
            and x.ndim == 2
            and x.is_contiguous()
            and not (torch.is_grad_enabled() and x.requires_grad)
        ):
            return _fused_ops.pool_sum_scale_cuda(
                x, self.kernel_size, self.scale_factor
            )

        x = self.max_pool(x.unsqueeze(1)).squeeze(1)
        return torch.sum(x, dim=1) * self.scale_factor
```
Result of evaluating it:
The solution failed to compile. Error output:
```
RuntimeError: Error building extension 'fused_maxpool_sum_scale_cuda_v1': [1/3] /opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/bin/nvcc -MD -MF cuda.cuda.o.d -DTORCH_EXTENSION_NAME=fused_maxpool_sum_scale_cuda_v1 -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/1791713195340410951-3456539-0/build/fused_maxpool_sum_scale_cuda_v1/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=fused_maxpool_sum_scale_cuda_v1 -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/1791713195340410951-3456539-0/build/fused_maxpool_sum_scale_cuda_v1/cuda.cu -o cuda.cuda.o 
/srv/jobs/1791713195340410951-3456539-0/build/fused_maxpool_sum_scale_cuda_v1/cuda.cu(12): error: identifier "CUDART_NAN_F" is undefined
      return (isnan(a) || isnan(b)) ? CUDART_NAN_F : fmaxf(a, b);
                                      ^

/srv/jobs/1791713195340410951-3456539-0/build/fused_maxpool_sum_scale_cuda_v1/cuda.cu(47): error: identifier "CUDART_INF_F" is undefined
              float maximum = -CUDART_INF_F;
                               ^

2 errors detected in the compilation of "/srv/jobs/1791713195340410951-3456539-0/build/fused_maxpool_sum_scale_cuda_v1/cuda.cu".
[2/3] c++ -MMD -MF main.o.d -DTORCH_EXTENSION_NAME=fused_maxpool_sum_scale_cuda_v1 -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 -O3 -c /srv/jobs/1791713195340410951-3456539-0/build/fused_maxpool_sum_scale_cuda_v1/main.cpp -o main.o 
ninja: build stopped: subcommand failed.

```

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.
