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):
    """
    Simple model that performs Layer Normalization.
    """
    def __init__(self, normalized_shape: tuple):
        """
        Initializes the LayerNorm layer.

        Args:
            normalized_shape (tuple): Shape of the input tensor to be normalized.
        """
        super(Model, self).__init__()
        self.ln = nn.LayerNorm(normalized_shape=normalized_shape)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Applies Layer Normalization to the input tensor.

        Args:
            x (torch.Tensor): Input tensor of shape (*, normalized_shape).

        Returns:
            torch.Tensor: Output tensor with Layer Normalization applied, same shape as input.
        """
        return self.ln(x)

batch_size = 16
features = 64
dim1 = 256
dim2 = 256

def get_inputs():
    x = torch.rand(batch_size, features, dim1, dim2)
    return [x]

def get_init_inputs():
    return [(features, dim1, dim2)]
    ```
    
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

# Custom fused LayerNorm CUDA implementation.
# Strategy (optimized for the common case of very large normalized dims):
#   1) partial-sums kernel: each block reduces a chunk of a row -> (sum, sumsq)
#      using vectorized float4 loads and warp/block reductions.
#   2) tiny kernel reduces the partials -> per-row mean and rstd.
#   3) normalize kernel: out = (x - mean) * rstd * weight + bias, vectorized.
# This splits each row across many blocks for full GPU occupancy (the default
# shape here is only 16 rows of ~4M elements each), while remaining
# memory-bandwidth bound.

layer_norm_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda_runtime.h>
#include <algorithm>

#define LN_THREADS 256
#define LN_WARPS (LN_THREADS / 32)

__device__ __forceinline__ void ln_warp_reduce(float &sum, float &sumsq) {
    #pragma unroll
    for (int off = 16; off > 0; off >>= 1) {
        sum   += __shfl_down_sync(0xffffffffu, sum, off);
        sumsq += __shfl_down_sync(0xffffffffu, sumsq, off);
    }
}

__device__ __forceinline__ void ln_block_reduce(float &sum, float &sumsq,
                                                float *sh_sum, float *sh_sumsq) {
    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;
    ln_warp_reduce(sum, sumsq);
    if (lane == 0) {
        sh_sum[warp]   = sum;
        sh_sumsq[warp] = sumsq;
    }
    __syncthreads();
    if (warp == 0) {
        const int nwarp = (blockDim.x + 31) >> 5;
        sum   = (lane < nwarp) ? sh_sum[lane]   : 0.0f;
        sumsq = (lane < nwarp) ? sh_sumsq[lane] : 0.0f;
        ln_warp_reduce(sum, sumsq);
    }
}

// ---------------- Kernel 1: partial sums (vectorized) ----------------
__global__ void ln_partial_sums_vec4(const float* __restrict__ x,
                                     float* __restrict__ partials,
                                     int N, int chunk, int splits) {
    const int row   = blockIdx.y;
    const int split = blockIdx.x;
    const float* row_ptr = x + (long long)row * N;

    const int start = split * chunk;
    int end = start + chunk;
    if (end > N) end = N;

    float s0 = 0.f, s1 = 0.f, s2 = 0.f, s3 = 0.f;
    float q0 = 0.f, q1 = 0.f, q2 = 0.f, q3 = 0.f;
    const int stride = blockDim.x * 4;
    for (int i = start + threadIdx.x * 4; i < end; i += stride) {
        const float4 v = reinterpret_cast<const float4*>(row_ptr)[i >> 2];
        s0 += v.x; s1 += v.y; s2 += v.z; s3 += v.w;
        q0 += v.x * v.x; q1 += v.y * v.y; q2 += v.z * v.z; q3 += v.w * v.w;
    }
    float sum   = (s0 + s1) + (s2 + s3);
    float sumsq = (q0 + q1) + (q2 + q3);

    __shared__ float sh_sum[LN_WARPS];
    __shared__ float sh_sumsq[LN_WARPS];
    ln_block_reduce(sum, sumsq, sh_sum, sh_sumsq);

    if (threadIdx.x == 0) {
        float* p = partials + ((long long)row * splits + split) * 2;
        p[0] = sum;
        p[1] = sumsq;
    }
}

// ---------------- Kernel 1: partial sums (scalar fallback) ----------------
__global__ void ln_partial_sums_scalar(const float* __restrict__ x,
                                       float* __restrict__ partials,
                                       int N, int chunk, int splits) {
    const int row   = blockIdx.y;
    const int split = blockIdx.x;
    const float* row_ptr = x + (long long)row * N;

    const int start = split * chunk;
    int end = start + chunk;
    if (end > N) end = N;

    float sum = 0.f, sumsq = 0.f;
    for (int i = start + threadIdx.x; i < end; i += blockDim.x) {
        const float v = row_ptr[i];
        sum   += v;
        sumsq += v * v;
    }

    __shared__ float sh_sum[LN_WARPS];
    __shared__ float sh_sumsq[LN_WARPS];
    ln_block_reduce(sum, sumsq, sh_sum, sh_sumsq);

    if (threadIdx.x == 0) {
        float* p = partials + ((long long)row * splits + split) * 2;
        p[0] = sum;
        p[1] = sumsq;
    }
}

// ---------------- Kernel 2: final per-row statistics ----------------
__global__ void ln_final_stats(const float* __restrict__ partials,
                               float* __restrict__ mean,
                               float* __restrict__ rstd,
                               int splits, int N, float eps) {
    const int row = blockIdx.x;
    float sum = 0.f, sumsq = 0.f;
    for (int i = threadIdx.x; i < splits; i += blockDim.x) {
        const float* p = partials + ((long long)row * splits + i) * 2;
        sum   += p[0];
        sumsq += p[1];
    }

    __shared__ float sh_sum[LN_WARPS];
    __shared__ float sh_sumsq[LN_WARPS];
    ln_block_reduce(sum, sumsq, sh_sum, sh_sumsq);

    if (threadIdx.x == 0) {
        const float m = sum / (float)N;
        float var = sumsq / (float)N - m * m;
        var = var < 0.f ? 0.f : var;  // guard against tiny negative roundoff
        mean[row] = m;
        rstd[row] = rsqrtf(var + eps);
    }
}

// ---------------- Kernel 3: normalize (vectorized) ----------------
__global__ void ln_normalize_vec4(const float* __restrict__ x,
                                  float* __restrict__ out,
                                  const float* __restrict__ mean,
                                  const float* __restrict__ rstd,
                                  const float* __restrict__ weight,
                                  const float* __restrict__ bias,
                                  int N) {
    const int row = blockIdx.y;
    const float m = mean[row];
    const float r = rstd[row];

    const float4* xv = reinterpret_cast<const float4*>(x + (long long)row * N);
    const float4* wv = reinterpret_cast<const float4*>(weight);
    const float4* bv = reinterpret_cast<const float4*>(bias);
    float4* ov = reinterpret_cast<float4*>(out + (long long)row * N);

    const int n4 = N >> 2;
    const int stride = gridDim.x * blockDim.x;
    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n4; i += stride) {
        const float4 v = xv[i];
        const float4 w = wv[i];
        const float4 b = bv[i];
        float4 o;
        o.x = (v.x - m) * r * w.x + b.x;
        o.y = (v.y - m) * r * w.y + b.y;
        o.z = (v.z - m) * r * w.z + b.z;
        o.w = (v.w - m) * r * w.w + b.w;
        ov[i] = o;
    }
}

// ---------------- Kernel 3: normalize (scalar fallback) ----------------
__global__ void ln_normalize_scalar(const float* __restrict__ x,
                                    float* __restrict__ out,
                                    const float* __restrict__ mean,
                                    const float* __restrict__ rstd,
                                    const float* __restrict__ weight,
                                    const float* __restrict__ bias,
                                    int N) {
    const int row = blockIdx.y;
    const float m = mean[row];
    const float r = rstd[row];
    const float* row_x = x + (long long)row * N;
    float* row_o = out + (long long)row * N;

    const int stride = gridDim.x * blockDim.x;
    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += stride) {
        row_o[i] = (row_x[i] - m) * r * weight[i] + bias[i];
    }
}

// ---------------- Host wrapper ----------------
torch::Tensor layernorm_forward(torch::Tensor x, torch::Tensor weight,
                                torch::Tensor bias, double eps) {
    const c10::cuda::CUDAGuard device_guard(x.device());
    TORCH_CHECK(x.is_cuda() && weight.is_cuda() && bias.is_cuda(),
                "All tensors must be CUDA tensors");

    auto xc = x.contiguous();
    auto wc = weight.contiguous();
    auto bc = bias.contiguous();
    TORCH_CHECK(xc.scalar_type() == at::kFloat &&
                wc.scalar_type() == at::kFloat &&
                bc.scalar_type() == at::kFloat,
                "Only float32 is supported by the custom kernel");

    const int64_t N = wc.numel();
    const int64_t rows = (N > 0) ? (xc.numel() / N) : 0;
    auto out = at::empty_like(xc);
    if (rows == 0 || N == 0) return out;
    TORCH_CHECK(N < (int64_t)1 << 31, "Normalized dim too large");

    auto stream = at::cuda::getCurrentCUDAStream();
    const float* xp = xc.data_ptr<float>();
    const float* wp = wc.data_ptr<float>();
    const float* bp = bc.data_ptr<float>();
    float* op = out.data_ptr<float>();

    const bool vec4 = (N % 4 == 0);

    int splits;
    int64_t chunk;
    if (vec4) {
        splits = (int)std::min<int64_t>(64, std::max<int64_t>(1, N / (LN_THREADS * 4)));
        chunk  = (((N + splits - 1) / splits) + 3) & ~3LL;  // keep 16B alignment
        splits = (int)((N + chunk - 1) / chunk);
    } else {
        splits = (int)std::min<int64_t>(64, std::max<int64_t>(1, N / LN_THREADS));
        chunk  = (N + splits - 1) / splits;
        splits = (int)((N + chunk - 1) / chunk);
    }

    auto partials = at::empty({rows * (int64_t)splits * 2}, xc.options());
    auto mean     = at::empty({rows}, xc.options());
    auto rstd     = at::empty({rows}, xc.options());
    float* pp = partials.data_ptr<float>();
    float* mp = mean.data_ptr<float>();
    float* rp = rstd.data_ptr<float>();

    const int64_t maxY = 65535;
    // Pass 1: partial reductions (chunk rows to respect the grid-y limit).
    for (int64_t r0 = 0; r0 < rows; r0 += maxY) {
        const int rc = (int)std::min<int64_t>(maxY, rows - r0);
        dim3 grid1(splits, rc);
        if (vec4) {
            ln_partial_sums_vec4<<<grid1, LN_THREADS, 0, stream>>>(
                xp + r0 * N, pp + r0 * splits * 2, (int)N, (int)chunk, splits);
        } else {
            ln_partial_sums_scalar<<<grid1, LN_THREADS, 0, stream>>>(
                xp + r0 * N, pp + r0 * splits * 2, (int)N, (int)chunk, splits);
        }
    }

    // Pass 2: per-row mean / rstd.
    ln_final_stats<<<(int)rows, LN_THREADS, 0, stream>>>(
        pp, mp, rp, splits, (int)N, (float)eps);

    // Pass 3: apply normalization with affine transform.
    for (int64_t r0 = 0; r0 < rows; r0 += maxY) {
        const int rc = (int)std::min<int64_t>(maxY, rows - r0);
        if (vec4) {
            const int64_t n4 = N >> 2;
            const int xb = (int)std::min<int64_t>(4096, (n4 + LN_THREADS - 1) / LN_THREADS);
            dim3 grid3(xb, rc);
            ln_normalize_vec4<<<grid3, LN_THREADS, 0, stream>>>(
                xp + r0 * N, op + r0 * N, mp + r0, rp + r0, wp, bp, (int)N);
        } else {
            const int xb = (int)std::min<int64_t>(4096, (N + LN_THREADS - 1) / LN_THREADS);
            dim3 grid3(xb, rc);
            ln_normalize_scalar<<<grid3, LN_THREADS, 0, stream>>>(
                xp + r0 * N, op + r0 * N, mp + r0, rp + r0, wp, bp, (int)N);
        }
    }

    return out;
}
"""

