Is there any issue in @csrc/quantization//** that can cause CUDA error: misaligned address on Windows?
--- Content from referenced files ---
Content from @C:\SageAttention\sageattention3_blackwell\csrc\quantization\cuda_utils.h:
#pragma once
#define CUDA_CHECK(cmd)
do {
cudaError_t e = cmd;
if (e != cudaSuccess) {
printf("Failed: Cuda error %s:%d '%s'\n", FILE, LINE,
cudaGetErrorString(e));
exit(EXIT_FAILURE);
}
} while (0)
int64_t get_device_attribute(int64_t attribute, int64_t device_id) {
static int value = = {
int device = static_cast(device_id);
if (device < 0) {
CUDA_CHECK(cudaGetDevice(&device));
}
int value;
CUDA_CHECK(cudaDeviceGetAttribute(
&value, static_cast(attribute), device));
return static_cast(value);
}();
return value;
}
namespace cuda_utils {
template
HOST_DEVICE_INLINE constexpr std::enable_if_t<std::is_integral_v, T>
ceil_div(T a, T b) {
return (a + b - 1) / b;
}
}; // namespace cuda_utils
Content from @C:\SageAttention\sageattention3_blackwell\csrc\quantization\fp4_quantization_4d.cu:
/*
Copyright (c) 2025 by SageAttention team.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Yes, there are potential issues in csrc/quantization/fp4_quantization_4d.cu that could cause CUDA error: misaligned address, especially on Windows where the compiler and memory layout behavior can differ from Linux.
The error is likely caused by memory misalignment during vectorized memory operations. The code uses reinterpret_cast to treat blocks of memory as PackedVec structs, which are 32 bytes in size. Loading or storing these structs often translates to wide memory accesses (e.g., 128-bit or 256-bit) which require the memory address to be aligned to a 16-byte or 32-byte boundary.
The code has two main areas of concern:
The PackedVec struct itself doesn't specify any alignment, so the compiler might only align it to 4 bytes, which is insufficient for wide loads.
In the scaled_fp4_quant_trans_kernel function, a shared memory array shared_input is allocated with the alignment of its base type (half or nv_bfloat16, 2 bytes), but then it's cast to a PackedVec*, which has stricter alignment needs.
I will apply two fixes to address these issues by enforcing 16-byte alignment.
First, I'll add an alignment specifier to the struct definition.
Assistant
Second, I'll modify the shared memory allocation in scaled_fp4_quant_trans_kernel to ensure it is 16-byte aligned before being cast to a PackedVec pointer.
Assistant
These changes should resolve the "misaligned address" error by correctly handling memory alignment for wide vector loads and stores.
User
Is there any other issue that can cause CUDA error: misaligned address on Windows?
Assistant
Based on my review of the code in csrc/quantization/fp4_quantization_4d.cu, the two changes I made address the most probable causes of a CUDA error: misaligned address.
To summarize:
PackedVec Alignment: By adding alignas(16), I've made the memory alignment requirement for the PackedVec struct explicit. This is the most likely culprit, as vectorized loads of this struct require stricter alignment than the compiler might provide by default, especially on a different OS/compiler toolchain like on Windows.
Shared Memory Alignment: By changing the declaration of the shared_input buffer in the scaled_fp4_quant_trans_kernel, I've ensured that the shared memory region is 16-byte aligned before it's cast to a PackedVec*. This resolves the other clear source of potential misalignment.
The remaining memory operations in the file, such as the final writes to the output and output_sf tensors, appear to be safe. The pointer arithmetic involves strides that should maintain correct alignment for the 4-byte and 8-byte writes being performed.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <torch/all.h>
#include <torch/python.h>
#include <torch/nn/functional.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda_runtime_api.h>
#include <cuda_runtime.h>
// Get type2 from type or vice versa (applied to half and bfloat16)
template
struct TypeConverter {
using Type = half2;
}; // keep for generality
template <>
struct TypeConverter {
using Type = half;
};
template <>
struct TypeConverter {
using Type = half2;
};
template <>
struct TypeConverter<__nv_bfloat162> {
using Type = __nv_bfloat16;
};
template <>
struct TypeConverter<__nv_bfloat16> {
using Type = __nv_bfloat162;
};
// Define a 32 bytes packed data type.
template
struct PackedVec {
typename TypeConverter::Type elts[8];
};
template <uint32_t head_dim, uint32_t BLOCK_SIZE, bool permute, typename T>
global void scaled_fp4_quant_kernel(
const T* input, uint8_t* output, uint8_t* output_sf,
int batch_size, int num_heads, int num_tokens,
int stride_bz_input, int stride_h_input, int stride_seq_input,
int stride_bz_output, int stride_h_output, int stride_seq_output,
int stride_bz_output_sf, int stride_h_output_sf, int stride_seq_output_sf) {
static_assert(std::is_same<T, half>::value || std::is_same<T, nv_bfloat16>::value, "Only half and bfloat16 input are supported");
using PackedVec = PackedVec;
const int batch_id = blockIdx.y;
const int head_id = blockIdx.z;
const int token_block_id = blockIdx.x;
static_assert(CVT_FP4_ELTS_PER_THREAD == 8 || CVT_FP4_ELTS_PER_THREAD == 16,
"CVT_FP4_ELTS_PER_THREAD must be 8 or 16");
static_assert(sizeof(PackedVec) == sizeof(T) * CVT_FP4_ELTS_PER_THREAD,
"Vec size is not matched.");
#pragma unroll
for (int i = 0; i < CVT_FP4_ELTS_PER_THREAD / 2; i++) {
reinterpret_cast<uint32_t&>(in_vec.elts[i]) = 0;
}
if (load_token_id < num_tokens) {
in_vec = reinterpret_cast<PackedVec const*>(input +
batch_id * stride_bz_input + // batch dim
head_id * stride_h_input + // head dim
load_token_id * stride_seq_input + // seq dim
(threadIdx.x % NUM_THREADS_PER_TOKEN) * CVT_FP4_ELTS_PER_THREAD)[0]; // feature dim
}
// calculate max of every consecutive 16 elements
auto localMax = __habs2(in_vec.elts[0]);
#pragma unroll
for (int i = 1; i < CVT_FP4_ELTS_PER_THREAD / 2; i++) { // local max
localMax = __hmax2(localMax, __habs2(in_vec.elts[i]));
}
if constexpr (CVT_FP4_ELTS_PER_THREAD == 8) { // shuffle across two threads
localMax = __hmax2(__shfl_xor_sync(0xffffffff, localMax, 1, 32), localMax);
}
template <uint32_t head_dim, uint32_t BLOCK_SIZE, typename T>
global void scaled_fp4_quant_trans_kernel(
const T* input, uint8_t* output, uint8_t* output_sf,
int batch_size, int num_heads, int num_tokens,
int stride_bz_input, int stride_h_input, int stride_seq_input,
int stride_bz_output, int stride_h_output, int stride_d_output,
int stride_bz_output_sf, int stride_h_output_sf, int stride_d_output_sf) {
static_assert(std::is_same<T, half>::value || std::is_same<T, nv_bfloat16>::value, "Only half and bfloat16 input are supported");
using PackedVec = PackedVec;
const int batch_id = blockIdx.y;
const int head_id = blockIdx.z;
const int token_block_id = blockIdx.x;
static_assert(CVT_FP4_ELTS_PER_THREAD == 8 || CVT_FP4_ELTS_PER_THREAD == 16,
"CVT_FP4_ELTS_PER_THREAD must be 8 or 16");
static_assert(sizeof(PackedVec) == sizeof(T) * CVT_FP4_ELTS_PER_THREAD,
"Vec size is not matched.");
// calculate max of every consecutive 16 elements
auto localMax = __habs2(in_vec.elts[0]);
#pragma unroll
for (int i = 1; i < CVT_FP4_ELTS_PER_THREAD / 2; i++) { // local max
localMax = __hmax2(localMax, __habs2(in_vec.elts[i]));
}
if constexpr (CVT_FP4_ELTS_PER_THREAD == 8) { // shuffle across two threads
localMax = __hmax2(__shfl_xor_sync(0xffffffff, localMax, 1, 32), localMax);
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("scaled_fp4_quant", &scaled_fp4_quant);
m.def("scaled_fp4_quant_permute", &scaled_fp4_quant_permute);
m.def("scaled_fp4_quant_trans", &scaled_fp4_quant_trans);
}
--- End of content ---
PackedVec
While it's impossible to guarantee with 100% certainty that no other issues exist without testing in the exact target environment, the fixes I've implemented address all the common and obvious sources of this specific CUDA error in the provided code. No other alignment issues are apparent.