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 6 of 6 for this task. Your previous solution (turn 5) 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 LayerNorm CUDA implementation.
#
# Workload shape: a few rows (16) x a huge normalized dim (4M floats, 16MB/row,
# 256MB total).  Exact LayerNorm needs global row stats before any output, so
# the classic lower bound on DRAM traffic is 2 reads of x + 1 write of the
# output.  This revision adds a *single-pass-DRAM* path:
#
#   ln_coop_vec4 is launched cooperatively (guaranteed co-residency).  Each
#   block owns a contiguous chunk of columns, sized so one row of chunks fits
#   in shared memory chip-wide (~38KB/block, 4 blocks/SM).  For every row:
#     1. block loads its chunk of x once from DRAM into shared memory while
#        accumulating sum/sumsq partials,
#     2. a lightweight atomic grid barrier,
#     3. every block redundantly reduces the few hundred partials -> mean/rstd
#        (no second barrier needed),
#     4. the block normalizes its shared-memory chunk and writes it out.
#
#   x is therefore read from DRAM exactly once.  Weights/bias are re-read per
#   row but stay resident in L2 (x loads and output stores use evict-first
#   hints), so DRAM traffic is read(x) + read(w,b once) + write(out) instead
#   of the previous revision's 2*read(x) + write(out) + read(w,b) -> ~1.4x
#   less traffic.  Partials are double-buffered by row parity so only one
#   barrier per row is required.
#
# A tuned 3-kernel fallback (partial sums -> stats -> normalize) handles
# arbitrary shapes, alignments, dtypes, and GPUs without cooperative launch.

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

#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);
        if (lane == 0) { sh_sum[0] = sum; sh_sumsq[0] = sumsq; }
    }
    __syncthreads();
    sum = sh_sum[0];
    sumsq = sh_sumsq[0];
    __syncthreads();
}

__device__ __forceinline__ float ln_f4_sum(const float4 v) {
    return (v.x + v.y) + (v.z + v.w);
}
__device__ __forceinline__ float ln_f4_sq(const float4 v) {
    return fmaf(v.x, v.x, fmaf(v.y, v.y, fmaf(v.z, v.z, v.w * v.w)));
}

// Sense-safe monotonic grid barrier.  bar[0] = arrival ticket counter,
// bar[1] = generation.  Requires all blocks to be co-resident (cooperative
// launch).  Tickets are never reset, so there is no reset race.
__device__ __forceinline__ void ln_grid_barrier(unsigned int* __restrict__ bar,
                                                int nblocks) {
    __syncthreads();
    if (threadIdx.x == 0) {
        volatile unsigned int* genp = (volatile unsigned int*)&bar[1];
        const unsigned int gen = *genp;
        __threadfence();
        const unsigned int ticket = atomicAdd(&bar[0], 1u);
        if ((ticket + 1u) % (unsigned int)nblocks == 0u) {
            __threadfence();
            atomicAdd(&bar[1], 1u);
        } else {
            while (*genp == gen) {
#if __CUDA_ARCH__ >= 700
                __nanosleep(32);
#endif
            }
            __threadfence();
        }
    }
    __syncthreads();
}

