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 4 of 6 for this task. Your previous solution (turn 3) 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

# Custom CUDA extension implementing blocked lower-triangular matmul.
#
# For lower-triangular A, B the product C = tril(A @ B) has the block sum
#     C[i, j] = sum_{k=j}^{i} A[i, k] @ B[k, j]
# so only block-column panels need to be computed:
#     C[k:, k:k2]  = A[k:, k:k2] @ B[k:k2, k:k2]     (beta = 0, first touch)
#     C[k:, :k]   += A[k:, k:k2] @ B[k:k2, :k]       (beta = 1, accumulate)
# This performs ~1.44 * N^3/3 FLOPs instead of 2 * N^3 (~4.2x fewer) while
# still using cuBLAS (TF32 tensor cores) for every block. Because the
# first-touch GEMMs use beta = 0, the output can be allocated with
# torch::empty (no full N^2 memset), and a small custom CUDA kernel zeroes
# only the strict upper triangle afterwards.
_CUDA_SRC = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda_runtime.h>
#include <algorithm>

__global__ void zero_upper_kernel(float* __restrict__ c, const long long n) {
    const long long col = (long long)blockIdx.x * blockDim.x + threadIdx.x;
    if (col >= n) return;
    for (long long row = blockIdx.y; row < col; row += gridDim.y) {
        c[row * n + col] = 0.0f;
    }
}

torch::Tensor trimul_lower(torch::Tensor A, torch::Tensor B, int64_t block_size) {
    TORCH_CHECK(A.is_cuda() && B.is_cuda(), "inputs must be CUDA tensors");
    TORCH_CHECK(A.scalar_type() == at::kFloat && B.scalar_type() == at::kFloat,
                "only float32 is supported");
    TORCH_CHECK(A.dim() == 2 && A.size(0) == A.size(1), "A must be square");
    TORCH_CHECK(B.dim() == 2 && B.size(0) == A.size(0) && B.size(1) == A.size(1),
                "B must have the same shape as A");
    TORCH_CHECK(block_size > 0, "block_size must be positive");

    const c10::cuda::CUDAGuard device_guard(A.device());
    auto Ac = A.contiguous();
    auto Bc = B.contiguous();
    const int64_t n = Ac.size(0);
    auto C = at::empty({n, n}, Ac.options());
    if (n == 0) {
        return C;
    }
    const int64_t bs = std::min<int64_t>(block_size, n);

    for (int64_t k = 0; k < n; k += bs) {
        const int64_t k2 = std::min(k + bs, n);
        auto Av = Ac.slice(0, k, n).slice(1, k, k2);        // (n-k) x (k2-k)
        auto Cv = C.slice(0, k, n).slice(1, k, k2);         // (n-k) x (k2-k)
        auto Bv = Bc.slice(0, k, k2).slice(1, k, k2);       // (k2-k) x (k2-k)
        Cv.addmm_(Av, Bv, /*beta=*/0, /*alpha=*/1);         // first touch
        if (k > 0) {
            auto Cv_l = C.slice(0, k, n).slice(1, 0, k);    // (n-k) x k
            auto Bv_l = Bc.slice(0, k, k2).slice(1, 0, k);  // (k2-k) x k
            Cv_l.addmm_(Av, Bv_l, /*beta=*/1, /*alpha=*/1); // accumulate
        }
    }

    if (n > 1) {
        cudaStream_t stream = at::cuda::getCurrentCUDAStream();
        const dim3 block(256);
        const dim3 grid((unsigned)((n + (int64_t)block.x - 1) / (int64_t)block.x),
                        (unsigned)std::min<int64_t>(n, 65535));
        zero_upper_kernel<<<grid, block, 0, stream>>>(C.data_ptr<float>(), (long long)n);
    }
    return C;
}
"""

_CPP_SRC = "torch::Tensor trimul_lower(torch::Tensor A, torch::Tensor B, int64_t block_size);"

try:
    _ext = load_inline(
        name="trimul_lower_ext",
        cpp_sources=_CPP_SRC,
        cuda_sources=_CUDA_SRC,
        functions=["trimul_lower"],
        verbose=False,
        extra_cflags=["-O3"],
        extra_cuda_cflags=["-O3"],
    )
except Exception:
    _ext = None


class ModelNew(nn.Module):
    """
    Optimized C = tril(A @ B) for lower-triangular A, B.

    Uses a blocked decomposition evaluated with cuBLAS (TF32 tensor cores,
    as allowed) plus a custom CUDA kernel that zeroes the strict upper
    triangle. Falls back to the reference computation on unsupported inputs.
    """

    def __init__(self, block_size: int = 512) -> None:
        super().__init__()
        self.block_size = int(block_size)

    def forward(self, A, B):
        if (
            _ext is not None
            and A.is_cuda and B.is_cuda
            and A.dtype == torch.float32 and B.dtype == torch.float32
            and A.dim() == 2 and A.size(0) == A.size(1)
            and B.dim() == 2 and B.size(0) == A.size(0) and B.size(1) == A.size(1)
        ):
            prev_tf32 = torch.backends.cuda.matmul.allow_tf32
            torch.backends.cuda.matmul.allow_tf32 = True
            try:
                return _ext.trimul_lower(A, B, self.block_size)
            finally:
                torch.backends.cuda.matmul.allow_tf32 = prev_tf32
        return torch.tril(torch.matmul(A, B))
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 0.619 ms; the PyTorch reference (with TF32 enabled) takes 1.12 ms; speedup 1.809x.
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_16x3_nn_align4>(cutlass_80_ten | 120.6 | 3 |
| void cutlass::Kernel2<cutlass_80_tensorop_s1688gemm_128x128_16x5_nn_align4>(cutlass_80_ten | 116.2 | 2 |
| void cutlass::Kernel2<cutlass_80_tensorop_s1688gemm_256x128_32x3_nn_align4>(cutlass_80_ten | 109.6 | 3 |
| void cutlass::Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_nn_align4>(cutlass_80_ten | 62.7 | 3 |
| void cutlass::Kernel2<cutlass_80_tensorop_s1688gemm_128x128_16x4_nn_align4>(cutlass_80_ten | 58.7 | 1 |
| zero_upper_kernel(float*, long long) | 50.4 | 1 |
| void cutlass::Kernel2<cutlass_80_tensorop_s1688gemm_128x64_32x6_nn_align4>(cutlass_80_tens | 30.7 | 2 |
| void cutlass::Kernel2<cutlass_80_tensorop_s1688gemm_64x64_32x6_nn_align4>(cutlass_80_tenso | 10.9 | 1 |

The fastest correct solution so far (1.955x 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
from torch.utils.cpp_extension import load_inline

# Custom CUDA kernel that zeroes the strict upper triangle of a square matrix
# in-place. It replaces torch.tril (which reads + writes the whole matrix)
# with a kernel that only writes the ~N^2/2 elements above the diagonal.
zero_upper_source = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>

__global__ void zero_upper_triangular_kernel(float* __restrict__ c, const int n) {
    const int row = blockIdx.y;
    const int col = blockIdx.x * blockDim.x + threadIdx.x;
    if (col > row && col < n) {
        c[static_cast<long long>(row) * static_cast<long long>(n) + col] = 0.0f;
    }
}

void zero_upper_triangular(torch::Tensor c) {
    TORCH_CHECK(c.is_cuda(), "c must be a CUDA tensor");
    TORCH_CHECK(c.scalar_type() == at::kFloat, "c must be float32");
    TORCH_CHECK(c.is_contiguous(), "c must be contiguous");
    TORCH_CHECK(c.dim() == 2 && c.size(0) == c.size(1), "c must be square");
    const int n = static_cast<int>(c.size(0));
    if (n <= 1) {
        return;
    }
    const dim3 block(256);
    const dim3 grid((n + block.x - 1) / block.x, n);
    zero_upper_triangular_kernel<<<grid, block>>>(c.data_ptr<float>(), n);
}
"""

