correct
16_Matmul_with_transposed_A.py
started
2026-05-05T02:19:54Z
timingkernelbench.timing
kernel mean / median / std
2.62 / — / 0.01 μs
ref mean / median / std
2.72 / — / 0.40 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
5.00x
energyNVML (pynvml)
ratio (ref / kernel)
2.50x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
154.02 GB/s
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
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)
M = 1024 * 2
K = 4096 * 2
N = 2048 * 2
def get_inputs():
A = torch.rand(K, M)
B = torch.rand(K, N)
return [A, B]
def get_init_inputs():
return [] # No special initialization inputs neededturn 050.9s turn · 50.9s LLM · 0.0s tools · FINAL
reasoning
**Considering CUDA optimization**
I'm thinking about implementing a custom CUDA sgemm with a transpose. This could be a way to outperform cuBLAS, which is interesting! I need to analyze what specific optimizations could make a difference. Maybe it involves better memory usage or utilizing shared memory more effectively? I wonder if there's a significant trade-off in complexity for the benefits I might gain. I’ll explore a range of performance metrics to see if it’s worth pursuing!
**Considering error handling**
I'm thinking about whether I should avoid macros and focus on a host wrapper instead. Maybe that's a safer approach? It's definitely important for me to consider how to handle errors properly in whatever system I'm working with. It's like ensuring everything runs smoothly without causing any unexpected issues. I really want to get this right, so I’ll make sure to think through error handling carefully as I work on this!
**Considering shape dimensions**
I'm thinking about shapes A and B, where A has dimensions (K, M) and B has dimensions (K, N). I believe these can fit as integers. However, I'm wondering if there are various combinations of M, N, and K that could also work. Maybe I should explore different scenarios a bit more to see how they interact. This might help clarify if other dimensions can fit!
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n\ntorch::Tensor matmul_at_b(torch::Tensor A, torch::Tensor B);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAGuard.h>\n#include <cublas_v2.h>\n\nstatic inline void check_cublas_status(cublasStatus_t status) {\n TORCH_CHECK(status == CUBLAS_STATUS_SUCCESS, \"cuBLAS error: \", (int)status);\n}\n\ntorch::Tensor matmul_at_b(torch::Tensor A, torch::Tensor B) {\n TORCH_CHECK(A.is_cuda() && B.is_cuda(), \"inputs must be CUDA tensors\");\n TORCH_CHECK(A.scalar_type() == torch::kFloat32 && B.scalar_type() == torch::kFloat32,\n \"only float32 tensors are supported\");\n TORCH_CHECK(A.dim() == 2 && B.dim() == 2, \"inputs must be 2D\");\n TORCH_CHECK(A.is_contiguous() && B.is_contiguous(), \"inputs must be contiguous\");\n\n const int64_t K64 = A.size(0);\n const int64_t M64 = A.size(1);\n TORCH_CHECK(B.size(0) == K64, \"inner dimensions must match\");\n const int64_t N64 = B.size(1);\n TORCH_CHECK(K64 <= INT_MAX && M64 <= INT_MAX && N64 <= INT_MAX, \"matrix too large\");\n\n const int K = (int)K64;\n const int M = (int)M64;\n const int N = (int)N64;\n\n auto C = torch::empty({M64, N64}, A.options());\n if (M == 0 || N == 0) return C;\n\n c10::cuda::CUDAGuard device_guard(A.device());\n cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();\n\n const float alpha = 1.0f;\n const float beta = 0.0f;\n\n // Row-major C(M,N) is the same memory as column-major Ct(N,M).\n // A(K,M) row-major is column-major At(M,K), B(K,N) row-major is Bt(N,K).\n // Hence Ct = Bt * At^T.\n check_cublas_status(cublasSgemm(handle,\n CUBLAS_OP_N, CUBLAS_OP_T,\n N, M, K,\n &alpha,\n B.data_ptr<float>(), N,\n A.data_ptr<float>(), M,\n &beta,\n C.data_ptr<float>(), N));\n return C;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"at_b_cublas_inline_ext\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"matmul_at_b\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\"],\n extra_ldflags=[\"-lcublas\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n\n def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:\n return _ext.matmul_at_b(A, B)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 2.62 μs
Runtime stats: mean=2.62μs median=?μs std=0.01μs
Numerical precision: max_abs_err=0.00e+00 mean_abs_err=0.00e+00 max_rel_err=0.00e+00
Memory: 256.0 MB peak (ref: 256.0 MB, ratio: 1.0x)
Kernel launches: 1 (ref: 5, fusion ratio: 5.0)
Energy: 483.12 mJ/run (ref: 1208.2 mJ, ratio: 2.5008x)
SOL score: 0.8166
final submitted kernel (79 lines, 2,605 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
_cpp_src = r"""
#include <torch/extension.h>
torch::Tensor matmul_at_b(torch::Tensor A, torch::Tensor B);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cublas_v2.h>
static inline void check_cublas_status(cublasStatus_t status) {
TORCH_CHECK(status == CUBLAS_STATUS_SUCCESS, "cuBLAS error: ", (int)status);
}
torch::Tensor matmul_at_b(torch::Tensor A, torch::Tensor B) {
TORCH_CHECK(A.is_cuda() && B.is_cuda(), "inputs must be CUDA tensors");
TORCH_CHECK(A.scalar_type() == torch::kFloat32 && B.scalar_type() == torch::kFloat32,
"only float32 tensors are supported");
TORCH_CHECK(A.dim() == 2 && B.dim() == 2, "inputs must be 2D");
TORCH_CHECK(A.is_contiguous() && B.is_contiguous(), "inputs must be contiguous");
const int64_t K64 = A.size(0);
const int64_t M64 = A.size(1);
TORCH_CHECK(B.size(0) == K64, "inner dimensions must match");
const int64_t N64 = B.size(1);
TORCH_CHECK(K64 <= INT_MAX && M64 <= INT_MAX && N64 <= INT_MAX, "matrix too large");
const int K = (int)K64;
const int M = (int)M64;
const int N = (int)N64;
auto C = torch::empty({M64, N64}, A.options());
if (M == 0 || N == 0) return C;
c10::cuda::CUDAGuard device_guard(A.device());
cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();
const float alpha = 1.0f;
const float beta = 0.0f;
// Row-major C(M,N) is the same memory as column-major Ct(N,M).
// A(K,M) row-major is column-major At(M,K), B(K,N) row-major is Bt(N,K).
// Hence Ct = Bt * At^T.
check_cublas_status(cublasSgemm(handle,
CUBLAS_OP_N, CUBLAS_OP_T,
N, M, K,
&alpha,
B.data_ptr<float>(), N,
A.data_ptr<float>(), M,
&beta,
C.data_ptr<float>(), N));
return C;
}
"""
_ext = load_inline(
name="at_b_cublas_inline_ext",
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=["matmul_at_b"],
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3"],
extra_ldflags=["-lcublas"],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
return _ext.matmul_at_b(A, B)