← Back to Leaderboard

The AI CUDA Engineer 👷

18_Matmul_with_transposed_bothoptimized_matmul_transpose_base

Level 1 • Task 18
import torch
import torch.nn as nn
import torch.nn.functional as F


def module_fn(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
    """
    Performs a single matrix multiplication with transposed A and B (C = A.T * B.T).

    Args:
        A: Input tensor of shape (K, M).
        B: Input tensor of shape (N, K).

    Returns:
        Output tensor of shape (M, N).
    """
    return torch.matmul(A.T, B.T)


class Model(nn.Module):
    """
    Simple model that performs a single matrix multiplication (C = A * B)
    """

    def __init__(self):
        super(Model, self).__init__()

    def forward(self, A: torch.Tensor, B: torch.Tensor, fn=module_fn) -> torch.Tensor:
        return fn(A, B)


M = 1024
K = 4096
N = 2048


def get_inputs():
    A = torch.randn(K, M)
    B = torch.randn(N, K)
    return [A, B]


def get_init_inputs():
    return []  # No special initialization inputs needed
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Simple model that performs a single matrix multiplication (C = A * B)
    """
    def __init__(self):
        super(Model, self).__init__()
    
    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        """
        Performs matrix multiplication.

        Args:
            A: Input tensor of shape (M, K).
            B: Input tensor of shape (K, N).

        Returns:
            Output tensor of shape (M, N).
        """
        return torch.matmul(A.T, B.T)

M = 1024
K = 4096
N = 2048

def get_inputs():
    A = torch.randn(K, M)
    B = torch.randn(N, K)
    return [A, B]

def get_init_inputs():
    return []  # No special initialization inputs needed

Kernel Information

Related Kernels (Level 1, Task 18 • 18_Matmul_with_transposed_both)

#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>

// Configurable block size as template parameter for compile-time optimization
template<int BLOCK_SIZE = 32>
struct SharedMemoryTile {
    template <typename scalar_t>
    __device__ __forceinline__ static void loadA(
        scalar_t (&tileA)[BLOCK_SIZE][BLOCK_SIZE],
        const scalar_t* __restrict__ A,
        const int row,
        const int tile_idx,
        const int M,
        const int K) {
        const int k_index = tile_idx * BLOCK_SIZE + threadIdx.y;
        if (k_index < K && row < M) {
            tileA[threadIdx.y][threadIdx.x] = A[k_index * M + row];
        } else {
            tileA[threadIdx.y][threadIdx.x] = 0.0;
        }
    }

    template <typename scalar_t>
    __device__ __forceinline__ static void loadB(
        scalar_t (&tileB)[BLOCK_SIZE][BLOCK_SIZE],
        const scalar_t* __restrict__ B,
        const int col,
        const int tile_idx,
        const int N,
        const int K) {
        const int k_index = tile_idx * BLOCK_SIZE + threadIdx.x;
        if (k_index < K && col < N) {
            tileB[threadIdx.y][threadIdx.x] = B[col * K + k_index];
        } else {
            tileB[threadIdx.y][threadIdx.x] = 0.0;
        }
    }

    template <typename scalar_t>
    __device__ __forceinline__ static scalar_t computeTileProduct(
        const scalar_t (&tileA)[BLOCK_SIZE][BLOCK_SIZE],
        const scalar_t (&tileB)[BLOCK_SIZE][BLOCK_SIZE]) {
        scalar_t sum = 0;
        #pragma unroll
        for (int k = 0; k < BLOCK_SIZE; ++k) {
            sum = __fmaf_rn(tileA[k][threadIdx.x], tileB[threadIdx.y][k], sum);
        }
        return sum;
    }
};

template <typename scalar_t, int BLOCK_SIZE = 32>
__global__ void matmul_transpose_kernel(
    const scalar_t* __restrict__ A,
    const scalar_t* __restrict__ B,
    scalar_t* __restrict__ C,
    const int M,
    const int N,
    const int K) {
    
    const int row = blockIdx.x * BLOCK_SIZE + threadIdx.x;
    const int col = blockIdx.y * BLOCK_SIZE + threadIdx.y;

    __shared__ scalar_t tileA[BLOCK_SIZE][BLOCK_SIZE];
    __shared__ scalar_t tileB[BLOCK_SIZE][BLOCK_SIZE];

    scalar_t sum = 0;
    
    #pragma unroll 4
    for (int t = 0; t < (K + BLOCK_SIZE - 1) / BLOCK_SIZE; ++t) {
        SharedMemoryTile<BLOCK_SIZE>::loadA(tileA, A, row, t, M, K);
        SharedMemoryTile<BLOCK_SIZE>::loadB(tileB, B, col, t, N, K);
        
        __syncthreads();
        
        sum += SharedMemoryTile<BLOCK_SIZE>::computeTileProduct(tileA, tileB);
        
        __syncthreads();
    }

    if (row < M && col < N) {
        C[row * N + col] = sum;
    }
}

torch::Tensor matmul_transpose_cuda(torch::Tensor A, torch::Tensor B) {
    const int K = A.size(0);
    const int M = A.size(1);
    const int N = B.size(0);

    auto C = torch::empty({M, N}, A.options());

    constexpr int BLOCK_SIZE = 32;
    dim3 threads(BLOCK_SIZE, BLOCK_SIZE);
    dim3 blocks((M + BLOCK_SIZE - 1) / BLOCK_SIZE,
                (N + BLOCK_SIZE - 1) / BLOCK_SIZE);

    AT_DISPATCH_FLOATING_TYPES(A.type(), "matmul_transpose_kernel", ([&] {
        matmul_transpose_kernel<scalar_t, BLOCK_SIZE><<<blocks, threads>>>(
            A.data_ptr<scalar_t>(),
            B.data_ptr<scalar_t>(),
            C.data_ptr<scalar_t>(),
            M, N, K
        );
    }));

    return C;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &matmul_transpose_cuda, "Optimized matrix multiplication with transpose (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.650 inst/cycle 0.000 5
Executed Ipc Elapsed 1.592 inst/cycle 0.000 5
Issue Slots Busy 41.148 % 0.000 5
Issued Ipc Active 1.650 inst/cycle 0.000 5
SM Busy 43.376 % 0.000 5
Memory Throughput 26816858623.670 byte/second 36488638319734000.000 5
Mem Busy 91.094 % 0.002 5
Max Bandwidth 86.542 % 0.001 5
L1/TEX Hit Rate 0.042 % 0.000 5
L2 Hit Rate 94.160 % 0.159 5
Mem Pipes Busy 76.176 % 0.001 5
Warp Cycles Per Issued Instruction 37.618 cycle 0.000 5
Warp Cycles Per Executed Instruction 37.620 cycle 0.000 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 31.990 0.000 5
Max Active Clusters 0.000 cluster 0.000 5
Max Cluster Size 8.000 block 0.000 5
Overall GPU Occupancy 0.000 % 0.000 5
Cluster Occupancy 0.000 % 0.000 5
Block Limit SM 32.000 block 0.000 5
Block Limit Registers 2.000 block 0.000 5
Block Limit Shared Mem 3.000 block 0.000 5
Block Limit Warps 2.000 block 0.000 5
Theoretical Active Warps per SM 64.000 warp 0.000 5
Theoretical Occupancy 100.000 % 0.000 5
Achieved Occupancy 96.736 % 0.000 5
Achieved Active Warps Per SM 61.910 warp 0.000 5
Analysis Rules
Rule Description
WRN HighPipeUtilization All compute pipelines are under-utilized. Either this kernel is very small or it doesn't issue enough warps per scheduler. Check the Launch Statistics and Scheduler Statistics sections for further details.
INF CPIStall Check the Warp Stall Sampling (All Cycles) table for the top stall locations in your source based on sampling data. The Kernel Profiling Guide (https://docs.nvidia.com/nsight-compute/ProfilingGuide/index.html#metrics-reference) provides more details on each stall reason.
INF Occupancy This kernel's theoretical occupancy is not impacted by any block limit.
Operation / Metric Value Unit
aten::to
CPU Time 517457.17 μs
Device Time 5159.62 μs
Self CPU Time 54.63 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::_to_copy
CPU Time 517402.54 μs
Device Time 5159.62 μs
Self CPU Time 149.95 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaLaunchKernel
CPU Time 5599417.88 μs
Device Time 8070.77 μs
Self CPU Time 5599417.88 μs
Self Device Time 8070.77 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void matmul_transpose_kernel<float, 32>(float const*, float const*, float*, int, int, int)
CPU Time 0.00 μs
Device Time 5956612.95 μs
Self CPU Time 0.00 μs
Self Device Time 5956612.95 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaEventRecord
CPU Time 12025.40 μs
Device Time 15762.31 μs
Self CPU Time 12025.40 μs
Self Device Time 15762.31 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::zero_
CPU Time 5429785.51 μs
Device Time 246604.11 μs
Self CPU Time 6507.60 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::fill_
CPU Time 5423280.04 μs
Device Time 246604.11 μs
Self CPU Time 9137.64 μs
Self Device Time 246604.11 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void at::native::vectorized_elementwise_kernel<4, at::native::FillFunctor<int>, at::detail::Array<char*, 1> >(int, at::native::FillFunctor<int>, at::detail::Array<char*, 1>)
CPU Time 0.00 μs
Device Time 246604.11 μs
Self CPU Time 0.00 μs
Self Device Time 246604.11 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
Status: Completed
45286 warnings generated when compiling for host.
Suppressed 45322 warnings (45275 in non-user code, 47 NOLINT).
Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:12:9 bugprone-easily-swappable-parameters
12 | const int row,
| ^~~~~~~~~~~~~~
13 | const int tile_idx,
| ~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:12:19: note: the first parameter in the range is 'row'
12 | const int row,
| ^~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:13:19: note: the last parameter in the range is 'tile_idx'
13 | const int tile_idx,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:28:9: warning: 2 adjacent parameters of 'loadB' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
28 | const int col,
| ^~~~~~~~~~~~~~
29 | const int tile_idx,
| ~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:28:19: note: the first parameter in the range is 'col'
28 | const int col,
| ^~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:29:19: note: the last parameter in the range is 'tile_idx'
29 | const int tile_idx,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:55:5: warning: 2 adjacent parameters of 'matmul_transpose_kernel' of similar type ('const scalar_t *__restrict') are easily swapped by mistake [bugprone-easily-swappable-parameters]
55 | const scalar_t* __restrict__ A,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
56 | const scalar_t* __restrict__ B,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:55:34: note: the first parameter in the range is 'A'
55 | const scalar_t* __restrict__ A,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:56:34: note: the last parameter in the range is 'B'
56 | const scalar_t* __restrict__ B,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:88:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
88 | const int K = A.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:89:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
89 | const int M = A.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:90:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
90 | const int N = B.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:99:5: warning: inside a lambda, '__func__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
99 | AT_DISPATCH_FLOATING_TYPES(A.type(), "matmul_transpose_kernel", ([&] {
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:237:34: note: expanded from macro 'AT_DISPATCH_FLOATING_TYPES'
237 | AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__))
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:233:3: note: expanded from macro 'AT_DISPATCH_CASE_FLOATING_TYPES'
233 | AT_DISPATCH_CASE(at::ScalarType::Double, __VA_ARGS__) \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:74:3: note: expanded from macro 'AT_DISPATCH_CASE'
74 | AT_PRIVATE_CASE_TYPE_USING_HINT(enum_type, scalar_t, __VA_ARGS__)
| ^
note: (skipping 1 expansions in backtrace; use -fmacro-backtrace-limit=0 to see all)
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:58:7: note: expanded from macro 'AT_PRIVATE_CHECK_SELECTIVE_BUILD'
58 | AT_ERROR( \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Exception.h:711:32: note: expanded from macro 'AT_ERROR'
711 | C10_EXPAND_MSVC_WORKAROUND(TORCH_CHECK(false, ::c10::str(__VA_ARGS__))); \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Exception.h:536:9: note: expanded from macro 'TORCH_CHECK'
536 | __func__, \
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:99:5: warning: 'scalar_type' is deprecated: passing at::DeprecatedTypeProperties to an AT_DISPATCH macro is deprecated, pass an at::ScalarType instead [clang-diagnostic-deprecated-declarations]
99 | AT_DISPATCH_FLOATING_TYPES(A.type(), "matmul_transpose_kernel", ([&] {
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:237:3: note: expanded from macro 'AT_DISPATCH_FLOATING_TYPES'
237 | AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__))
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:218:36: note: expanded from macro 'AT_DISPATCH_SWITCH'
218 | at::ScalarType _st = ::detail::scalar_type(the_type); \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:106:1: note: 'scalar_type' has been explicitly marked deprecated here
106 | C10_DEPRECATED_MESSAGE(
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Deprecated.h:24:43: note: expanded from macro 'C10_DEPRECATED_MESSAGE'
24 | #define C10_DEPRECATED_MESSAGE(message) [[deprecated(message)]]
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_18/b4_s3_optimized_matmul_transpose/base/base.cu:99:34: warning: 'type' is deprecated: Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device(). [clang-diagnostic-deprecated-declarations]
99 | AT_DISPATCH_FLOATING_TYPES(A.type(), "matmul_transpose_kernel", ([&] {
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/core/TensorBody.h:224:3: note: 'type' has been explicitly marked deprecated here
224 | C10_DEPRECATED_MESSAGE("Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device().")
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Deprecated.h:24:43: note: expanded from macro 'C10_DEPRECATED_MESSAGE'
24 | #define C10_DEPRECATED_MESSAGE(message) [[deprecated(message)]]
| ^