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 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

_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
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 8 ms; the PyTorch reference (with TF32 enabled) takes 1.38 ms; speedup 0.172x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| ampere_sgemm_128x32_tn | 7896.4 | 1 |
| void fused_norm_residual_kernel<float, 32>(float const*, float const*, float*, long, doubl | 125.2 | 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.