// ---------------- Single-DRAM-pass cooperative kernel ---------------------
__global__ void __launch_bounds__(LN_THREADS, 4)
ln_coop_vec4(const float4* __restrict__ x, float4* __restrict__ out,
             const float4* __restrict__ w, const float4* __restrict__ b,
             float* __restrict__ partials, unsigned int* __restrict__ bar,
             int N4, int rows, int chunk, float nInv, float eps) {
    extern __shared__ float4 sdata[];  // chunk float4
    __shared__ float sh_sum[LN_WARPS], sh_sumsq[LN_WARPS];
    __shared__ float s_mean, s_rstd;

    const int tid     = threadIdx.x;
    const int nt      = blockDim.x;
    const int bid     = blockIdx.x;
    const int nblocks = gridDim.x;
    const int c0      = bid * chunk;
    const int cnt     = min(chunk, N4 - c0);
    const int pstride = 2 * nblocks;  // partials per parity buffer

    for (int r = 0; r < rows; ++r) {
        const size_t rowoff = (size_t)r * N4;
        const float4* xr = x + rowoff + c0;

        // Phase 1: load chunk -> shared, accumulate partials.
        float s0 = 0.f, q0 = 0.f, s1 = 0.f, q1 = 0.f;
        float s2 = 0.f, q2 = 0.f, s3 = 0.f, q3 = 0.f;
        int i = tid;
        for (; i + 3 * nt < cnt; i += 4 * nt) {
            const float4 v0 = __ldcs(xr + i);
            const float4 v1 = __ldcs(xr + i + nt);
            const float4 v2 = __ldcs(xr + i + 2 * nt);
            const float4 v3 = __ldcs(xr + i + 3 * nt);
            sdata[i]          = v0;
            sdata[i + nt]     = v1;
            sdata[i + 2 * nt] = v2;
            sdata[i + 3 * nt] = v3;
            s0 += ln_f4_sum(v0); q0 += ln_f4_sq(v0);
            s1 += ln_f4_sum(v1); q1 += ln_f4_sq(v1);
            s2 += ln_f4_sum(v2); q2 += ln_f4_sq(v2);
            s3 += ln_f4_sum(v3); q3 += ln_f4_sq(v3);
        }
        for (; i < cnt; i += nt) {
            const float4 v = __ldcs(xr + i);
            sdata[i] = v;
            s0 += ln_f4_sum(v); q0 += ln_f4_sq(v);
        }
        float sum = (s0 + s1) + (s2 + s3);
        float ssq = (q0 + q1) + (q2 + q3);
        ln_block_reduce(sum, ssq, sh_sum, sh_sumsq);

        float* pbuf = partials + (r & 1) * pstride;
        if (tid == 0) {
            pbuf[bid]            = sum;
            pbuf[nblocks + bid]  = ssq;
        }
        ln_grid_barrier(bar, nblocks);

        // Phase 2: every block redundantly reduces the partials.
        sum = 0.f; ssq = 0.f;
        for (int j = tid; j < nblocks; j += nt) {
            sum += pbuf[j];
            ssq += pbuf[nblocks + j];
        }
        ln_block_reduce(sum, ssq, sh_sum, sh_sumsq);
        if (tid == 0) {
            const float m = sum * nInv;
            float var = ssq * nInv - m * m;
            var = var < 0.f ? 0.f : var;
            s_mean = m;
            s_rstd = rsqrtf(var + eps);
        }
        __syncthreads();
        const float m = s_mean;
        const float t = s_rstd;

        // Phase 3: normalize the shared chunk and write it out.
        float4* orow = out + rowoff + c0;
        const float4* wc = w + c0;
        const float4* bc = b + c0;
        for (i = tid; i + nt < cnt; i += 2 * nt) {
            const float4 v0 = sdata[i];
            const float4 v1 = sdata[i + nt];
            const float4 w0 = wc[i];
            const float4 w1 = wc[i + nt];
            const float4 b0 = bc[i];
            const float4 b1 = bc[i + nt];
            float4 o0, o1;
            o0.x = (v0.x - m) * t * w0.x + b0.x;
            o0.y = (v0.y - m) * t * w0.y + b0.y;
            o0.z = (v0.z - m) * t * w0.z + b0.z;
            o0.w = (v0.w - m) * t * w0.w + b0.w;
            o1.x = (v1.x - m) * t * w1.x + b1.x;
            o1.y = (v1.y - m) * t * w1.y + b1.y;
            o1.z = (v1.z - m) * t * w1.z + b1.z;
            o1.w = (v1.w - m) * t * w1.w + b1.w;
            __stcs(orow + i, o0);
            __stcs(orow + i + nt, o1);
        }
        for (; i < cnt; i += nt) {
            const float4 v = sdata[i];
            const float4 wv = wc[i];
            const float4 bv = bc[i];
            float4 o;
            o.x = (v.x - m) * t * wv.x + bv.x;
            o.y = (v.y - m) * t * wv.y + bv.y;
            o.z = (v.z - m) * t * wv.z + bv.z;
            o.w = (v.w - m) * t * wv.w + bv.w;
            __stcs(orow + i, o);
        }
    }
}

