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 a matrix multiplication (C = A * B) where A and B are lower triangular matrices. 
    """
    def __init__(self):
        super(Model, self).__init__()
    
    def forward(self, A, B):
        """
        Performs matrix multiplication of lower triangular matrices A and B.

        Args:
            A (torch.Tensor): Lower triangular matrix of shape (N, N).
            B (torch.Tensor): Lower triangular matrix of shape (N, N).

        Returns:
            torch.Tensor: The result of matrix multiplication C of shape (N, N).
        """
        return torch.tril(torch.matmul(A, B))

M = 4096

def get_inputs():
    A = torch.rand(M, M)
    B = torch.rand(M, M)
    A = torch.tril(A)
    B = torch.tril(B)
    return [A, B]

def get_init_inputs():
    return []  # No special initialization inputs needed
    ```
    
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 5 of 6 for this task. Your previous solution (turn 4) 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
from torch.utils.cpp_extension import load_inline

# Fused lower-triangular matmul (C = tril(A @ B)) using TF32 tensor cores.
#
# Optimizations vs. the previous version:
#  * Block tile 128x128, but now 4 warps with a 64x64 warp tile. This doubles
#    the MMA:instruction ratio (16 MMAs per 8 fragment loads per k-step), so
#    the tensor cores become the bottleneck instead of the instruction issue
#    path (the old 64x32 warp tile was issue/latency bound at ~33% of peak).
#  * Bank-conflict-free shared-memory layouts (LDSA=36, LDSB=132 words give a
#    4-word row-stride modulo 32 banks -> conflict-free ldmatrix for both A
#    and B fragments while keeping 16B alignment for cp.async).
#  * cp.async double-buffered global->shared pipeline (2 stages, 70.7KB),
#    2 thread blocks per SM on A100 (141KB smem, ~190 regs/thread).
#  * Block-triangular work skipping: C tile (t, s) only accumulates k-tiles
#    s..t (~6x FLOP reduction vs. dense GEMM); strictly-upper tiles are
#    written as zeros directly; heavy rows are scheduled first so the tail is
#    made of the lightest blocks.
_tril_mm_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>
#include <cuda_pipeline.h>
#include <mma.h>

using namespace nvcuda;

#define BM 128
#define BN 128
#define BK 32
#define LDSA 36            // padded strides: conflict-free ldmatrix, 16B aligned
#define LDSB 132
#define NTHREADS 128       // 4 warps, each with a 64x64 warp tile
#define STAGE_A (BM * LDSA)
#define STAGE_B (BK * LDSB)
#define SMEM_FLOATS (2 * (STAGE_A + STAGE_B))

__global__ void __launch_bounds__(NTHREADS, 2)
tril_matmul_tf32_v2_kernel(const float* __restrict__ A,
                           const float* __restrict__ B,
                           float* __restrict__ C,
                           const int N)
{
#if !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 800)
    const int s = blockIdx.x;                  // column tile of C
    const int t = gridDim.y - 1 - blockIdx.y;  // row tile of C (heavy rows first)
    const int tid = threadIdx.x;
    float* Cg = C + (size_t)t * BM * N + (size_t)s * BN;

    if (s > t) {
        // Strictly upper-triangular output tile: exactly zero.
        #pragma unroll
        for (int i = 0; i < (BM * BN / 4) / NTHREADS; ++i) {
            const int idx = tid + i * NTHREADS;
            const int r = idx >> 5;
            const int c4 = (idx & 31) * 4;
            *reinterpret_cast<float4*>(Cg + (size_t)r * N + c4) =
                make_float4(0.f, 0.f, 0.f, 0.f);
        }
        return;
    }

    extern __shared__ float smem[];
    float* As[2] = {smem, smem + STAGE_A};
    float* Bs[2] = {smem + 2 * STAGE_A, smem + 2 * STAGE_A + STAGE_B};

    const int warpId = tid >> 5;
    const int warpM = warpId >> 1;   // 0..1
    const int warpN = warpId & 1;    // 0..1

    const float* Ag = A + (size_t)t * BM * N;   // A tile rows
    const float* Bg = B + (size_t)s * BN;       // B tile cols

    const int kStart = s * BN;                  // first contributing k element
    const int numKt = (t - s + 1) * (BN / BK);  // k-tiles: s..t (128-tile space)

    // Global -> shared loader coordinates (16B cp.async chunks).
    const int aRow = tid >> 3;        // rows aRow + i*16 cover 0..127
    const int aC4  = (tid & 7) * 4;   // 8 chunks per 32-col row
    const int bRow = tid >> 5;        // rows bRow + i*4 cover 0..31
    const int bC4  = (tid & 31) * 4;  // 32 chunks per 128-col row

    auto issue_tile = [&](int kt, int buf) {
        const int k0 = kStart + kt * BK;
        #pragma unroll
        for (int i = 0; i < 8; ++i) {
            const int row = aRow + i * 16;
            __pipeline_memcpy_async(&As[buf][row * LDSA + aC4],
                                    Ag + (size_t)row * N + k0 + aC4, 16);
        }
        #pragma unroll
        for (int i = 0; i < 8; ++i) {
            const int row = bRow + i * 4;
            __pipeline_memcpy_async(&Bs[buf][row * LDSB + bC4],
                                    Bg + (size_t)(k0 + row) * N + bC4, 16);
        }
    };

    wmma::fragment<wmma::accumulator, 16, 16, 8, float> acc[4][4];
    #pragma unroll
    for (int i = 0; i < 4; ++i)
        #pragma unroll
        for (int j = 0; j < 4; ++j)
            wmma::fill_fragment(acc[i][j], 0.0f);

    issue_tile(0, 0);
    __pipeline_commit();

    for (int kt = 0; kt < numKt; ++kt) {
        if (kt + 1 < numKt) issue_tile(kt + 1, (kt + 1) & 1);
        __pipeline_commit();
        __pipeline_wait_prior(1);
        __syncthreads();

        const float* Asb = As[kt & 1];
        const float* Bsb = Bs[kt & 1];

        #pragma unroll
        for (int kk = 0; kk < BK; kk += 8) {
            wmma::fragment<wmma::matrix_a, 16, 16, 8,
                           wmma::precision::tf32, wmma::row_major> af[4];
            wmma::fragment<wmma::matrix_b, 16, 16, 8,
                           wmma::precision::tf32, wmma::row_major> bf[4];
            #pragma unroll
            for (int i = 0; i < 4; ++i)
                wmma::load_matrix_sync(af[i], &Asb[(warpM * 64 + i * 16) * LDSA + kk], LDSA);
            #pragma unroll
            for (int j = 0; j < 4; ++j)
                wmma::load_matrix_sync(bf[j], &Bsb[kk * LDSB + warpN * 64 + j * 16], LDSB);
            #pragma unroll
            for (int i = 0; i < 4; ++i)
                #pragma unroll
                for (int j = 0; j < 4; ++j)
                    wmma::mma_sync(acc[i][j], af[i], bf[j], acc[i][j]);
        }
        __syncthreads();
    }

    // Epilogue: write the full 128x128 tile. Upper entries of diagonal tiles
    // are exact zeros (all their products are exactly 0), matching tril.
    #pragma unroll
    for (int i = 0; i < 4; ++i)
        #pragma unroll
        for (int j = 0; j < 4; ++j)
            wmma::store_matrix_sync(
                &Cg[(size_t)(warpM * 64 + i * 16) * N + warpN * 64 + j * 16],
                acc[i][j], N, wmma::mem_row_major);
#else
    // Portable fallback (never used; the host wrapper guards capability >= 8).
    const int s = blockIdx.x;
    const int t = gridDim.y - 1 - blockIdx.y;
    const int tid = threadIdx.x;
    float* Cg = C + (size_t)t * BM * N + (size_t)s * BN;
    for (int idx = tid; idx < BM * BN; idx += NTHREADS) {
        const int r = idx / BN, c = idx % BN;
        const int gr = t * BM + r, gc = s * BN + c;
        float v = 0.f;
        if (s <= t && gc <= gr) {
            for (int k = gc; k <= gr; ++k) v += A[(size_t)gr * N + k] * B[(size_t)k * N + gc];
        }
        Cg[(size_t)r * N + c] = v;
    }
#endif
}

torch::Tensor tril_matmul(torch::Tensor A, torch::Tensor B) {
    const int N = (int)A.size(0);
    auto C = torch::empty({N, N}, A.options());
    const int NT = N / BM;
    dim3 grid(NT, NT);
    dim3 block(NTHREADS);
    static const int smemBytes = (int)(SMEM_FLOATS * sizeof(float));
    static bool configured = []() {
        cudaFuncSetAttribute(tril_matmul_tf32_v2_kernel,
                             cudaFuncAttributeMaxDynamicSharedMemorySize, smemBytes);
        cudaFuncSetAttribute(tril_matmul_tf32_v2_kernel,
                             cudaFuncAttributePreferredSharedMemoryCarveout, 100);
        return true;
    }();
    (void)configured;
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    tril_matmul_tf32_v2_kernel<<<grid, block, smemBytes, stream>>>(
        A.data_ptr<float>(), B.data_ptr<float>(), C.data_ptr<float>(), N);
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return C;
}
"""

