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 a batch matrix multiplication, instance normalization, summation, residual addition, and multiplication.
    """
    def __init__(self, in_features, out_features, eps=1e-5, momentum=0.1):
        super(Model, self).__init__()
        self.bmm = nn.Linear(in_features, out_features)
        self.instance_norm = nn.InstanceNorm2d(out_features, eps=eps, momentum=momentum)

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

        Returns:
            torch.Tensor: Output tensor of shape (batch_size, out_features).
        """
        x = self.bmm(x)
        x = self.instance_norm(x.unsqueeze(1).unsqueeze(1)).squeeze(1).squeeze(1)
        x = x + y
        x = x * y
        return x

batch_size = 1024  # Increased batch size
in_features = 8192  # Increased input features
out_features = 8192  # Increased output features

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

def get_init_inputs():
    return [in_features, out_features]
    ```
    
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 3 of 6 for this task. Your previous solution (turn 2) was:
```python
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline

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

__device__ __forceinline__ float block_sum(float value) {
    __shared__ float partial[8];
    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;

    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1)
        value += __shfl_down_sync(0xffffffff, value, offset);

    if (lane == 0)
        partial[warp] = value;
    __syncthreads();

    if (warp == 0) {
        value = lane < 8 ? partial[lane] : 0.0f;
        #pragma unroll
        for (int offset = 16; offset > 0; offset >>= 1)
            value += __shfl_down_sync(0xffffffff, value, offset);
        if (lane == 0)
            partial[0] = value;
    }
    __syncthreads();

    float result = partial[0];
    __syncthreads();
    return result;
}

template<int ITEMS>
__global__ void bias_norm_residual_mul_kernel(
    const float* __restrict__ linear,
    const float* __restrict__ bias,
    const float* __restrict__ residual,
    float* __restrict__ output,
    int columns,
    float epsilon
) {
    const int tid = threadIdx.x;
    const int64_t base = int64_t(blockIdx.x) * columns;

    float values[ITEMS];
    float sum = 0.0f;

    #pragma unroll
    for (int i = 0; i < ITEMS; ++i) {
        const int column = tid + i * 256;
        float value = 0.0f;
        if (column < columns)
            value = __fadd_rn(linear[base + column], bias[column]);
        values[i] = value;
        sum += value;
    }

    const float mean = block_sum(sum) / float(columns);
    float squared_sum = 0.0f;

    #pragma unroll
    for (int i = 0; i < ITEMS; ++i) {
        const int column = tid + i * 256;
        if (column < columns) {
            values[i] -= mean;
            squared_sum += values[i] * values[i];
        }
    }

    const float variance = block_sum(squared_sum) / float(columns);
    const float inverse_std = rsqrtf(variance + epsilon);

    #pragma unroll
    for (int i = 0; i < ITEMS; ++i) {
        const int column = tid + i * 256;
        if (column < columns) {
            const float y = residual[base + column];
            const float normalized = __fmul_rn(values[i], inverse_std);
            output[base + column] =
                __fmul_rn(__fadd_rn(normalized, y), y);
        }
    }
}