// ---------------- Fallback pass 1: partial sums ----------------
__global__ void ln_partial_sums_vec4(const float* __restrict__ x,
                                     float* __restrict__ ps,
                                     float* __restrict__ pq,
                                     int N, int splits) {
    const int row = blockIdx.y;
    const int n4 = N >> 2;
    const float4* xv = reinterpret_cast<const float4*>(x + (long long)row * N);
    const int gstride = gridDim.x * blockDim.x;
    const int tid0 = blockIdx.x * blockDim.x + threadIdx.x;

    float s[4], q[4];
    #pragma unroll
    for (int k = 0; k < 4; ++k) { s[k] = 0.f; q[k] = 0.f; }
    int i = tid0;
    for (; i + 3 * gstride < n4; i += 4 * gstride) {
        #pragma unroll
        for (int k = 0; k < 4; ++k) {
            const float4 v = __ldcs(xv + i + k * gstride);
            s[k] += ln_f4_sum(v);
            q[k] += ln_f4_sq(v);
        }
    }
    for (; i < n4; i += gstride) {
        const float4 v = __ldcs(xv + i);
        s[0] += ln_f4_sum(v);
        q[0] += ln_f4_sq(v);
    }
    float sum = (s[0] + s[1]) + (s[2] + s[3]);
    float ssq = (q[0] + q[1]) + (q[2] + q[3]);
    __shared__ float sh_sum[LN_WARPS], sh_sumsq[LN_WARPS];
    ln_block_reduce(sum, ssq, sh_sum, sh_sumsq);
    if (threadIdx.x == 0) {
        ps[(long long)row * splits + blockIdx.x] = sum;
        pq[(long long)row * splits + blockIdx.x] = ssq;
    }
}

__global__ void ln_partial_sums_scalar(const float* __restrict__ x,
                                       float* __restrict__ ps,
                                       float* __restrict__ pq,
                                       int N, int splits) {
    const int row = blockIdx.y;
    const float* row_ptr = x + (long long)row * N;
    const int gstride = gridDim.x * blockDim.x;
    float s0 = 0.f, q0 = 0.f, s1 = 0.f, q1 = 0.f;
    float s2 = 0.f, q2 = 0.f, s3 = 0.f, q3 = 0.f;
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    for (; i + 3 * gstride < N; i += 4 * gstride) {
        const float v0 = row_ptr[i];
        const float v1 = row_ptr[i + gstride];
        const float v2 = row_ptr[i + 2 * gstride];
        const float v3 = row_ptr[i + 3 * gstride];
        s0 += v0; q0 += v0 * v0;
        s1 += v1; q1 += v1 * v1;
        s2 += v2; q2 += v2 * v2;
        s3 += v3; q3 += v3 * v3;
    }
    for (; i < N; i += gstride) {
        const float v = row_ptr[i];
        s0 += v; q0 += v * v;
    }
    float sum = (s0 + s1) + (s2 + s3);
    float ssq = (q0 + q1) + (q2 + q3);
    __shared__ float sh_sum[LN_WARPS], sh_sumsq[LN_WARPS];
    ln_block_reduce(sum, ssq, sh_sum, sh_sumsq);
    if (threadIdx.x == 0) {
        ps[(long long)row * splits + blockIdx.x] = sum;
        pq[(long long)row * splits + blockIdx.x] = ssq;
    }
}

// ---------------- Fallback pass 2: final per-row statistics ----------------
__global__ void ln_final_stats(const float* __restrict__ ps,
                               const float* __restrict__ pq,
                               float* __restrict__ mean,
                               float* __restrict__ rstd,
                               int splits, int N, float eps) {
    const int row = blockIdx.x;
    float sum = 0.f, ssq = 0.f;
    const long long base = (long long)row * splits;
    for (int i = threadIdx.x; i < splits; i += blockDim.x) {
        sum += ps[base + i];
        ssq += pq[base + i];
    }
    __shared__ float sh_sum[LN_WARPS], sh_sumsq[LN_WARPS];
    ln_block_reduce(sum, ssq, sh_sum, sh_sumsq);
    if (threadIdx.x == 0) {
        const float m = sum / (float)N;
        float var = ssq / (float)N - m * m;
        var = var < 0.f ? 0.f : var;
        mean[row] = m;
        rstd[row] = rsqrtf(var + eps);
    }
}

// ---------------- Fallback pass 3: normalize ----------------
__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;
    }
}

