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

# ---------------------------------------------------------------------------
# Enable TF32 tensor-core math for FP32 GEMMs. The reference is benchmarked
# with TF32 enabled as well; the (1024x8192) @ (8192x8192) matmul dominates
# the runtime, and TF32 tensor cores make it several times faster than FP32
# CUDA-core SGEMM.
# ---------------------------------------------------------------------------
def _enable_tf32():
    try:
        torch.backends.cuda.matmul.allow_tf32 = True
    except Exception:
        pass
    try:
        torch.backends.cudnn.allow_tf32 = True
    except Exception:
        pass
    try:
        torch.set_float32_matmul_precision("high")
    except Exception:
        pass

_enable_tf32()

# ---------------------------------------------------------------------------
# Fused CUDA kernel:
#   1) per-row instance normalization (equivalent to InstanceNorm2d applied to
#      a (B, 1, 1, F) tensor, i.e. biased-variance normalization of each row)
#   2) residual addition  (+ y)
#   3) elementwise multiplication  (* y)
#
# The row is cached in shared memory so global traffic is the minimum:
# read z once, read y once, write out once (96 MB total for the given shapes).
# ---------------------------------------------------------------------------
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_smem_kernel(
    const float* __restrict__ x,
    const float* __restrict__ y,
    float* __restrict__ out,
    const int Fdim,
    const float eps)
{
    extern __shared__ float s_row[];
    __shared__ float s_sum[32];
    __shared__ float s_sq[32];

    const int row = blockIdx.x;
    const size_t base = (size_t)row * (size_t)Fdim;
    const float* xr = x + base;
    const float* yr = y + base;
    float* orow = out + base;

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

    // ---- load row into shared memory, accumulate statistics ----
    if (VEC) {
        const int F4 = Fdim >> 2;
        const float4* xr4 = reinterpret_cast<const float4*>(xr);
        float4* s4 = reinterpret_cast<float4*>(s_row);
        for (int i = threadIdx.x; i < F4; i += blockDim.x) {
            float4 v = xr4[i];
            s4[i] = v;
            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];
            s_row[i] = v;
            sum   += v;
            sumsq += v * v;
        }
    }

    // ---- block reduction (warp shuffles + shared memory) ----
    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);

    // ---- normalize from shared memory + add + multiply ----
    if (VEC) {
        const int F4 = Fdim >> 2;
        const float4* s4  = reinterpret_cast<const float4*>(s_row);
        const float4* yr4 = reinterpret_cast<const float4*>(yr);
        float4* o4 = reinterpret_cast<float4*>(orow);
        for (int i = threadIdx.x; i < F4; i += blockDim.x) {
            float4 xv = s4[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;
            o4[i] = ov;
        }
    } else {
        for (int i = threadIdx.x; i < Fdim; i += blockDim.x) {
            float yv = yr[i];
            orow[i] = ((s_row[i] - mean) * inv + yv) * yv;
        }
    }
}

// Fallback for very large rows that do not fit in shared memory:
// two passes over global memory.
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 size_t base = (size_t)row * (size_t)Fdim;
    const float* xr = x + base;
    const float* yr = y + base;
    float* orow = out + base;

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

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

    __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;
    const float inv  = rsqrtf(var + eps);

    if (VEC) {
        const int F4 = Fdim >> 2;
        const float4* xr4 = reinterpret_cast<const float4*>(xr);
        const float4* yr4 = reinterpret_cast<const float4*>(yr);
        float4* o4 = 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;
            o4[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 && y.scalar_type() == torch::kFloat32,
                "x and y must be float32");
    TORCH_CHECK(x.sizes().equals(y.sizes()), "x and y must have the same shape");

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

    const int B = (int)xc.size(0);
    const int Fdim = (int)xc.size(1);
    if (B == 0 || Fdim == 0) {
        return out;
    }

    const int threads = 256;
    const bool vec = (Fdim & 3) == 0;
    const size_t smem = (size_t)Fdim * sizeof(float);
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    if (smem <= 44 * 1024) {
        if (vec) {
            fused_inorm_add_mul_smem_kernel<true><<<B, threads, smem, stream>>>(
                xc.data_ptr<float>(), yc.data_ptr<float>(),
                out.data_ptr<float>(), Fdim, (float)eps);
        } else {
            fused_inorm_add_mul_smem_kernel<false><<<B, threads, smem, stream>>>(
                xc.data_ptr<float>(), yc.data_ptr<float>(),
                out.data_ptr<float>(), Fdim, (float)eps);
        }
    } else {
        if (vec) {
            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_v2",
    cpp_sources=fused_cpp_source,
    cuda_sources=fused_cuda_source,
    functions=["fused_inorm_add_mul"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3", "--use_fast_math"],
)


class ModelNew(nn.Module):
    """
    Optimized model:
      * Linear (GEMM) runs on TF32 tensor cores via cuBLAS (the dominant op).
      * InstanceNorm + residual add + elementwise multiply are fused into a
        single custom CUDA kernel with the row cached in shared memory.
    """
    def __init__(self, in_features, out_features, eps=1e-5, momentum=0.1):
        super(ModelNew, self).__init__()
        _enable_tf32()
        self.bmm = nn.Linear(in_features, out_features)
        self.eps = float(eps)
        self.fused = fused_inorm_add_mul

    def forward(self, x, y):
        _enable_tf32()
        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 1.2 ms; the PyTorch reference (with TF32 enabled) takes 1.38 ms; speedup 1.150x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| void cutlass::Kernel2<cutlass_80_tensorop_s1688gemm_256x128_32x3_tn_align4>(cutlass_80_ten | 1058.1 | 1 |
| void fused_inorm_add_mul_smem_kernel<true>(float const*, float const*, float*, int, float) | 75.9 | 1 |
| Memset (Device) | 1.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.