torch::Tensor linear_norm_residual_mul(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias,
    torch::Tensor y,
    double epsilon
) {
    TORCH_CHECK(
        x.is_cuda() && weight.is_cuda() && bias.is_cuda() && y.is_cuda(),
        "Expected CUDA tensors");
    TORCH_CHECK(
        x.device() == weight.device() &&
        x.device() == bias.device() &&
        x.device() == y.device(),
        "Devices must match");
    TORCH_CHECK(
        x.scalar_type() == at::kFloat &&
        weight.scalar_type() == at::kFloat &&
        bias.scalar_type() == at::kFloat &&
        y.scalar_type() == at::kFloat,
        "Expected float32 tensors");
    TORCH_CHECK(
        x.is_contiguous() && weight.is_contiguous() &&
        bias.is_contiguous() && y.is_contiguous(),
        "Expected contiguous tensors");
    TORCH_CHECK(
        x.dim() == 2 && weight.dim() == 2 &&
        bias.dim() == 1 && y.dim() == 2,
        "Invalid tensor dimensions");
    TORCH_CHECK(
        x.size(1) == weight.size(1) &&
        bias.size(0) == weight.size(0) &&
        y.size(0) == x.size(0) &&
        y.size(1) == weight.size(0),
        "Incompatible shapes");

    const int64_t rows64 = x.size(0);
    const int64_t columns64 = weight.size(0);
    const int64_t inner64 = x.size(1);
    TORCH_CHECK(
        rows64 <= INT_MAX && inner64 > 0 && inner64 <= INT_MAX &&
        columns64 > 1 && columns64 <= 8192,
        "Unsupported matrix dimensions");

    const c10::cuda::CUDAGuard guard(x.device());
    const int rows = int(rows64);
    const int columns = int(columns64);
    const int inner = int(inner64);

    auto linear = torch::empty({rows64, columns64}, x.options());
    auto output = torch::empty_like(linear);
    if (rows == 0)
        return output;

    const auto stream = at::cuda::getCurrentCUDAStream();
    cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();

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

    // Row-major X @ W.T is column-major W.T @ X.
    // Explicit TF32 compute enables tensor cores without changing global
    // PyTorch precision settings.
    const cublasStatus_t status = cublasGemmEx(
        handle,
        CUBLAS_OP_T,
        CUBLAS_OP_N,
        columns,
        rows,
        inner,
        &alpha,
        weight.data_ptr<float>(),
        CUDA_R_32F,
        inner,
        x.data_ptr<float>(),
        CUDA_R_32F,
        inner,
        &beta,
        linear.data_ptr<float>(),
        CUDA_R_32F,
        columns,
        CUBLAS_COMPUTE_32F_FAST_TF32,
        CUBLAS_GEMM_DEFAULT_TENSOR_OP
    );
    TORCH_CHECK(status == CUBLAS_STATUS_SUCCESS,
                "cublasGemmEx failed: ", int(status));

    if (columns <= 2048) {
        bias_norm_residual_mul_kernel<8><<<rows, 256, 0, stream>>>(
            linear.data_ptr<float>(), bias.data_ptr<float>(),
            y.data_ptr<float>(), output.data_ptr<float>(),
            columns, float(epsilon));
    } else if (columns <= 4096) {
        bias_norm_residual_mul_kernel<16><<<rows, 256, 0, stream>>>(
            linear.data_ptr<float>(), bias.data_ptr<float>(),
            y.data_ptr<float>(), output.data_ptr<float>(),
            columns, float(epsilon));
    } else {
        bias_norm_residual_mul_kernel<32><<<rows, 256, 0, stream>>>(
            linear.data_ptr<float>(), bias.data_ptr<float>(),
            y.data_ptr<float>(), output.data_ptr<float>(),
            columns, float(epsilon));
    }

    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}