__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");
    TORCH_CHECK(rows < (int64_t)1 << 31, "Too many rows");

    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) &&
        ((reinterpret_cast<uintptr_t>(xp) & 15) == 0) &&
        ((reinterpret_cast<uintptr_t>(op) & 15) == 0) &&
        ((reinterpret_cast<uintptr_t>(wp) & 15) == 0) &&
        ((reinterpret_cast<uintptr_t>(bp) & 15) == 0);

    // ---------- Fast path: single-DRAM-pass cooperative kernel ----------
    if (vec4 && rows <= 4096 && N >= (1 << 18)) {
        static int coop_ok = -1;
        static int num_sms = 0;
        if (coop_ok < 0) {
            int dev = 0, attr = 0, sms = 0;
            cudaGetDevice(&dev);
            cudaDeviceGetAttribute(&attr, cudaDevAttrCooperativeLaunch, dev);
            cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev);
            coop_ok = attr ? 1 : 0;
            num_sms = sms;
        }
        if (coop_ok) {
            const int64_t N4 = N >> 2;
            int grid = 0, chunk = 0;
            size_t shbytes = 0;
            for (int t = 4; t >= 1 && grid == 0; --t) {
                const int g = num_sms * t;
                const int c = (int)((N4 + g - 1) / g);
                const size_t sh = (size_t)c * sizeof(float4) + 64;
                if (sh > 160 * 1024) continue;
                if (sh > 48 * 1024) {
                    cudaFuncSetAttribute((const void*)ln_coop_vec4,
                                         cudaFuncAttributeMaxDynamicSharedMemorySize,
                                         (int)sh);
                }
                int occ = 0;
                cudaOccupancyMaxActiveBlocksPerMultiprocessor(
                    &occ, (const void*)ln_coop_vec4, LN_THREADS, sh);
                if (occ >= t) { grid = g; chunk = c; shbytes = sh; }
            }
            if (grid > 0 && (int64_t)grid * chunk >= N4) {
                auto scratch = at::empty({4 * grid + 2},
                                         xc.options().dtype(at::kInt));
                unsigned int* bar = reinterpret_cast<unsigned int*>(
                    scratch.data_ptr<int>());
                float* partials = reinterpret_cast<float*>(bar + 2);
                cudaMemsetAsync(bar, 0, 2 * sizeof(unsigned int), stream);

                const float nInv = 1.0f / (float)N;
                int N4i = (int)N4, rowsi = (int)rows, chunki = chunk;
                float nInvf = nInv, epsf = (float)eps;
                const float4* x4 = reinterpret_cast<const float4*>(xp);
                float4* o4 = reinterpret_cast<float4*>(op);
                const float4* w4 = reinterpret_cast<const float4*>(wp);
                const float4* b4 = reinterpret_cast<const float4*>(bp);
                void* args[] = {(void*)&x4, (void*)&o4, (void*)&w4, (void*)&b4,
                                (void*)&partials, (void*)&bar, (void*)&N4i,
                                (void*)&rowsi, (void*)&chunki, (void*)&nInvf,
                                (void*)&epsf};
                const cudaError_t err = cudaLaunchCooperativeKernel(
                    (const void*)ln_coop_vec4, dim3(grid), dim3(LN_THREADS),
                    args, shbytes, stream.stream());
                TORCH_CHECK(err == cudaSuccess,
                            "cooperative layernorm launch failed: ",
                            cudaGetErrorString(err));
                TORCH_CHECK(cudaGetLastError() == cudaSuccess,
                            "cooperative layernorm kernel failed");
                return out;
            }
        }
    }

    // ---------- Fallback: 3-kernel path ----------
    int splits;
    if (vec4) {
        const int64_t n4 = N >> 2;
        splits = (int)std::max<int64_t>(
            32, std::min<int64_t>(2048, n4 / (LN_THREADS * 8)));
    } else {
        splits = (int)std::max<int64_t>(
            32, std::min<int64_t>(2048, N / (LN_THREADS * 4)));
    }

    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* ps = partials.data_ptr<float>();
    float* pq = ps + rows * (int64_t)splits;
    float* mp = mean.data_ptr<float>();
    float* rp = rstd.data_ptr<float>();

    const int64_t maxY = 65535;
    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, ps + r0 * splits, pq + r0 * splits, (int)N, splits);
        } else {
            ln_partial_sums_scalar<<<grid1, LN_THREADS, 0, stream>>>(
                xp + r0 * N, ps + r0 * splits, pq + r0 * splits, (int)N, splits);
        }
    }

    ln_final_stats<<<(int)rows, LN_THREADS, 0, stream>>>(
        ps, pq, mp, rp, splits, (int)N, (float)eps);

    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_v4",
    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.97 ms; the PyTorch reference (with TF32 enabled) takes 10.1 ms; speedup 10.412x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| ln_coop_vec4(float4 const*, float4*, float4 const*, float4 const*, float*, unsigned int*,  | 944.5 | 1 |
| Memset (Device) | 1.0 | 1 |

The fastest correct solution so far (15.757x speedup) is:
```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.
#
# The workload is a small number of very long rows (e.g. 16 rows x 4M floats),
# so the whole computation is DRAM-bandwidth bound.  The previous revision used
# three kernels (partial sums -> stats -> normalize) which move
# read(x) + read(x) + read(w,b) + write(out) bytes.  This revision keeps the
# same overall structure but tunes the bandwidth-critical kernels:
#
#   * partial-sums kernel: grid-stride column ownership with 8 independent
#     float4 accumulators (was: one 4KB chunk per block), giving a much larger
#     memory-level parallelism per thread and better DRAM utilization.
#   * normalize kernel: each thread owns a column and loops over all rows, so
#     weight/bias are fetched exactly once.  The row loop is unrolled by 8
#     (was 4) with software-pipelined load batches to keep more loads in
#     flight, and rows are visited in reverse so the tail of the reduction
#     pass (still resident in L2) is consumed first.
#   * stats kernel: fused reduction of both partial arrays in one pass.
#
# Fallback kernels handle arbitrary shapes / alignments / dtypes.

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

#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, grid-stride, 8 accumulators ------
__global__ void ln_partial_sums_vec4(const float* __restrict__ x,
                                     float* __restrict__ ps,
                                     float* __restrict__ pq,
                                     int N, int splits) {
    const int row   = blockIdx.y;
    const int n4    = N >> 2;
    const float4* xv = reinterpret_cast<const float4*>(x + (long long)row * N);

    const int gstride = gridDim.x * blockDim.x;
    const int tid0    = blockIdx.x * blockDim.x + threadIdx.x;

    float s[8], q[8];
    #pragma unroll
    for (int k = 0; k < 8; ++k) { s[k] = 0.f; q[k] = 0.f; }

    int i = tid0;
    const int stride8 = gstride * 8;
    for (; i + 7 * gstride < n4; i += stride8) {
        #pragma unroll
        for (int k = 0; k < 8; ++k) {
            const float4 v = xv[i + k * gstride];
            s[k] += v.x + v.y;
            s[k] += v.z + v.w;
            q[k] += v.x * v.x + v.y * v.y;
            q[k] += v.z * v.z + v.w * v.w;
        }
    }
    for (; i < n4; i += gstride) {
        const float4 v = xv[i];
        s[0] += v.x + v.y;
        s[0] += v.z + v.w;
        q[0] += v.x * v.x + v.y * v.y;
        q[0] += v.z * v.z + v.w * v.w;
    }

    float sum = 0.f, sumsq = 0.f;
    #pragma unroll
    for (int k = 0; k < 8; ++k) { sum += s[k]; sumsq += q[k]; }

    __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) {
        ps[(long long)row * splits + blockIdx.x] = sum;
        pq[(long long)row * splits + blockIdx.x] = sumsq;
    }
}

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

    const int gstride = gridDim.x * blockDim.x;
    float s0 = 0.f, q0 = 0.f, s1 = 0.f, q1 = 0.f;
    float s2 = 0.f, q2 = 0.f, s3 = 0.f, q3 = 0.f;

    int i = blockIdx.x * blockDim.x + threadIdx.x;
    for (; i + 3 * gstride < N; i += 4 * gstride) {
        const float v0 = row_ptr[i];
        const float v1 = row_ptr[i + gstride];
        const float v2 = row_ptr[i + 2 * gstride];
        const float v3 = row_ptr[i + 3 * gstride];
        s0 += v0; q0 += v0 * v0;
        s1 += v1; q1 += v1 * v1;
        s2 += v2; q2 += v2 * v2;
        s3 += v3; q3 += v3 * v3;
    }
    for (; i < N; i += gstride) {
        const float v = row_ptr[i];
        s0 += v; q0 += v * v;
    }
    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) {
        ps[(long long)row * splits + blockIdx.x] = sum;
        pq[(long long)row * splits + blockIdx.x] = sumsq;
    }
}

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

    __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 3a: normalize, thread owns a column and loops over
// all rows (weight/bias loaded once into registers), unroll 8 with
// software-pipelined load batches. -----------------------------------------
__global__ void ln_apply_rows_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, int rows) {
    const int n4 = N >> 2;
    const int c = blockIdx.x * blockDim.x + threadIdx.x;
    if (c >= n4) return;

    const float4 w = reinterpret_cast<const float4*>(weight)[c];
    const float4 b = reinterpret_cast<const float4*>(bias)[c];
    const float4* xv = reinterpret_cast<const float4*>(x) + c;
    float4* ov = reinterpret_cast<float4*>(out) + c;

    int r = rows;
    for (; r >= 8; r -= 8) {
        const long long o0 = (long long)(r - 1) * n4;
        const long long o1 = (long long)(r - 2) * n4;
        const long long o2 = (long long)(r - 3) * n4;
        const long long o3 = (long long)(r - 4) * n4;
        const long long o4 = (long long)(r - 5) * n4;
        const long long o5 = (long long)(r - 6) * n4;
        const long long o6 = (long long)(r - 7) * n4;
        const long long o7 = (long long)(r - 8) * n4;
        const float4 v0 = __ldcs(xv + o0);
        const float4 v1 = __ldcs(xv + o1);
        const float4 v2 = __ldcs(xv + o2);
        const float4 v3 = __ldcs(xv + o3);
        const float4 v4 = __ldcs(xv + o4);
        const float4 v5 = __ldcs(xv + o5);
        const float4 v6 = __ldcs(xv + o6);
        const float4 v7 = __ldcs(xv + o7);
        const float m0 = mean[r - 1], t0 = rstd[r - 1];
        const float m1 = mean[r - 2], t1 = rstd[r - 2];
        const float m2 = mean[r - 3], t2 = rstd[r - 3];
        const float m3 = mean[r - 4], t3 = rstd[r - 4];
        const float m4 = mean[r - 5], t4 = rstd[r - 5];
        const float m5 = mean[r - 6], t5 = rstd[r - 6];
        const float m6 = mean[r - 7], t6 = rstd[r - 7];
        const float m7 = mean[r - 8], t7 = rstd[r - 8];
        float4 u;
        u.x = (v0.x - m0) * t0 * w.x + b.x;
        u.y = (v0.y - m0) * t0 * w.y + b.y;
        u.z = (v0.z - m0) * t0 * w.z + b.z;
        u.w = (v0.w - m0) * t0 * w.w + b.w;
        __stcs(ov + o0, u);
        u.x = (v1.x - m1) * t1 * w.x + b.x;
        u.y = (v1.y - m1) * t1 * w.y + b.y;
        u.z = (v1.z - m1) * t1 * w.z + b.z;
        u.w = (v1.w - m1) * t1 * w.w + b.w;
        __stcs(ov + o1, u);
        u.x = (v2.x - m2) * t2 * w.x + b.x;
        u.y = (v2.y - m2) * t2 * w.y + b.y;
        u.z = (v2.z - m2) * t2 * w.z + b.z;
        u.w = (v2.w - m2) * t2 * w.w + b.w;
        __stcs(ov + o2, u);
        u.x = (v3.x - m3) * t3 * w.x + b.x;
        u.y = (v3.y - m3) * t3 * w.y + b.y;
        u.z = (v3.z - m3) * t3 * w.z + b.z;
        u.w = (v3.w - m3) * t3 * w.w + b.w;
        __stcs(ov + o3, u);
        u.x = (v4.x - m4) * t4 * w.x + b.x;
        u.y = (v4.y - m4) * t4 * w.y + b.y;
        u.z = (v4.z - m4) * t4 * w.z + b.z;
        u.w = (v4.w - m4) * t4 * w.w + b.w;
        __stcs(ov + o4, u);
        u.x = (v5.x - m5) * t5 * w.x + b.x;
        u.y = (v5.y - m5) * t5 * w.y + b.y;
        u.z = (v5.z - m5) * t5 * w.z + b.z;
        u.w = (v5.w - m5) * t5 * w.w + b.w;
        __stcs(ov + o5, u);
        u.x = (v6.x - m6) * t6 * w.x + b.x;
        u.y = (v6.y - m6) * t6 * w.y + b.y;
        u.z = (v6.z - m6) * t6 * w.z + b.z;
        u.w = (v6.w - m6) * t6 * w.w + b.w;
        __stcs(ov + o6, u);
        u.x = (v7.x - m7) * t7 * w.x + b.x;
        u.y = (v7.y - m7) * t7 * w.y + b.y;
        u.z = (v7.z - m7) * t7 * w.z + b.z;
        u.w = (v7.w - m7) * t7 * w.w + b.w;
        __stcs(ov + o7, u);
    }
    for (; r > 0; --r) {
        const long long o = (long long)(r - 1) * n4;
        const float4 v = __ldcs(xv + o);
        const float m = mean[r - 1], t = rstd[r - 1];
        float4 u;
        u.x = (v.x - m) * t * w.x + b.x;
        u.y = (v.y - m) * t * w.y + b.y;
        u.z = (v.z - m) * t * w.z + b.z;
        u.w = (v.w - m) * t * w.w + b.w;
        __stcs(ov + o, u);
    }
}

__global__ void ln_apply_rows_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, int rows) {
    const int c = blockIdx.x * blockDim.x + threadIdx.x;
    if (c >= N) return;

    const float w = weight[c];
    const float b = bias[c];
    const float* xp = x + c;
    float* op = out + c;

    int r = rows;
    for (; r >= 4; r -= 4) {
        const long long o0 = (long long)(r - 1) * N;
        const long long o1 = (long long)(r - 2) * N;
        const long long o2 = (long long)(r - 3) * N;
        const long long o3 = (long long)(r - 4) * N;
        const float v0 = __ldcs(xp + o0);
        const float v1 = __ldcs(xp + o1);
        const float v2 = __ldcs(xp + o2);
        const float v3 = __ldcs(xp + o3);
        __stcs(op + o0, (v0 - mean[r - 1]) * rstd[r - 1] * w + b);
        __stcs(op + o1, (v1 - mean[r - 2]) * rstd[r - 2] * w + b);
        __stcs(op + o2, (v2 - mean[r - 3]) * rstd[r - 3] * w + b);
        __stcs(op + o3, (v3 - mean[r - 4]) * rstd[r - 4] * w + b);
    }
    for (; r > 0; --r) {
        const long long o = (long long)(r - 1) * N;
        __stcs(op + o, (__ldcs(xp + o) - mean[r - 1]) * rstd[r - 1] * w + b);
    }
}

// ------------- Kernel 3b: fallback 2D 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 3b: fallback 2D normalize (scalar) ---------------
__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");
    TORCH_CHECK(rows < (int64_t)1 << 31, "Too many rows");

    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) &&
        ((reinterpret_cast<uintptr_t>(xp) & 15) == 0) &&
        ((reinterpret_cast<uintptr_t>(op) & 15) == 0) &&
        ((reinterpret_cast<uintptr_t>(wp) & 15) == 0) &&
        ((reinterpret_cast<uintptr_t>(bp) & 15) == 0);

    // Split count for the reduction: enough blocks to fill the device, but
    // few enough that per-block reduction tails stay negligible.
    int splits;
    if (vec4) {
        const int64_t n4 = N >> 2;
        splits = (int)std::max<int64_t>(
            32, std::min<int64_t>(2048, n4 / (LN_THREADS * 8)));
    } else {
        splits = (int)std::max<int64_t>(
            32, std::min<int64_t>(2048, N / (LN_THREADS * 4)));
    }

    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* ps = partials.data_ptr<float>();
    float* pq = ps + rows * (int64_t)splits;
    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, ps + r0 * splits, pq + r0 * splits, (int)N, splits);
        } else {
            ln_partial_sums_scalar<<<grid1, LN_THREADS, 0, stream>>>(
                xp + r0 * N, ps + r0 * splits, pq + r0 * splits, (int)N, splits);
        }
    }

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

    // Pass 3: apply normalization with affine transform.
    const int64_t units = vec4 ? (N >> 2) : N;
    const int64_t col_blocks = (units + LN_THREADS - 1) / LN_THREADS;

    if (col_blocks >= 400 && rows <= 32768) {
        // Preferred: each thread owns a column and loops over all rows, so
        // weight/bias are fetched exactly once.
        dim3 grid3((unsigned int)col_blocks);
        if (vec4) {
            ln_apply_rows_vec4<<<grid3, LN_THREADS, 0, stream>>>(
                xp, op, mp, rp, wp, bp, (int)N, (int)rows);
        } else {
            ln_apply_rows_scalar<<<grid3, LN_THREADS, 0, stream>>>(
                xp, op, mp, rp, wp, bp, (int)N, (int)rows);
        }
    } else {
        // Fallback for narrow normalized dims or extremely many rows.
        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_v3",
    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
        )
```

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.
