Skip to content

Commit 148a5c1

Browse files
authored
[Bugfix]fix output Nan/Inf in marlin if dtype=float16 (vllm-project#33972)
Signed-off-by: IriKa Qiu <qiujie.jq@gmail.com>
1 parent b69bf2f commit 148a5c1

8 files changed

Lines changed: 83 additions & 55 deletions

File tree

csrc/moe/marlin_moe_wna16/kernel.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
const int4 *__restrict__ b_bias_ptr, \
1414
const float *__restrict__ a_scales_ptr, \
1515
const int4 *__restrict__ scales_ptr, \
16-
const uint16_t *__restrict__ global_scale_ptr, \
16+
const float *__restrict__ global_scale_ptr, \
1717
const int4 *__restrict__ zp_ptr, const int *__restrict__ g_idx, \
1818
const int32_t *__restrict__ sorted_token_ids_ptr, \
1919
const int32_t *__restrict__ expert_ids_ptr, \

csrc/moe/marlin_moe_wna16/marlin_template.h

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ __global__ void Marlin(
260260
// fp16 quantization scales. shape (k/groupsize, n)
261261
const int4* __restrict__ scales_ptr,
262262
// fp16 global scale (for nvfp4// only)
263-
const uint16_t* __restrict__ global_scale_ptr,
263+
const float* __restrict__ global_scale_ptr,
264264
// 4bit packed zero-points of shape
265265
// (k/groupsize, n/pack_factor)
266266
const int4* __restrict__ zp_ptr,
@@ -308,7 +308,14 @@ __global__ void Marlin(
308308
constexpr int moe_block_size = m_block_size_8 ? 8 : (16 * thread_m_blocks);
309309

310310
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ == 750
311-
constexpr bool use_fp16_accum = a_type_id == vllm::kFloat16.id();
311+
static constexpr auto num_bits =
312+
vllm::ScalarType::from_id(b_type_id).size_bits();
313+
// Disable use_fp16_accum for NVFP4 and cases when group_size == -1 &&
314+
// num_bits == 4
315+
constexpr bool use_fp16_accum =
316+
a_type_id == vllm::kFloat16.id() &&
317+
(!(b_type_id == vllm::kFE2M1f.id() && s_type_id == vllm::kFE4M3fn.id()) &&
318+
!(group_blocks == -1 && num_bits == 4));
312319
#else
313320
constexpr bool use_fp16_accum = false;
314321
#endif
@@ -357,7 +364,7 @@ __global__ void Marlin(
357364
has_zp && !is_zp_float && !std::is_same<scalar_t, nv_bfloat16>::value ||
358365
has_zp && !is_zp_float && !(b_type == vllm::kU8);
359366

360-
c_scalar_t2 global_scale;
367+
float global_scale_f32 = 1.0f;
361368

362369
constexpr bool has_act_order = group_blocks == 0;
363370

@@ -507,11 +514,12 @@ __global__ void Marlin(
507514

508515
if (mul_topk_weights) {
509516
idx = idx < prob_m_top_k ? idx : 0;
510-
c_scalar_t2 topk_weight_val =
511-
Cdtype::num2num2(Cdtype::float2num(topk_weights_ptr[idx]));
517+
float topk_weight_tmp = topk_weights_ptr[idx];
512518
if constexpr (b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn) {
513-
topk_weight_val = __hmul2(topk_weight_val, global_scale);
519+
topk_weight_tmp *= global_scale_f32;
514520
}
521+
c_scalar_t2 topk_weight_val =
522+
Cdtype::num2num2(Cdtype::float2num(topk_weight_tmp));
515523
sh_block_topk_weights[threadIdx.x] = topk_weight_val;
516524
}
517525
}
@@ -532,8 +540,7 @@ __global__ void Marlin(
532540
expert_id = expert_ids_ptr[block_id];
533541

534542
if constexpr (b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn) {
535-
uint16_t val = global_scale_ptr[expert_id];
536-
global_scale = Cdtype::num2num2(*reinterpret_cast<c_scalar_t*>(&val));
543+
global_scale_f32 = global_scale_ptr[expert_id];
537544
}
538545

539546
B_expert_off = expert_id * prob_n * prob_k / (pack_factor * 4);
@@ -1784,6 +1791,13 @@ __global__ void Marlin(
17841791
// We first reorder in shared memory to guarantee the most efficient final
17851792
// global write patterns
17861793
auto write = [&](int idx, float c0, float c1, FragS& s, FragS& b_bias) {
1794+
if constexpr (b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn) {
1795+
if (!mul_topk_weights) {
1796+
c0 *= global_scale_f32;
1797+
c1 *= global_scale_f32;
1798+
}
1799+
}
1800+
17871801
c_scalar_t2 res =
17881802
Cdtype::nums2num2(Cdtype::float2num(c0), Cdtype::float2num(c1));
17891803

@@ -1800,11 +1814,6 @@ __global__ void Marlin(
18001814
res = __hmul2(res, tmp_scale);
18011815
}
18021816

1803-
if constexpr (b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn) {
1804-
if (!mul_topk_weights) {
1805-
res = __hmul2(res, global_scale);
1806-
}
1807-
}
18081817
if (has_bias && last) {
18091818
c_scalar_t2 tmp_bias = b_bias[0];
18101819
if constexpr (m_block_size_8) {

csrc/moe/marlin_moe_wna16/ops.cu

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ void marlin_mm(const void* A, const void* B, void* C, void* C_tmp, void* b_bias,
382382
const int4* bias_ptr = (const int4*)b_bias;
383383
const float* a_s_ptr = (const float*)a_s;
384384
const int4* b_s_ptr = (const int4*)b_s;
385-
const uint16_t* g_s_ptr = (const uint16_t*)g_s;
385+
const float* g_s_ptr = (const float*)g_s;
386386
const int4* zp_ptr = (const int4*)zp;
387387
const int* g_idx_ptr = (const int*)g_idx;
388388
const int* perm_ptr = (const int*)perm;
@@ -759,7 +759,7 @@ torch::Tensor moe_wna16_marlin_gemm(
759759
TORCH_CHECK(b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn,
760760
"global_scale can only be used for nvfp4 format.");
761761
} else {
762-
global_scale = torch::empty({0}, options);
762+
global_scale = torch::empty({0}, options_fp32);
763763
TORCH_CHECK(!(b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn),
764764
"the global_scale parameter must be passed for nvfp4 format.");
765765
}
@@ -842,8 +842,8 @@ torch::Tensor moe_wna16_marlin_gemm(
842842

843843
TORCH_CHECK(a_scales.scalar_type() == at::ScalarType::Float,
844844
"scalar type of a_scales must be float");
845-
TORCH_CHECK(global_scale.scalar_type() == c.scalar_type(),
846-
"scalar type of global_scale must be the same with c");
845+
TORCH_CHECK(global_scale.scalar_type() == at::ScalarType::Float,
846+
"scalar type of global_scale must be float");
847847
if (a_type.size_bits() == 16) {
848848
TORCH_CHECK(
849849
a.scalar_type() == c.scalar_type(),

csrc/quantization/activation_kernels.cu

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -189,10 +189,7 @@ __device__ __forceinline__ void cp_async_wait<0>() {
189189
}
190190

191191
__device__ __forceinline__ float clip(float v, float mmin, float mmax) {
192-
#if __CUDACC_VER_MAJOR__ >= 11 && __CUDA_ARCH__ >= 800
193192
return fminf(mmax, fmaxf(v, mmin));
194-
#else
195-
#endif
196193
}
197194

198195
__device__ __forceinline__ __nv_bfloat16 clip(__nv_bfloat16 v,

csrc/quantization/marlin/kernel.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
const int4 *__restrict__ b_bias_ptr, \
1414
const float *__restrict__ a_scales_ptr, \
1515
const int4 *__restrict__ scales_ptr, \
16-
const uint16_t *__restrict__ global_scale_ptr, \
16+
const float *__restrict__ global_scale_ptr, \
1717
const int4 *__restrict__ zp_ptr, const int *__restrict__ g_idx, \
1818
int num_groups, int prob_m, int prob_n, int prob_k, int lda, int *locks, \
1919
bool has_bias, bool use_atomic_add, bool use_fp32_reduce, \

csrc/quantization/marlin/marlin.cu

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ torch::Tensor marlin_gemm(
5757
int64_t size_k, bool is_k_full, bool use_atomic_add, bool use_fp32_reduce,
5858
bool is_zp_float) {
5959
TORCH_CHECK_NOT_IMPLEMENTED(false,
60-
"marlin_gemm(..) requires CUDA_ARCH >= 8.0");
60+
"marlin_gemm(..) requires CUDA_ARCH >= 7.5");
6161
return torch::empty({1, 1});
6262
}
6363

@@ -356,7 +356,7 @@ void marlin_mm(const void* A, const void* B, void* C, void* C_tmp, void* b_bias,
356356
const int4* bias_ptr = (const int4*)b_bias;
357357
const float* a_s_ptr = (const float*)a_s;
358358
const int4* b_s_ptr = (const int4*)b_s;
359-
const uint16_t* g_s_ptr = (const uint16_t*)g_s;
359+
const float* g_s_ptr = (const float*)g_s;
360360

361361
const int4* zp_ptr = (const int4*)zp;
362362
const int* g_idx_ptr = (const int*)g_idx;
@@ -751,7 +751,7 @@ torch::Tensor marlin_gemm(
751751
TORCH_CHECK(b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn,
752752
"global_scale can only be used for nvfp4 format.");
753753
} else {
754-
global_scale = torch::empty({0}, options);
754+
global_scale = torch::empty({0}, options_fp32);
755755
TORCH_CHECK(!(b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn),
756756
"the global_scale parameter must be passed for nvfp4 format.");
757757
}
@@ -832,8 +832,8 @@ torch::Tensor marlin_gemm(
832832

833833
TORCH_CHECK(a_scales.scalar_type() == at::ScalarType::Float,
834834
"scalar type of a_scales must be float");
835-
TORCH_CHECK(global_scale.scalar_type() == c.scalar_type(),
836-
"scalar type of global_scale must be the same with c");
835+
TORCH_CHECK(global_scale.scalar_type() == at::ScalarType::Float,
836+
"scalar type of global_scale must be float");
837837
if (a_type.size_bits() == 16) {
838838
TORCH_CHECK(
839839
a.scalar_type() == c.scalar_type(),

csrc/quantization/marlin/marlin_template.h

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -251,8 +251,8 @@ __global__ void Marlin(
251251
const float* __restrict__ a_scales_ptr,
252252
// fp16 quantization scales. shape (k/groupsize, n)
253253
const int4* __restrict__ scales_ptr,
254-
// fp16 global scale (for nvfp4// only)
255-
const uint16_t* __restrict__ global_scale_ptr,
254+
// float global scale (for nvfp4// only)
255+
const float* __restrict__ global_scale_ptr,
256256
// 4bit packed zero-points of shape
257257
// (k/groupsize, n/pack_factor)
258258
const int4* __restrict__ zp_ptr,
@@ -292,7 +292,13 @@ __global__ void Marlin(
292292
#endif
293293

294294
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ == 750
295-
constexpr bool use_fp16_accum = a_type_id == vllm::kFloat16.id();
295+
constexpr auto num_bits = vllm::ScalarType::from_id(b_type_id).size_bits();
296+
// Disable use_fp16_accum for NVFP4 and cases when group_size == -1 &&
297+
// num_bits == 4
298+
constexpr bool use_fp16_accum =
299+
a_type_id == vllm::kFloat16.id() &&
300+
(!(b_type_id == vllm::kFE2M1f.id() && s_type_id == vllm::kFE4M3fn.id()) &&
301+
!(group_blocks == -1 && num_bits == 4));
296302
#else
297303
constexpr bool use_fp16_accum = false;
298304
#endif
@@ -342,11 +348,10 @@ __global__ void Marlin(
342348
has_zp && !is_zp_float && !std::is_same<scalar_t, nv_bfloat16>::value ||
343349
has_zp && !is_zp_float && !(b_type == vllm::kU8);
344350

345-
c_scalar_t2 global_scale;
351+
float global_scale_f32 = 1.0f;
346352

347353
if constexpr (b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn) {
348-
uint16_t val = global_scale_ptr[0];
349-
global_scale = Cdtype::num2num2(*reinterpret_cast<c_scalar_t*>(&val));
354+
global_scale_f32 = global_scale_ptr[0];
350355
}
351356

352357
constexpr bool has_act_order = group_blocks == 0;
@@ -1644,6 +1649,10 @@ __global__ void Marlin(
16441649
// We first reorder in shared memory to guarantee the most efficient final
16451650
// global write patterns
16461651
auto write = [&](int idx, float c0, float c1, FragS& s, FragS& b_bias) {
1652+
if constexpr (b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn) {
1653+
c0 *= global_scale_f32;
1654+
c1 *= global_scale_f32;
1655+
}
16471656
c_scalar_t2 res =
16481657
Cdtype::nums2num2(Cdtype::float2num(c0), Cdtype::float2num(c1));
16491658

@@ -1659,10 +1668,6 @@ __global__ void Marlin(
16591668
}
16601669
res = __hmul2(res, tmp_scale);
16611670
}
1662-
1663-
if constexpr (b_type == vllm::kFE2M1f && s_type == vllm::kFE4M3fn) {
1664-
res = __hmul2(res, global_scale);
1665-
}
16661671
if (has_bias && last) {
16671672
c_scalar_t2 tmp_bias = b_bias[0];
16681673
if constexpr (m_block_size_8) {

vllm/model_executor/layers/quantization/utils/marlin_utils_fp4.py

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,19 @@ def is_fp4_marlin_supported():
2727
return current_platform.has_device_capability(75)
2828

2929

30-
def _nvfp4_compute_scale_factor(marlin_scales: torch.Tensor) -> float:
30+
def _nvfp4_compute_scale_factor(
31+
marlin_scales: torch.Tensor,
32+
a_dtype: torch.dtype | None = None,
33+
) -> float:
3134
"""Compute the power-of-2 scale_factor needed so that all non-zero
3235
values in marlin_scales * 2^7 are >= 2 after rescaling.
3336
Returns a Python float (power of 2, >= 1.0)."""
37+
38+
# Since half has a smaller dynamic range compared to bfloat16,
39+
# no rescaling is applied here if active dtype is half.
40+
if a_dtype is not None and a_dtype == torch.half:
41+
return 1.0
42+
3443
ws_float = marlin_scales.float() * (2**7)
3544
nonzero_mask = ws_float > 0
3645
if nonzero_mask.any():
@@ -44,6 +53,7 @@ def _nvfp4_compute_scale_factor(marlin_scales: torch.Tensor) -> float:
4453
def nvfp4_marlin_process_scales(
4554
marlin_scales: torch.Tensor,
4655
scale_factor: float | None = None,
56+
a_dtype: torch.dtype | None = None,
4757
) -> tuple[torch.Tensor, float]:
4858
"""Process NVFP4 weight scales into the special S0E5M3 format for Marlin.
4959
@@ -91,7 +101,7 @@ def nvfp4_marlin_process_scales(
91101
# to fully utilize the E4M3 dynamic range (e.g., global_scale=1).
92102
# The caller must compensate by dividing global_scale by scale_factor.
93103
if scale_factor is None:
94-
scale_factor = _nvfp4_compute_scale_factor(marlin_scales)
104+
scale_factor = _nvfp4_compute_scale_factor(marlin_scales, a_dtype)
95105
if scale_factor > 1.0:
96106
marlin_scales = (marlin_scales.float() * scale_factor).to(torch.half)
97107

@@ -119,12 +129,14 @@ def mxfp4_marlin_process_scales(marlin_scales, input_dtype=None):
119129
return marlin_scales
120130

121131

122-
def nvfp4_marlin_process_global_scale(global_scale):
123-
assert global_scale.dtype in [torch.half, torch.bfloat16]
132+
def nvfp4_marlin_process_global_scale(global_scale, a_dtype: torch.dtype | None = None):
133+
if a_dtype is None:
134+
a_dtype = global_scale.dtype
135+
assert a_dtype in [torch.half, torch.bfloat16]
124136
fp4_exponent = 2
125-
if global_scale.dtype == torch.half:
137+
if a_dtype == torch.half:
126138
target_exponent = 5
127-
elif global_scale.dtype == torch.bfloat16:
139+
elif a_dtype == torch.bfloat16:
128140
target_exponent = 8
129141
# exponent_bias_fp16 = 2 ** 4 - 2 ** 1 = 14
130142
# exponent_bias_bf16 = 2 ** 7 - 2 ** 1 = 126
@@ -244,11 +256,15 @@ def prepare_fp4_layer_for_marlin(
244256
)
245257

246258
if is_nvfp4:
247-
weight_scale, scale_factor = nvfp4_marlin_process_scales(weight_scale)
259+
weight_scale, scale_factor = nvfp4_marlin_process_scales(
260+
weight_scale, a_dtype=param_dtype
261+
)
248262
layer.weight_scale = torch.nn.Parameter(weight_scale, requires_grad=False)
249263

250-
weight_global_scale = layer.weight_global_scale.to(param_dtype)
251-
weight_global_scale = nvfp4_marlin_process_global_scale(weight_global_scale)
264+
weight_global_scale = layer.weight_global_scale.to(torch.float32)
265+
weight_global_scale = nvfp4_marlin_process_global_scale(
266+
weight_global_scale, param_dtype
267+
)
252268
weight_global_scale = weight_global_scale / scale_factor
253269
layer.weight_global_scale = torch.nn.Parameter(
254270
weight_global_scale, requires_grad=False
@@ -339,7 +355,6 @@ def premute_scales(
339355
scales: torch.Tensor, g_scales: torch.Tensor, name: str
340356
) -> tuple[torch.Tensor, torch.Tensor]:
341357
scales = scales.to(param_dtype)
342-
g_scales = g_scales.to(param_dtype)
343358

344359
tensor_list = []
345360
num_shards = 2 if is_act_and_mul else 1
@@ -350,7 +365,7 @@ def premute_scales(
350365

351366
# All experts share one global_scale, so compute the max
352367
# scale_factor across all experts first, then apply uniformly.
353-
combined_scale_factor = _nvfp4_compute_scale_factor(scales)
368+
combined_scale_factor = _nvfp4_compute_scale_factor(scales, param_dtype)
354369

355370
for i in range(E):
356371
scale = scales[i].T
@@ -362,12 +377,12 @@ def premute_scales(
362377
is_a_8bit=is_a_8bit,
363378
)
364379
marlin_scales, _ = nvfp4_marlin_process_scales(
365-
marlin_scales, scale_factor=combined_scale_factor
380+
marlin_scales, scale_factor=combined_scale_factor, a_dtype=param_dtype
366381
)
367382
tensor_list.append(marlin_scales)
368383

369384
scales = torch.cat([x.unsqueeze(0) for x in tensor_list], 0)
370-
g_scales = nvfp4_marlin_process_global_scale(g_scales)
385+
g_scales = nvfp4_marlin_process_global_scale(g_scales, param_dtype)
371386
g_scales = g_scales / combined_scale_factor
372387
return scales, g_scales
373388

@@ -438,7 +453,7 @@ def prepare_moe_fp4_layer_for_marlin(
438453
scales = scales.view(torch.float8_e8m0fnu)
439454
scales = scales.to(param_dtype)
440455
if is_nvfp4:
441-
global_scale = getattr(layer, name + "_weight_scale_2").to(param_dtype)
456+
global_scale = getattr(layer, name + "_weight_scale_2")
442457

443458
tensor_list = []
444459
if "w13" in name:
@@ -449,7 +464,7 @@ def prepare_moe_fp4_layer_for_marlin(
449464
# For NVFP4: compute unified scale_factor across all experts
450465
combined_scale_factor = None
451466
if is_nvfp4:
452-
combined_scale_factor = _nvfp4_compute_scale_factor(scales)
467+
combined_scale_factor = _nvfp4_compute_scale_factor(scales, param_dtype)
453468

454469
for i in range(e):
455470
scale = scales[i].T
@@ -463,7 +478,9 @@ def prepare_moe_fp4_layer_for_marlin(
463478
)
464479
if is_nvfp4:
465480
marlin_scales, _ = nvfp4_marlin_process_scales(
466-
marlin_scales, scale_factor=combined_scale_factor
481+
marlin_scales,
482+
scale_factor=combined_scale_factor,
483+
a_dtype=param_dtype,
467484
)
468485
else:
469486
marlin_scales = mxfp4_marlin_process_scales(
@@ -477,7 +494,7 @@ def prepare_moe_fp4_layer_for_marlin(
477494

478495
if is_nvfp4:
479496
assert combined_scale_factor is not None
480-
global_scale = nvfp4_marlin_process_global_scale(global_scale)
497+
global_scale = nvfp4_marlin_process_global_scale(global_scale, param_dtype)
481498
global_scale = global_scale / combined_scale_factor
482499
global_scale = torch.nn.Parameter(global_scale, requires_grad=False)
483500
setattr(layer, name + "_weight_scale_2", global_scale)
@@ -665,7 +682,7 @@ def rand_marlin_weight_nvfp4_like(weight, group_size, input_dtype=None):
665682
)
666683
marlin_scales, scale_factor = nvfp4_marlin_process_scales(marlin_scales)
667684

668-
global_scale = nvfp4_marlin_process_global_scale(global_scale)
685+
global_scale = nvfp4_marlin_process_global_scale(global_scale).to(torch.float32)
669686
global_scale = global_scale / scale_factor
670687

671688
return weight_ref.T, marlin_qweight, marlin_scales, global_scale

0 commit comments

Comments
 (0)