"""

_ops = load_inline(
    name="tf32_linear_fused_instance_norm_v2",
    cpp_sources=r"""
        torch::Tensor linear_norm_residual_mul(
            torch::Tensor x,
            torch::Tensor weight,
            torch::Tensor bias,
            torch::Tensor y,
            double epsilon);
    """,
    cuda_sources=_cuda_source,
    functions=["linear_norm_residual_mul"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3", "--fmad=false"],
    extra_ldflags=["-lcublas"],
    verbose=False,
)


class ModelNew(nn.Module):
    def __init__(self, in_features, out_features, eps=1e-5, momentum=0.1):
        super().__init__()
        self.bmm = nn.Linear(in_features, out_features)
        self.instance_norm = nn.InstanceNorm2d(
            out_features, eps=eps, momentum=momentum
        )

    def forward(self, x, y):
        weight = self.bmm.weight
        bias = self.bmm.bias

        if (
            x.is_cuda
            and y.is_cuda
            and x.device == y.device == weight.device == bias.device
            and x.dtype == y.dtype == weight.dtype == bias.dtype == torch.float32
            and x.ndim == 2
            and y.ndim == 2
            and x.shape[1] == weight.shape[1]
            and x.shape[1] > 0
            and y.shape == (x.shape[0], weight.shape[0])
            and 1 < weight.shape[0] <= 8192
            and not torch.is_autocast_enabled()
        ):
            return _ops.linear_norm_residual_mul(
                x.contiguous(),
                weight.contiguous(),
                bias.contiguous(),
                y.contiguous(),
                self.instance_norm.eps,
            )

        z = self.bmm(x)
        z = self.instance_norm(z.unsqueeze(1).unsqueeze(1))
        z = z.squeeze(1).squeeze(1)
        return (z + y) * y
```
Result of evaluating it:
The solution compiled and ran but its output did not match the reference. Details:
```
{"avg_difference": ["0.000113", "0.000113", "0.000113", "0.000113", "0.000113"], "correctness_issue": "Output mismatch", "correctness_trials": "(0 / 5)", "max_difference": ["0.001286", "0.001332", "0.001452", "0.001305", "0.001293"]}
```

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

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

template <typename T>
__device__ __forceinline__ T block_sum(T value) {
    __shared__ T warp_sums[8];

    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;

    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1)
        value += __shfl_down_sync(0xffffffff, value, offset);

    if (lane == 0)
        warp_sums[warp] = value;
    __syncthreads();

    if (warp == 0) {
        value = lane < 8 ? warp_sums[lane] : T(0);
        #pragma unroll
        for (int offset = 16; offset > 0; offset >>= 1)
            value += __shfl_down_sync(0xffffffff, value, offset);
        if (lane == 0)
            warp_sums[0] = value;
    }
    __syncthreads();

    T result = warp_sums[0];
    __syncthreads();
    return result;
}

template <typename scalar_t, int ITEMS>
__global__ void fused_norm_residual_kernel(
    const scalar_t* __restrict__ x,
    const scalar_t* __restrict__ y,
    scalar_t* __restrict__ output,
    int64_t columns,
    double epsilon
) {
    using acc_t = at::acc_type<scalar_t, true>;
    const int64_t base = int64_t(blockIdx.x) * columns;
    const int tid = threadIdx.x;

    acc_t values[ITEMS];
    acc_t sum = acc_t(0);

    #pragma unroll
    for (int i = 0; i < ITEMS; ++i) {
        const int64_t column = tid + int64_t(i) * blockDim.x;
        values[i] = column < columns ? acc_t(x[base + column]) : acc_t(0);
        sum += values[i];
    }

    const acc_t mean = block_sum(sum) / acc_t(columns);
    acc_t squared_sum = acc_t(0);

    #pragma unroll
    for (int i = 0; i < ITEMS; ++i) {
        const int64_t column = tid + int64_t(i) * blockDim.x;
        if (column < columns) {
            values[i] -= mean;
            squared_sum += values[i] * values[i];
        }
    }

    const acc_t variance = block_sum(squared_sum) / acc_t(columns);
    const acc_t inverse_std = acc_t(1) / sqrt(variance + acc_t(epsilon));

    #pragma unroll
    for (int i = 0; i < ITEMS; ++i) {
        const int64_t column = tid + int64_t(i) * blockDim.x;
        if (column < columns) {
            const acc_t residual = acc_t(y[base + column]);
            const scalar_t normalized = scalar_t(values[i] * inverse_std);
            const scalar_t added = scalar_t(acc_t(normalized) + residual);
            output[base + column] = scalar_t(acc_t(added) * residual);
        }
    }
}

torch::Tensor fused_norm_residual(
    torch::Tensor x,
    torch::Tensor y,
    double epsilon
) {
    TORCH_CHECK(x.is_cuda() && y.is_cuda(), "Expected CUDA tensors");
    TORCH_CHECK(x.device() == y.device(), "Devices must match");
    TORCH_CHECK(x.scalar_type() == y.scalar_type(), "Dtypes must match");
    TORCH_CHECK(x.dim() == 2 && x.sizes() == y.sizes(), "Expected matching matrices");
    TORCH_CHECK(x.is_contiguous() && y.is_contiguous(), "Expected contiguous tensors");
    TORCH_CHECK(x.size(1) > 1 && x.size(1) <= 8192, "Unsupported row width");

    const c10::cuda::CUDAGuard device_guard(x.device());
    auto output = torch::empty_like(x);
    if (x.size(0) == 0)
        return output;

    const auto stream = at::cuda::getCurrentCUDAStream();
    const int64_t columns = x.size(1);

    AT_DISPATCH_FLOATING_TYPES_AND2(
        at::ScalarType::Half, at::ScalarType::BFloat16,
        x.scalar_type(), "fused_norm_residual", [&] {
            if (columns <= 2048) {
                fused_norm_residual_kernel<scalar_t, 8>
                    <<<x.size(0), 256, 0, stream>>>(
                        x.data_ptr<scalar_t>(), y.data_ptr<scalar_t>(),
                        output.data_ptr<scalar_t>(), columns, epsilon);
            } else {
                fused_norm_residual_kernel<scalar_t, 32>
                    <<<x.size(0), 256, 0, stream>>>(
                        x.data_ptr<scalar_t>(), y.data_ptr<scalar_t>(),
                        output.data_ptr<scalar_t>(), columns, epsilon);
            }
        });

    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}
"""

_fused_ops = load_inline(
    name="fused_instance_norm_residual_mul_v1",
    cpp_sources=[
        "torch::Tensor fused_norm_residual("
        "torch::Tensor x, torch::Tensor y, double epsilon);"
    ],
    cuda_sources=_cuda_source,
    functions=["fused_norm_residual"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3", "--fmad=false"],
    verbose=False,
)


class ModelNew(nn.Module):
    def __init__(self, in_features, out_features, eps=1e-5, momentum=0.1):
        super().__init__()
        self.bmm = nn.Linear(in_features, out_features)
        self.instance_norm = nn.InstanceNorm2d(
            out_features, eps=eps, momentum=momentum
        )

    def forward(self, x, y):
        x = self.bmm(x)

        if (
            x.is_cuda
            and y.is_cuda
            and x.device == y.device
            and x.dtype == y.dtype
            and x.dtype in (
                torch.float16, torch.bfloat16, torch.float32, torch.float64
            )
            and x.ndim == 2
            and x.shape == y.shape
            and 1 < x.shape[1] <= 8192
        ):
            return _fused_ops.fused_norm_residual(
                x.contiguous(), y.contiguous(), self.instance_norm.eps
            )

        x = self.instance_norm(
            x.unsqueeze(1).unsqueeze(1)
        ).squeeze(1).squeeze(1)
        return (x + y) * y
```

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.
