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
# 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 CUDA kernel:
#   1) per-row instance normalization  (equivalent to InstanceNorm2d applied
#      on a (B, 1, 1, F) tensor, i.e. normalize each row with biased variance)
#   2) residual addition  (+ y)
#   3) elementwise multiplication  (* y)
#
# The expensive (B, in) x (in, out) GEMM is left to cuBLAS via F.linear,
# everything after it is executed in a single kernel launch.
# ---------------------------------------------------------------------------
fused_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>

template <bool VEC>
__global__ void fused_inorm_add_mul_kernel(
    const float* __restrict__ x,
    const float* __restrict__ y,
    float* __restrict__ out,
    const int Fdim,
    const float eps)
{
    const int row = blockIdx.x;
    const float* xr = x + (long)row * Fdim;
    const float* yr = y + (long)row * Fdim;
    float* orow = out + (long)row * Fdim;

    float sum = 0.f;
    float sumsq = 0.f;

    // ---- pass 1: accumulate row statistics ----
    if (VEC) {
        const int F4 = Fdim >> 2;
        const float4* xr4 = reinterpret_cast<const float4*>(xr);
        for (int i = threadIdx.x; i < F4; i += blockDim.x) {
            float4 v = xr4[i];
            sum   += v.x + v.y + v.z + v.w;
            sumsq += v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w;
        }
    } else {
        for (int i = threadIdx.x; i < Fdim; i += blockDim.x) {
            float v = xr[i];
            sum   += v;
            sumsq += v * v;
        }
    }

    // ---- block reduction (warp shuffles + shared memory) ----
    __shared__ float s_sum[32];
    __shared__ float s_sq[32];
    const unsigned int mask = 0xffffffffu;
    for (int off = 16; off > 0; off >>= 1) {
        sum   += __shfl_down_sync(mask, sum, off);
        sumsq += __shfl_down_sync(mask, sumsq, off);
    }
    const int lane = threadIdx.x & 31;
    const int wid  = threadIdx.x >> 5;
    if (lane == 0) {
        s_sum[wid] = sum;
        s_sq[wid]  = sumsq;
    }
    __syncthreads();

    const int nwarps = blockDim.x >> 5;
    if (wid == 0) {
        float a = (lane < nwarps) ? s_sum[lane] : 0.f;
        float b = (lane < nwarps) ? s_sq[lane]  : 0.f;
        for (int off = 16; off > 0; off >>= 1) {
            a += __shfl_down_sync(mask, a, off);
            b += __shfl_down_sync(mask, b, off);
        }
        if (lane == 0) {
            s_sum[0] = a;
            s_sq[0]  = b;
        }
    }
    __syncthreads();

    const float mean = s_sum[0] / (float)Fdim;
    const float var  = s_sq[0] / (float)Fdim - mean * mean;  // biased, like InstanceNorm
    const float inv  = rsqrtf(var + eps);

    // ---- pass 2: normalize + add + multiply ----
    if (VEC) {
        const int F4 = Fdim >> 2;
        const float4* xr4 = reinterpret_cast<const float4*>(xr);
        const float4* yr4 = reinterpret_cast<const float4*>(yr);
        float4* or4 = reinterpret_cast<float4*>(orow);
        for (int i = threadIdx.x; i < F4; i += blockDim.x) {
            float4 xv = xr4[i];
            float4 yv = yr4[i];
            float4 ov;
            ov.x = ((xv.x - mean) * inv + yv.x) * yv.x;
            ov.y = ((xv.y - mean) * inv + yv.y) * yv.y;
            ov.z = ((xv.z - mean) * inv + yv.z) * yv.z;
            ov.w = ((xv.w - mean) * inv + yv.w) * yv.w;
            or4[i] = ov;
        }
    } else {
        for (int i = threadIdx.x; i < Fdim; i += blockDim.x) {
            float xv = xr[i];
            float yv = yr[i];
            orow[i] = ((xv - mean) * inv + yv) * yv;
        }
    }
}

torch::Tensor fused_inorm_add_mul(torch::Tensor x, torch::Tensor y, double eps) {
    TORCH_CHECK(x.is_cuda() && y.is_cuda(), "x and y must be CUDA tensors");
    TORCH_CHECK(x.dim() == 2 && y.dim() == 2, "x and y must be 2-D");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "x must be float32");

    auto xc = x.contiguous();
    auto yc = y.contiguous();
    auto out = torch::empty_like(xc);

    const int B = xc.size(0);
    const int Fdim = xc.size(1);
    const int threads = 256;
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    if ((Fdim & 3) == 0) {
        fused_inorm_add_mul_kernel<true><<<B, threads, 0, stream>>>(
            xc.data_ptr<float>(), yc.data_ptr<float>(),
            out.data_ptr<float>(), Fdim, (float)eps);
    } else {
        fused_inorm_add_mul_kernel<false><<<B, threads, 0, stream>>>(
            xc.data_ptr<float>(), yc.data_ptr<float>(),
            out.data_ptr<float>(), Fdim, (float)eps);
    }
    return out;
}
"""

fused_cpp_source = (
    "torch::Tensor fused_inorm_add_mul(torch::Tensor x, torch::Tensor y, double eps);"
)

fused_inorm_add_mul = load_inline(
    name="fused_inorm_add_mul",
    cpp_sources=fused_cpp_source,
    cuda_sources=fused_cuda_source,
    functions=["fused_inorm_add_mul"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model: the Linear (GEMM) runs on cuBLAS, while the instance
    normalization + residual add + elementwise multiply are fused into a
    single custom CUDA kernel.
    """
    def __init__(self, in_features, out_features, eps=1e-5, momentum=0.1):
        super(ModelNew, self).__init__()
        self.bmm = nn.Linear(in_features, out_features)
        self.eps = eps
        self.fused = fused_inorm_add_mul

    def forward(self, x, y):
        z = F.linear(x, self.bmm.weight, self.bmm.bias)
        if z.is_cuda and z.dtype == torch.float32:
            return self.fused.fused_inorm_add_mul(z, y, self.eps)
        # fallback path (CPU / non-float32) replicating the original ops
        mean = z.mean(dim=1, keepdim=True)
        var = z.var(dim=1, unbiased=False, keepdim=True)
        z = (z - mean) / torch.sqrt(var + self.eps)
        return (z + y) * y
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 7.94 ms; the PyTorch reference (with TF32 enabled) takes 1.38 ms; speedup 0.174x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| ampere_sgemm_128x32_tn | 7851.2 | 1 |
| void fused_inorm_add_mul_kernel<true>(float const*, float const*, float*, int, float) | 89.6 | 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.
