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

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

std::vector<torch::Tensor> linear_pool_sum_cuda(
    torch::Tensor x, torch::Tensor weight, torch::Tensor bias,
    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 <cublasLt.h>
#include <cuda_runtime.h>
#include <math_constants.h>
#include <algorithm>
#include <climits>
#include <limits>
#include <map>
#include <mutex>
#include <tuple>
#include <vector>

static void check_blas(cublasStatus_t status) {
    TORCH_CHECK(status == CUBLAS_STATUS_SUCCESS,
                "cuBLASLt error: ", static_cast<int>(status));
}

struct LtHandle {
    cublasLtHandle_t handle;
    LtHandle() { check_blas(cublasLtCreate(&handle)); }
    ~LtHandle() { cublasLtDestroy(handle); }
};

struct Descriptors {
    cublasLtMatmulDesc_t operation;
    cublasLtMatrixLayout_t a, b, c;

    Descriptors(int batch, int inputs, int outputs) {
        check_blas(cublasLtMatmulDescCreate(
            &operation, CUBLAS_COMPUTE_32F_FAST_TF32, CUDA_R_32F));
        cublasOperation_t trans_a = CUBLAS_OP_T;
        cublasOperation_t trans_b = CUBLAS_OP_N;
        check_blas(cublasLtMatmulDescSetAttribute(
            operation, CUBLASLT_MATMUL_DESC_TRANSA,
            &trans_a, sizeof(trans_a)));
        check_blas(cublasLtMatmulDescSetAttribute(
            operation, CUBLASLT_MATMUL_DESC_TRANSB,
            &trans_b, sizeof(trans_b)));

        check_blas(cublasLtMatrixLayoutCreate(
            &a, CUDA_R_32F, inputs, outputs, inputs));
        check_blas(cublasLtMatrixLayoutCreate(
            &b, CUDA_R_32F, inputs, batch, inputs));
        check_blas(cublasLtMatrixLayoutCreate(
            &c, CUDA_R_32F, outputs, batch, outputs));
    }

    ~Descriptors() {
        cublasLtMatrixLayoutDestroy(a);
        cublasLtMatrixLayoutDestroy(b);
        cublasLtMatrixLayoutDestroy(c);
        cublasLtMatmulDescDestroy(operation);
    }
};

struct Plan {
    cublasLtMatmulAlgo_t algorithm;
    size_t workspace;
};

static std::mutex plan_mutex;
static std::map<int, LtHandle> handles;
static std::map<std::tuple<int, int, int, int>, Plan> plans;

static cublasStatus_t launch_gemm(
    cublasLtHandle_t handle,
    const Descriptors& desc,
    const Plan& plan,
    const float* weight,
    const float* x,
    float* output,
    void* workspace,
    cudaStream_t stream
) {
    const float alpha = 1.0f;
    const float beta = 0.0f;
    return cublasLtMatmul(
        handle, desc.operation,
        &alpha, weight, desc.a, x, desc.b,
        &beta, output, desc.c, output, desc.c,
        &plan.algorithm, workspace, plan.workspace, stream);
}

static Plan select_plan(
    cublasLtHandle_t handle,
    const Descriptors& desc,
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor output,
    cudaStream_t stream,
    bool tune
) {
    constexpr size_t workspace_limit = 128ULL * 1024 * 1024;

    cublasLtMatmulPreference_t preference;
    check_blas(cublasLtMatmulPreferenceCreate(&preference));
    check_blas(cublasLtMatmulPreferenceSetAttribute(
        preference, CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES,
        &workspace_limit, sizeof(workspace_limit)));

    cublasLtMatmulHeuristicResult_t heuristics[16];
    int count = 0;
    const auto status = cublasLtMatmulAlgoGetHeuristic(
        handle, desc.operation, desc.a, desc.b, desc.c, desc.c,
        preference, 16, heuristics, &count);
    cublasLtMatmulPreferenceDestroy(preference);
    check_blas(status);
    TORCH_CHECK(count > 0, "No supported cuBLASLt algorithm");

    std::vector<Plan> candidates;

    auto add_candidate = [&](const cublasLtMatmulAlgo_t& algorithm) {
        cublasLtMatmulHeuristicResult_t checked;
        const auto s = cublasLtMatmulAlgoCheck(
            handle, desc.operation, desc.a, desc.b, desc.c, desc.c,
            &algorithm, &checked);
        if (s == CUBLAS_STATUS_SUCCESS &&
            checked.state == CUBLAS_STATUS_SUCCESS &&
            checked.workspaceSize <= workspace_limit) {
            candidates.push_back({algorithm, checked.workspaceSize});
        }
    };

    for (int i = 0; i < count; ++i) {
        if (heuristics[i].state == CUBLAS_STATUS_SUCCESS)
            add_candidate(heuristics[i].algo);
    }

    TORCH_CHECK(!candidates.empty(), "No valid cuBLASLt algorithm");
    if (!tune)
        return candidates.front();

    // Small output batches and very long reductions benefit from
    // smaller tiles and/or split-K parallelism.
    const uint32_t tiles[] = {
        CUBLASLT_MATMUL_TILE_64x64,
        CUBLASLT_MATMUL_TILE_64x128,
        CUBLASLT_MATMUL_TILE_128x64,
        CUBLASLT_MATMUL_TILE_128x128,
        CUBLASLT_MATMUL_TILE_256x64,
        CUBLASLT_MATMUL_TILE_256x128
    };

    for (int h = 0; h < std::min(count, 4); ++h) {
        for (uint32_t split : {2u, 4u, 8u}) {
            auto algorithm = heuristics[h].algo;
            const uint32_t reduction = CUBLASLT_REDUCTION_SCHEME_INPLACE;
            if (cublasLtMatmulAlgoConfigSetAttribute(
                    &algorithm, CUBLASLT_ALGO_CONFIG_SPLITK_NUM,
                    &split, sizeof(split)) != CUBLAS_STATUS_SUCCESS)
                continue;
            if (cublasLtMatmulAlgoConfigSetAttribute(
                    &algorithm, CUBLASLT_ALGO_CONFIG_REDUCTION_SCHEME,
                    &reduction, sizeof(reduction)) != CUBLAS_STATUS_SUCCESS)
                continue;
            add_candidate(algorithm);
        }
    }

    for (int h = 0; h < std::min(count, 2); ++h) {
        for (uint32_t tile : tiles) {
            for (uint32_t split : {1u, 4u}) {
                auto algorithm = heuristics[h].algo;
                const uint32_t reduction =
                    split == 1 ? CUBLASLT_REDUCTION_SCHEME_NONE
                               : CUBLASLT_REDUCTION_SCHEME_INPLACE;
                if (cublasLtMatmulAlgoConfigSetAttribute(
                        &algorithm, CUBLASLT_ALGO_CONFIG_TILE_ID,
                        &tile, sizeof(tile)) != CUBLAS_STATUS_SUCCESS)
                    continue;
                if (cublasLtMatmulAlgoConfigSetAttribute(
                        &algorithm, CUBLASLT_ALGO_CONFIG_SPLITK_NUM,
                        &split, sizeof(split)) != CUBLAS_STATUS_SUCCESS)
                    continue;
                if (cublasLtMatmulAlgoConfigSetAttribute(
                        &algorithm, CUBLASLT_ALGO_CONFIG_REDUCTION_SCHEME,
                        &reduction, sizeof(reduction)) != CUBLAS_STATUS_SUCCESS)
                    continue;
                add_candidate(algorithm);
            }
        }
    }

    auto scratch = torch::empty(
        {static_cast<int64_t>(workspace_limit)},
        x.options().dtype(at::kByte));

    cudaEvent_t start, stop;
    C10_CUDA_CHECK(cudaEventCreate(&start));
    C10_CUDA_CHECK(cudaEventCreate(&stop));

    Plan best = candidates.front();
    float best_time = std::numeric_limits<float>::infinity();

    for (const Plan& candidate : candidates) {
        // Warm up each configuration before timing it.
        if (launch_gemm(
                handle, desc, candidate,
                weight.data_ptr<float>(), x.data_ptr<float>(),
                output.data_ptr<float>(), scratch.data_ptr(), stream)
            != CUBLAS_STATUS_SUCCESS)
            continue;

        C10_CUDA_CHECK(cudaEventRecord(start, stream));
        const auto s = launch_gemm(
            handle, desc, candidate,
            weight.data_ptr<float>(), x.data_ptr<float>(),
            output.data_ptr<float>(), scratch.data_ptr(), stream);
        C10_CUDA_CHECK(cudaEventRecord(stop, stream));
        C10_CUDA_CHECK(cudaEventSynchronize(stop));

        if (s != CUBLAS_STATUS_SUCCESS)
            continue;

        float elapsed = 0.0f;
        C10_CUDA_CHECK(cudaEventElapsedTime(&elapsed, start, stop));
        if (elapsed < best_time) {
            best_time = elapsed;
            best = candidate;
        }
    }

    C10_CUDA_CHECK(cudaEventDestroy(start));
    C10_CUDA_CHECK(cudaEventDestroy(stop));
    TORCH_CHECK(best_time < std::numeric_limits<float>::infinity(),
                "All cuBLASLt configurations failed");
    return best;
}

__device__ __forceinline__ float maximum_nan(float a, float b) {
    return isnan(b) || a < b ? b : a;
}

__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 bias_pool_sum_kernel(
    const float* __restrict__ input,
    const float* __restrict__ bias,
    float* __restrict__ output,
    int columns,
    int kernel_size,
    float scale
) {
    const int tid = threadIdx.x;
    const float* row = input + static_cast<int64_t>(blockIdx.x) * columns;
    float sum0 = 0.0f;
    float sum1 = 0.0f;

    if constexpr (PAIRS) {
        const float4* values = reinterpret_cast<const float4*>(row);
        const float4* biases = reinterpret_cast<const float4*>(bias);
        for (int i = tid; i < columns / 4; i += blockDim.x) {
            const float4 v = values[i];
            const float4 b = biases[i];
            sum0 += maximum_nan(v.x + b.x, v.y + b.y);
            sum1 += maximum_nan(v.z + b.z, v.w + b.w);
        }
    } else {
        for (int i = tid; i < columns / kernel_size; i += blockDim.x) {
            const int start = i * kernel_size;
            float maximum = -CUDART_INF_F;
            for (int j = 0; j < kernel_size; ++j)
                maximum = maximum_nan(
                    maximum, row[start + j] + bias[start + j]);
            sum0 += maximum;
        }
    }

    float sum = warp_sum(sum0 + sum1);
    __shared__ float partial[8];
    const int lane = tid & 31;
    const int warp = tid >> 5;
    if (lane == 0)
        partial[warp] = sum;
    __syncthreads();

    if (warp == 0) {
        sum = warp_sum(lane < 8 ? partial[lane] : 0.0f);
        if (lane == 0)
            output[blockIdx.x] = sum * scale;
    }
}

std::vector<torch::Tensor> linear_pool_sum_cuda(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias,
    int64_t kernel_size,
    double scale
) {
    TORCH_CHECK(x.is_cuda() && weight.is_cuda() && bias.is_cuda(),
                "Expected CUDA tensors");
    TORCH_CHECK(x.device() == weight.device() &&
                x.device() == bias.device(), "Device mismatch");
    TORCH_CHECK(x.scalar_type() == at::kFloat &&
                weight.scalar_type() == at::kFloat &&
                bias.scalar_type() == at::kFloat, "Expected float32");
    TORCH_CHECK(x.dim() == 2 && weight.dim() == 2 && bias.dim() == 1,
                "Invalid dimensions");
    TORCH_CHECK(x.is_contiguous() && weight.is_contiguous() &&
                bias.is_contiguous(), "Expected contiguous tensors");
    TORCH_CHECK(x.size(1) == weight.size(1) &&
                weight.size(0) == bias.size(0), "Shape mismatch");
    TORCH_CHECK(kernel_size > 0 && kernel_size <= weight.size(0),
                "Invalid pooling kernel");
    TORCH_CHECK(x.size(0) <= INT_MAX && x.size(1) <= INT_MAX &&
                weight.size(0) <= INT_MAX, "Dimensions too large");

    const c10::cuda::CUDAGuard guard(x.device());
    const int batch = static_cast<int>(x.size(0));
    const int inputs = static_cast<int>(x.size(1));
    const int outputs = static_cast<int>(weight.size(0));

    auto linear = torch::empty({batch, outputs}, x.options());
    auto result = torch::empty({batch}, x.options());
    if (batch == 0)
        return {result, linear};

    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    if (inputs == 0) {
        C10_CUDA_CHECK(cudaMemsetAsync(
            linear.data_ptr<float>(), 0,
            linear.numel() * sizeof(float), stream));
    } else {
        std::lock_guard<std::mutex> lock(plan_mutex);
        const int device = x.get_device();
        auto handle_it = handles.try_emplace(device).first;
        const auto handle = handle_it->second.handle;
        Descriptors desc(batch, inputs, outputs);

        const auto key = std::make_tuple(device, batch, inputs, outputs);
        auto it = plans.find(key);
        Plan plan;

        if (it != plans.end()) {
            plan = it->second;
        } else {
            cudaStreamCaptureStatus capture;
            C10_CUDA_CHECK(cudaStreamIsCapturing(stream, &capture));
            const bool tune = capture == cudaStreamCaptureStatusNone;
            plan = select_plan(handle, desc, x, weight, linear, stream, tune);
            if (tune)
                plans.emplace(key, plan);
        }

        auto workspace = torch::empty(
            {static_cast<int64_t>(plan.workspace)},
            x.options().dtype(at::kByte));
        check_blas(launch_gemm(
            handle, desc, plan,
            weight.data_ptr<float>(), x.data_ptr<float>(),
            linear.data_ptr<float>(),
            plan.workspace ? workspace.data_ptr() : nullptr, stream));
    }

    if (kernel_size == 2 && outputs % 4 == 0 &&
        reinterpret_cast<uintptr_t>(bias.data_ptr<float>()) % 16 == 0) {
        bias_pool_sum_kernel<true><<<batch, 256, 0, stream>>>(
            linear.data_ptr<float>(), bias.data_ptr<float>(),
            result.data_ptr<float>(), outputs, 2,
            static_cast<float>(scale));
    } else {
        bias_pool_sum_kernel<false><<<batch, 256, 0, stream>>>(
            linear.data_ptr<float>(), bias.data_ptr<float>(),
            result.data_ptr<float>(), outputs,
            static_cast<int>(kernel_size), static_cast<float>(scale));
    }

    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return {result, linear};
}
"""

_ops = load_inline(
    name="lt_tuned_linear_fused_pool_sum_v4",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["linear_pool_sum_cuda"],
    extra_cflags=["-O3", "-std=c++17"],
    extra_cuda_cflags=["-O3", "-std=c++17"],
    extra_ldflags=["-lcublasLt"],
    verbose=False,
)


class _LinearPoolSum(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, weight, bias, kernel_size, scale):
        result, linear = _ops.linear_pool_sum_cuda(
            x, weight, bias, kernel_size, scale
        )
        ctx.kernel_size = kernel_size
        ctx.scale = scale
        if any(ctx.needs_input_grad[:3]):
            ctx.save_for_backward(x, weight, bias, linear)
        return result

    @staticmethod
    def backward(ctx, grad_output):
        x, weight, bias, linear = ctx.saved_tensors
        _, indices = F.max_pool1d(
            (linear + bias).unsqueeze(1),
            kernel_size=ctx.kernel_size,
            stride=ctx.kernel_size,
            return_indices=True,
        )
        indices = indices.squeeze(1)
        grad_linear = torch.zeros_like(linear)
        values = (grad_output * ctx.scale).unsqueeze(1).expand_as(indices)
        grad_linear.scatter_(1, indices, values)

        grad_x = (
            grad_linear.matmul(weight) if ctx.needs_input_grad[0] else None
        )
        grad_weight = (
            grad_linear.t().matmul(x) if ctx.needs_input_grad[1] else None
        )
        grad_bias = (
            grad_linear.sum(dim=0) if ctx.needs_input_grad[2] else None
        )
        return grad_x, grad_weight, grad_bias, None, None


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, list))
            else kernel_size
        )
        self.scale_factor = scale_factor

    def forward(self, x):
        weight = self.matmul.weight
        bias = self.matmul.bias
        if (
            x.is_cuda
            and x.dtype == torch.float32
            and x.ndim == 2
            and weight.dtype == torch.float32
            and bias.dtype == torch.float32
            and not torch.is_autocast_enabled()
        ):
            return _LinearPoolSum.apply(
                x.contiguous(),
                weight.contiguous(),
                bias.contiguous(),
                self.kernel_size,
                self.scale_factor,
            )

        x = self.matmul(x)
        x = self.max_pool(x.unsqueeze(1)).squeeze(1)
        return x.sum(dim=1) * self.scale_factor
```
Result of evaluating it:
The solution failed to compile. Error output:
```
...[truncated]
 ?const c10::intrusive_ptr<torch::autograd::Node>? to ?const c10::SymInt&?
  493 | DECLARE_SYMINT_OP(float, SymFloat) // just for completeness
      | ^~~~~~~~~~~~~~~~~
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/SymInt.h:493:1: note: candidate: ?bool c10::operator!=(float, const SymInt&)?
  493 | DECLARE_SYMINT_OP(float, SymFloat) // just for completeness
      | ^~~~~~~~~~~~~~~~~
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/SymInt.h:493:1: note:   no known conversion for argument 2 from ?std::nullptr_t? to ?const c10::SymInt&?
  493 | DECLARE_SYMINT_OP(float, SymFloat) // just for completeness
      | ^~~~~~~~~~~~~~~~~
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/ScalarTypeToTypeMeta.h:50:13: note: candidate: ?bool c10::operator!=(ScalarType, caffe2::TypeMeta)?
   50 | inline bool operator!=(ScalarType t, caffe2::TypeMeta m) {
      |             ^~~~~~~~
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/ScalarTypeToTypeMeta.h:50:35: note:   no known conversion for argument 1 from ?const c10::intrusive_ptr<torch::autograd::Node>? to ?c10::ScalarType?
   50 | inline bool operator!=(ScalarType t, caffe2::TypeMeta m) {
      |                        ~~~~~~~~~~~^
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/ScalarTypeToTypeMeta.h:54:13: note: candidate: ?bool c10::operator!=(caffe2::TypeMeta, ScalarType)?
   54 | inline bool operator!=(caffe2::TypeMeta m, ScalarType t) {
      |             ^~~~~~~~
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/ScalarTypeToTypeMeta.h:54:41: note:   no known conversion for argument 1 from ?const c10::intrusive_ptr<torch::autograd::Node>? to ?caffe2::TypeMeta?
   54 | inline bool operator!=(caffe2::TypeMeta m, ScalarType t) {
      |                        ~~~~~~~~~~~~~~~~~^
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/Allocator.h:152:13: note: candidate: ?bool c10::operator!=(const DataPtr&, std::nullptr_t)?
  152 | inline bool operator!=(const DataPtr& dp, std::nullptr_t) noexcept {
      |             ^~~~~~~~
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/Allocator.h:152:39: note:   no known conversion for argument 1 from ?const c10::intrusive_ptr<torch::autograd::Node>? to ?const c10::DataPtr&?
  152 | inline bool operator!=(const DataPtr& dp, std::nullptr_t) noexcept {
      |                        ~~~~~~~~~~~~~~~^~
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/Allocator.h:155:13: note: candidate: ?bool c10::operator!=(std::nullptr_t, const DataPtr&)?
  155 | inline bool operator!=(std::nullptr_t, const DataPtr& dp) noexcept {
      |             ^~~~~~~~
/opt/kbv/v/lib/python3.12/site-packages/torch/include/c10/core/Allocator.h:155:24: note:   no known conversion for argument 1 from ?const c10::intrusive_ptr<torch::autograd::Node>? to ?std::nullptr_t?
  155 | inline bool operator!=(std::nullptr_t, const DataPtr& dp) noexcept {
      |                        ^~~~~~~~~~~~~~
In file included from /opt/kbv/v/lib/python3.12/site-packages/torch/include/torch/csrc/autograd/input_metadata.h:4,
                 from /opt/kbv/v/lib/python3.12/site-packages/torch/include/torch/csrc/autograd/node.h:8,
                 from /opt/kbv/v/lib/python3.12/site-packages/torch/include/torch/csrc/autograd/variable.h:11:
/opt/kbv/v/lib/python3.12/site-packages/torch/include/ATen/ExpandUtils.h: In function ?at::Tensor at::_sum_to(Tensor, c10::ArrayRef<T>, bool)?:
/opt/kbv/v/lib/python3.12/site-packages/torch/include/ATen/ExpandUtils.h:470:28: error: ?sizes? is not a member of ?at::symint?
  470 |   auto sizes = at::symint::sizes<T>(tensor);
      |                            ^~~~~
/opt/kbv/v/lib/python3.12/site-packages/torch/include/ATen/ExpandUtils.h:470:35: error: expected primary-expression before ?>? token
  470 |   auto sizes = at::symint::sizes<T>(tensor);
      |                                   ^
ninja: build stopped: subcommand failed.

```

The fastest correct solution so far (1.012x speedup) is:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline

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

std::vector<torch::Tensor> linear_pool_sum_cuda(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias,
    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 <cublas_v2.h>
#include <cuda_runtime.h>
#include <math_constants.h>
#include <climits>
#include <vector>

static void check_cublas(cublasStatus_t status) {
    TORCH_CHECK(status == CUBLAS_STATUS_SUCCESS,
                "cuBLAS failed with status ", static_cast<int>(status));
}

__device__ __forceinline__ float maximum_nan(float a, float b) {
    return isnan(b) || a < b ? b : a;
}

__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 bias_pool_sum_kernel(
    const float* __restrict__ input,
    const float* __restrict__ bias,
    float* __restrict__ output,
    int columns,
    int kernel_size,
    float scale
) {
    const int tid = threadIdx.x;
    const float* row = input + static_cast<int64_t>(blockIdx.x) * columns;

    float sum0 = 0.0f;
    float sum1 = 0.0f;

    if constexpr (PAIRS) {
        const float4* values = reinterpret_cast<const float4*>(row);
        const float4* biases = reinterpret_cast<const float4*>(bias);
        for (int i = tid; i < columns / 4; i += blockDim.x) {
            const float4 v = values[i];
            const float4 b = biases[i];
            sum0 += maximum_nan(v.x + b.x, v.y + b.y);
            sum1 += maximum_nan(v.z + b.z, v.w + b.w);
        }
    } else {
        for (int i = tid; i < columns / kernel_size; i += blockDim.x) {
            const int start = i * kernel_size;
            float maximum = -CUDART_INF_F;
            for (int j = 0; j < kernel_size; ++j)
                maximum = maximum_nan(
                    maximum, row[start + j] + bias[start + j]);
            sum0 += maximum;
        }
    }

    float sum = warp_sum(sum0 + sum1);
    __shared__ float partial[8];

    const int lane = tid & 31;
    const int warp = tid >> 5;
    if (lane == 0)
        partial[warp] = sum;
    __syncthreads();

    if (warp == 0) {
        sum = warp_sum(lane < 8 ? partial[lane] : 0.0f);
        if (lane == 0)
            output[blockIdx.x] = sum * scale;
    }
}

std::vector<torch::Tensor> linear_pool_sum_cuda(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias,
    int64_t kernel_size,
    double scale
) {
    TORCH_CHECK(x.is_cuda() && weight.is_cuda() && bias.is_cuda(),
                "All inputs must be CUDA tensors");
    TORCH_CHECK(x.device() == weight.device() &&
                x.device() == bias.device(), "Device mismatch");
    TORCH_CHECK(x.scalar_type() == at::kFloat &&
                weight.scalar_type() == at::kFloat &&
                bias.scalar_type() == at::kFloat,
                "All inputs must be float32");
    TORCH_CHECK(x.dim() == 2 && weight.dim() == 2 && bias.dim() == 1,
                "Invalid input dimensions");
    TORCH_CHECK(x.is_contiguous() && weight.is_contiguous() &&
                bias.is_contiguous(), "Inputs must be contiguous");
    TORCH_CHECK(x.size(1) == weight.size(1) &&
                bias.size(0) == weight.size(0), "Shape mismatch");
    TORCH_CHECK(kernel_size > 0 && kernel_size <= weight.size(0),
                "Invalid pooling kernel size");
    TORCH_CHECK(x.size(0) <= INT_MAX && x.size(1) <= INT_MAX &&
                weight.size(0) <= INT_MAX, "Dimensions are too large");

    const c10::cuda::CUDAGuard guard(x.device());
    const int batch = static_cast<int>(x.size(0));
    const int inputs = static_cast<int>(x.size(1));
    const int outputs = static_cast<int>(weight.size(0));

    auto linear = torch::empty({batch, outputs}, x.options());
    auto result = torch::empty({batch}, x.options());

    if (batch == 0)
        return {result, linear};

    const auto stream = at::cuda::getCurrentCUDAStream();

    if (inputs == 0) {
        C10_CUDA_CHECK(cudaMemsetAsync(
            linear.data_ptr<float>(), 0,
            linear.numel() * sizeof(float), stream));
    } else {
        cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();
        cublasMath_t previous_math;
        cublasPointerMode_t previous_pointer;
        check_cublas(cublasGetMathMode(handle, &previous_math));
        check_cublas(cublasGetPointerMode(handle, &previous_pointer));
        check_cublas(cublasSetPointerMode(handle, CUBLAS_POINTER_MODE_HOST));
        check_cublas(cublasSetMathMode(handle, CUBLAS_TF32_TENSOR_OP_MATH));

        const float alpha = 1.0f;
        const float beta = 0.0f;

        // Row-major X @ W.T is column-major W @ X.T.
        const cublasStatus_t status = cublasGemmEx(
            handle,
            CUBLAS_OP_T, CUBLAS_OP_N,
            outputs, batch, inputs,
            &alpha,
            weight.data_ptr<float>(), CUDA_R_32F, inputs,
            x.data_ptr<float>(), CUDA_R_32F, inputs,
            &beta,
            linear.data_ptr<float>(), CUDA_R_32F, outputs,
            CUBLAS_COMPUTE_32F_FAST_TF32,
            CUBLAS_GEMM_DEFAULT_TENSOR_OP);

        const auto math_status = cublasSetMathMode(handle, previous_math);
        const auto pointer_status =
            cublasSetPointerMode(handle, previous_pointer);
        check_cublas(status);
        check_cublas(math_status);
        check_cublas(pointer_status);
    }

    if (kernel_size == 2 && outputs % 4 == 0 &&
        reinterpret_cast<uintptr_t>(bias.data_ptr<float>()) % 16 == 0) {
        bias_pool_sum_kernel<true><<<batch, 256, 0, stream>>>(
            linear.data_ptr<float>(), bias.data_ptr<float>(),
            result.data_ptr<float>(), outputs, 2,
            static_cast<float>(scale));
    } else {
        bias_pool_sum_kernel<false><<<batch, 256, 0, stream>>>(
            linear.data_ptr<float>(), bias.data_ptr<float>(),
            result.data_ptr<float>(), outputs,
            static_cast<int>(kernel_size), static_cast<float>(scale));
    }

    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return {result, linear};
}
"""

_ops = load_inline(
    name="tf32_linear_fused_bias_pool_sum_v3",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["linear_pool_sum_cuda"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    extra_ldflags=["-lcublas"],
    verbose=False,
)


class _LinearPoolSum(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, weight, bias, kernel_size, scale):
        result, linear = _ops.linear_pool_sum_cuda(
            x, weight, bias, kernel_size, scale
        )
        ctx.kernel_size = kernel_size
        ctx.scale = scale
        if any(ctx.needs_input_grad[:3]):
            ctx.save_for_backward(x, weight, bias, linear)
        return result

    @staticmethod
    def backward(ctx, grad_output):
        x, weight, bias, linear = ctx.saved_tensors
        _, indices = F.max_pool1d(
            (linear + bias).unsqueeze(1),
            kernel_size=ctx.kernel_size,
            stride=ctx.kernel_size,
            return_indices=True,
        )
        indices = indices.squeeze(1)
        grad_linear = torch.zeros_like(linear)
        values = (grad_output * ctx.scale).unsqueeze(1).expand_as(indices)
        grad_linear.scatter_(1, indices, values)

        grad_x = (
            grad_linear.matmul(weight) if ctx.needs_input_grad[0] else None
        )
        grad_weight = (
            grad_linear.t().matmul(x) if ctx.needs_input_grad[1] else None
        )
        grad_bias = (
            grad_linear.sum(dim=0) if ctx.needs_input_grad[2] else None
        )
        return grad_x, grad_weight, grad_bias, None, None


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, list))
            else kernel_size
        )
        self.scale_factor = scale_factor

    def forward(self, x):
        weight = self.matmul.weight
        bias = self.matmul.bias
        if (
            x.is_cuda
            and x.dtype == torch.float32
            and x.ndim == 2
            and weight.dtype == torch.float32
            and bias.dtype == torch.float32
            and not torch.is_autocast_enabled()
        ):
            return _LinearPoolSum.apply(
                x.contiguous(),
                weight.contiguous(),
                bias.contiguous(),
                self.kernel_size,
                self.scale_factor,
            )

        x = self.matmul(x)
        x = self.max_pool(x.unsqueeze(1)).squeeze(1)
        return x.sum(dim=1) * 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.
