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):
    """
    Performs a transposed 2D convolution with square input and square kernel.

    Args:
        in_channels (int): Number of channels in the input tensor.
        out_channels (int): Number of channels produced by the convolution.
        kernel_size (int): Size of the square convolution kernel.
        stride (int, optional): Stride of the convolution. Defaults to 1.
        padding (int, optional): Padding applied to the input. Defaults to 0.
        output_padding (int, optional): Additional size added to one side of the output shape. Defaults to 0.
        groups (int, optional): Number of blocked connections from input channels to output channels. Defaults to 1.
        bias (bool, optional): If `True`, adds a learnable bias to the output. Defaults to `False`.
    """
    def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, output_padding: int = 0, groups: int = 1, bias: bool = False):
        super(Model, self).__init__()
        self.conv_transpose2d = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Performs the transposed 2D convolution.

        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, in_channels, height, width).

        Returns:
            torch.Tensor: Output tensor of shape (batch_size, out_channels, height_out, width_out).
        """
        return self.conv_transpose2d(x)

# Test code
batch_size = 8
in_channels = 64  # double channels for heavier compute
out_channels = 64
kernel_size = 3
# larger square input
height = 1024
width = 1024

def get_inputs():
    x = torch.rand(batch_size, in_channels, height, width)
    return [x]

def get_init_inputs():
    return [in_channels, out_channels, kernel_size]  # Provide in_channels, out_channels, kernel_size for initialization
    ```
    
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 CUDA implementation of ConvTranspose2d (stride=1, groups=1) via an
# implicit-GEMM formulation on tensor cores (WMMA, fp16 inputs / fp32 accumulate).
#
# Math: ConvTranspose2d(s=1, p, k)  ==  Conv2d(padding=k-1-p) with the kernel
# flipped spatially and in/out channels swapped:
#     out[b,o,y,x] = sum_{c,u,v} xpad[b,c,y+u,x+v] * wf[o,c,u,v],
#     wf[o,c,u,v]  = w[c,o,K-1-u,K-1-v]
# This is evaluated as an implicit GEMM over K = C*K*K without materializing
# an im2col matrix.
# ----------------------------------------------------------------------------------

cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <mma.h>

using namespace nvcuda;

#define TK 32
#define HALO 8

// Gather weights rearrangement is done on the host side (pure tensor permute).

__global__ void __launch_bounds__(256, 2) imtconv_wmma_kernel(
    const float* __restrict__ x,
    const half*  __restrict__ w2,   // [C*RK*RK, OC] row major
    float* __restrict__ out,
    const unsigned char* __restrict__ ku,
    const unsigned char* __restrict__ kv,
    const unsigned char* __restrict__ kc,
    int B, int C, int H, int W, int OC, int OH, int OW,
    int pad, int Ktot, int TM)
{
    extern __shared__ char smem_raw[];
    // dynamic smem layout: As[2][TK][TMp] half, Bs[2][TK][NB] half
    const int TMp = TM + 8;
    const int NB  = 80;
    half* As = reinterpret_cast<half*>(smem_raw);
    half* Bs = As + 2 * TK * TMp;

    const int tile_id = blockIdx.x;
    const int tiles_per_row = (OW + TM - 1) / TM;
    const int y   = tile_id % OH;
    const int tmp = tile_id / OH;
    const int ti  = tmp % tiles_per_row;
    const int b   = tmp / tiles_per_row;
    const int x0  = ti * TM;

    const int tid  = threadIdx.x;
    const int warp = tid >> 5;

    // accumulators: 2 m-fragments x 4 n-fragments
    wmma::fragment<wmma::accumulator, 16, 16, 16, float> acc[2][4];
#pragma unroll
    for (int i = 0; i < 2; ++i)
#pragma unroll
        for (int j = 0; j < 4; ++j)
            wmma::fill_fragment(acc[i][j], 0.0f);

    const bool interior = (x0 + TM <= OW);
    const int m_valid   = interior ? TM : (OW - x0);
    const int m_load    = min(TM, (W + pad) - (x0 - pad));  // xx<W possible only for m < m_load

    const long HW  = (long)H * (long)W;
    const long bHW = (long)b * HW;

    const int nk = (Ktot + TK - 1) / TK;

    // ---- loader: fills shared buffers for k-chunk c ----
    auto load_chunk = [&](int c, int buf) {
        half* Abuf = As + buf * TK * TMp;
        half* Bbuf = Bs + buf * TK * NB;
        const int kbase = c * TK;
        // A tile : TM x TK (transposed store, conflict free)
#pragma unroll 4
        for (int kk = 0; kk < TK; ++kk) {
            const int k = kbase + kk;
            half hv = __float2half(0.0f);
            if (k < Ktot) {
                const int u = (int)ku[k];
                const int v = (int)kv[k];
                const int yy = y + u - pad;
                if ((unsigned)yy < (unsigned)H) {
                    const int cc = (int)kc[k];
                    const int xx = x0 + tid + v - pad;      // m = tid
                    if ((unsigned)xx < (unsigned)W) {
                        hv = __float2half(__ldg(x + (bHW + (long)cc * HW) + (long)yy * W + xx));
                    }
                }
            }
            Abuf[kk * TMp + tid] = hv;
        }
        // B tile : TK x OC
        const int nwarps = blockDim.x >> 5;
        const int lane   = tid & 31;
        const int total  = TK * OC;
        const int per_w  = (total + nwarps - 1) / nwarps;
        const int start  = warp * per_w;
        const int end    = min(total, start + per_w);
        for (int idx = start + lane; idx < end; idx += 32) {
            const int kr = idx / OC;
            const int o  = idx - kr * OC;
            const int gk = kbase + kr;
            half hv = __float2half(0.0f);
            if (gk < Ktot) hv = w2[(long)gk * OC + o];
            Bbuf[kr * NB + o] = hv;
        }
    };

    load_chunk(0, 0);
    __syncthreads();

    for (int c = 0; c < nk; ++c) {
        const int buf = c & 1;
        if (c + 1 < nk) load_chunk(c + 1, buf ^ 1);   // prefetch next tile
        // compute on buf
        const half* Abuf = As + buf * TK * TMp;
        const half* Bbuf = Bs + buf * TK * NB;
#pragma unroll
        for (int ks = 0; ks < TK; ks += 16) {
            wmma::fragment<wmma::matrix_b, 16, 16, 16, half, wmma::row_major> bfrag[4];
#pragma unroll
            for (int nf = 0; nf < 4; ++nf)
                wmma::load_matrix_sync(bfrag[nf], Bbuf + ks * NB + nf * 16, NB);
#pragma unroll
            for (int mf = 0; mf < 2; ++mf) {
                wmma::fragment<wmma::matrix_a, 16, 16, 16, half, wmma::col_major> afrag;
                wmma::load_matrix_sync(afrag, Abuf + ks * TMp + warp * 32 + mf * 16, TMp);
#pragma unroll
                for (int nf = 0; nf < 4; ++nf)
                    wmma::mma_sync(acc[mf][nf], afrag, bfrag[nf], acc[mf][nf]);
            }
        }
        __syncthreads();
    }

    // ---- epilogue ----
    const long OHOW = (long)OH * (long)OW;
    if (interior) {
        float* outb = out + (long)b * OC * OHOW + (long)y * OW + x0;
#pragma unroll
        for (int mf = 0; mf < 2; ++mf) {
#pragma unroll
            for (int nf = 0; nf < 4; ++nf) {
                float* p = outb + (long)(nf * 16) * OHOW + warp * 32 + mf * 16;
                wmma::store_matrix_sync(p, acc[mf][nf], OHOW, wmma::mem_col_major);
            }
        }
    } else {
        // rare boundary tile: stage through shared memory with predicated writes
        float* Cs = reinterpret_cast<float*>(smem_raw);
#pragma unroll
        for (int mf = 0; mf < 2; ++mf) {
#pragma unroll
            for (int nf = 0; nf < 4; ++nf) {
                wmma::store_matrix_sync(Cs + warp * (32 * 64) + mf * 16 + nf * 16 * 32,
                                        acc[mf][nf], 32, wmma::mem_row_major);
            }
        }
        __syncthreads();
        for (int idx = tid; idx < m_valid * OC; idx += blockDim.x) {
            const int m = idx / OC;
            const int o = idx - m * OC;
            out[(long)b * OC * OHOW + (long)o * OHOW + (long)y * OW + (x0 + m)] = Cs[m * 64 + o];
        }
    }
}

torch::Tensor conv_transpose2d_wmma(torch::Tensor x, torch::Tensor w2,
                                    torch::Tensor ku, torch::Tensor kv, torch::Tensor kc,
                                    int64_t pad, int64_t TM) {
    TORCH_CHECK(x.is_cuda() && x.dtype() == torch::kFloat32, "x must be CUDA fp32");
    const int B  = x.size(0);
    const int C  = x.size(1);
    const int H  = x.size(2);
    const int W  = x.size(3);
    const int OC = w2.size(1);
    const int Ktot = w2.size(0);
    const int OH = (H - 1) - 2 * (int)pad + 3;   // stride 1, kernel 3
    const int OW = (W - 1) - 2 * (int)pad + 3;

    auto out = torch::empty({B, OC, OH, OW}, x.options());
    if (out.numel() == 0) return out;

    const int tiles_per_row = (OW + (int)TM - 1) / (int)TM;
    const long blocks = (long)B * OH * tiles_per_row;

    const int TMp = (int)TM + 8;
    size_t sh = (size_t)(2 * TK * TMp + 2 * TK * 80) * sizeof(half);
    size_t sh_edge = (size_t)TM * 64 * sizeof(float);
    if (sh_edge > sh) sh = sh_edge;

    auto stream = at::cuda::getCurrentCUDAStream();
    static size_t max_sh = 0;
    if (sh > max_sh) {
        cudaFuncSetAttribute(imtconv_wmma_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)sh);
        max_sh = sh;
    }

    imtconv_wmma_kernel<<<(unsigned)blocks, 256, sh, stream>>>(
        x.data_ptr<float>(),
        reinterpret_cast<const half*>(w2.data_ptr<at::Half>()),
        out.data_ptr<float>(),
        ku.data_ptr<unsigned char>(), kv.data_ptr<unsigned char>(), kc.data_ptr<unsigned char>(),
        B, C, H, W, OC, OH, OW, (int)pad, Ktot, (int)TM);

    return out;
}
"""

