79_conv_transposed_1D_asymmetric_input_square_kernel___padded____strided____dilated__
• shared_memory_conv_transpose1d_base
import torch
import torch.nn as nn
import torch.nn.functional as F
def module_fn(
x: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor,
stride: int,
padding: int,
dilation: int,
) -> torch.Tensor:
"""
Performs a transposed 1D convolution operation with asymmetric input and square kernel. Supports padding, striding, and dilation.
Args:
x (torch.Tensor): Input tensor
weight (torch.Tensor): Convolution weights
bias (torch.Tensor): Bias tensor (optional)
stride (int): Stride of the convolution
padding (int): Padding applied to the input
dilation (int): Spacing between kernel elements
Returns:
torch.Tensor: Output tensor
"""
return F.conv_transpose1d(
x, weight, bias=bias, stride=stride, padding=padding, dilation=dilation
)
class Model(nn.Module):
"""
Performs a transposed 1D convolution operation with asymmetric input and square kernel.
Supports padding, striding, and dilation.
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): Stride of the convolution.
padding (int): Padding applied to the input.
dilation (int): Spacing between kernel elements.
bias (bool): If `True`, adds a learnable bias to the output.
"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int,
padding: int,
dilation: int,
bias: bool,
):
super(Model, self).__init__()
self.conv_transpose1d = nn.ConvTranspose1d(
in_channels,
out_channels,
kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
)
# Copy the initialized parameters
self.weight = nn.Parameter(self.conv_transpose1d.weight.clone())
self.bias = nn.Parameter(self.conv_transpose1d.bias.clone()) if bias else None
self.stride = stride
self.padding = padding
self.dilation = dilation
def forward(self, x: torch.Tensor, fn=module_fn) -> torch.Tensor:
return fn(
x,
self.weight,
self.bias,
self.stride,
self.padding,
self.dilation,
)
# Constants
batch_size = 16
in_channels = 32
out_channels = 64
kernel_size = 3
length = 128
stride = 2
padding = 1
dilation = 2
bias = False
def get_inputs():
x = torch.randn(batch_size, in_channels, length)
return [x]
def get_init_inputs():
return [in_channels, out_channels, kernel_size, stride, padding, dilation, bias]
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Performs a transposed 1D convolution operation with asymmetric input and square kernel.
Supports padding, striding, and dilation.
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.
dilation (int, optional): Spacing between kernel elements. 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,
dilation: int = 1,
bias: bool = False,
):
super(Model, self).__init__()
self.conv1d_transpose = nn.ConvTranspose1d(
in_channels,
out_channels,
kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Performs the transposed 1D convolution.
Args:
x (torch.Tensor): Input tensor of shape (batch_size, in_channels, length).
Returns:
torch.Tensor: Output tensor of shape (batch_size, out_channels, length_out).
"""
return self.conv1d_transpose(x)
# Constants
batch_size = 16
in_channels = 32
out_channels = 64
kernel_size = 3
length = 128
stride = 2
padding = 1
dilation = 2
bias = False
def get_inputs():
x = torch.randn(batch_size, in_channels, length)
return [x]
def get_init_inputs():
return [in_channels, out_channels, kernel_size, stride, padding, dilation, bias]
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
// Compute output length given convolution parameters
inline int compute_output_length(int input_length, int stride, int padding, int dilation, int kernel_size) {
return (input_length - 1) * stride - 2 * padding + dilation * (kernel_size - 1) + 1;
}
// This kernel uses shared memory to hold the weight data for a specific out_channel,
// which is reused across all threads in the block. Each block is responsible for one
// (batch, out_channel) pair, and threads collaboratively load the weight slice into shared memory.
__global__ void conv_transpose1d_kernel_shared(
const float* __restrict__ x_ptr,
const float* __restrict__ weight_ptr,
const float* __restrict__ bias_ptr,
float* __restrict__ output_ptr,
int batch_size,
int in_channels,
int out_channels,
int input_length,
int output_length,
int kernel_size,
int stride,
int padding,
int dilation
) {
// grid configuration: blockIdx.y = batch index, blockIdx.x = output channel index
int b = blockIdx.y;
int oc = blockIdx.x;
// Allocate shared memory for the weight slice for this (oc) across all in_channels and kernel positions
extern __shared__ float sweight[]; // size: in_channels * kernel_size floats
int weight_count = in_channels * kernel_size;
// Cooperative loading: each thread loads multiple elements if needed
for (int idx = threadIdx.x; idx < weight_count; idx += blockDim.x) {
int ic = idx / kernel_size;
int k = idx % kernel_size;
// Weight layout: [in_channels, out_channels, kernel_size]
sweight[idx] = weight_ptr[ic * out_channels * kernel_size + oc * kernel_size + k];
}
__syncthreads();
// Each thread computes one or more output positions along the temporal dimension
for (int o = threadIdx.x; o < output_length; o += blockDim.x) {
float sum = 0.0f;
// Iterate over kernel positions
for (int k = 0; k < kernel_size; ++k) {
int i_pos = o + padding - k * dilation;
// Check if the computed input position aligns with the stride
if (i_pos % stride != 0) continue;
int i = i_pos / stride;
if (i < 0 || i >= input_length) continue;
// Sum over all input channels
for (int ic = 0; ic < in_channels; ++ic) {
// Fetch the preloaded weight from shared memory
float w = sweight[ic * kernel_size + k];
int x_idx = b * in_channels * input_length + ic * input_length + i;
sum += x_ptr[x_idx] * w;
}
}
// Add bias if provided
if (bias_ptr) {
sum += bias_ptr[oc];
}
int out_idx = b * out_channels * output_length + oc * output_length + o;
output_ptr[out_idx] = sum;
}
}
// Forward CUDA function using the shared memory optimized kernel
torch::Tensor forward_cuda(
torch::Tensor x,
torch::Tensor weight,
torch::optional<torch::Tensor> bias,
int stride,
int padding,
int dilation
) {
TORCH_CHECK(x.device().is_cuda(), "x must be a CUDA tensor");
TORCH_CHECK(weight.device().is_cuda(), "weight must be a CUDA tensor");
TORCH_CHECK(x.dim() == 3, "x must be 3D (batch, in_channels, input_length)");
TORCH_CHECK(weight.dim() == 3, "weight must be 3D (in_channels, out_channels, kernel_size)");
x = x.contiguous();
weight = weight.contiguous();
torch::Tensor bias_contig;
const float* bias_ptr = nullptr;
if (bias.has_value()) {
bias_contig = bias->contiguous();
TORCH_CHECK(bias_contig.device().is_cuda(), "bias must be a CUDA tensor");
TORCH_CHECK(bias_contig.dim() == 1, "bias must be 1D");
bias_ptr = bias_contig.data_ptr<float>();
}
int batch_size = x.size(0);
int in_channels = x.size(1);
int input_length = x.size(2);
int out_channels = weight.size(1);
int kernel_size = weight.size(2);
TORCH_CHECK(weight.size(0) == in_channels, "weight's in_channels must match x's in_channels");
if (bias.has_value()) {
TORCH_CHECK(bias_contig.size(0) == out_channels, "bias size must match out_channels");
}
int output_length = compute_output_length(input_length, stride, padding, dilation, kernel_size);
auto output = torch::zeros({batch_size, out_channels, output_length}, x.options());
// Launch configuration: each block computes one output channel for one batch sample
dim3 grid(out_channels, batch_size);
int threads_per_block = 256;
size_t shared_mem_size = in_channels * kernel_size * sizeof(float);
conv_transpose1d_kernel_shared<<<grid, threads_per_block, shared_mem_size>>>(
x.data_ptr<float>(),
weight.data_ptr<float>(),
bias_ptr,
output.data_ptr<float>(),
batch_size,
in_channels,
out_channels,
input_length,
output_length,
kernel_size,
stride,
padding,
dilation
);
return output;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &forward_cuda, "ConvTranspose1D forward (CUDA) with shared memory",
py::arg("x"), py::arg("weight"), py::arg("bias") = py::none(),
py::arg("stride"), py::arg("padding"), py::arg("dilation"));
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 2.350 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 1.994 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 59.248 | % | 0.102 | 5 |
Issued Ipc Active | 2.368 | inst/cycle | 0.000 | 5 |
SM Busy | 59.248 | % | 0.102 | 5 |
Memory Throughput | 17085028951.964 | byte/second | 4086669952845110.500 | 5 |
Mem Busy | 46.508 | % | 0.030 | 5 |
Max Bandwidth | 45.256 | % | 0.029 | 5 |
L1/TEX Hit Rate | 72.192 | % | 0.000 | 5 |
L2 Hit Rate | 95.782 | % | 0.471 | 5 |
Mem Pipes Busy | 45.256 | % | 0.029 | 5 |
Warp Cycles Per Issued Instruction | 20.004 | cycle | 0.050 | 5 |
Warp Cycles Per Executed Instruction | 20.162 | cycle | 0.051 | 5 |
Avg. Active Threads Per Warp | 18.860 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 18.060 | 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 | 8.000 | block | 0.000 | 5 |
Block Limit Shared Mem | 23.000 | block | 0.000 | 5 |
Block Limit Warps | 8.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 | 73.918 | % | 0.054 | 5 |
Achieved Active Warps Per SM | 47.310 | warp | 0.022 | 5 |
Rule | Description |
---|---|
INF HighPipeUtilization | FMA is the highest-utilized pipeline (32.6%) based on active cycles, taking into account the rates of its different instructions. It executes 32-bit floating point (FADD, FMUL, FMAD, ...) and integer (IMUL, IMAD) operations. It is well-utilized, but should not be a bottleneck. |
WRN ThreadDivergence | Instructions are executed in warps, which are groups of 32 threads. Optimal instruction throughput is achieved if all 32 threads of a warp execute the same instruction. The chosen launch configuration, early thread completion, and divergent flow control can significantly lower the number of active threads in a warp per cycle. This kernel achieves an average of 18.9 threads being active per cycle. This is further reduced to 18.1 threads per warp due to predication. The compiler may use predication to avoid an actual branch. Instead, all instructions are scheduled, but a per-thread condition code or predicate controls which threads execute the instructions. Try to avoid different execution paths within a warp when possible. In addition, ensure your kernel makes use of Independent Thread Scheduling, which allows a warp to reconverge after a data-dependent conditional block by explicitly calling __syncwarp(). |
WRN Occupancy | This kernel's theoretical occupancy is not impacted by any block limit. The difference between calculated theoretical (100.0%) and measured achieved occupancy (74.1%) can be the result of warp scheduling overheads or workload imbalances during the kernel execution. Load imbalances can occur between warps within a block as well as across blocks of the same kernel. See the CUDA Best Practices Guide (https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#occupancy) for more details on optimizing occupancy. |
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. |
Operation / Metric | Value | Unit |
---|---|---|
aten::to | ||
CPU Time | 521770.15 | μs |
Device Time | 16.90 | μs |
Self CPU Time | 60.49 | μ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::zeros | ||
CPU Time | 6171831.36 | μs |
Device Time | 235921.91 | μs |
Self CPU Time | 142603.22 | μ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::zero_ | ||
CPU Time | 6634900.40 | μs |
Device Time | 7157660.03 | μs |
Self CPU Time | 309160.70 | μ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 | 6325741.23 | μs |
Device Time | 7157660.03 | μs |
Self CPU Time | 377130.15 | μs |
Self Device Time | 7157660.03 | μ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 | 6272457.58 | μs |
Device Time | 2782.01 | μs |
Self CPU Time | 6272457.58 | μs |
Self Device Time | 2782.01 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
conv_transpose1d_kernel_shared(float const*, float const*, float const*, float*, int, int, int, int, int, int, int, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 1256502.70 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 1256502.70 | μ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 | 198133.04 | μs |
Device Time | 1147858.08 | μs |
Self CPU Time | 198133.04 | μs |
Self Device Time | 1147858.08 | μ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 | 6921738.12 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 6921738.12 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45294 warnings generated when compiling for host. Suppressed 45326 warnings (45279 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.