-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunittest.cpp
More file actions
1858 lines (1674 loc) · 85.8 KB
/
unittest.cpp
File metadata and controls
1858 lines (1674 loc) · 85.8 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
/*!
\file unittest.cpp
\author Sho Ikeda
\brief Unit test implementations for linear algebra, MLP inference/training, and atomic operations
\copyright Copyright (c) 2026 Advanced Micro Devices, Inc. All Rights Reserved.
SPDX-License-Identifier: MIT
*/
// Standard C++ library
#include <algorithm>
#include <array>
#include <bit>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstring>
#include <filesystem>
#include <functional>
#include <format>
#include <iomanip>
#include <iostream>
#include <memory>
#include <limits>
#include <numeric>
#include <random>
#include <sstream>
#include <string_view>
#include <thread>
#include <vector>
// GoogleTest
#include "gtest/gtest.h"
// Half
#include "half.hpp"
// Example
#include "common/activation.hpp"
// CLI
#include "CLI/CLI.hpp"
// Test
#include "test.hpp"
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
#include "hlsl_include_dirs.hpp"
#include "common/gfx_utility.hpp"
#endif // MINIDXNN_CPP_FALLBACK_ONLY
#include "common/loss.hpp"
#include "common/matrix.hpp"
#include "common/optimizer.hpp"
#include "common/xoshiro128plus.hpp"
// C++ fallback infrastructure (includes hlsl_compat.hpp, mlp.hlsl, utility, mlp_layer)
#include "common/cpp_fallback.hpp"
#include "kernel/mlp_test_common.hlsl"
static_assert(sizeof(half_float::half) == 2);
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
using test::LinearAlgebraMatrixTest;
#endif
using test::CppFallbackTest;
namespace {
test::TestParameters g_testParams;
} // namespace
namespace {
template <ex::Arithmetic Type>
[[nodiscard]]
auto createRandomInputs(const size_t size, ex::Xoshiro128Plus& rng) -> std::vector<Type>
{
std::normal_distribution<float> sampler{1.0f, 0.5f};
std::vector<Type> result;
result.resize(size);
std::ranges::for_each(result, [&rng, &sampler](Type& v)
{
v = static_cast<Type>(sampler(rng));
ex::validateValue(v);
});
return result;
}
template <ex::Arithmetic Type>
[[nodiscard]]
auto createRandomMlp(const size_t inputDim,
const size_t outputDim,
const size_t hiddenLayerDim,
const size_t numBackboneLayers,
const bool hasBias,
const ex::ActivationType activationHidden,
const ex::ActivationType activationLast,
ex::Xoshiro128Plus rng) -> std::vector<ex::MlpLayer<Type, Type>>
{
std::vector<ex::LayerConfiguration> mlpConfiguration;
if (numBackboneLayers == 0) {
mlpConfiguration.emplace_back(inputDim, outputDim, activationLast);
}
else {
mlpConfiguration.emplace_back(inputDim, hiddenLayerDim, activationHidden);
for (size_t depth = 1; depth < numBackboneLayers; ++depth)
mlpConfiguration.emplace_back(hiddenLayerDim, hiddenLayerDim, activationHidden);
mlpConfiguration.emplace_back(hiddenLayerDim, outputDim, activationLast);
}
std::vector mlpData = ex::createMlp<Type, Type>(mlpConfiguration, hasBias, rng);
return mlpData;
}
// Calculate the similarity of the given two values from 0 to 1
template <ex::Arithmetic Type>
[[nodiscard]]
auto calcSimilarity(const Type lhs, const Type rhs) noexcept -> double
{
const double l = static_cast<double>(lhs);
const double r = static_cast<double>(rhs);
const double diff = std::abs(l - r);
const double norm = std::max((std::abs(l) + std::abs(r)) / 2.0, std::numeric_limits<double>::epsilon());
const double similarity = 1.0 - std::clamp(diff / norm, 0.0, 1.0);
return similarity;
}
[[nodiscard, maybe_unused]]
auto calcThreadGroupSize(const size_t numTasks, const size_t numThreads) noexcept -> size_t
{
assert(std::has_single_bit(numThreads));
return (numTasks + (numThreads - 1)) / numThreads;
}
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
/*!
\brief Build common MLP kernel definitions for test shaders.
Creates the shared compile-time definitions array used by both inference and training
test kernels. Additional test-specific definitions (e.g., MINIDXNN_NUM_TASKS,
MINIDXNN_BATCH_SIZE) should be appended by the caller.
*/
[[nodiscard]]
auto buildMlpTestDefinitions(const test::TestParameters& testParams,
const size_t inputDim,
const size_t outputDim,
const size_t hiddenLayerDim,
const size_t numLayers,
const ex::ActivationType activationHidden,
const ex::ActivationType activationLast,
const bool hasBias,
const bool useSoftwareLinAlgImpl,
const ex::MatrixLayout weightMatrixLayout,
const size_t matrixAlignment,
const size_t vectorStrideAlignment,
const size_t biasAlignment) -> std::vector<ex::OptionString>
{
return {
ex::createOptionString("MINIDXNN_HAS_BIAS={}", hasBias ? 1 : 0),
ex::createOptionString("MINIDXNN_INPUT_DIMENSION={}", inputDim),
ex::createOptionString("MINIDXNN_OUTPUT_DIMENSION={}", outputDim),
ex::createOptionString("MINIDXNN_HIDDEN_LAYER_DIMENSIONS={}", hiddenLayerDim),
ex::createOptionString("MINIDXNN_NUM_LAYERS={}", numLayers),
ex::createOptionString("MINIDXNN_ACTIVATION_HIDDEN_TYPE={}", ex::getActivationTypeString(activationHidden)),
ex::createOptionString("MINIDXNN_ACTIVATION_LAST_TYPE={}", ex::getActivationTypeString(activationLast)),
ex::createOptionString("MINIDXNN_WEIGHT_MATRIX_LAYOUT={}", ex::toHlslMatrixLayout(weightMatrixLayout)),
ex::createOptionString("MINIDXNN_WEIGHT_MATRIX_ALIGNMENT={}", matrixAlignment),
ex::createOptionString("MINIDXNN_WEIGHT_MATRIX_VECTOR_STRIDE_ALIGNMENT={}", vectorStrideAlignment),
ex::createOptionString("MINIDXNN_BIAS_VECTOR_ALIGNMENT={}", biasAlignment),
ex::createOptionString("MINIDXNN_NUM_THREADS_X={}", testParams.m_numThreadsX),
ex::createOptionString("MINIDXNN_USE_SOFTWARE_LINALG_IMPL={}", useSoftwareLinAlgImpl ? 1 : 0),
};
}
#endif // !MINIDXNN_CPP_FALLBACK_ONLY
template <ex::Arithmetic Type>
[[nodiscard]]
auto assertSimilarity(const char* expectedLabel,
const char* valueLabel,
const Type expected,
const Type value,
const double similarityThreshold) -> ::testing::AssertionResult
{
const double e = static_cast<double>(expected);
const double v = static_cast<double>(value);
const double similarity = calcSimilarity(e, v);
if (similarity < similarityThreshold) {
return ::testing::AssertionFailure()
<< "\n"
<< std::format("expected: {:.8g} ('{}') and\n", e, expectedLabel)
<< std::format("value : {:.8g} ('{}')\n", v, valueLabel)
<< " the similarity is less than the threshold. "
<< std::format("(similarity={:.5g} < {:.5g}).", similarity, similarityThreshold);
}
return ::testing::AssertionSuccess();
}
template <ex::Arithmetic Type>
[[nodiscard]]
auto assertSimilarityBatch(const std::span<const Type> expected,
const std::span<const Type> values,
const double similarityThreshold,
const std::string_view testLabel,
const bool isDebugMode = false) -> ::testing::AssertionResult
{
assert(expected.size() == values.size());
const size_t numElements = expected.size();
std::vector<double> similarities(numElements);
std::ranges::transform(expected, values, similarities.begin(), [](const Type e, const Type v)
{
return calcSimilarity(e, v);
});
const auto [minIt, maxIt] = std::ranges::minmax_element(similarities);
const double averageSimilarity = std::accumulate(similarities.begin(), similarities.end(), 0.0) / static_cast<double>(numElements);
const double maxSimilarity = *maxIt;
const double minSimilarity = *minIt;
std::cout << std::format("{}: Similarity stats - avg: {:.6f}, max: {:.6f}, min: {:.6f}\n", testLabel, averageSimilarity, maxSimilarity, minSimilarity);
if (isDebugMode and (minSimilarity < similarityThreshold)) {
std::stringstream errorMessage;
errorMessage << std::format("\n{}: [Warning] Minimum similarity ({:.6f}) is below threshold ({:.6f})\n", testLabel, minSimilarity, similarityThreshold);
errorMessage << "Elements below threshold:\n";
for (size_t i = 0; i < numElements; ++i) {
if (similarities[i] < similarityThreshold) {
errorMessage << std::format(" [{}]: expected={:.8f}, value={:.8f}, similarity={:.6f}\n", i, static_cast<double>(expected[i]), static_cast<double>(values[i]), similarities[i]);
}
}
std::cerr << errorMessage.str() << '\n';
}
if (averageSimilarity < similarityThreshold) {
return ::testing::AssertionFailure()
<< std::format("\n{}: [Error] Average similarity ({:.6f}) is below threshold ({:.6f})\n", testLabel, averageSimilarity, similarityThreshold);
}
return ::testing::AssertionSuccess();
}
} // namespace
// ============================================================================
// C++ fallback infrastructure (always available)
// Packs MLP layer data into flat byte buffers matching mlp.hlsl's layout,
// then dispatches forward/backward through compile-time template instantiations
// ============================================================================
namespace {
// C++ fallback helper functions, kernel dispatch, and smoke test
#include "cpp_fallback_path.hpp"
// ----------------------------------------------------------------------------
// Unified linear algebra, vector accumulation, and atomic test functions
// Shared between LinearAlgebraMatrixTest (GPU) and CppFallbackTest (C++ fallback).
// GPU-specific code is guarded by #ifndef MINIDXNN_CPP_FALLBACK_ONLY.
// ----------------------------------------------------------------------------
template <ex::Arithmetic Type, int ROW_SIZE, int COLUMN_SIZE, bool IS_TRANSPOSED, bool HAS_BIAS>
auto testLinearAlgebraMul(const test::TestParameters& testParams,
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
GfxContext& gfxContext,
const bool useSoftwareLinAlgImpl,
const bool useCppFallback,
#endif
ex::MatrixLayout weightMatrixLayout,
const size_t numOfTests = 5) -> void
{
#ifdef MINIDXNN_CPP_FALLBACK_ONLY
(void)weightMatrixLayout;
#endif
constexpr size_t rowSize = static_cast<size_t>(ROW_SIZE);
constexpr size_t columnSize = static_cast<size_t>(COLUMN_SIZE);
ex::Xoshiro128Plus rng{testParams.m_seed};
for (size_t trial = 0; trial < numOfTests; ++trial) {
std::vector<Type> matrixData = ::createRandomInputs<Type>(rowSize * columnSize, rng);
const std::unique_ptr matrix = IS_TRANSPOSED
? ex::makeTransposedMatrix<Type>(columnSize, rowSize, std::span<Type>{matrixData})
: ex::makeMatrix<Type>(rowSize, columnSize, std::span<Type>{matrixData});
std::vector<Type> bias;
if constexpr (HAS_BIAS)
bias = ::createRandomInputs<Type>(rowSize, rng);
const std::vector<Type> inputVec = ::createRandomInputs<Type>(columnSize, rng);
const std::vector references = HAS_BIAS
? ex::mulAdd<Type, Type, Type, Type>(*matrix, inputVec, bias)
: ex::mul<Type, Type, Type>(*matrix, inputVec);
ASSERT_EQ(references.size(), rowSize);
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
if (!useCppFallback) {
const std::filesystem::path shaderDir = ex::getComputeShaderDir();
const std::array includeDirList = ex::getHlslIncludeDirList();
std::shared_ptr program = ex::createGfxProgram(gfxContext, "linear_algebra_test", shaderDir, includeDirList);
std::shared_ptr inputBuffer = ex::createGfxBuffer<Type>(gfxContext, inputVec);
const size_t outputSize = testParams.m_numThreadsX * rowSize;
std::shared_ptr outputBuffer = ex::createGfxBuffer<Type>(gfxContext, outputSize);
// Build D3D12MatrixInfo for the single weight matrix
ex::D3D12MatrixInfo<Type> weightInfo;
weightInfo.m_srcData = matrixData;
if constexpr (IS_TRANSPOSED) {
// Transposed: physical storage is columnSize × rowSize
weightInfo.m_rowSize = columnSize;
weightInfo.m_columnSize = rowSize;
} else {
weightInfo.m_rowSize = rowSize;
weightInfo.m_columnSize = columnSize;
}
weightInfo.m_layout = weightMatrixLayout;
std::vector<ex::D3D12MatrixInfo<Type>> matrixInfoList{weightInfo};
std::shared_ptr weightBuffer = ex::packAsD3D12MatrixBuffer<Type>(gfxContext, matrixInfoList);
ASSERT_TRUE(weightBuffer) << "packAsD3D12MatrixBuffer failed for layout " << static_cast<int>(weightMatrixLayout);
// Build D3D12VectorInfo for bias
ex::D3D12VectorInfo<Type> biasInfo;
biasInfo.m_srcData = bias;
std::vector<ex::D3D12VectorInfo<Type>> vectorInfoList{biasInfo};
std::shared_ptr biasBuffer = ex::packAsD3D12VectorBuffer<Type>(gfxContext, vectorInfoList);
{
const ex::OptionString kernelName = ex::createOptionString("testLinearAlgebraMulF{}Kernel", 8 * sizeof(Type));
const std::array kernelDefinitions = std::to_array<ex::OptionString>({
ex::createOptionString("MINIDXNN_HAS_BIAS={}", HAS_BIAS ? 1 : 0),
ex::createOptionString("MINIDXNN_ROW_SIZE={}", rowSize),
ex::createOptionString("MINIDXNN_COLUMN_SIZE={}", columnSize),
ex::createOptionString("MINIDXNN_WEIGHT_MATRIX_LAYOUT={}", ex::toHlslMatrixLayout(matrixInfoList[0].m_layout)),
ex::createOptionString("MINIDXNN_WEIGHT_MATRIX_IS_TRANSPOSED={}", IS_TRANSPOSED ? 1 : 0),
ex::createOptionString("MINIDXNN_MATRIX_VECTOR_STRIDE_ALIGNMENT={}", matrixInfoList[0].m_vectorStrideAlignment),
ex::createOptionString("MINIDXNN_NUM_THREADS_X={}", testParams.m_numThreadsX),
ex::createOptionString("MINIDXNN_NUM_TASKS={}", testParams.m_numThreadsX),
ex::createOptionString("MINIDXNN_USE_SOFTWARE_LINALG_IMPL={}", useSoftwareLinAlgImpl ? 1 : 0),
});
std::shared_ptr kernel = ex::createGfxComputeKernel(gfxContext, *program, kernelName.data(), kernelDefinitions);
constexpr size_t threadGroupSize = 1;
ex::runKernel(gfxContext, *program, *kernel, threadGroupSize,
{
ex::bind(*inputBuffer, "InputBuffer"),
ex::bind(*outputBuffer, "OutputBuffer"),
ex::bind(*weightBuffer, "WeightBuffer"),
ex::bind(*biasBuffer, "BiasBuffer"),
});
}
std::vector<Type> result;
{
std::shared_ptr staging = ex::createGfxBuffer<Type>(gfxContext, outputSize, kGfxCpuAccess_Read);
ex::copyBuffer(gfxContext, *outputBuffer, *staging);
const std::span output = ex::mapToCpu<Type>(gfxContext, *staging);
result.resize(outputSize);
std::ranges::copy(output, result.begin());
}
const std::span<const Type> values{result.data(), rowSize};
const std::string testLabel = std::format("Mul{}", trial + 1);
ASSERT_TRUE(assertSimilarityBatch<Type>(references, values, testParams.m_similarityThreshold, testLabel, testParams.m_enableDebugMode));
} else
#endif // !MINIDXNN_CPP_FALLBACK_ONLY
{
auto [weightBuf, vectorStride] = ex::packSingleMatrix<Type>(matrixData, rowSize, columnSize, IS_TRANSPOSED);
std::vector<std::uint8_t> biasBuf = HAS_BIAS ? ex::packSingleBias<Type>(bias, rowSize)
: std::vector<std::uint8_t>{};
std::vector<Type> result;
cppFallbackLinearAlgebraMul<Type, ROW_SIZE, COLUMN_SIZE, IS_TRANSPOSED, HAS_BIAS>(weightBuf, vectorStride, biasBuf, inputVec, result);
const std::string testLabel = std::format("Mul{}", trial + 1);
ASSERT_TRUE(assertSimilarityBatch<Type>(references, result, testParams.m_similarityThreshold, testLabel, testParams.m_enableDebugMode));
}
}
}
template <ex::Arithmetic Type>
auto testVectorAcc(const test::TestParameters& testParams,
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
GfxContext& gfxContext,
const bool useSoftwareLinAlgImpl,
const bool useCppFallback,
#endif
const size_t numOfTests = 5) -> void
{
constexpr size_t size = 4;
constexpr size_t numTasks = 1ull << (std::min)(std::numeric_limits<Type>::digits, 18);
for (size_t trial = 0; trial < numOfTests; ++trial) {
std::array<Type, size> result{};
result.fill(static_cast<Type>(0));
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
if (!useCppFallback) {
const std::filesystem::path shaderDir = ex::getComputeShaderDir();
const std::array includeDirList = ex::getHlslIncludeDirList();
std::shared_ptr program = ex::createGfxProgram(gfxContext, "linear_algebra_test", shaderDir, includeDirList);
std::shared_ptr outputBuffer = ex::createGfxBuffer<Type>(gfxContext, result);
{
const ex::OptionString kernelName = ex::createOptionString("testLinearAlgebraVectorAccF{}Kernel", 8 * sizeof(Type));
const std::array kernelDefinitions = std::to_array<ex::OptionString>({
ex::createOptionString("MINIDXNN_HAS_BIAS={}", 0),
ex::createOptionString("MINIDXNN_ROW_SIZE={}", 1),
ex::createOptionString("MINIDXNN_COLUMN_SIZE={}", size),
ex::createOptionString("MINIDXNN_WEIGHT_MATRIX_LAYOUT={}", 0),
ex::createOptionString("MINIDXNN_WEIGHT_MATRIX_IS_TRANSPOSED={}", 0),
ex::createOptionString("MINIDXNN_MATRIX_VECTOR_STRIDE_ALIGNMENT={}", ex::MATRIX_VECTOR_STRIDE_ALIGNMENT),
ex::createOptionString("MINIDXNN_NUM_THREADS_X={}", testParams.m_numThreadsX),
ex::createOptionString("MINIDXNN_NUM_TASKS={}", numTasks),
ex::createOptionString("MINIDXNN_USE_SOFTWARE_LINALG_IMPL={}", useSoftwareLinAlgImpl ? 1 : 0),
});
std::shared_ptr kernel = ex::createGfxComputeKernel(gfxContext, *program, kernelName.data(), kernelDefinitions);
const size_t threadGroupSize = calcThreadGroupSize(numTasks, testParams.m_numThreadsX);
ex::runKernel(gfxContext, *program, *kernel, threadGroupSize,
{
ex::bind(*outputBuffer, "OutputBuffer"),
});
}
{
std::shared_ptr staging = ex::createGfxBuffer<Type>(gfxContext, size, kGfxCpuAccess_Read);
ex::copyBuffer(gfxContext, *outputBuffer, *staging);
const std::span output = ex::mapToCpu<Type>(gfxContext, *staging);
for (size_t i = 0; i < size; ++i)
result[i] = output[i];
}
} else
#endif // !MINIDXNN_CPP_FALLBACK_ONLY
{
std::vector<std::uint8_t> outputData(size * sizeof(Type), 0);
RWByteAddressBuffer outputBuf{outputData};
cppFallbackVectorAcc<Type, static_cast<int>(size)>(outputBuf, numTasks);
for (size_t i = 0; i < size; ++i)
std::memcpy(&result[i], outputData.data() + i * sizeof(Type), sizeof(Type));
}
const auto assertTest = [&testParams](const char* expectedLabel, const char* valueLabel, const Type expected, const Type value)
{
return assertSimilarity(expectedLabel, valueLabel, expected, value, testParams.m_similarityThreshold);
};
for (size_t i = 0; i < size; ++i) {
const Type expected = static_cast<Type>(static_cast<float>(numTasks << i));
EXPECT_PRED_FORMAT2(assertTest, expected, result[i]);
}
}
}
template <ex::Arithmetic Type>
auto testAtomicFetchAdd(const test::TestParameters& testParams,
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
GfxContext& gfxContext,
const bool useCppFallback,
#endif
const size_t numOfTests = 5) -> void
{
constexpr size_t size = 8;
// For F16, cap thread count so the total sum stays within half precision range
// (half can only accumulate small integers exactly up to 2^11 = 2048).
// For F32, use high thread count (2^17) for maximum CAS contention.
constexpr size_t numTasks = sizeof(Type) >= 4
? (1ull << (std::min)(std::numeric_limits<Type>::digits, 17))
: 512;
// High iteration count to maximize CAS contention and expose optimization bugs
constexpr size_t numIterations = sizeof(Type) >= 4 ? 32 : 1;
for (size_t trial = 0; trial < numOfTests; ++trial) {
std::array<Type, size> result{};
result.fill(static_cast<Type>(0));
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
if (!useCppFallback) {
const std::filesystem::path shaderDir = ex::getComputeShaderDir();
const std::array includeDirList = ex::getHlslIncludeDirList();
std::shared_ptr program = ex::createGfxProgram(gfxContext, "atomic_test", shaderDir, includeDirList);
std::shared_ptr outputBuffer = ex::createGfxBuffer<Type>(gfxContext, result);
{
const ex::OptionString kernelName = ex::createOptionString("testAtomicFetchAddF{}Kernel", 8 * sizeof(Type));
const std::array kernelDefinitions = std::to_array<ex::OptionString>({
ex::createOptionString("MINIDXNN_NUM_THREADS_X={}", testParams.m_numThreadsX),
ex::createOptionString("MINIDXNN_NUM_TASKS={}", numTasks),
ex::createOptionString("MINIDXNN_NUM_ITERATIONS={}", numIterations),
});
std::shared_ptr kernel = ex::createGfxComputeKernel(gfxContext, *program, kernelName.data(), kernelDefinitions);
const size_t threadGroupSize = calcThreadGroupSize(numTasks, testParams.m_numThreadsX);
ex::runKernel(gfxContext, *program, *kernel, threadGroupSize,
{
ex::bind(*outputBuffer, "OutputBuffer"),
});
}
{
std::shared_ptr staging = ex::createGfxBuffer<Type>(gfxContext, size, kGfxCpuAccess_Read);
ex::copyBuffer(gfxContext, *outputBuffer, *staging);
const std::span output = ex::mapToCpu<Type>(gfxContext, *staging);
for (size_t i = 0; i < size; ++i)
result[i] = output[i];
}
} else
#endif // !MINIDXNN_CPP_FALLBACK_ONLY
{
std::vector<std::uint8_t> outputData(size * sizeof(Type), 0);
RWByteAddressBuffer outputBuf{outputData};
cppFallbackAtomicFetchAdd<Type>(outputBuf, numTasks, numIterations);
for (size_t i = 0; i < size; ++i)
std::memcpy(&result[i], outputData.data() + i * sizeof(Type), sizeof(Type));
}
const auto assertTest = [&testParams](const char* expectedLabel, const char* valueLabel, const Type expected, const Type value)
{
return assertSimilarity(expectedLabel, valueLabel, expected, value, testParams.m_similarityThreshold);
};
const double N = static_cast<double>(numTasks);
const double I = static_cast<double>(numIterations);
// Slot 0-3: constant accumulation
for (size_t i = 0; i < 4; ++i) {
const Type expected = static_cast<Type>(static_cast<float>(N * I * static_cast<double>(1u << i)));
EXPECT_PRED_FORMAT2(assertTest, expected, result[i]);
}
// Slot 4: 0.125 * N * I
{
const Type expected = static_cast<Type>(static_cast<float>(N * I * 0.125));
EXPECT_PRED_FORMAT2(assertTest, expected, result[4]);
}
// Slot 5: 0.0625 * N * I
{
const Type expected = static_cast<Type>(static_cast<float>(N * I * 0.0625));
EXPECT_PRED_FORMAT2(assertTest, expected, result[5]);
}
// Slot 6: alternating +1/-1 by thread ID; even threads add +1, odd add -1
// Net = numIterations * (numEvenThreads - numOddThreads) where numTasks is even → net = 0
{
const bool evenTasks = (numTasks & 1u) == 0u;
const double net = evenTasks ? 0.0 : I;
const Type expected = static_cast<Type>(static_cast<float>(net));
// Near-zero expected value: use absolute tolerance
EXPECT_NEAR(static_cast<double>(result[6]), static_cast<double>(expected),
std::max(1.0, static_cast<double>(numTasks) * 0.01));
}
// Slot 7: 3 * N * I
{
const Type expected = static_cast<Type>(static_cast<float>(N * I * 3.0));
EXPECT_PRED_FORMAT2(assertTest, expected, result[7]);
}
}
}
template <ex::Arithmetic Type, int ROW_SIZE, int COLUMN_SIZE>
auto testOuterProductAcc(const test::TestParameters& testParams,
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
GfxContext& gfxContext,
const bool useSoftwareLinAlgImpl,
const bool useCppFallback,
#endif
[[maybe_unused]] ex::MatrixLayout weightMatrixLayout,
const size_t numOfTests = 5) -> void
{
// For F16, cap tasks to stay within half precision range
constexpr size_t numTasks = sizeof(Type) >= 4
? (1ull << (std::min)(std::numeric_limits<Type>::digits, 16))
: 512;
for (size_t trial = 0; trial < numOfTests; ++trial) {
// Compute expected outer product accumulation:
// lhs[i] = i+1, rhs[j] = 1.0 => matrix[i][j] = numTasks * (i+1)
constexpr size_t rowSize = static_cast<size_t>(ROW_SIZE);
constexpr size_t columnSize = static_cast<size_t>(COLUMN_SIZE);
const size_t vectorStride = ex::alignBytes(columnSize * sizeof(Type), ex::MATRIX_VECTOR_STRIDE_ALIGNMENT);
const size_t totalBytes = ex::alignBytes(rowSize * vectorStride, ex::MATRIX_ALIGNMENT);
std::vector<Type> result(rowSize * columnSize, static_cast<Type>(0));
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
if (!useCppFallback) {
// GPU path (placeholder — currently delegates to SW via outerProductAccHW)
(void)gfxContext;
(void)useSoftwareLinAlgImpl;
// TODO: Add GPU kernel dispatch for outerProductAcc test
// For now, fall through to C++ fallback
std::vector<std::uint8_t> outputData(totalBytes, 0);
RWByteAddressBuffer outputBuf{outputData};
cppFallbackOuterProductAcc<Type, ROW_SIZE, COLUMN_SIZE>(outputBuf, vectorStride, numTasks);
for (size_t r = 0; r < rowSize; ++r)
for (size_t c = 0; c < columnSize; ++c)
std::memcpy(&result[r * columnSize + c],
outputData.data() + r * vectorStride + c * sizeof(Type),
sizeof(Type));
} else
#endif // !MINIDXNN_CPP_FALLBACK_ONLY
{
std::vector<std::uint8_t> outputData(totalBytes, 0);
RWByteAddressBuffer outputBuf{outputData};
cppFallbackOuterProductAcc<Type, ROW_SIZE, COLUMN_SIZE>(outputBuf, vectorStride, numTasks);
for (size_t r = 0; r < rowSize; ++r)
for (size_t c = 0; c < columnSize; ++c)
std::memcpy(&result[r * columnSize + c],
outputData.data() + r * vectorStride + c * sizeof(Type),
sizeof(Type));
}
const auto assertTest = [&testParams](const char* expectedLabel, const char* valueLabel, const Type expected, const Type value)
{
return assertSimilarity(expectedLabel, valueLabel, expected, value, testParams.m_similarityThreshold);
};
for (size_t r = 0; r < rowSize; ++r) {
for (size_t c = 0; c < columnSize; ++c) {
// lhs[r] = r+1, rhs[c] = 1.0 => expected = numTasks * (r+1)
const Type expected = static_cast<Type>(static_cast<float>(numTasks * (r + 1)));
EXPECT_PRED_FORMAT2(assertTest, expected, result[r * columnSize + c]);
}
}
}
}
// ============================================================================
// Unified MLP test functions — shared between LinearAlgebraMatrixTest and CppFallbackTest
// ============================================================================
template <ex::Arithmetic Type>
auto testSimpleMlpForwardFloat(const test::TestParameters& testParams,
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
GfxContext& gfxContext,
const bool useSoftwareLinAlgImpl,
const bool useCppFallback,
#endif
const size_t inputDim,
const size_t outputDim,
const size_t hiddenLayerDim,
const size_t numBackboneLayers,
const bool hasBias,
ex::MatrixLayout weightMatrixLayout,
const size_t numOfTests = 5) -> void
{
#ifdef MINIDXNN_CPP_FALLBACK_ONLY
(void)weightMatrixLayout;
#endif
ex::Xoshiro128Plus rng{testParams.m_seed};
for (size_t trial = 0; trial < numOfTests; ++trial) {
// Create a random MLP
constexpr ex::ActivationType activationHidden = ex::ActivationType::IDENTITY;
constexpr ex::ActivationType activationLast = ex::ActivationType::IDENTITY;
std::vector mlpData = ::createRandomMlp<Type>(inputDim, outputDim, hiddenLayerDim, numBackboneLayers, hasBias, activationHidden, activationLast, rng);
const size_t numTasks = testParams.m_numTasks;
// Create inputs and references
const std::vector inputs = ::createRandomInputs<Type>(inputDim * numTasks, rng);
const std::vector references = ex::forwardBatch<Type, Type, Type, Type, Type>(inputs, mlpData);
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
if (!useCppFallback) {
// GPU path
// Load the test program
const std::filesystem::path shaderDir = ex::getComputeShaderDir();
const std::array includeDirList = ex::getHlslIncludeDirList();
std::shared_ptr program = ex::createGfxProgram(gfxContext, "simple_mlp_inference_test", shaderDir, includeDirList);
// Build D3D12MatrixInfo list from MLP layers
std::vector<ex::D3D12MatrixInfo<Type>> matrixInfoList;
matrixInfoList.reserve(mlpData.size());
for (const auto& layer : mlpData) {
ex::D3D12MatrixInfo<Type> info;
info.m_srcData = layer.weightData();
info.m_rowSize = layer.outputDimension();
info.m_columnSize = layer.inputDimension();
info.m_layout = weightMatrixLayout;
matrixInfoList.push_back(info);
}
// Create buffers
std::shared_ptr inputBuffer = ex::createGfxBuffer<Type>(gfxContext, inputs);
std::shared_ptr outputBuffer = ex::createGfxBuffer<Type>(gfxContext, references.size());
std::shared_ptr weightBuffer = ex::packAsD3D12MatrixBuffer<Type>(gfxContext, matrixInfoList);
ASSERT_TRUE(weightBuffer) << "packAsD3D12MatrixBuffer failed for layout " << static_cast<int>(weightMatrixLayout);
// Build D3D12VectorInfo list from MLP layers
std::vector<ex::D3D12VectorInfo<Type>> vectorInfoList;
vectorInfoList.reserve(mlpData.size());
for (const auto& layer : mlpData) {
ex::D3D12VectorInfo<Type> info;
info.m_srcData = layer.biasData();
vectorInfoList.push_back(info);
}
std::shared_ptr biasBuffer = ex::packAsD3D12VectorBuffer<Type>(gfxContext, vectorInfoList);
// Create and run the test kernel
{
const ex::OptionString kernelName = ex::createOptionString("testMlpInferenceF{}Kernel", 8 * sizeof(Type));
std::vector kernelDefinitions = buildMlpTestDefinitions(testParams, inputDim, outputDim, hiddenLayerDim, numBackboneLayers + 1, activationHidden, activationLast, hasBias, useSoftwareLinAlgImpl, matrixInfoList[0].m_layout, matrixInfoList[0].m_alignment, matrixInfoList[0].m_vectorStrideAlignment, vectorInfoList[0].m_alignment);
kernelDefinitions.push_back(ex::createOptionString("MINIDXNN_NUM_TASKS={}", numTasks));
std::shared_ptr kernel = ex::createGfxComputeKernel(gfxContext, *program, kernelName.data(), kernelDefinitions);
const size_t threadGroupSize = calcThreadGroupSize(numTasks, testParams.m_numThreadsX);
ex::runKernel(gfxContext, *program, *kernel, threadGroupSize,
{
ex::bind(*inputBuffer, "InputBuffer"),
ex::bind(*outputBuffer, "OutputBuffer"),
ex::bind(*weightBuffer, "WeightBuffer"),
ex::bind(*biasBuffer, "BiasBuffer"),
},
{
ex::bind(static_cast<std::int32_t>(matrixInfoList.front().m_dataSize), "TEST_WEIGHT_MATRIX_SIZE_FIRST"),
ex::bind(static_cast<std::int32_t>((matrixInfoList.size() > 1) ? matrixInfoList.at(1).m_dataSize : 0), "TEST_WEIGHT_MATRIX_SIZE_HIDDEN"),
});
}
{
std::shared_ptr staging = ex::createGfxBuffer<Type>(gfxContext, references.size(), kGfxCpuAccess_Read);
ex::copyBuffer(gfxContext, *outputBuffer, *staging);
const std::span outputs = ex::mapToCpu<Type>(gfxContext, *staging);
const std::string testLabel = std::format("MLP{}", trial + 1);
ASSERT_TRUE(assertSimilarityBatch<Type>(references, outputs, testParams.m_similarityThreshold, testLabel, testParams.m_enableDebugMode));
}
} else
#endif // !MINIDXNN_CPP_FALLBACK_ONLY
{
// C++ fallback path
const size_t effectiveHiddenDim = (numBackboneLayers == 0)
? std::max(inputDim, outputDim)
: hiddenLayerDim;
ex::PackedMlpBuffers<Type> packed;
packed.pack(mlpData, hasBias);
std::vector<Type> outputs(numTasks * outputDim);
const bool dispatched = dispatchForward<Type>(
mlpData.size(), effectiveHiddenDim, inputDim, outputDim,
activationHidden, activationLast,
packed, inputs, outputs, numTasks, hasBias);
ASSERT_TRUE(dispatched)
<< "Unsupported MLP config: layers=" << mlpData.size()
<< " hiddenDim=" << effectiveHiddenDim
<< " inputDim=" << inputDim
<< " outputDim=" << outputDim;
const std::string testLabel = std::format("CppFallback_Forward{}", trial + 1);
ASSERT_TRUE(assertSimilarityBatch<Type>(references, outputs, testParams.m_similarityThreshold, testLabel, testParams.m_enableDebugMode));
}
}
}
template <ex::Arithmetic Type>
auto testSimpleMlpBackwardFloat(const test::TestParameters& testParams,
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
GfxContext& gfxContext,
const bool useSoftwareLinAlgImpl,
const bool useCppFallback,
#endif
const size_t hiddenLayerDim,
const size_t numBackboneLayers,
const size_t batchSize,
const bool hasBias,
ex::MatrixLayout weightMatrixLayout,
const size_t numOfTests = 5) -> void
{
#ifdef MINIDXNN_CPP_FALLBACK_ONLY
(void)weightMatrixLayout;
#endif
constexpr size_t inputDim = 2;
constexpr size_t outputDim = 4;
constexpr ex::ActivationType activationHidden = ex::ActivationType::LEAKY_RELU;
constexpr ex::ActivationType activationLast = ex::ActivationType::SIGMOID;
ex::Xoshiro128Plus rng{testParams.m_seed};
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
// GPU-only: load test program and create kernels outside the trial loop
std::shared_ptr<GfxProgram> gfxProgram;
std::shared_ptr<GfxKernel> gfxFwdKernel;
std::shared_ptr<GfxKernel> gfxBwdKernel;
if (!useCppFallback) {
// Pre-check: verify the GPU supports matrix conversion for optimal layouts
if (ex::needsMatrixConversion(weightMatrixLayout)) {
constexpr uint32_t dataType = ex::toD3D12DataType<Type>();
const uint32_t d3dLayout = ex::toD3D12MatrixLayout(weightMatrixLayout);
ASSERT_NE(gfxGetMatrixMemorySize(gfxContext, static_cast<uint32_t>(hiddenLayerDim), static_cast<uint32_t>(inputDim), d3dLayout, dataType, 0), 0u)
<< "GPU does not support layout " << static_cast<int>(weightMatrixLayout) << " conversion";
}
// Query representative D3D12 info for kernel define values
ex::D3D12MatrixInfo<Type> representativeMatrixInfo;
representativeMatrixInfo.m_rowSize = hiddenLayerDim;
representativeMatrixInfo.m_columnSize = inputDim;
representativeMatrixInfo.m_layout = weightMatrixLayout;
ex::getD3D12MatrixInfo(representativeMatrixInfo);
ex::D3D12VectorInfo<Type> representativeVectorInfo;
representativeVectorInfo.m_srcData = {};
ex::getD3D12VectorInfo(representativeVectorInfo);
const std::filesystem::path shaderDir = ex::getComputeShaderDir();
const std::array includeDirList = ex::getHlslIncludeDirList();
gfxProgram = ex::createGfxProgram(gfxContext, "simple_mlp_training_test", shaderDir, includeDirList);
std::vector kernelDefinitions = buildMlpTestDefinitions(testParams, inputDim, outputDim, hiddenLayerDim, numBackboneLayers + 1, activationHidden, activationLast, hasBias, useSoftwareLinAlgImpl, representativeMatrixInfo.m_layout, representativeMatrixInfo.m_alignment, representativeMatrixInfo.m_vectorStrideAlignment, representativeVectorInfo.m_alignment);
kernelDefinitions.push_back(ex::createOptionString("MINIDXNN_BATCH_SIZE={}", batchSize));
const ex::OptionString fwdName = ex::createOptionString("testMlpTrainingForwardF{}Kernel", 8 * sizeof(Type));
gfxFwdKernel = ex::createGfxComputeKernel(gfxContext, *gfxProgram, fwdName.data(), kernelDefinitions);
const ex::OptionString bwdName = ex::createOptionString("testMlpTrainingBackwardF{}Kernel", 8 * sizeof(Type));
gfxBwdKernel = ex::createGfxComputeKernel(gfxContext, *gfxProgram, bwdName.data(), kernelDefinitions);
}
#endif // !MINIDXNN_CPP_FALLBACK_ONLY
for (size_t trial = 0; trial < numOfTests; ++trial) {
// Create a random MLP (UV 2D -> RGBA 4D)
std::vector mlpData = ::createRandomMlp<Type>(inputDim, outputDim, hiddenLayerDim, numBackboneLayers, hasBias, activationHidden, activationLast, rng);
using LayerT = typename decltype(mlpData)::value_type;
// Create random inputs and targets for the batch
std::vector<Type> inputs(batchSize * inputDim);
std::vector<Type> targets(batchSize * outputDim);
std::vector<Type> outputs(batchSize * outputDim);
std::ranges::for_each(inputs, [&rng](Type& v) { v = static_cast<Type>(rng.draw()); });
std::ranges::for_each(targets, [&rng](Type& v) { v = static_cast<Type>(rng.draw()); });
// Reset gradients before processing the batch
std::ranges::for_each(mlpData, [](LayerT& layer) { layer.resetGrads(); });
// CPU reference: forward + backward
const float batchScale = 1.0f / static_cast<float>(batchSize);
const size_t cacheStride = (mlpData.size() - 1) * mlpData.back().inputDimension() + mlpData.back().outputDimension();
std::vector<Type> logitsCache(batchSize * cacheStride);
for (size_t s = 0; s < batchSize; ++s) {
const std::span<const Type> inputSpan{inputs.data() + (s * inputDim), inputDim};
std::span<Type> logitsSpan{logitsCache.data() + (s * cacheStride), cacheStride};
std::span<Type> outputSpan{outputs.data() + (s * outputDim), outputDim};
ex::forward<Type, Type, Type, Type, Type>(outputSpan, inputSpan, mlpData, logitsSpan);
const std::span<const Type> targetSpan{targets.data() + (s * outputDim), outputDim};
std::vector lossGradient = ex::mseLossGradient<Type>(outputSpan, targetSpan);
std::ranges::for_each(lossGradient, [batchScale](Type& v) { v *= batchScale; });
[[maybe_unused]] const std::vector upstreamGrad = ex::backward<Type, Type, Type, Type, Type>(lossGradient, inputSpan, mlpData, logitsSpan);
}
#ifndef MINIDXNN_CPP_FALLBACK_ONLY
if (!useCppFallback) {
// GPU path
// Build D3D12 matrix info list from MLP layers
std::vector<ex::D3D12MatrixInfo<Type>> matrixInfoList;
matrixInfoList.reserve(mlpData.size());
for (const LayerT& layer : mlpData) {
ex::D3D12MatrixInfo<Type> info;
info.m_srcData = layer.weightData();
info.m_rowSize = layer.outputDimension();
info.m_columnSize = layer.inputDimension();
info.m_layout = weightMatrixLayout;
matrixInfoList.push_back(info);
}
// Build D3D12 vector info list from MLP layers
std::vector<ex::D3D12VectorInfo<Type>> vectorInfoList;
vectorInfoList.reserve(mlpData.size());
for (const LayerT& layer : mlpData) {
ex::D3D12VectorInfo<Type> info;
info.m_srcData = layer.biasData();
vectorInfoList.push_back(info);
}
// Create buffers
std::shared_ptr inputBuffer = ex::createGfxBuffer<Type>(gfxContext, inputs);
std::shared_ptr targetBuffer = ex::createGfxBuffer<Type>(gfxContext, targets);
std::shared_ptr outputBuffer = ex::createGfxBuffer<Type>(gfxContext, outputs.size());
std::shared_ptr weightBuffer = ex::packAsD3D12MatrixBuffer<Type>(gfxContext, matrixInfoList);
ASSERT_TRUE(weightBuffer) << "packAsD3D12MatrixBuffer failed for layout " << static_cast<int>(weightMatrixLayout);
std::shared_ptr biasBuffer = ex::packAsD3D12VectorBuffer<Type>(gfxContext, vectorInfoList);
std::shared_ptr weightGradBuffer = ex::createGfxBuffer<Type>(gfxContext, weightBuffer->getSize() / sizeof(Type));
const size_t biasStride = biasBuffer->getSize() / sizeof(Type);
std::shared_ptr biasGradBuffer = ex::createGfxBuffer<Type>(gfxContext, biasStride);
std::shared_ptr logitsCacheBuffer = ex::createGfxBuffer<Type>(gfxContext, batchSize * biasStride);
const size_t threadGroupSize = calcThreadGroupSize(batchSize, testParams.m_numThreadsX);
// Forward pass
ex::runKernel(gfxContext, *gfxProgram, *gfxFwdKernel, threadGroupSize,
{
ex::bind(*inputBuffer, "InputBuffer"),
ex::bind(*outputBuffer, "OutputBuffer"),
ex::bind(*weightBuffer, "WeightBuffer"),
ex::bind(*biasBuffer, "BiasBuffer"),
ex::bind(*logitsCacheBuffer, "LogitsCacheBuffer"),
},
{
ex::bind(static_cast<std::int32_t>(matrixInfoList.front().m_dataSize), "TEST_WEIGHT_MATRIX_SIZE_FIRST"),
ex::bind(static_cast<std::int32_t>((matrixInfoList.size() > 1) ? matrixInfoList.at(1).m_dataSize : 0), "TEST_WEIGHT_MATRIX_SIZE_HIDDEN"),
ex::bind(static_cast<std::int32_t>(biasStride * sizeof(Type)), "TEST_BIAS_STRIDE"),
});
{ // Test outputs
std::shared_ptr staging = ex::createGfxBuffer<Type>(gfxContext, outputs.size(), kGfxCpuAccess_Read);
ex::copyBuffer(gfxContext, *outputBuffer, *staging);
const std::span data = ex::mapToCpu<Type>(gfxContext, *staging);
const std::string testLabel = std::format("MLP{} forward: outputs", trial + 1);
ASSERT_TRUE(assertSimilarityBatch<Type>(outputs, data, testParams.m_similarityThreshold, testLabel, testParams.m_enableDebugMode));
}
{ // test logits
std::shared_ptr staging = ex::createGfxBuffer<Type>(gfxContext, logitsCacheBuffer->getSize() / sizeof(Type), kGfxCpuAccess_Read);
ex::copyBuffer(gfxContext, *logitsCacheBuffer, *staging);
const std::span data = ex::mapToCpu<Type>(gfxContext, *staging);
std::vector<Type> logitsData;
logitsData.resize(logitsCache.size());
for (size_t batchId = 0; batchId < batchSize; ++batchId) {
for (size_t i = 0; i < mlpData.size(); ++i) {
const size_t layerInDim = mlpData[i].inputDimension();
const size_t layerOutDim = mlpData[i].outputDimension();
const size_t srcIndex = batchId * biasStride + i * ex::alignN<Type>(layerInDim, ex::VECTOR_ALIGNMENT);
const size_t dstIndex = batchId * cacheStride + i * layerInDim;
const std::ptrdiff_t srcBegin = static_cast<std::ptrdiff_t>(srcIndex);
const std::ptrdiff_t srcEnd = static_cast<std::ptrdiff_t>(srcIndex + layerOutDim);
const std::ptrdiff_t dstBegin = static_cast<std::ptrdiff_t>(dstIndex);
std::copy(data.begin() + srcBegin, data.begin() + srcEnd, logitsData.begin() + dstBegin);
}
}
const std::string testLabel = std::format("MLP{} forward: logits", trial + 1);
ASSERT_TRUE(assertSimilarityBatch<Type>(logitsCache, logitsData, testParams.m_similarityThreshold, testLabel, testParams.m_enableDebugMode));
}
gfxCommandClearBuffer(gfxContext, *weightGradBuffer);
gfxCommandClearBuffer(gfxContext, *biasGradBuffer);
gfxFinish(gfxContext);
// Backward pass
ex::runKernel(gfxContext, *gfxProgram, *gfxBwdKernel, threadGroupSize,
{
ex::bind(*inputBuffer, "InputBuffer"),
ex::bind(*targetBuffer, "TargetBuffer"),
ex::bind(*outputBuffer, "OutputBuffer"),
ex::bind(*weightBuffer, "WeightBuffer"),
ex::bind(*biasBuffer, "BiasBuffer"),
ex::bind(*weightGradBuffer, "WeightGradBuffer"),
ex::bind(*biasGradBuffer, "BiasGradBuffer"),
ex::bind(*logitsCacheBuffer, "LogitsCacheBuffer"),
},
{
ex::bind(static_cast<std::int32_t>(matrixInfoList.front().m_dataSize), "TEST_WEIGHT_MATRIX_SIZE_FIRST"),
ex::bind(static_cast<std::int32_t>((matrixInfoList.size() > 1) ? matrixInfoList.at(1).m_dataSize : 0), "TEST_WEIGHT_MATRIX_SIZE_HIDDEN"),
ex::bind(static_cast<std::int32_t>(biasStride * sizeof(Type)), "TEST_BIAS_STRIDE"),
});
{ // weight grad
const std::vector<Type> actualGrads = ex::unpackD3D12MatrixBuffer<Type>(gfxContext, *weightGradBuffer, matrixInfoList);
std::vector<Type> expectedGrads;
expectedGrads.reserve(actualGrads.size());
for (const LayerT& layer : mlpData) {
const ex::MatrixRef expected = layer.weightGradMatrix();
for (size_t row = 0; row < expected.rowSize(); ++row)
for (size_t column = 0; column < expected.columnSize(); ++column)
expectedGrads.emplace_back(expected(row, column));
}
const std::string testLabel = std::format("MLP{} backward: weight grads", trial + 1);
ASSERT_TRUE(assertSimilarityBatch<Type>(expectedGrads, actualGrads, testParams.m_similarityThreshold, testLabel, testParams.m_enableDebugMode));
}
if (hasBias) { // bias grad
std::shared_ptr staging = ex::createGfxBuffer<Type>(gfxContext, biasGradBuffer->getSize() / sizeof(Type), kGfxCpuAccess_Read);
ex::copyBuffer(gfxContext, *biasGradBuffer, *staging);
const std::span data = ex::mapToCpu<Type>(gfxContext, *staging);
const size_t n = std::transform_reduce(mlpData.begin(), mlpData.end(), static_cast<size_t>(0), std::plus{}, [](const LayerT& layer) -> size_t
{
return layer.biasGrads().size();
});
std::vector<Type> expectedGrads;
std::vector<Type> actualGrads;
expectedGrads.reserve(n);
actualGrads.reserve(n);
for (size_t layerIndex = 0, offset = 0; layerIndex < mlpData.size(); ++layerIndex) {
const LayerT& layer = mlpData[layerIndex];
const std::span expected = layer.biasGrads();
const std::span<Type> actual{data.data() + offset, expected.size()};
expectedGrads.insert(expectedGrads.end(), expected.begin(), expected.end());
actualGrads.insert(actualGrads.end(), actual.begin(), actual.end());
const size_t stride = ex::alignN<Type>(expected.size(), ex::VECTOR_ALIGNMENT);
offset += stride;
}
const std::string testLabel = std::format("MLP{} backward: bias grads", trial + 1);
ASSERT_TRUE(assertSimilarityBatch<Type>(expectedGrads, actualGrads, testParams.m_similarityThreshold, testLabel, testParams.m_enableDebugMode));
}
} else
#endif // !MINIDXNN_CPP_FALLBACK_ONLY
{
// C++ fallback path
const size_t effectiveHiddenDim = (numBackboneLayers == 0)
? std::max(inputDim, outputDim)
: hiddenLayerDim;
ex::PackedMlpBuffers<Type> packed;
packed.pack(mlpData, hasBias);
std::vector<Type> fbOutputs(batchSize * outputDim);
std::vector<std::uint8_t> weightGradBuf, biasGradBuf;
const bool dispatched = dispatchBackward<Type>(
mlpData.size(), effectiveHiddenDim, inputDim, outputDim,
activationHidden, activationLast,