import torch
import torch.nn as nn
import torch.nn.functional as F
def module_fn(predictions: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""
Computes the Smooth L1 (Huber) Loss for regression tasks.
Args:
predictions (torch.Tensor): Predicted values.
targets (torch.Tensor): Target values.
Returns:
torch.Tensor: Smooth L1 (Huber) Loss.
"""
return F.smooth_l1_loss(predictions, targets)
class Model(nn.Module):
"""
A model that computes Smooth L1 (Huber) Loss for regression tasks.
Parameters:
None
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, predictions, targets, fn=module_fn):
return fn(predictions, targets)
batch_size = 128
input_shape = (4096,)
dim = 1
def get_inputs():
return [
torch.randn(batch_size, *input_shape),
torch.randn(batch_size, *input_shape),
]
def get_init_inputs():
return []
import torch
import torch.nn as nn
class Model(nn.Module):
"""
A model that computes Smooth L1 (Huber) Loss for regression tasks.
Parameters:
None
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, predictions, targets):
return torch.nn.functional.smooth_l1_loss(predictions, targets)
batch_size = 128
input_shape = (4096, )
dim = 1
def get_inputs():
return [torch.randn(batch_size, *input_shape), torch.randn(batch_size, *input_shape)]
def get_init_inputs():
return []
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>
__global__ void smooth_l1_loss_strided_kernel(
const float* __restrict__ predictions,
const float* __restrict__ targets,
float* output,
const int n_elements,
const int vec_elements
) {
const int tid = threadIdx.x;
const int block_stride = blockDim.x * gridDim.x;
const int global_start = blockIdx.x * blockDim.x + tid;
float thread_sum = 0.0f;
const float4* pred4 = reinterpret_cast<const float4*>(predictions);
const float4* targ4 = reinterpret_cast<const float4*>(targets);
#pragma unroll 4
for (int i = global_start; i < vec_elements; i += block_stride) {
float4 p = __ldg(pred4 + i);
float4 t = __ldg(targ4 + i);
float diff = p.x - t.x;
float abs_diff = fabsf(diff);
thread_sum += (abs_diff < 1.0f) ? 0.5f * diff * diff : abs_diff - 0.5f;
diff = p.y - t.y;
abs_diff = fabsf(diff);
thread_sum += (abs_diff < 1.0f) ? 0.5f * diff * diff : abs_diff - 0.5f;
diff = p.z - t.z;
abs_diff = fabsf(diff);
thread_sum += (abs_diff < 1.0f) ? 0.5f * diff * diff : abs_diff - 0.5f;
diff = p.w - t.w;
abs_diff = fabsf(diff);
thread_sum += (abs_diff < 1.0f) ? 0.5f * diff * diff : abs_diff - 0.5f;
}
const int remainder_start = vec_elements * 4;
#pragma unroll 4
for (int i = remainder_start + global_start; i < n_elements; i += block_stride) {
float diff = __ldg(predictions + i) - __ldg(targets + i);
float abs_diff = fabsf(diff);
thread_sum += (abs_diff < 1.0f) ? 0.5f * diff * diff : abs_diff - 0.5f;
}
__shared__ float smem[256];
smem[tid] = thread_sum;
__syncthreads();
if (tid < 128) smem[tid] += smem[tid + 128];
__syncthreads();
if (tid < 64) smem[tid] += smem[tid + 64];
__syncthreads();
if (tid < 32) {
volatile float* vmem = smem;
vmem[tid] += vmem[tid + 32];
vmem[tid] += vmem[tid + 16];
vmem[tid] += vmem[tid + 8];
vmem[tid] += vmem[tid + 4];
vmem[tid] += vmem[tid + 2];
vmem[tid] += vmem[tid + 1];
}
if (tid == 0) {
atomicAdd(output, smem[0] / n_elements);
}
}
torch::Tensor smooth_l1_loss_strided(
torch::Tensor predictions,
torch::Tensor targets
) {
TORCH_CHECK(predictions.sizes() == targets.sizes(), "Input tensors must have the same shape");
TORCH_CHECK(predictions.is_contiguous() && targets.is_contiguous(), "Input tensors must be contiguous");
TORCH_CHECK(predictions.device().is_cuda() && targets.device().is_cuda(), "Inputs must be CUDA tensors");
const int n_elements = predictions.numel();
const int vec_elements = n_elements / 4;
auto output = torch::zeros({1}, predictions.options());
const int block_size = 256;
const int min_elements_per_thread = 4;
const int target_thread_count = (vec_elements + min_elements_per_thread - 1) / min_elements_per_thread;
const int grid_size = std::min(
(target_thread_count + block_size - 1) / block_size,
32768
);
smooth_l1_loss_strided_kernel<<<grid_size, block_size>>>(
predictions.data_ptr<float>(),
targets.data_ptr<float>(),
output.data_ptr<float>(),
n_elements,
vec_elements
);
return output;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &smooth_l1_loss_strided, "Strided Smooth L1 Loss (CUDA)");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 0.274 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 0.152 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 7.204 | % | 0.011 | 5 |
Issued Ipc Active | 0.288 | inst/cycle | 0.000 | 5 |
SM Busy | 7.204 | % | 0.011 | 5 |
Memory Throughput | 731814950979.742 | byte/second | 50599672541815750656.000 | 5 |
Mem Busy | 12.730 | % | 0.016 | 5 |
Max Bandwidth | 21.988 | % | 0.045 | 5 |
L1/TEX Hit Rate | 0.000 | % | 0.000 | 5 |
L2 Hit Rate | 18.540 | % | 0.000 | 5 |
Mem Pipes Busy | 2.062 | % | 0.000 | 5 |
Warp Cycles Per Issued Instruction | 26.938 | cycle | 1.512 | 5 |
Warp Cycles Per Executed Instruction | 28.436 | cycle | 1.680 | 5 |
Avg. Active Threads Per Warp | 31.850 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 28.560 | 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 | 16.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 | 11.946 | % | 0.000 | 5 |
Achieved Active Warps Per SM | 7.644 | warp | 0.000 | 5 |
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. |
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 (11.9%) 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. |
Operation / Metric | Value | Unit |
---|---|---|
aten::to | ||
CPU Time | 548157.41 | μs |
Device Time | 313.41 | μs |
Self CPU Time | 45.29 | μ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 | 5827809.05 | μs |
Device Time | 231881.03 | μs |
Self CPU Time | 159626.06 | μ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 | 6179253.13 | μs |
Device Time | 7710402.47 | μs |
Self CPU Time | 331647.38 | μ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 | 5847609.08 | μs |
Device Time | 7710402.47 | μs |
Self CPU Time | 436673.22 | μs |
Self Device Time | 7710399.88 | μ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 | 5798733.67 | μs |
Device Time | 2927.70 | μs |
Self CPU Time | 5798733.67 | μs |
Self Device Time | 2927.70 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
smooth_l1_loss_strided_kernel(float const*, float const*, float*, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 527280.13 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 527280.13 | μ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 | 269136.92 | μs |
Device Time | 1240345.13 | μs |
Self CPU Time | 269136.92 | μs |
Self Device Time | 1240345.13 | μ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 | 7478521.44 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 7478521.44 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45285 warnings generated when compiling for host. Suppressed 45324 warnings (45277 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.