cpp_src = "torch::Tensor conv_transpose2d_wmma(torch::Tensor x, torch::Tensor w2, torch::Tensor ku, torch::Tensor kv, torch::Tensor kc, int64_t pad, int64_t TM);"

_conv_mod = load_inline(
    name="conv_transpose2d_wmma",
    cpp_sources=cpp_src,
    cuda_sources=cuda_src,
    functions=["conv_transpose2d_wmma"],
    verbose=False,
    extra_cuda_cflags=["-O3", "--use_fast_math"],
)


class ModelNew(nn.Module):
    """
    ConvTranspose2d accelerated with a custom tensor-core implicit-GEMM CUDA kernel.

    Fast path covers stride=1, groups=1, kernel 3x3 (the benchmarked configuration).
    All other configurations fall back to the cuDNN implementation.
    """

    def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1,
                 padding: int = 0, output_padding: int = 0, groups: int = 1, bias: bool = False):
        super(ModelNew, self).__init__()
        self.conv_transpose2d = nn.ConvTranspose2d(in_channels, out_channels, kernel_size,
                                                   stride=stride, padding=padding,
                                                   output_padding=output_padding,
                                                   groups=groups, bias=bias)
        self.stride = stride
        self.padding = padding
        self.groups = groups
        self.kernel_size = kernel_size

        self._fast = (stride == 1 and groups == 1 and kernel_size == 3 and padding <= 2
                      and out_channels % 64 == 0)
        self._TM = 256 if in_channels >= 16 else 128

        if self._fast:
            C = in_channels
            w2, ku, kv, kc = self._build_tables(self.conv_transpose2d.weight.detach())
            self.register_buffer("w2", w2)
            self.register_buffer("ku", ku)
            self.register_buffer("kv", kv)
            self.register_buffer("kc", kc)

    def _build_tables(self, w):
        # w : [C, OC, 3, 3]  ->  w2[k, o] with k = (u*K+v)*C + c : w[c, o, K-1-u, K-1-v]
        C, OC, K, _ = w.shape
        w2 = w.permute(2, 3, 0, 1).flip(0, 1).reshape(K * K * C, OC).contiguous()
        k = torch.arange(K * K * C, dtype=torch.long)
        c = torch.remainder(k, C)
        r = torch.div(k, C, rounding_mode="floor")
        u = torch.div(r, K, rounding_mode="floor")
        v = torch.remainder(r, K)
        return (w2.to(torch.float16),
                u.to(torch.uint8), v.to(torch.uint8), c.to(torch.uint8))

    def train(self, mode: bool = True):
        super().train(mode)
        if self._fast:
            w2, ku, kv, kc = self._build_tables(self.conv_transpose2d.weight.detach())
            self.w2, self.ku, self.kv, self.kc = w2, ku, kv, kc
        return self

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        w = self.conv_transpose2d
        if (self._fast and x.is_cuda and x.dtype == torch.float32
                and w.bias is None and x.size(1) == self.w2.size(0) // 9):
            x = x.contiguous()
            return _conv_mod.conv_transpose2d_wmma(x, self.w2, self.ku, self.kv, self.kc,
                                                   self.padding, self._TM)
        return F.conv_transpose2d(x, w.weight, w.bias, self.stride, self.padding,
                                  0, self.groups)
```
Result of evaluating it:
The solution compiled but failed at run time. Error output:
```
expected scalar type Half but found Float
```

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.
