-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_ops_nvfp4_fp4.cpp
More file actions
2767 lines (2571 loc) · 118 KB
/
Copy pathtest_ops_nvfp4_fp4.cpp
File metadata and controls
2767 lines (2571 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// vllm.cpp runtime tests. Core W4A4 references mirror the pinned quant kernels;
// the W3-D packed-QKV case also ports QKVParallelLinear's loader topology from
// tests/model_executor/model_loader/test_reload.py:150 and the logical shard
// mapping exercised by tests/models/test_adapters.py:44-60.
// TRUE W4A4 (fp4 activations x fp4 weights) ops — the 27B path (notes §7). These
// validate the CPU kernels vt::ScaledFp4Quant + vt::MatmulNvfp4Fp4 against the
// pinned vLLM CPU truth:
// - ScaledFp4Quant must be BYTE-EXACT vs vllm::RefScaledFp4Quant, and its
// decode must reproduce vllm::RefNvfp4QuantDequant's x_dq.
// - MatmulNvfp4Fp4( ScaledFp4Quant(x), W ) must equal vllm::RunNvfp4Emulation
// (the emulated true-W4A4 linear) up to K-reduction float order.
// CPU-only (also the reference the future CUDA kernels validate against).
#include <doctest/doctest.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <filesystem>
#include <fstream>
#include <future>
#include <random>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_set>
#include <utility>
#include <vector>
#include "vllm/model_executor/layers/quantization/compressed_tensors/nvfp4_emulation.h"
#include "vllm/model_executor/model_loader/nvfp4_dequant.h" // F8E4M3ToF32, kE2M1Lut
#include "vllm/model_executor/models/qwen3_5_weights.h"
#include "vt/backend.h"
#ifdef VLLM_CPP_CUDA
#include <cuda_runtime.h>
#include "vt/cuda/cuda_arch_tactics.h"
#include "vt/cuda/cuda_device_caps.h"
#endif
#include "vt/cuda/nvfp4_autotune.h"
#include "vt/cuda/nvfp4_plan_cache.h"
#include "vt/cuda/nvfp4_tactic_ids.h"
#include "vt/dtype.h"
#include "vt/ops.h"
using vt::Device;
using vt::DeviceType;
using vt::DType;
using vt::Queue;
using vt::Tensor;
namespace {
Device Cpu() { return Device{DeviceType::kCPU, 0}; }
Queue CpuQueue() { return Queue{Cpu(), nullptr}; }
uint16_t FloatToBf16(float value) {
uint32_t bits = 0;
std::memcpy(&bits, &value, sizeof(bits));
bits += 0x7FFFU + ((bits >> 16U) & 1U);
return static_cast<uint16_t>(bits >> 16U);
}
// Decode a fp4 activation row-trip from the ScaledFp4Quant outputs, mirroring the
// GEMM's a-operand: a_fp4 * f8(a_scale) / input_global_scale (== x_dq).
float DecodeActElem(const uint8_t* packed, const uint8_t* scale, int64_t k, int64_t row,
int64_t col, float input_global_scale) {
const int64_t groups = k / 16;
const uint8_t nib = (col % 2 == 0) ? (packed[(row * k + col) / 2] & 0x0FU)
: (packed[(row * k + col) / 2] >> 4);
const float mag = vllm::kE2M1Lut[nib & 0x7U] * ((nib & 0x8U) ? -1.0F : 1.0F);
const float sf = vllm::F8E4M3ToF32(scale[row * groups + col / 16]);
return mag * sf / input_global_scale; // block_scale = sf/global
}
int64_t RoundUpTo(int64_t value, int64_t multiple) {
return (value + multiple - 1) / multiple * multiple;
}
int64_t CutlassScaleOffset(int64_t row, int64_t col, int64_t padded_cols) {
const int64_t m_tile = row / 128;
const int64_t outer_m = row % 32;
const int64_t inner_m = (row % 128) / 32;
const int64_t k_tile = col / 4;
const int64_t inner_k = col % 4;
return ((((m_tile * (padded_cols / 4) + k_tile) * 32 + outer_m) * 4 +
inner_m) *
4 +
inner_k);
}
std::vector<uint8_t> SwizzleScaleReference(const std::vector<uint8_t>& linear,
int64_t rows, int64_t cols) {
const int64_t padded_rows = RoundUpTo(rows, 128);
const int64_t padded_cols = RoundUpTo(cols, 4);
std::vector<uint8_t> swizzled(
static_cast<size_t>(padded_rows * padded_cols), uint8_t{0});
for (int64_t row = 0; row < rows; ++row) {
for (int64_t col = 0; col < cols; ++col) {
swizzled[static_cast<size_t>(
CutlassScaleOffset(row, col, padded_cols))] =
linear[static_cast<size_t>(row * cols + col)];
}
}
return swizzled;
}
} // namespace
TEST_CASE("FlashInfer NVFP4 hybrid M buckets preserve small decode shapes") {
using vt::cuda::nvfp4::HybridMBucket;
const std::vector<std::pair<uint32_t, uint32_t>> cases = {
{0, 1}, {1, 1}, {2, 2}, {3, 4}, {4, 4},
{8, 8}, {16, 16}, {255, 256}, {256, 256}, {257, 512},
{2048, 2048}, {2049, 2560}, {4096, 4096}, {4097, 8192}, {32768, 32768},
};
for (const auto& [value, expected] : cases) {
CAPTURE(value);
CHECK(HybridMBucket(value) == expected);
}
using vt::cuda::nvfp4::LegacyMBucket;
CHECK(LegacyMBucket(0) == 16);
CHECK(LegacyMBucket(1) == 16);
CHECK(LegacyMBucket(2) == 16);
CHECK(LegacyMBucket(8) == 16);
CHECK(LegacyMBucket(16) == 16);
CHECK(LegacyMBucket(17) == 32);
CHECK_THROWS_AS(vt::cuda::nvfp4::NextPositivePowerOfTwo(0x80000001U),
std::overflow_error);
using vt::cuda::nvfp4::HybridMTuningBuckets;
CHECK(HybridMTuningBuckets(2048) ==
std::vector<uint32_t>{1, 2, 4, 8, 16, 32, 64, 128, 256, 512,
768, 1024, 1280, 1536, 1792, 2048});
CHECK(HybridMTuningBuckets(4096) ==
std::vector<uint32_t>{1, 2, 4, 8, 16, 32, 64,
128, 256, 512, 768, 1024, 1280, 1536,
1792, 2048, 2560, 3072, 3584, 4096});
CHECK(HybridMTuningBuckets(5000).back() == 5000);
}
TEST_CASE("FlashInfer SM12 NVFP4 tactics retain exact stable descriptor order") {
using vt::cuda::nvfp4::TacticDescriptorForId;
using vt::cuda::nvfp4::kFullTacticDescriptors;
using vt::cuda::nvfp4::kFullTacticSetVersion;
using vt::cuda::nvfp4::kW1TacticIds;
using vt::cuda::nvfp4::kW1TacticSetVersion;
constexpr std::array<std::array<int, 3>, 8> tiles{{
{128, 32, 128}, {128, 32, 256}, {128, 64, 128}, {128, 64, 256},
{128, 128, 128}, {128, 128, 256}, {256, 128, 128}, {128, 256, 128},
}};
REQUIRE(kFullTacticDescriptors.size() == tiles.size() * 4);
for (size_t tile = 0; tile < tiles.size(); ++tile) {
for (size_t variant = 0; variant < 4; ++variant) {
const size_t id = tile * 4 + variant;
const auto& descriptor = kFullTacticDescriptors[id];
CAPTURE(id);
CHECK(descriptor.id == static_cast<int>(id));
CHECK(descriptor.tile_m == tiles[tile][0]);
CHECK(descriptor.tile_n == tiles[tile][1]);
CHECK(descriptor.tile_k == tiles[tile][2]);
CHECK(descriptor.swap_ab == (variant == 0 || variant == 2));
CHECK(descriptor.stream_k == (variant >= 2));
CHECK(std::string(descriptor.name).empty() == false);
CHECK(TacticDescriptorForId(static_cast<int>(id)) == &descriptor);
}
}
CHECK(TacticDescriptorForId(-1) == nullptr);
CHECK(TacticDescriptorForId(32) == nullptr);
CHECK((kW1TacticIds == std::array<int, 4>{17, 25, 21, 29}));
CHECK(kW1TacticSetVersion == 1);
CHECK(kFullTacticSetVersion == 2);
}
TEST_CASE("NVFP4 plan key covers device architecture dtype shape and tactic ABI") {
using vt::cuda::nvfp4::PlanKey;
using vt::cuda::nvfp4::PlanKeyHash;
const PlanKey base{16, 5120, 17408, 0, 121, 2, 1};
std::unordered_set<PlanKey, PlanKeyHash> keys;
keys.insert(base);
auto key = base;
key.m_bucket = 8;
keys.insert(key);
key = base;
key.n = 1024;
keys.insert(key);
key = base;
key.k = 5120;
keys.insert(key);
key = base;
key.device_ordinal = 1;
keys.insert(key);
key = base;
key.architecture = 120;
keys.insert(key);
key = base;
key.output_dtype = 1;
keys.insert(key);
key = base;
key.tactic_set_version = 2;
keys.insert(key);
CHECK(keys.size() == 8);
CHECK(keys.contains(base));
}
TEST_CASE("NVFP4 plan tuning is single-flight per key and independent across keys") {
using vt::cuda::nvfp4::PlanKey;
using vt::cuda::nvfp4::ResolvePlan;
using vt::cuda::nvfp4::SingleFlightPlanCache;
SingleFlightPlanCache<int> cache;
const PlanKey key{16, 5120, 17408, 0, 121, 2, 1};
std::promise<void> owner_started;
auto owner_started_future = owner_started.get_future();
std::promise<void> release_owner;
const auto release_future = release_owner.get_future().share();
std::atomic<int> tune_count{0};
std::vector<int> results(16, -1);
std::vector<std::exception_ptr> errors(16);
std::thread owner([&] {
try {
results[0] = ResolvePlan(
cache, key, [] { return true; }, [&] {
++tune_count;
owner_started.set_value();
release_future.wait();
return 7;
});
} catch (...) {
errors[0] = std::current_exception();
}
});
owner_started_future.wait();
std::vector<std::thread> waiters;
for (size_t i = 1; i < results.size(); ++i) {
waiters.emplace_back([&, i] {
try {
results[i] = ResolvePlan(cache, key, [] { return true; }, [&] {
++tune_count;
return 99;
});
} catch (...) {
errors[i] = std::current_exception();
}
});
}
while (cache.WaiterCountForTesting(key) != 15) std::this_thread::yield();
release_owner.set_value();
owner.join();
for (auto& waiter : waiters) waiter.join();
CHECK(tune_count.load() == 1);
CHECK(cache.SizeForTesting() == 1);
for (size_t i = 0; i < results.size(); ++i) {
CAPTURE(i);
CHECK(errors[i] == nullptr);
CHECK(results[i] == 7);
}
// A tuner blocked on one shape never owns the global map mutex.
const PlanKey blocked_key{8, 5120, 5120, 0, 121, 2, 1};
const PlanKey independent_key{8, 1024, 5120, 0, 121, 2, 1};
std::promise<void> blocked_started;
auto blocked_started_future = blocked_started.get_future();
std::promise<void> release_blocked;
const auto blocked_release_future = release_blocked.get_future().share();
int blocked_result = -1;
std::thread blocked([&] {
blocked_result = ResolvePlan(
cache, blocked_key, [] { return true; }, [&] {
blocked_started.set_value();
blocked_release_future.wait();
return 11;
});
});
blocked_started_future.wait();
CHECK(ResolvePlan(cache, independent_key, [] { return true; }, [] { return 13; }) == 13);
release_blocked.set_value();
blocked.join();
CHECK(blocked_result == 11);
}
TEST_CASE("NVFP4 plan cache rejects capture misses and retries failed tuning") {
using vt::cuda::nvfp4::PlanKey;
using vt::cuda::nvfp4::ResolvePlan;
using vt::cuda::nvfp4::SingleFlightPlanCache;
SingleFlightPlanCache<int> cache;
const PlanKey key{4, 5120, 17408, 0, 121, 2, 1};
int capture_queries = 0;
std::atomic<int> tune_count{0};
CHECK_THROWS_WITH_AS(
ResolvePlan(
cache, key,
[&] {
++capture_queries;
return false;
},
[&] {
++tune_count;
return 1;
}),
"NVFP4 plan cache miss while tuning is disallowed", std::runtime_error);
CHECK(capture_queries == 1);
CHECK(tune_count.load() == 0);
CHECK(cache.SizeForTesting() == 0);
std::promise<void> failed_owner_started;
auto failed_owner_started_future = failed_owner_started.get_future();
std::promise<void> release_failed_owner;
const auto failed_release_future = release_failed_owner.get_future().share();
std::vector<std::exception_ptr> failures(8);
std::thread failed_owner([&] {
try {
static_cast<void>(ResolvePlan(cache, key, [] { return true; }, [&]() -> int {
++tune_count;
failed_owner_started.set_value();
failed_release_future.wait();
throw std::runtime_error("tune failed");
}));
} catch (...) {
failures[0] = std::current_exception();
}
});
failed_owner_started_future.wait();
std::vector<std::thread> failed_waiters;
for (size_t i = 1; i < failures.size(); ++i) {
failed_waiters.emplace_back([&, i] {
try {
static_cast<void>(ResolvePlan(cache, key, [] { return true; }, [&] {
++tune_count;
return 99;
}));
} catch (...) {
failures[i] = std::current_exception();
}
});
}
while (cache.WaiterCountForTesting(key) != 7) std::this_thread::yield();
release_failed_owner.set_value();
failed_owner.join();
for (auto& waiter : failed_waiters) waiter.join();
CHECK(tune_count.load() == 1);
for (size_t i = 0; i < failures.size(); ++i) {
CAPTURE(i);
REQUIRE(failures[i] != nullptr);
try {
std::rethrow_exception(failures[i]);
} catch (const std::runtime_error& error) {
CHECK(std::string(error.what()) == "tune failed");
}
}
CHECK(cache.SizeForTesting() == 0);
CHECK(ResolvePlan(cache, key, [] { return true; }, [&] {
++tune_count;
return 17;
}) == 17);
CHECK(tune_count.load() == 2);
// A ready graph-capture lookup never evaluates the capture predicate.
capture_queries = 0;
CHECK(ResolvePlan(
cache, key,
[&] {
++capture_queries;
return false;
},
[] { return 23; }) == 17);
CHECK(capture_queries == 0);
}
TEST_CASE("scaled_fp4_quant CPU == vllm::RefScaledFp4Quant (byte-exact) + decode") {
const int64_t M = 5, K = 64;
std::mt19937 rng(1234);
std::normal_distribution<float> nd(0.0F, 3.0F);
std::vector<float> x(static_cast<size_t>(M * K));
for (auto& v : x) v = nd(rng);
const float input_global_scale = 7.3F; // on-disk divisor (used directly)
std::vector<uint8_t> ref_packed(static_cast<size_t>(M * K / 2));
std::vector<uint8_t> ref_scale(static_cast<size_t>(M * K / 16));
vllm::RefScaledFp4Quant(x.data(), M, K, input_global_scale, ref_packed.data(),
ref_scale.data());
std::vector<uint8_t> op_packed(static_cast<size_t>(M * K / 2), 0);
std::vector<uint8_t> op_scale(static_cast<size_t>(M * K / 16), 0);
Tensor tx = Tensor::Contiguous(x.data(), DType::kF32, Cpu(), {M, K});
Tensor tp = Tensor::Contiguous(op_packed.data(), DType::kI8, Cpu(), {M, K / 2});
Tensor ts = Tensor::Contiguous(op_scale.data(), DType::kI8, Cpu(), {M, K / 16});
Queue q = CpuQueue();
vt::ScaledFp4Quant(q, tp, ts, tx, input_global_scale);
for (size_t i = 0; i < ref_packed.size(); ++i) CHECK(op_packed[i] == ref_packed[i]);
for (size_t i = 0; i < ref_scale.size(); ++i) CHECK(op_scale[i] == ref_scale[i]);
// Decode == RefNvfp4QuantDequant x_dq (the emulation activation round-trip).
std::vector<float> x_dq(static_cast<size_t>(M * K));
vllm::RefNvfp4QuantDequant(x.data(), M, K, input_global_scale, x_dq.data());
for (int64_t r = 0; r < M; ++r)
for (int64_t c = 0; c < K; ++c) {
const float got = DecodeActElem(op_packed.data(), op_scale.data(), K, r, c, input_global_scale);
CHECK(got == doctest::Approx(x_dq[static_cast<size_t>(r * K + c)]).epsilon(1e-6));
}
}
// Ports [email protected]
// tests/kernels/quantization/test_nvfp4_quant.py::
// test_python_util_matches_cpp_allocation,
// test_quantize_to_fp4_with_padded_output, and
// test_quantize_to_fp4_padded{,_no_sf_swizzled}.
// The direct producer must be byte-identical to linear production followed by
// the standalone swizzle, including every zero-filled padded scale slot.
TEST_CASE("scaled_fp4_quant direct CUTLASS scales match linear swizzle on CPU") {
Queue queue = CpuQueue();
constexpr float kInputGlobalScale = 7.3F;
const std::array<std::pair<int64_t, int64_t>, 6> shapes{{
{1, 64}, {32, 4096}, {127, 1024}, {128, 4096},
{256, 16384}, {32, 14336},
}};
for (const auto& [m, k] : shapes) {
CAPTURE(m);
CAPTURE(k);
std::vector<float> input(static_cast<size_t>(m * k));
for (int64_t index = 0; index < m * k; ++index) {
input[static_cast<size_t>(index)] =
static_cast<float>((index * 37) % 257 - 128) / 19.0F;
}
std::vector<uint8_t> linear_packed(static_cast<size_t>(m * k / 2));
std::vector<uint8_t> direct_packed(linear_packed.size(), uint8_t{0xA5});
std::vector<uint8_t> linear_scale(static_cast<size_t>(m * k / 16));
const int64_t padded_rows = RoundUpTo(m, 128);
const int64_t padded_cols = RoundUpTo(k / 16, 4);
std::vector<uint8_t> direct_scale(
static_cast<size_t>(padded_rows * padded_cols), uint8_t{0xA5});
Tensor x = Tensor::Contiguous(input.data(), DType::kF32, Cpu(), {m, k});
Tensor linear_packed_tensor = Tensor::Contiguous(
linear_packed.data(), DType::kI8, Cpu(), {m, k / 2});
Tensor direct_packed_tensor = Tensor::Contiguous(
direct_packed.data(), DType::kI8, Cpu(), {m, k / 2});
Tensor linear_scale_tensor = Tensor::Contiguous(
linear_scale.data(), DType::kI8, Cpu(), {m, k / 16});
Tensor direct_scale_tensor = Tensor::Contiguous(
direct_scale.data(), DType::kI8, Cpu(), {padded_rows, padded_cols});
vt::ScaledFp4Quant(queue, linear_packed_tensor, linear_scale_tensor, x,
kInputGlobalScale);
vt::ScaledFp4Quant(queue, direct_packed_tensor, direct_scale_tensor, x,
kInputGlobalScale,
vt::Fp4ScaleLayout::kCutlassSwizzled);
CHECK(direct_packed == linear_packed);
CHECK(direct_scale ==
SwizzleScaleReference(linear_scale, m, k / 16));
}
}
TEST_CASE("direct CUTLASS scale layout is explicit and validates exact shape") {
Queue queue = CpuQueue();
constexpr int64_t kM = 1;
constexpr int64_t kK = 64;
std::vector<float> input(static_cast<size_t>(kM * kK), 1.0F);
std::vector<uint8_t> packed(static_cast<size_t>(kM * kK / 2));
std::vector<uint8_t> ambiguous_scale(static_cast<size_t>(kM * kK / 16));
Tensor x = Tensor::Contiguous(input.data(), DType::kF32, Cpu(), {kM, kK});
Tensor packed_tensor = Tensor::Contiguous(
packed.data(), DType::kI8, Cpu(), {kM, kK / 2});
Tensor ambiguous_tensor = Tensor::Contiguous(
ambiguous_scale.data(), DType::kI8, Cpu(), {kM, kK / 16});
CHECK_THROWS_AS(
vt::ScaledFp4Quant(queue, packed_tensor, ambiguous_tensor, x, 7.3F,
vt::Fp4ScaleLayout::kCutlassSwizzled),
std::runtime_error);
}
TEST_CASE("matmul_nvfp4_fp4 CPU == vllm::RunNvfp4Emulation") {
const int64_t M = 4, K = 96, N = 7;
std::mt19937 rng(99);
std::normal_distribution<float> nd(0.0F, 2.0F);
std::uniform_int_distribution<int> byte_d(0, 255);
std::uniform_real_distribution<float> scale_d(0.05F, 4.0F);
// Random bf16-ish activations (f32).
std::vector<float> x(static_cast<size_t>(M * K));
for (auto& v : x) v = nd(rng);
// Random fp4 weight bytes [N, K/2] + fp8 group scales [N, K/16] (sane, no NaN)
// + a global divisor.
std::vector<uint8_t> w_packed(static_cast<size_t>(N * K / 2));
for (auto& b : w_packed) b = static_cast<uint8_t>(byte_d(rng));
std::vector<uint8_t> w_scale(static_cast<size_t>(N * K / 16));
for (auto& s : w_scale) s = vllm::F32ToF8E4M3(scale_d(rng));
const float weight_global_scale_disk = 6.1F; // divisor
const float input_global_scale_disk = 9.4F; // divisor
// Reference: the emulated true-W4A4 linear.
std::vector<float> ref(static_cast<size_t>(M * N));
vllm::RunNvfp4Emulation(x.data(), M, K, w_packed.data(), w_scale.data(),
weight_global_scale_disk, input_global_scale_disk, N, ref.data());
// Op path: quantize activations, then fp4xfp4 GEMM with the folded alpha.
std::vector<uint8_t> a_packed(static_cast<size_t>(M * K / 2), 0);
std::vector<uint8_t> a_scale(static_cast<size_t>(M * K / 16), 0);
Queue q = CpuQueue();
{
Tensor tx = Tensor::Contiguous(x.data(), DType::kF32, Cpu(), {M, K});
Tensor tp = Tensor::Contiguous(a_packed.data(), DType::kI8, Cpu(), {M, K / 2});
Tensor ts = Tensor::Contiguous(a_scale.data(), DType::kI8, Cpu(), {M, K / 16});
vt::ScaledFp4Quant(q, tp, ts, tx, input_global_scale_disk);
}
const float alpha = (1.0F / input_global_scale_disk) * (1.0F / weight_global_scale_disk);
std::vector<float> out(static_cast<size_t>(M * N), -1.0F);
Tensor tap = Tensor::Contiguous(a_packed.data(), DType::kI8, Cpu(), {M, K / 2});
Tensor tas = Tensor::Contiguous(a_scale.data(), DType::kI8, Cpu(), {M, K / 16});
Tensor tbp = Tensor::Contiguous(w_packed.data(), DType::kI8, Cpu(), {N, K / 2});
Tensor tbs = Tensor::Contiguous(w_scale.data(), DType::kI8, Cpu(), {N, K / 16});
Tensor to = Tensor::Contiguous(out.data(), DType::kF32, Cpu(), {M, N});
vt::MatmulNvfp4Fp4(q, to, tap, tas, tbp, tbs, alpha);
for (int64_t i = 0; i < M * N; ++i) {
// Real-arithmetic identical to RunNvfp4Emulation; only float K-order differs.
CHECK(out[static_cast<size_t>(i)] ==
doctest::Approx(ref[static_cast<size_t>(i)]).epsilon(1e-5).scale(1.0));
}
}
// --- CUDA device-vs-CPU cross-check (GB10; skips cleanly without a GPU) --------
namespace {
bool HasCuda() {
try {
vt::GetBackend(DeviceType::kCUDA);
return true;
} catch (const std::runtime_error&) {
return false;
}
}
Device Gpu() { return Device{DeviceType::kCUDA, 0}; }
Tensor GpuTensor(const std::vector<int64_t>& shape) {
Tensor t;
t.device = Gpu();
t.rank = static_cast<int>(shape.size());
int64_t stride = 1;
for (int i = t.rank - 1; i >= 0; --i) {
t.shape[i] = shape[static_cast<size_t>(i)];
t.stride[i] = stride;
stride *= shape[static_cast<size_t>(i)];
}
return t;
}
} // namespace
TEST_CASE("scaled_fp4_quant + matmul_nvfp4_fp4 CUDA == CPU") {
if (!HasCuda()) return;
auto& b = vt::GetBackend(DeviceType::kCUDA);
Queue gq = b.CreateQueue();
const int64_t M = 40, K = 128, N = 33; // M >= 32 exercises the WMMA path
std::mt19937 rng(7);
std::normal_distribution<float> nd(0.0F, 2.0F);
std::uniform_int_distribution<int> byte_d(0, 255);
std::uniform_real_distribution<float> scale_d(0.05F, 4.0F);
std::vector<float> x(static_cast<size_t>(M * K));
for (auto& v : x) v = nd(rng);
std::vector<uint8_t> w_packed(static_cast<size_t>(N * K / 2));
for (auto& v : w_packed) v = static_cast<uint8_t>(byte_d(rng));
std::vector<uint8_t> w_scale(static_cast<size_t>(N * K / 16));
for (auto& v : w_scale) v = vllm::F32ToF8E4M3(scale_d(rng));
const float input_global_scale = 8.2F, weight_global_scale = 5.5F;
const float alpha = (1.0F / input_global_scale) * (1.0F / weight_global_scale);
// CPU reference (already validated vs vllm::RunNvfp4Emulation above).
std::vector<uint8_t> cpu_ap(static_cast<size_t>(M * K / 2), 0), cpu_as(static_cast<size_t>(M * K / 16), 0);
std::vector<float> cpu_out(static_cast<size_t>(M * N), 0);
{
Queue cq = CpuQueue();
Tensor tx = Tensor::Contiguous(x.data(), DType::kF32, Cpu(), {M, K});
Tensor tp = Tensor::Contiguous(cpu_ap.data(), DType::kI8, Cpu(), {M, K / 2});
Tensor ts = Tensor::Contiguous(cpu_as.data(), DType::kI8, Cpu(), {M, K / 16});
vt::ScaledFp4Quant(cq, tp, ts, tx, input_global_scale);
Tensor tbp = Tensor::Contiguous(w_packed.data(), DType::kI8, Cpu(), {N, K / 2});
Tensor tbs = Tensor::Contiguous(w_scale.data(), DType::kI8, Cpu(), {N, K / 16});
Tensor to = Tensor::Contiguous(cpu_out.data(), DType::kF32, Cpu(), {M, N});
vt::MatmulNvfp4Fp4(cq, to, tp, ts, tbp, tbs, alpha);
}
// Device path.
auto up = [&](const void* h, size_t nb) { void* p = b.Alloc(nb); b.Copy(gq, p, h, nb); return p; };
void* dx = up(x.data(), x.size() * sizeof(float));
void* dbp = up(w_packed.data(), w_packed.size());
void* dbs = up(w_scale.data(), w_scale.size());
void* dap = b.Alloc(static_cast<size_t>(M * K / 2));
void* das = b.Alloc(static_cast<size_t>(M * K / 16));
void* dout = b.Alloc(static_cast<size_t>(M * N) * sizeof(float));
Tensor tx = GpuTensor({M, K}); tx.data = dx; tx.dtype = DType::kF32; tx.device = Gpu();
Tensor tap = GpuTensor({M, K / 2}); tap.data = dap; tap.dtype = DType::kI8; tap.device = Gpu();
Tensor tas = GpuTensor({M, K / 16}); tas.data = das; tas.dtype = DType::kI8; tas.device = Gpu();
Tensor tbp = GpuTensor({N, K / 2}); tbp.data = dbp; tbp.dtype = DType::kI8; tbp.device = Gpu();
Tensor tbs = GpuTensor({N, K / 16}); tbs.data = dbs; tbs.dtype = DType::kI8; tbs.device = Gpu();
Tensor to = GpuTensor({M, N}); to.data = dout; to.dtype = DType::kF32; to.device = Gpu();
vt::ScaledFp4Quant(gq, tap, tas, tx, input_global_scale);
vt::MatmulNvfp4Fp4(gq, to, tap, tas, tbp, tbs, alpha);
std::vector<uint8_t> g_ap(static_cast<size_t>(M * K / 2)), g_as(static_cast<size_t>(M * K / 16));
std::vector<float> g_out(static_cast<size_t>(M * N));
b.Copy(gq, g_ap.data(), dap, g_ap.size());
b.Copy(gq, g_as.data(), das, g_as.size());
b.Copy(gq, g_out.data(), dout, g_out.size() * sizeof(float));
b.Synchronize(gq);
// Quant: the device kernel uses the hardware fp8 cast (matches the real vLLM
// kernel), the CPU op the emulation codec — expect byte-exact for almost all
// groups; a handful of fp8-tie edge cases are benign (allow a small fraction).
size_t scale_mismatch = 0;
for (size_t i = 0; i < g_as.size(); ++i) scale_mismatch += (g_as[i] != cpu_as[i]);
CHECK(scale_mismatch <= g_as.size() / 50 + 1); // <= ~2% fp8 ties
// GEMM close device-vs-CPU (bf16 tensor-core dequant vs f32 CPU): matmul tol.
for (size_t i = 0; i < g_out.size(); ++i)
CHECK(g_out[i] == doctest::Approx(cpu_out[i]).epsilon(0.02).scale(1.0));
for (void* p : {dx, dbp, dbs, dap, das, dout}) b.Free(p);
b.DestroyQueue(gq);
}
TEST_CASE("scaled_fp4_quant CUDA direct scales match linear swizzle") {
if (!HasCuda()) return;
auto& b = vt::GetBackend(DeviceType::kCUDA);
Queue queue = b.CreateQueue();
constexpr float kInputGlobalScale = 8.2F;
auto run_check = [&](int64_t m, int64_t k, DType dtype) {
CAPTURE(m);
CAPTURE(k);
CAPTURE(static_cast<int>(dtype));
std::vector<float> input_f32(static_cast<size_t>(m * k));
for (int64_t index = 0; index < m * k; ++index) {
input_f32[static_cast<size_t>(index)] =
static_cast<float>((index * 37) % 257 - 128) / 19.0F;
}
std::vector<uint16_t> input_bf16;
const void* input_host = input_f32.data();
size_t input_bytes = input_f32.size() * sizeof(float);
if (dtype == DType::kBF16) {
input_bf16.resize(input_f32.size());
std::transform(input_f32.begin(), input_f32.end(), input_bf16.begin(),
FloatToBf16);
input_host = input_bf16.data();
input_bytes = input_bf16.size() * sizeof(uint16_t);
}
const int64_t padded_rows = RoundUpTo(m, 128);
const int64_t padded_cols = RoundUpTo(k / 16, 4);
auto allocate = [&](size_t bytes) { return b.Alloc(bytes); };
void* input_device = allocate(input_bytes);
b.Copy(queue, input_device, input_host, input_bytes);
void* linear_packed_device =
allocate(static_cast<size_t>(m * k / 2));
void* direct_packed_device =
allocate(static_cast<size_t>(m * k / 2));
void* linear_scale_device =
allocate(static_cast<size_t>(m * k / 16));
void* direct_scale_device =
allocate(static_cast<size_t>(padded_rows * padded_cols));
b.Memset(queue, direct_scale_device, 0xA5,
static_cast<size_t>(padded_rows * padded_cols));
Tensor input = GpuTensor({m, k});
input.data = input_device;
input.dtype = dtype;
input.device = Gpu();
Tensor linear_packed = GpuTensor({m, k / 2});
linear_packed.data = linear_packed_device;
linear_packed.dtype = DType::kI8;
linear_packed.device = Gpu();
Tensor direct_packed = GpuTensor({m, k / 2});
direct_packed.data = direct_packed_device;
direct_packed.dtype = DType::kI8;
direct_packed.device = Gpu();
Tensor linear_scale = GpuTensor({m, k / 16});
linear_scale.data = linear_scale_device;
linear_scale.dtype = DType::kI8;
linear_scale.device = Gpu();
Tensor direct_scale = GpuTensor({padded_rows, padded_cols});
direct_scale.data = direct_scale_device;
direct_scale.dtype = DType::kI8;
direct_scale.device = Gpu();
vt::ScaledFp4Quant(queue, linear_packed, linear_scale, input,
kInputGlobalScale);
vt::ScaledFp4Quant(queue, direct_packed, direct_scale, input,
kInputGlobalScale,
vt::Fp4ScaleLayout::kCutlassSwizzled);
std::vector<uint8_t> linear_packed_host(
static_cast<size_t>(m * k / 2));
std::vector<uint8_t> direct_packed_host(linear_packed_host.size());
std::vector<uint8_t> linear_scale_host(
static_cast<size_t>(m * k / 16));
std::vector<uint8_t> direct_scale_host(
static_cast<size_t>(padded_rows * padded_cols));
b.Copy(queue, linear_packed_host.data(), linear_packed_device,
linear_packed_host.size());
b.Copy(queue, direct_packed_host.data(), direct_packed_device,
direct_packed_host.size());
b.Copy(queue, linear_scale_host.data(), linear_scale_device,
linear_scale_host.size());
b.Copy(queue, direct_scale_host.data(), direct_scale_device,
direct_scale_host.size());
b.Synchronize(queue);
CHECK(direct_packed_host == linear_packed_host);
CHECK(direct_scale_host ==
SwizzleScaleReference(linear_scale_host, m, k / 16));
for (void* pointer : {input_device, linear_packed_device,
direct_packed_device, linear_scale_device,
direct_scale_device}) {
b.Free(pointer);
}
};
run_check(1, 64, DType::kF32);
run_check(127, 1024, DType::kF32);
run_check(1, 5120, DType::kBF16);
run_check(32, 14336, DType::kBF16);
run_check(9, 17408, DType::kBF16);
b.DestroyQueue(queue);
}
TEST_CASE("sigmoid_gate_fp4_quant CPU == SigmoidGateBf16 + ScaledFp4Quant (BYTE-EXACT)") {
Queue queue = CpuQueue();
constexpr float kInputGlobalScale = 6.7F;
for (DType attn_dtype : {DType::kF32, DType::kBF16}) {
for (const auto& [m, k] :
{std::pair<int64_t, int64_t>{1, 64}, {37, 128}}) {
CAPTURE(m);
CAPTURE(k);
CAPTURE(static_cast<int>(attn_dtype));
std::mt19937 rng(static_cast<unsigned>(701 + m * 131 + k));
std::normal_distribution<float> normal(0.0F, 2.0F);
std::vector<float> attn_f32(static_cast<size_t>(m * k));
std::vector<float> gate_f32(static_cast<size_t>(m * k));
for (float& value : attn_f32) value = normal(rng);
for (float& value : gate_f32) value = normal(rng);
std::vector<uint16_t> attn_bf16;
void* attn_data = attn_f32.data();
if (attn_dtype == DType::kBF16) {
attn_bf16.resize(attn_f32.size());
std::transform(attn_f32.begin(), attn_f32.end(), attn_bf16.begin(),
FloatToBf16);
attn_data = attn_bf16.data();
}
std::vector<uint16_t> gated(static_cast<size_t>(m * k));
std::vector<uint8_t> reference_packed(static_cast<size_t>(m * k / 2));
std::vector<uint8_t> reference_scale(static_cast<size_t>(m * k / 16));
std::vector<uint8_t> fused_packed(reference_packed.size());
std::vector<uint8_t> fused_scale(reference_scale.size());
Tensor attn = Tensor::Contiguous(attn_data, attn_dtype, Cpu(), {m, k});
Tensor gate = Tensor::Contiguous(gate_f32.data(), DType::kF32, Cpu(), {m, k});
Tensor gated_t =
Tensor::Contiguous(gated.data(), DType::kBF16, Cpu(), {m, k});
Tensor ref_packed = Tensor::Contiguous(
reference_packed.data(), DType::kI8, Cpu(), {m, k / 2});
Tensor ref_scale = Tensor::Contiguous(
reference_scale.data(), DType::kI8, Cpu(), {m, k / 16});
Tensor got_packed = Tensor::Contiguous(
fused_packed.data(), DType::kI8, Cpu(), {m, k / 2});
Tensor got_scale = Tensor::Contiguous(
fused_scale.data(), DType::kI8, Cpu(), {m, k / 16});
vt::SigmoidGateBf16(queue, gated_t, attn, gate);
vt::ScaledFp4Quant(queue, ref_packed, ref_scale, gated_t, kInputGlobalScale);
vt::SigmoidGateFp4Quant(queue, got_packed, got_scale, attn, gate,
kInputGlobalScale);
CHECK(fused_packed == reference_packed);
CHECK(fused_scale == reference_scale);
}
}
}
TEST_CASE("sigmoid_gate_fp4_quant CUDA == SigmoidGateBf16 + ScaledFp4Quant (BYTE-EXACT)") {
if (!HasCuda()) return;
auto& b = vt::GetBackend(DeviceType::kCUDA);
Queue gq = b.CreateQueue();
const float input_global_scale = 6.7F;
auto run_check = [&](int64_t M, int64_t K) {
std::mt19937 rng(static_cast<unsigned>(707 + M * 131 + K));
std::normal_distribution<float> nd(0.0F, 2.0F);
std::vector<float> attn(static_cast<size_t>(M * K)), gate(static_cast<size_t>(M * K));
for (auto& v : attn) v = nd(rng);
for (auto& v : gate) v = nd(rng);
auto upl = [&](const void* h, size_t nb) { void* p = b.Alloc(nb); b.Copy(gq, p, h, nb); return p; };
void* dattn = upl(attn.data(), attn.size() * sizeof(float));
void* dgate = upl(gate.data(), gate.size() * sizeof(float));
Tensor tattn = GpuTensor({M, K}); tattn.data = dattn; tattn.dtype = DType::kF32; tattn.device = Gpu();
Tensor tgate = GpuTensor({M, K}); tgate.data = dgate; tgate.dtype = DType::kF32; tgate.device = Gpu();
// Unfused reference: SigmoidGateBf16 -> bf16 gated, then ScaledFp4Quant.
void* dgated = b.Alloc(static_cast<size_t>(M * K) * sizeof(uint16_t));
void* dref_ap = b.Alloc(static_cast<size_t>(M * K / 2));
void* dref_as = b.Alloc(static_cast<size_t>(M * K / 16));
Tensor tgated = GpuTensor({M, K}); tgated.data = dgated; tgated.dtype = DType::kBF16; tgated.device = Gpu();
Tensor tref_ap = GpuTensor({M, K / 2}); tref_ap.data = dref_ap; tref_ap.dtype = DType::kI8; tref_ap.device = Gpu();
Tensor tref_as = GpuTensor({M, K / 16}); tref_as.data = dref_as; tref_as.dtype = DType::kI8; tref_as.device = Gpu();
vt::SigmoidGateBf16(gq, tgated, tattn, tgate);
vt::ScaledFp4Quant(gq, tref_ap, tref_as, tgated, input_global_scale);
// Fused (linear scale layout).
void* dfu_ap = b.Alloc(static_cast<size_t>(M * K / 2));
void* dfu_as = b.Alloc(static_cast<size_t>(M * K / 16));
Tensor tfu_ap = GpuTensor({M, K / 2}); tfu_ap.data = dfu_ap; tfu_ap.dtype = DType::kI8; tfu_ap.device = Gpu();
Tensor tfu_as = GpuTensor({M, K / 16}); tfu_as.data = dfu_as; tfu_as.dtype = DType::kI8; tfu_as.device = Gpu();
vt::SigmoidGateFp4Quant(gq, tfu_ap, tfu_as, tattn, tgate, input_global_scale);
b.Synchronize(gq);
std::vector<uint8_t> ref_ap(static_cast<size_t>(M * K / 2)), fu_ap(ref_ap.size());
std::vector<uint8_t> ref_as(static_cast<size_t>(M * K / 16)), fu_as(ref_as.size());
b.Copy(gq, ref_ap.data(), dref_ap, ref_ap.size());
b.Copy(gq, fu_ap.data(), dfu_ap, fu_ap.size());
b.Copy(gq, ref_as.data(), dref_as, ref_as.size());
b.Copy(gq, fu_as.data(), dfu_as, fu_as.size());
b.Synchronize(gq);
CHECK(fu_ap == ref_ap);
CHECK(fu_as == ref_as);
for (void* p : {dattn, dgate, dgated, dref_ap, dref_as, dfu_ap, dfu_as}) b.Free(p);
};
run_check(1, 64);
run_check(37, 128);
run_check(128, 512);
}
TEST_CASE("silu_mul_fp4_quant CUDA == MoeSiluMul + ScaledFp4Quant (BYTE-EXACT)") {
if (!HasCuda()) return;
auto& b = vt::GetBackend(DeviceType::kCUDA);
Queue gq = b.CreateQueue();
const float input_global_scale = 6.7F;
auto run_check = [&](int64_t M, int64_t I) {
std::mt19937 rng(static_cast<unsigned>(99 + M * 131 + I));
std::normal_distribution<float> nd(0.0F, 2.0F);
std::vector<float> gate(static_cast<size_t>(M * I)), up(static_cast<size_t>(M * I));
for (auto& v : gate) v = nd(rng);
for (auto& v : up) v = nd(rng);
auto upl = [&](const void* h, size_t nb) { void* p = b.Alloc(nb); b.Copy(gq, p, h, nb); return p; };
void* dgate = upl(gate.data(), gate.size() * sizeof(float));
void* dup = upl(up.data(), up.size() * sizeof(float));
Tensor tgate = GpuTensor({M, I}); tgate.data = dgate; tgate.dtype = DType::kF32; tgate.device = Gpu();
Tensor tup = GpuTensor({M, I}); tup.data = dup; tup.dtype = DType::kF32; tup.device = Gpu();
// Unfused reference: MoeSiluMul -> bf16 act, then ScaledFp4Quant.
void* dact = b.Alloc(static_cast<size_t>(M * I) * sizeof(uint16_t));
void* dref_ap = b.Alloc(static_cast<size_t>(M * I / 2));
void* dref_as = b.Alloc(static_cast<size_t>(M * I / 16));
Tensor tact = GpuTensor({M, I}); tact.data = dact; tact.dtype = DType::kBF16; tact.device = Gpu();
Tensor tref_ap = GpuTensor({M, I / 2}); tref_ap.data = dref_ap; tref_ap.dtype = DType::kI8; tref_ap.device = Gpu();
Tensor tref_as = GpuTensor({M, I / 16}); tref_as.data = dref_as; tref_as.dtype = DType::kI8; tref_as.device = Gpu();
vt::MoeSiluMul(gq, tact, tgate, tup);
vt::ScaledFp4Quant(gq, tref_ap, tref_as, tact, input_global_scale);
// Fused.
void* dfu_ap = b.Alloc(static_cast<size_t>(M * I / 2));
void* dfu_as = b.Alloc(static_cast<size_t>(M * I / 16));
Tensor tfu_ap = GpuTensor({M, I / 2}); tfu_ap.data = dfu_ap; tfu_ap.dtype = DType::kI8; tfu_ap.device = Gpu();
Tensor tfu_as = GpuTensor({M, I / 16}); tfu_as.data = dfu_as; tfu_as.dtype = DType::kI8; tfu_as.device = Gpu();
vt::SiluMulFp4Quant(gq, tfu_ap, tfu_as, tgate, tup, input_global_scale);
const int64_t padded_rows = RoundUpTo(M, 128);
const int64_t padded_cols = RoundUpTo(I / 16, 4);
void* ddir_ap = b.Alloc(static_cast<size_t>(M * I / 2));
void* ddir_as =
b.Alloc(static_cast<size_t>(padded_rows * padded_cols));
b.Memset(gq, ddir_as, 0xA5,
static_cast<size_t>(padded_rows * padded_cols));
Tensor tdir_ap = GpuTensor({M, I / 2});
tdir_ap.data = ddir_ap;
tdir_ap.dtype = DType::kI8;
tdir_ap.device = Gpu();
Tensor tdir_as = GpuTensor({padded_rows, padded_cols});
tdir_as.data = ddir_as;
tdir_as.dtype = DType::kI8;
tdir_as.device = Gpu();
vt::SiluMulFp4Quant(gq, tdir_ap, tdir_as, tgate, tup,
input_global_scale,
vt::Fp4ScaleLayout::kCutlassSwizzled);
std::vector<uint8_t> ref_ap(static_cast<size_t>(M * I / 2)), ref_as(static_cast<size_t>(M * I / 16));
std::vector<uint8_t> fu_ap(static_cast<size_t>(M * I / 2)), fu_as(static_cast<size_t>(M * I / 16));
std::vector<uint8_t> dir_ap(fu_ap.size());
std::vector<uint8_t> dir_as(
static_cast<size_t>(padded_rows * padded_cols));
b.Copy(gq, ref_ap.data(), dref_ap, ref_ap.size());
b.Copy(gq, ref_as.data(), dref_as, ref_as.size());
b.Copy(gq, fu_ap.data(), dfu_ap, fu_ap.size());
b.Copy(gq, fu_as.data(), dfu_as, fu_as.size());
b.Copy(gq, dir_ap.data(), ddir_ap, dir_ap.size());
b.Copy(gq, dir_as.data(), ddir_as, dir_as.size());
b.Synchronize(gq);
size_t pmis = 0, smis = 0;
for (size_t i = 0; i < ref_ap.size(); ++i) pmis += (fu_ap[i] != ref_ap[i]);
for (size_t i = 0; i < ref_as.size(); ++i) smis += (fu_as[i] != ref_as[i]);
CHECK(pmis == 0); // fused packed fp4 == unfused, byte-for-byte
CHECK(smis == 0); // fused fp8 block scales == unfused, byte-for-byte
CHECK(dir_ap == fu_ap);
CHECK(dir_as == SwizzleScaleReference(fu_as, M, I / 16));
for (void* p : {dgate, dup, dact, dref_ap, dref_as, dfu_ap, dfu_as,
ddir_ap, ddir_as}) {
b.Free(p);
}
};
run_check(1, 64); // decode single-row
run_check(8, 256); // small batch, many groups/row
run_check(40, 128); // prefill-ish
run_check(37, 2048); // the real 27B intermediate_size class, non-32-aligned M
b.DestroyQueue(gq);
}
// Port of vllm@e24d1b24
// tests/kernels/quantization/test_silu_mul_nvfp4_quant.py::
// test_silu_mul_nvfp4_quant. The local gate is intentionally stronger than the
// upstream dequantized tolerance: the fused producer must preserve the eager
// BF16 SiluAndMul -> ScaledFp4Quant boundary byte-for-byte.
TEST_CASE("silu_and_mul_nvfp4_quant one-input CPU is BYTE-EXACT") {
Queue queue = CpuQueue();
constexpr float kInputGlobalScale = 6.7F;
for (DType dtype : {DType::kF32, DType::kBF16}) {
for (const auto& [m, i] :
{std::pair<int64_t, int64_t>{1, 64}, {37, 128}}) {
CAPTURE(m);
CAPTURE(i);
CAPTURE(static_cast<int>(dtype));
std::mt19937 rng(static_cast<unsigned>(401 + m * 131 + i));
std::normal_distribution<float> normal(0.0F, 2.0F);
std::vector<float> input_f32(static_cast<size_t>(m * 2 * i));
for (float& value : input_f32) value = normal(rng);
std::vector<uint16_t> input_bf16;
void* input_data = input_f32.data();
if (dtype == DType::kBF16) {
input_bf16.resize(input_f32.size());
std::transform(input_f32.begin(), input_f32.end(), input_bf16.begin(),
FloatToBf16);
input_data = input_bf16.data();
}
std::vector<uint16_t> activation(static_cast<size_t>(m * i));
std::vector<uint8_t> reference_packed(static_cast<size_t>(m * i / 2));
std::vector<uint8_t> reference_scale(static_cast<size_t>(m * i / 16));
std::vector<uint8_t> fused_packed(reference_packed.size());
std::vector<uint8_t> fused_scale(reference_scale.size());
Tensor input = Tensor::Contiguous(input_data, dtype, Cpu(), {m, 2 * i});
Tensor act = Tensor::Contiguous(activation.data(), DType::kBF16, Cpu(),
{m, i});
Tensor ref_packed = Tensor::Contiguous(
reference_packed.data(), DType::kI8, Cpu(), {m, i / 2});
Tensor ref_scale = Tensor::Contiguous(
reference_scale.data(), DType::kI8, Cpu(), {m, i / 16});
Tensor got_packed = Tensor::Contiguous(
fused_packed.data(), DType::kI8, Cpu(), {m, i / 2});
Tensor got_scale = Tensor::Contiguous(
fused_scale.data(), DType::kI8, Cpu(), {m, i / 16});
vt::SiluAndMul(queue, act, input);
vt::ScaledFp4Quant(queue, ref_packed, ref_scale, act,
kInputGlobalScale);
vt::SiluAndMulFp4Quant(queue, got_packed, got_scale, input,
kInputGlobalScale);
CHECK(fused_packed == reference_packed);
CHECK(fused_scale == reference_scale);
}
}
}
TEST_CASE("fused SiLU NVFP4 producers emit direct CUTLASS scales on CPU") {
Queue queue = CpuQueue();
constexpr int64_t kM = 37;
constexpr int64_t kI = 128;
constexpr float kInputGlobalScale = 6.7F;
std::vector<float> gate(static_cast<size_t>(kM * kI));
std::vector<float> up(gate.size());
for (int64_t index = 0; index < kM * kI; ++index) {
gate[static_cast<size_t>(index)] =
static_cast<float>((index * 17) % 193 - 96) / 23.0F;
up[static_cast<size_t>(index)] =
static_cast<float>((index * 29) % 181 - 90) / 17.0F;
}
std::vector<float> gate_up(static_cast<size_t>(kM * 2 * kI));