zero_upper_cpp_source = "void zero_upper_triangular(torch::Tensor c);"

try:
    _zero_upper_mod = load_inline(
        name="lower_triangular_matmul_ext",
        cpp_sources=zero_upper_cpp_source,
        cuda_sources=zero_upper_source,
        functions=["zero_upper_triangular"],
        verbose=False,
        extra_cflags=["-O3"],
        extra_cuda_cflags=["-O3"],
    )
    _zero_upper_fn = _zero_upper_mod.zero_upper_triangular
except Exception:
    _zero_upper_fn = None


class ModelNew(nn.Module):
    """
    Optimized lower-triangular matrix multiplication.

    Rather than one dense (N x N) @ (N x N) matmul followed by torch.tril,
    the product is evaluated as a sequence of block-GEMMs:

        C[k*B:, :(k+1)*B] += A[k*B:, k*B:(k+1)*B] @ B[k*B:(k+1)*B, :(k+1)*B]

    for k = 0 .. nb-1. Because A and B are lower triangular, every block of
    the product strictly above the diagonal is zero, and k-values outside
    [j, i] contribute zeros to C[i, j]. This performs ~N^3/3 FLOPs instead of
    2*N^3 (~6x fewer) while still using cuBLAS (TF32 tensor cores, which are
    allowed) for each block. A small custom CUDA kernel then zeroes the
    strict upper triangle (replacing torch.tril).
    """

    def __init__(self, block_size: int = 512) -> None:
        super().__init__()
        self.block_size = block_size

    def forward(self, A, B):
        # Allow TF32 tensor-core math for the FP32 block-GEMMs.
        prev_tf32 = torch.backends.cuda.matmul.allow_tf32
        torch.backends.cuda.matmul.allow_tf32 = True
        try:
            n = A.size(0)
            A = A.contiguous()
            B = B.contiguous()
            C = A.new_zeros((n, n))
            bs = self.block_size
            for k in range(0, n, bs):
                k2 = k + bs
                if k2 > n:
                    k2 = n
                # In-place block-GEMM update (strides map directly onto
                # cuBLAS leading dimensions, so no copies are made):
                # C[k:, :k2] += A[k:, k:k2] @ B[k:k2, :k2]
                C[k:, :k2].addmm_(A[k:, k:k2], B[k:k2, :k2])
            if _zero_upper_fn is not None and C.is_cuda and C.dtype == torch.float32:
                _zero_upper_fn(C)
            else:
                torch.tril_(C)
        finally:
            torch.backends.cuda.matmul.allow_tf32 = prev_tf32
        return C
```

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.


Precision rule: the timed forward must compute in FP32 (TF32 tensor-core math is allowed, as in the PyTorch reference). Do not cast inputs, weights or intermediate results to float16 or bfloat16 and do not call half-precision kernels in forward().