layer_norm_cpp_source = (
    "torch::Tensor layernorm_forward(torch::Tensor x, torch::Tensor weight, "
    "torch::Tensor bias, double eps);"
)

# Compile the inline CUDA LayerNorm kernels
_ln_ext = load_inline(
    name="fused_layer_norm_ext",
    cpp_sources=layer_norm_cpp_source,
    cuda_sources=layer_norm_cuda_source,
    functions=["layernorm_forward"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    LayerNorm model accelerated with custom fused CUDA kernels.
    """

    def __init__(self, normalized_shape: tuple):
        """
        Initializes the LayerNorm layer.

        Args:
            normalized_shape (tuple): Shape of the input tensor to be normalized.
        """
        super(ModelNew, self).__init__()
        self.ln = nn.LayerNorm(normalized_shape=normalized_shape)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Applies Layer Normalization using the custom CUDA kernel.

        Args:
            x (torch.Tensor): Input tensor of shape (*, normalized_shape).

        Returns:
            torch.Tensor: Output tensor with Layer Normalization applied, same shape as input.
        """
        if x.is_cuda and x.dtype == torch.float32:
            return _ln_ext.layernorm_forward(
                x, self.ln.weight, self.ln.bias, float(self.ln.eps)
            )
        # Fallback for CPU tensors or non-float32 dtypes.
        return F.layer_norm(
            x, self.ln.normalized_shape, self.ln.weight, self.ln.bias, self.ln.eps
        )
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 0.996 ms; the PyTorch reference (with TF32 enabled) takes 10.1 ms; speedup 10.141x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| ln_normalize_vec4(float const*, float*, float const*, float const*, float const*, float co | 767.7 | 1 |
| ln_partial_sums_vec4(float const*, float*, int, int, int) | 202.8 | 1 |
| ln_final_stats(float const*, float*, float*, int, int, float) | 3.1 | 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.