_tril_mm_cpp_src = "torch::Tensor tril_matmul(torch::Tensor A, torch::Tensor B);"

_tril_mm = load_inline(
    name="tril_matmul_tf32_v2_ext",
    cpp_sources=_tril_mm_cpp_src,
    cuda_sources=_tril_mm_cuda_src,
    functions=["tril_matmul"],
    extra_cuda_cflags=["-O3"],
    verbose=False,
)


class ModelNew(nn.Module):
    """
    Optimized model: fused lower-triangular matmul via a custom block-triangular
    TF32 tensor-core CUDA GEMM kernel. Falls back to the reference PyTorch ops
    for any input the kernel does not support.
    """
    def __init__(self):
        super(ModelNew, self).__init__()

    def forward(self, A, B):
        if (
            A.is_cuda and B.is_cuda
            and A.dtype == torch.float32 and B.dtype == torch.float32
            and A.dim() == 2 and B.dim() == 2
            and A.shape == B.shape
            and A.size(0) == A.size(1)
            and A.size(0) > 0
            and A.size(0) % 128 == 0
            and A.is_contiguous() and B.is_contiguous()
            and torch.cuda.get_device_capability(A.device)[0] >= 8
        ):
            return _tril_mm.tril_matmul(A, B)
        return torch.tril(torch.matmul(A, B))
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 0.544 ms; the PyTorch reference (with TF32 enabled) takes 1.12 ms; speedup 2.059x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| tril_matmul_tf32_v2_kernel(float const*, float const*, float*, int) | 507.8 | 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.
